Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(heterogeneous-agents): read Kimi Code token usage from session wire log after run (#19722)

Arvin Xucb83d764d1b1
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 5904cd88ccf..b5ca2cd0a80 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -65,6 +65,7 @@ the next free number of that prefix.
- **L-S22** A per-account cap that a round consumes (artifact deployments) is cleared for the account the surface actually authenticates as, and re-cleared between rounds.
- **L-S23** A hand-built `node_modules` symlink farm runs unit tests but cannot start the dev server; clone a working checkout's `node_modules` instead of a fresh install, which this lockfile-less repo resolves against a moving registry.
- **L-S24** Read the dev server's URL from its own log, and treat "ready" as any status but `000` — `/` answers `302` to `/signin` when signed out.
+- **L-S25** `dev:static` 的 Electron 重启会清空 `dist/renderer`(renderer Vite dev server 启动即删 outDir);`start`/`restart` 后必须重建 renderer 再驱动,否则页面只有 Internal Server Error。
## Entries
@@ -591,3 +592,16 @@ a separate Vite port in the Debug Proxy line); and the app answers `/` with
**Rule:** take both URLs from the log, never from memory or a default. Probe with
PROJECT.md's predicate as written — any code but `000` — and confirm health by
following the redirect, not by demanding `200` at the root.
+
+### L-S25 — dev:static 重启后 dist/renderer 被清空
+
+`since 2026-09-20` · `holds-while: dev.mjs 的 renderer Vite dev server 在启动时删除 renderer outDir`
+
+**Trap:** `DESKTOP_RENDERER_STATIC=1 electron-dev.sh start|restart` 后立刻驱动页面,
+只看到 `Internal Server Error`(静态 handler 报 `ENOENT dist/renderer/apps/desktop/index.html`)。
+dev.mjs 每次启动都会拉起 renderer Vite dev server,而后者启动即清空
+`apps/desktop/dist/renderer`;静态产物是在启动序列里被删的,与是否使用静态模式无关。
+
+**Rule:** 每次 `start`/`restart` 之后、驱动之前,先 `cd apps/desktop && pnpm build:renderer`
+(约 25s)并确认 `dist/renderer/apps/desktop/index.html` 存在。同一个 dev.mjs 生命周期内
+的后续重启不会再次清空;改用 `restart` 而不是 `start` 时也按同一规则处理。
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index b18619c747f..36ab364881a 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -3303,6 +3303,12 @@ export default class HeterogeneousAgentCtr {
void stdoutDrained
.then(() => stdoutBroadcastQueue)
.finally(async () => {
+ // Kimi Code reports token usage only via its on-disk session wire
+ // log, so it can only be collected now that the process has exited.
+ // Broadcast BEFORE `heteroAgentSessionComplete` so the renderer
+ // persists it with the run. No-op for other agent types.
+ broadcastStreamEvents(await pipeline.collectPostRunUsage({ env: spawnEnv }));
+
// Tear down the AskUserQuestion bridge / temp `mcp.json` for this
// op. Pending MCP handlers get a `session_ended` cancellation so
// they return cleanly even if CC was killed mid-tool-call.
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index e2fcbd0e417..b9f38bdbd6b 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -1179,6 +1179,18 @@ export class FlatListBuilder {
role: role as any,
};
+ // Heterogeneous agents (e.g. kimi-code) may only learn model/provider at
+ // run end, stamped on the LAST step's assistant row — the group spreads
+ // the FIRST row, so backfill from the last chain assistant carrying one.
+ if (!result.model) {
+ const withModel = assistantChain.findLast((assistant) => !!assistant.model);
+ if (withModel) result.model = withModel.model;
+ }
+ if (!result.provider) {
+ const withProvider = assistantChain.findLast((assistant) => !!assistant.provider);
+ if (withProvider) result.provider = withProvider.provider;
+ }
+
// Remove fields that should not be in assistantGroup/supervisor
delete result.imageList;
delete result.metadata;
diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
index 162fa229f93..da1c87e2347 100644
--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
@@ -280,6 +280,158 @@ describe('FlatListBuilder', () => {
expect(result[1].usage).toBeDefined();
});
+ it('should backfill group model/provider from a later step assistant', () => {
+ // Kimi Code only learns model/provider at run end (stamped on the LAST
+ // step's assistant via turn_metadata); the group spreads the first row.
+ const messages: Message[] = [
+ {
+ content: 'Request',
+ createdAt: 0,
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ content: 'Using tool',
+ createdAt: 0,
+ id: 'msg-2',
+ parentId: 'msg-1',
+ role: 'assistant',
+ tools: [
+ { apiName: 'test', arguments: '{}', id: 'tool-1', identifier: 'test', type: 'default' },
+ ],
+ updatedAt: 0,
+ },
+ {
+ content: 'Tool result',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ updatedAt: 0,
+ },
+ {
+ content: 'Done',
+ createdAt: 0,
+ id: 'msg-3',
+ metadata: { totalInputTokens: 30, totalOutputTokens: 7 },
+ model: 'kimi-code/k3',
+ parentId: 'tool-1',
+ provider: 'kimi-code',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result).toHaveLength(2);
+ expect(result[1].role).toBe('assistantGroup');
+ expect(result[1].model).toBe('kimi-code/k3');
+ expect(result[1].provider).toBe('kimi-code');
+ expect(result[1].usage).toMatchObject({ totalInputTokens: 30, totalOutputTokens: 7 });
+ });
+
+ it('should keep the first assistant model/provider when already set', () => {
+ const messages: Message[] = [
+ {
+ content: 'Request',
+ createdAt: 0,
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ content: 'Using tool',
+ createdAt: 0,
+ id: 'msg-2',
+ model: 'claude-opus-4-7',
+ parentId: 'msg-1',
+ provider: 'claude-code',
+ role: 'assistant',
+ tools: [
+ { apiName: 'test', arguments: '{}', id: 'tool-1', identifier: 'test', type: 'default' },
+ ],
+ updatedAt: 0,
+ },
+ {
+ content: 'Tool result',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ updatedAt: 0,
+ },
+ {
+ content: 'Done',
+ createdAt: 0,
+ id: 'msg-3',
+ model: 'kimi-code/k3',
+ parentId: 'tool-1',
+ provider: 'kimi-code',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result[1].role).toBe('assistantGroup');
+ expect(result[1].model).toBe('claude-opus-4-7');
+ expect(result[1].provider).toBe('claude-code');
+ });
+
+ it('should leave group model/provider undefined when no assistant carries one', () => {
+ const messages: Message[] = [
+ {
+ content: 'Request',
+ createdAt: 0,
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ content: 'Using tool',
+ createdAt: 0,
+ id: 'msg-2',
+ parentId: 'msg-1',
+ role: 'assistant',
+ tools: [
+ { apiName: 'test', arguments: '{}', id: 'tool-1', identifier: 'test', type: 'default' },
+ ],
+ updatedAt: 0,
+ },
+ {
+ content: 'Tool result',
+ createdAt: 0,
+ id: 'tool-1',
+ parentId: 'msg-2',
+ role: 'tool',
+ tool_call_id: 'tool-1',
+ updatedAt: 0,
+ },
+ {
+ content: 'Done',
+ createdAt: 0,
+ id: 'msg-3',
+ parentId: 'tool-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ expect(result[1].role).toBe('assistantGroup');
+ expect(result[1].model).toBeUndefined();
+ expect(result[1].provider).toBeUndefined();
+ });
+
it('keeps a terminal finish type on its originating assistant block', () => {
const messages: Message[] = [
{ content: 'Request', createdAt: 0, id: 'user-1', role: 'user', updatedAt: 0 },
diff --git a/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts b/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
index 996c73b0e94..126da316cbf 100644
--- a/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
@@ -1,8 +1,41 @@
-import { describe, expect, it } from 'vitest';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
import { KimiCodeAdapter } from './kimiCode';
+const tempDirs: string[] = [];
+
+const makeTempKimiHome = async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'lobe-kimi-adapter-'));
+ tempDirs.push(dir);
+ return dir;
+};
+
+const writeWireLog = async (
+ kimiHome: string,
+ sessionId: string,
+ usageRecords: { model?: string; usage: Record<string, number> }[],
+) => {
+ const dir = path.join(kimiHome, 'sessions', 'wd_test', sessionId, 'agents', 'main');
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, 'wire.jsonl'),
+ usageRecords
+ .map(({ model, usage }) =>
+ JSON.stringify({ agentId: 'main', model, type: 'usage.record', usage }),
+ )
+ .join('\n'),
+ );
+};
+
describe('KimiCodeAdapter', () => {
+ afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+ });
+
it('maps the documented text, parallel tools, results, and resume hint sequence', () => {
const adapter = new KimiCodeAdapter();
const first = adapter.adapt({
@@ -169,4 +202,75 @@ describe('KimiCodeAdapter', () => {
expect(adapter.adapt({ role: 'meta', type: 'system.version', version: '0.28.0' })).toEqual([]);
expect(adapter.adapt({ status: 'complete', type: 'goal.summary' })).toEqual([]);
});
+
+ describe('collectPostRunUsage', () => {
+ it('emits aggregated wire-log usage as a turn_metadata step_complete on the last step', async () => {
+ const kimiHome = await makeTempKimiHome();
+ const adapter = new KimiCodeAdapter();
+ adapter.adapt({ role: 'meta', session_id: 'session-1', type: 'session.resume_hint' });
+ // Two steps, so the usage event must land on stepIndex 1.
+ adapter.adapt({
+ role: 'assistant',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'Read' }, id: 'call-1', type: 'function' },
+ ],
+ });
+ adapter.adapt({ content: 'contents', role: 'tool', tool_call_id: 'call-1' });
+ adapter.adapt({ content: 'Done.', role: 'assistant' });
+ await writeWireLog(kimiHome, 'session-1', [
+ { model: 'kimi-code/k3', usage: { inputCacheRead: 22_784, inputOther: 225, output: 27 } },
+ { model: 'kimi-code/k3', usage: { inputCacheCreation: 10, inputOther: 100, output: 53 } },
+ ]);
+
+ const events = await adapter.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } });
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({
+ data: {
+ model: 'kimi-k3',
+ phase: 'turn_metadata',
+ provider: 'kimi-code',
+ usage: {
+ inputCacheMissTokens: 325,
+ inputCachedTokens: 22_784,
+ inputWriteCacheTokens: 10,
+ totalInputTokens: 23_119,
+ totalOutputTokens: 80,
+ totalTokens: 23_199,
+ },
+ },
+ stepIndex: 1,
+ type: 'step_complete',
+ });
+ });
+
+ it('omits the model from the event when the wire log does not record one', async () => {
+ const kimiHome = await makeTempKimiHome();
+ const adapter = new KimiCodeAdapter();
+ adapter.adapt({ role: 'meta', session_id: 'session-2', type: 'session.resume_hint' });
+ await writeWireLog(kimiHome, 'session-2', [{ usage: { inputOther: 7, output: 3 } }]);
+
+ const events = await adapter.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } });
+ expect(events).toHaveLength(1);
+ expect(events[0].data).not.toHaveProperty('model');
+ expect(events[0]).toMatchObject({
+ data: { phase: 'turn_metadata', usage: { totalTokens: 10 } },
+ type: 'step_complete',
+ });
+ });
+
+ it('no-ops without a session id or wire log', async () => {
+ const kimiHome = await makeTempKimiHome();
+
+ const noSession = new KimiCodeAdapter();
+ await expect(
+ noSession.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toEqual([]);
+
+ const missingLog = new KimiCodeAdapter();
+ missingLog.adapt({ role: 'meta', session_id: 'nope', type: 'session.resume_hint' });
+ await expect(
+ missingLog.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toEqual([]);
+ });
+ });
});
diff --git a/packages/heterogeneous-agents/src/adapters/kimiCode.ts b/packages/heterogeneous-agents/src/adapters/kimiCode.ts
index 9360a616058..df805980436 100644
--- a/packages/heterogeneous-agents/src/adapters/kimiCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/kimiCode.ts
@@ -3,9 +3,11 @@ import type {
AgentEventAdapter,
HeterogeneousAgentEvent,
HeterogeneousToolResultImage,
+ PostRunUsageOptions,
ToolCallPayload,
ToolResultData,
} from '../types';
+import { readKimiCodeSessionUsage } from '../utils/kimiCodeUsage';
const KIMI_CODE_IDENTIFIER = 'kimi-code';
@@ -100,6 +102,31 @@ export class KimiCodeAdapter implements AgentEventAdapter {
return [];
}
+ /**
+ * Kimi Code's stream-json stdout carries no usage; the session wire log
+ * does. After process exit, read + aggregate it and emit the total as
+ * `turn_metadata` — the phase the executor persists (its `result_usage`
+ * grand-total phase is intentionally ignored), stamped on the last step.
+ */
+ async collectPostRunUsage(options?: PostRunUsageOptions): Promise<HeterogeneousAgentEvent[]> {
+ try {
+ const result = await readKimiCodeSessionUsage(this.sessionId, { env: options?.env });
+ if (!result) return [];
+ return [
+ this.makeEvent('step_complete', {
+ // `model` lets the per-message Usage footer render (it requires a
+ // model for local heterogeneous types); `usage` carries the totals.
+ ...(result.model ? { model: result.model } : {}),
+ phase: 'turn_metadata',
+ provider: KIMI_CODE_IDENTIFIER,
+ usage: result.usage,
+ }),
+ ];
+ } catch {
+ return [];
+ }
+ }
+
flush(): HeterogeneousAgentEvent[] {
if (this.flushed) return [];
this.flushed = true;
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 8a72d636024..4612065d581 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -1,7 +1,13 @@
-import { describe, expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { AgentStreamPipeline } from './agentStreamPipeline';
+const tempDirs: string[] = [];
+
const init = (sessionId = 'cc-1') =>
`${JSON.stringify({
model: 'claude-sonnet-4-6',
@@ -53,6 +59,10 @@ const contentOf = (events: { data?: any; type: string }[]) =>
events.find((e) => e.type === 'tool_result')?.data?.content;
describe('AgentStreamPipeline', () => {
+ afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+ });
+
it('runs JSONL → adapter → toStreamEvent and stamps operationId', async () => {
const pipeline = new AgentStreamPipeline({
agentType: 'claude-code',
@@ -177,11 +187,68 @@ describe('AgentStreamPipeline', () => {
expect(Array.isArray(flushed)).toBe(true);
});
+ describe('collectPostRunUsage', () => {
+ it('no-ops for adapters without a post-run usage hook', async () => {
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ });
+
+ await expect(pipeline.collectPostRunUsage()).resolves.toEqual([]);
+ });
+
+ it('emits Kimi Code wire-log usage as an operationId-stamped turn_metadata event', async () => {
+ const kimiHome = await mkdtemp(path.join(os.tmpdir(), 'lobe-kimi-pipeline-'));
+ tempDirs.push(kimiHome);
+ const wireDir = path.join(kimiHome, 'sessions', 'wd_test', 'session-9', 'agents', 'main');
+ await mkdir(wireDir, { recursive: true });
+ await writeFile(
+ path.join(wireDir, 'wire.jsonl'),
+ `${JSON.stringify({
+ agentId: 'main',
+ model: 'kimi-code/k3',
+ time: 1_700_000_000_000,
+ type: 'usage.record',
+ usage: { inputCacheRead: 1000, inputOther: 200, output: 50 },
+ })}\n`,
+ );
+
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'kimi-code',
+ operationId: 'op-kimi',
+ });
+ await pipeline.push(
+ `${JSON.stringify({ role: 'meta', session_id: 'session-9', type: 'session.resume_hint' })}\n`,
+ );
+
+ const events = await pipeline.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } });
+
+ expect(events).toEqual([
+ expect.objectContaining({
+ data: {
+ model: 'kimi-k3',
+ phase: 'turn_metadata',
+ provider: 'kimi-code',
+ usage: {
+ inputCacheMissTokens: 200,
+ inputCachedTokens: 1000,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 1200,
+ totalOutputTokens: 50,
+ totalTokens: 1250,
+ },
+ },
+ operationId: 'op-kimi',
+ stepIndex: 0,
+ type: 'step_complete',
+ }),
+ ]);
+ });
+ });
+
describe('tool_result image upload ()', () => {
it('rewrites base64 pluginState.images into uploaded references', async () => {
- const uploadImage = vi
- .fn()
- .mockResolvedValue({ fileId: 'file_1', url: 'https://cdn/x.png' });
+ const uploadImage = vi.fn().mockResolvedValue({ fileId: 'file_1', url: 'https://cdn/x.png' });
const pipeline = new AgentStreamPipeline({
agentType: 'claude-code',
operationId: 'op-1',
@@ -225,7 +292,9 @@ describe('AgentStreamPipeline', () => {
expect(uploadImage).toHaveBeenCalledTimes(1);
expect(imagesOf(events)).toBeUndefined();
// The `[Image: …]` placeholder is still the content fallback.
- expect(events.find((e) => e.type === 'tool_result')?.data?.content).toBe('[Image: image/png]');
+ expect(events.find((e) => e.type === 'tool_result')?.data?.content).toBe(
+ '[Image: image/png]',
+ );
});
it('drops the image when the uploader declines (returns undefined)', async () => {
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
index 1d0bc7500cc..d7b136f814c 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
@@ -6,6 +6,7 @@ import type {
AgentEventAdapter,
HeterogeneousAgentEvent,
HeterogeneousToolResultImage,
+ PostRunUsageOptions,
UsageData,
} from '../types';
import { CodexFileChangeTracker } from './codexFileChangeTracker';
@@ -130,6 +131,20 @@ export class AgentStreamPipeline {
]);
}
+ /**
+ * Run the adapter's post-exit usage hook (Kimi Code reads its session wire
+ * log from disk). Call after {@link flush} and process exit. Always
+ * best-effort: adapters without the hook — or a throwing hook — yield `[]`.
+ */
+ async collectPostRunUsage(options?: PostRunUsageOptions): Promise<AgentStreamEvent[]> {
+ try {
+ const events = (await this.adapter.collectPostRunUsage?.(options)) ?? [];
+ return this.toStreamEvents(events);
+ } catch {
+ return [];
+ }
+ }
+
/**
* Validate provider-specific terminal contracts after a successful process
* exit. Call only after {@link flush} has drained the full stdout stream.
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index 3d3a95c177e..4e92a38dd8e 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -800,6 +800,12 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
if (code === 0 && !killedByUs) {
for (const event of pipeline.validateCompletion()) queue.push(event);
}
+ // Kimi Code reports usage only via its on-disk session wire log, so
+ // it can only be collected now that the process has exited. The hook
+ // is a no-op for every other agent type.
+ for (const event of await pipeline.collectPostRunUsage({ env: childEnv })) {
+ queue.push(event);
+ }
} catch (err) {
streamError = err instanceof Error ? err : new Error(String(err));
} finally {
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 47d268829f2..1a79ef79e4d 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -385,12 +385,29 @@ export interface HeterogeneousTerminalErrorData {
* Adapters maintain internal state (e.g., pending tool calls) to correctly
* emit lifecycle events like tool_start / tool_end.
*/
+/**
+ * Options for {@link AgentEventAdapter.collectPostRunUsage}. `env` is the
+ * child process environment, so home-resolution honors relocations like
+ * `KIMI_CODE_HOME` that only exist in the spawn env.
+ */
+export interface PostRunUsageOptions {
+ env?: Record<string, string | undefined>;
+}
+
export interface AgentEventAdapter {
/**
* Convert a single raw event into zero or more HeterogeneousAgentEvents.
*/
adapt: (raw: any) => HeterogeneousAgentEvent[];
+ /**
+ * Optional post-exit hook for agents whose token usage never appears on
+ * stdout (e.g. Kimi Code logs usage only to the session's wire.jsonl).
+ * Called after stdout drained and the child process exited. Must be
+ * best-effort: usage collection failures resolve to `[]`, never throw.
+ */
+ collectPostRunUsage?: (options?: PostRunUsageOptions) => Promise<HeterogeneousAgentEvent[]>;
+
/**
* Flush any buffered events (call at end of stream).
*/
diff --git a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts b/packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts
new file mode 100644
index 00000000000..4f4605c961b
--- /dev/null
+++ b/packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts
@@ -0,0 +1,276 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ aggregateKimiCodeUsage,
+ getKimiCodeHome,
+ parseKimiCodeWireUsage,
+ readKimiCodeSessionUsage,
+ toKimiCodeUsageData,
+} from './kimiCodeUsage';
+
+const tempDirs: string[] = [];
+
+const makeTempKimiHome = async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'lobe-kimi-usage-'));
+ tempDirs.push(dir);
+ return dir;
+};
+
+const writeWireLog = async (
+ kimiHome: string,
+ wdKey: string,
+ sessionId: string,
+ lines: string[],
+) => {
+ const dir = path.join(kimiHome, 'sessions', wdKey, sessionId, 'agents', 'main');
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, 'wire.jsonl'), lines.join('\n'));
+};
+
+const usageLine = (usage: Record<string, number>) =>
+ JSON.stringify({ content: 'Working.', role: 'assistant', usage });
+
+const usageRecordLine = (model: string, usage: Record<string, number>) =>
+ JSON.stringify({ agentId: 'main', model, time: 1_700_000_000_000, type: 'usage.record', usage });
+
+describe('kimiCodeUsage', () => {
+ afterEach(async () => {
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+ });
+
+ describe('getKimiCodeHome', () => {
+ it('prefers KIMI_CODE_HOME over the default home dir', () => {
+ expect(getKimiCodeHome({ KIMI_CODE_HOME: '/managed/kimi' }, '/home/u')).toBe('/managed/kimi');
+ expect(getKimiCodeHome({}, '/home/u')).toBe(path.join('/home/u', '.kimi-code'));
+ expect(getKimiCodeHome({ KIMI_CODE_HOME: ' ' }, '/home/u')).toBe(
+ path.join('/home/u', '.kimi-code'),
+ );
+ });
+ });
+
+ describe('toKimiCodeUsageData', () => {
+ it('maps wire usage fields onto the UsageData cache split', () => {
+ expect(
+ toKimiCodeUsageData({
+ inputCacheCreation: 100,
+ inputCacheRead: 22_784,
+ inputOther: 225,
+ output: 27,
+ }),
+ ).toEqual({
+ inputCacheMissTokens: 225,
+ inputCachedTokens: 22_784,
+ inputWriteCacheTokens: 100,
+ totalInputTokens: 23_109,
+ totalOutputTokens: 27,
+ totalTokens: 23_136,
+ });
+ });
+
+ it('omits zero cache fields and returns undefined for empty usage', () => {
+ expect(toKimiCodeUsageData({ inputOther: 5, output: 2 })).toEqual({
+ inputCacheMissTokens: 5,
+ inputCachedTokens: undefined,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 5,
+ totalOutputTokens: 2,
+ totalTokens: 7,
+ });
+ expect(toKimiCodeUsageData({})).toBeUndefined();
+ expect(toKimiCodeUsageData(undefined)).toBeUndefined();
+ });
+ });
+
+ describe('aggregateKimiCodeUsage', () => {
+ it('sums multiple per-request records into a grand total', () => {
+ expect(
+ aggregateKimiCodeUsage([
+ { usage: { inputCacheCreation: 0, inputCacheRead: 22_784, inputOther: 225, output: 27 } },
+ {
+ usage: { inputCacheCreation: 512, inputCacheRead: 23_000, inputOther: 100, output: 53 },
+ },
+ ]),
+ ).toEqual({
+ model: undefined,
+ usage: {
+ inputCacheMissTokens: 325,
+ inputCachedTokens: 45_784,
+ inputWriteCacheTokens: 512,
+ totalInputTokens: 46_621,
+ totalOutputTokens: 80,
+ totalTokens: 46_701,
+ },
+ });
+ });
+
+ it('takes the model from the last usage-bearing record, without the provider prefix', () => {
+ expect(
+ aggregateKimiCodeUsage([
+ { model: 'kimi-code/k2', usage: { inputOther: 10, output: 5 } },
+ { model: 'kimi-code/k3', usage: { inputOther: 20, output: 6 } },
+ ]),
+ ).toMatchObject({ model: 'kimi-k3' });
+ });
+
+ it('passes a model without the kimi-code/ prefix through unchanged', () => {
+ expect(
+ aggregateKimiCodeUsage([{ model: 'k3', usage: { inputOther: 10, output: 5 } }]),
+ ).toMatchObject({ model: 'k3' });
+ });
+
+ it('returns undefined when no record carries tokens', () => {
+ expect(aggregateKimiCodeUsage([])).toBeUndefined();
+ expect(aggregateKimiCodeUsage([{ usage: { inputOther: 0, output: 0 } }])).toBeUndefined();
+ });
+ });
+
+ describe('parseKimiCodeWireUsage', () => {
+ it('extracts usage objects and skips non-usage or malformed lines', () => {
+ const records = parseKimiCodeWireUsage(
+ [
+ JSON.stringify({ role: 'meta', type: 'system.version', version: '2.0.2' }),
+ usageLine({ inputCacheRead: 100, inputOther: 10, output: 5 }),
+ 'not json {',
+ JSON.stringify({ role: 'assistant', content: 'no usage here' }),
+ usageLine({ inputOther: 3, output: 1 }),
+ '',
+ ].join('\n'),
+ );
+ expect(records).toEqual([
+ { model: undefined, usage: { inputCacheRead: 100, inputOther: 10, output: 5 } },
+ { model: undefined, usage: { inputOther: 3, output: 1 } },
+ ]);
+ });
+
+ it('captures the model from usage.record lines and ignores other typed lines', () => {
+ const records = parseKimiCodeWireUsage(
+ [
+ usageRecordLine('kimi-code/k3', { inputCacheRead: 100, inputOther: 10, output: 5 }),
+ JSON.stringify({
+ content: 'Working.',
+ role: 'assistant',
+ type: 'assistant.message',
+ usage: { inputOther: 999, output: 999 },
+ }),
+ ].join('\n'),
+ );
+ expect(records).toEqual([
+ { model: 'kimi-code/k3', usage: { inputCacheRead: 100, inputOther: 10, output: 5 } },
+ ]);
+ });
+ });
+
+ describe('readKimiCodeSessionUsage', () => {
+ it('reads and aggregates usage from the session wire log across wd buckets', async () => {
+ const kimiHome = await makeTempKimiHome();
+ await writeWireLog(kimiHome, 'wd_lobehub_a3de130d1c24', 'session-1', [
+ JSON.stringify({ role: 'meta', type: 'system.version', version: '2.0.2' }),
+ usageRecordLine('kimi-code/k3', {
+ inputCacheCreation: 0,
+ inputCacheRead: 22_784,
+ inputOther: 225,
+ output: 27,
+ }),
+ usageRecordLine('kimi-code/k3', {
+ inputCacheCreation: 10,
+ inputCacheRead: 23_000,
+ inputOther: 100,
+ output: 53,
+ }),
+ ]);
+
+ await expect(
+ readKimiCodeSessionUsage('session-1', { env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toEqual({
+ model: 'kimi-k3',
+ usage: {
+ inputCacheMissTokens: 325,
+ inputCachedTokens: 45_784,
+ inputWriteCacheTokens: 10,
+ totalInputTokens: 46_119,
+ totalOutputTokens: 80,
+ totalTokens: 46_199,
+ },
+ });
+ });
+
+ it('omits the model when usage records do not carry one', async () => {
+ const kimiHome = await makeTempKimiHome();
+ await writeWireLog(kimiHome, 'wd_legacy', 'session-5', [
+ usageLine({ inputOther: 7, output: 3 }),
+ ]);
+
+ await expect(
+ readKimiCodeSessionUsage('session-5', { env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toEqual({
+ model: undefined,
+ usage: {
+ inputCacheMissTokens: 7,
+ inputCachedTokens: undefined,
+ inputWriteCacheTokens: undefined,
+ totalInputTokens: 7,
+ totalOutputTokens: 3,
+ totalTokens: 10,
+ },
+ });
+ });
+
+ it('resolves undefined for a missing session id, log, or usage records', async () => {
+ const kimiHome = await makeTempKimiHome();
+ await expect(
+ readKimiCodeSessionUsage(undefined, { env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toBeUndefined();
+ await expect(
+ readKimiCodeSessionUsage('missing', {
+ env: { KIMI_CODE_HOME: kimiHome },
+ maxAttempts: 1,
+ }),
+ ).resolves.toBeUndefined();
+
+ await writeWireLog(kimiHome, 'wd_x', 'session-2', [
+ JSON.stringify({ role: 'meta', type: 'system.version' }),
+ ]);
+ await expect(
+ readKimiCodeSessionUsage('session-2', {
+ env: { KIMI_CODE_HOME: kimiHome },
+ maxAttempts: 1,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('picks the newest wire log when several buckets hold the same session id', async () => {
+ const kimiHome = await makeTempKimiHome();
+ await writeWireLog(kimiHome, 'wd_old', 'session-3', [
+ usageLine({ inputOther: 1, output: 1 }),
+ ]);
+ // Ensure a strictly newer mtime for the second log.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await writeWireLog(kimiHome, 'wd_new', 'session-3', [
+ usageLine({ inputOther: 50, output: 5 }),
+ ]);
+
+ await expect(
+ readKimiCodeSessionUsage('session-3', { env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toMatchObject({ usage: { totalInputTokens: 50, totalOutputTokens: 5 } });
+ });
+
+ it('retries while the wire log is not flushed yet', async () => {
+ const kimiHome = await makeTempKimiHome();
+ const pending = readKimiCodeSessionUsage('session-4', {
+ env: { KIMI_CODE_HOME: kimiHome },
+ maxAttempts: 5,
+ retryDelayMs: 30,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ await writeWireLog(kimiHome, 'wd_late', 'session-4', [
+ usageLine({ inputOther: 7, output: 3 }),
+ ]);
+
+ await expect(pending).resolves.toMatchObject({ usage: { totalTokens: 10 } });
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts b/packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts
new file mode 100644
index 00000000000..b0baf708ac8
--- /dev/null
+++ b/packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts
@@ -0,0 +1,241 @@
+import { readdir, readFile, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { UsageData } from '../types';
+
+type KimiCodeEnv = Record<string, string | undefined>;
+
+/**
+ * Usage shape Kimi Code writes into the session wire log
+ * (`<kimiHome>/sessions/<wd_key>/<session_id>/agents/main/wire.jsonl`).
+ * One record per model request; `inputOther` is the cache-miss portion.
+ */
+export interface KimiCodeWireUsage {
+ inputCacheCreation?: number;
+ inputCacheRead?: number;
+ inputOther?: number;
+ output?: number;
+}
+
+/**
+ * One usage-bearing wire-log line. Current CLI versions tag these with
+ * `type: 'usage.record'` and carry the request's `model` alongside `usage`;
+ * older/untyped lines that just have a top-level `usage` are tolerated.
+ */
+export interface KimiCodeWireUsageRecord {
+ model?: string;
+ usage: KimiCodeWireUsage;
+}
+
+/** Aggregated session usage plus the model the usage was consumed with. */
+export interface KimiCodeSessionUsage {
+ model?: string;
+ usage: UsageData;
+}
+
+export interface ReadKimiCodeSessionUsageOptions {
+ env?: KimiCodeEnv;
+ homeDir?: string;
+ /**
+ * The CLI may still be flushing the wire log right after process exit, so
+ * the read retries while no usage is found. Defaults to 3 attempts.
+ */
+ maxAttempts?: number;
+ /** Delay between attempts. Defaults to 400ms (~1s total budget). */
+ retryDelayMs?: number;
+}
+
+export const getKimiCodeHome = (
+ env: KimiCodeEnv = process.env,
+ homeDir: string = os.homedir(),
+): string => {
+ const configured = env.KIMI_CODE_HOME?.trim();
+ return configured || path.join(homeDir, '.kimi-code');
+};
+
+const toFiniteNumber = (value: unknown): number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+
+/**
+ * Map one wire-log usage record into the provider-agnostic `UsageData` shape.
+ * Cache fields mirror Claude Code's Anthropic mapping (`toUsageData`):
+ * `inputOther` ≈ `input_tokens` (cache miss), `inputCacheRead` ≈
+ * `cache_read_input_tokens`, `inputCacheCreation` ≈ `cache_creation_input_tokens`.
+ */
+export const toKimiCodeUsageData = (
+ raw: KimiCodeWireUsage | null | undefined,
+): UsageData | undefined => {
+ if (!raw) return undefined;
+ const inputCacheMissTokens = toFiniteNumber(raw.inputOther);
+ const inputCachedTokens = toFiniteNumber(raw.inputCacheRead);
+ const inputWriteCacheTokens = toFiniteNumber(raw.inputCacheCreation);
+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens + inputWriteCacheTokens;
+ const totalOutputTokens = toFiniteNumber(raw.output);
+ if (totalInputTokens + totalOutputTokens === 0) return undefined;
+ return {
+ inputCacheMissTokens,
+ inputCachedTokens: inputCachedTokens || undefined,
+ inputWriteCacheTokens: inputWriteCacheTokens || undefined,
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens: totalInputTokens + totalOutputTokens,
+ };
+};
+
+const KIMI_CODE_MODEL_PREFIX = 'kimi-code/';
+
+/**
+ * The wire log names models with the provider namespace (`kimi-code/k3`).
+ * The provider is persisted separately as `kimi-code`, so the stored model
+ * keeps only the `kimi-` family form — a value without the prefix passes
+ * through unchanged.
+ */
+const toKimiModelName = (model: string): string =>
+ model.startsWith(KIMI_CODE_MODEL_PREFIX)
+ ? `kimi-${model.slice(KIMI_CODE_MODEL_PREFIX.length)}`
+ : model;
+
+/**
+ * Sum multiple per-request wire-log usage records into a single grand total,
+ * matching the semantic of Claude Code's `result` event usage. The model is
+ * taken from the LAST usage-bearing record — all records in one session agree.
+ */
+export const aggregateKimiCodeUsage = (
+ records: KimiCodeWireUsageRecord[],
+): KimiCodeSessionUsage | undefined => {
+ let inputCacheMissTokens = 0;
+ let inputCachedTokens = 0;
+ let inputWriteCacheTokens = 0;
+ let totalOutputTokens = 0;
+ let model: string | undefined;
+ let seen = false;
+
+ for (const record of records) {
+ const usage = toKimiCodeUsageData(record.usage);
+ if (!usage) continue;
+ seen = true;
+ if (record.model) model = toKimiModelName(record.model);
+ inputCacheMissTokens += usage.inputCacheMissTokens;
+ inputCachedTokens += usage.inputCachedTokens || 0;
+ inputWriteCacheTokens += usage.inputWriteCacheTokens || 0;
+ totalOutputTokens += usage.totalOutputTokens;
+ }
+
+ if (!seen) return undefined;
+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens + inputWriteCacheTokens;
+ return {
+ model,
+ usage: {
+ inputCacheMissTokens,
+ inputCachedTokens: inputCachedTokens || undefined,
+ inputWriteCacheTokens: inputWriteCacheTokens || undefined,
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens: totalInputTokens + totalOutputTokens,
+ },
+ };
+};
+
+const hasUsageShape = (value: unknown): value is KimiCodeWireUsage =>
+ !!value &&
+ typeof value === 'object' &&
+ ('inputOther' in value || 'inputCacheRead' in value || 'output' in value);
+
+const getNonEmptyString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim() ? value : undefined;
+
+/** Extract every usage record from wire.jsonl content, skipping malformed lines. */
+export const parseKimiCodeWireUsage = (content: string): KimiCodeWireUsageRecord[] => {
+ const records: KimiCodeWireUsageRecord[] = [];
+ for (const line of content.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (!trimmed || !trimmed.includes('"usage"')) continue;
+ try {
+ const record = JSON.parse(trimmed);
+ // Typed lines must be usage records; untyped legacy lines with a
+ // top-level `usage` are tolerated.
+ if (record?.type !== undefined && record.type !== 'usage.record') continue;
+ if (hasUsageShape(record?.usage)) {
+ records.push({ model: getNonEmptyString(record.model), usage: record.usage });
+ }
+ } catch {
+ continue;
+ }
+ }
+ return records;
+};
+
+/**
+ * Locate the session's `agents/main/wire.jsonl` under the Kimi home.
+ * Sessions live at `sessions/<wd_key>/<session_id>/`; the working-directory
+ * key segment is derived from the cwd and not reconstructable here, so match
+ * every session bucket and keep the newest.
+ */
+const findWireLog = async (kimiHome: string, sessionId: string): Promise<string | undefined> => {
+ let buckets;
+ try {
+ buckets = await readdir(path.join(kimiHome, 'sessions'), { withFileTypes: true });
+ } catch {
+ return;
+ }
+
+ const candidates = await Promise.all(
+ buckets
+ .filter((entry) => entry.isDirectory())
+ .map(async (entry) => {
+ const file = path.join(
+ kimiHome,
+ 'sessions',
+ entry.name,
+ sessionId,
+ 'agents',
+ 'main',
+ 'wire.jsonl',
+ );
+ try {
+ const info = await stat(file);
+ return info.isFile() ? { file, mtimeMs: info.mtimeMs } : undefined;
+ } catch {
+ return;
+ }
+ }),
+ );
+
+ const matches = candidates.filter((item): item is { file: string; mtimeMs: number } => !!item);
+ matches.sort((a, b) => b.mtimeMs - a.mtimeMs);
+ return matches[0]?.file;
+};
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Read the aggregated token usage (and the model it was consumed with) for a
+ * finished Kimi Code run from its session wire log. Best-effort by contract:
+ * any failure (no session id, missing home/log, parse errors) resolves to
+ * `undefined` and never throws.
+ */
+export const readKimiCodeSessionUsage = async (
+ sessionId: string | undefined,
+ {
+ env = process.env,
+ homeDir,
+ maxAttempts = 3,
+ retryDelayMs = 400,
+ }: ReadKimiCodeSessionUsageOptions = {},
+): Promise<KimiCodeSessionUsage | undefined> => {
+ if (!sessionId) return;
+
+ const kimiHome = getKimiCodeHome(env, homeDir);
+ const attempts = Math.max(1, maxAttempts);
+
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
+ const wireLog = await findWireLog(kimiHome, sessionId);
+ if (wireLog) {
+ const content = await readFile(wireLog, 'utf8').catch(() => undefined);
+ const result = content ? aggregateKimiCodeUsage(parseKimiCodeWireUsage(content)) : undefined;
+ if (result) return result;
+ }
+ if (attempt < attempts - 1) await sleep(retryDelayMs);
+ }
+};