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.

πŸ› fix(heterogeneous-agents): keep Kimi Code's file-system usage reader out of the browser bundle (#20116)

Arvin Xuf4b84774f613
diff --git a/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts b/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
index 126da316cbf..e0dfc3c6d96 100644
--- a/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/kimiCode.test.ts
@@ -1,41 +1,8 @@
-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 { 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({
@@ -203,9 +170,8 @@ describe('KimiCodeAdapter', () => {
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();
+ describe('buildPostRunUsageEvents', () => {
+ it('emits the post-run usage as a turn_metadata step_complete on the last step', () => {
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.
@@ -217,39 +183,36 @@ describe('KimiCodeAdapter', () => {
});
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 } });
+ const usage = {
+ inputCacheMissTokens: 325,
+ inputCachedTokens: 22_784,
+ inputWriteCacheTokens: 10,
+ totalInputTokens: 23_119,
+ totalOutputTokens: 80,
+ totalTokens: 23_199,
+ };
+ const events = adapter.buildPostRunUsageEvents({ model: 'kimi-k3', usage });
+
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,
- },
- },
+ data: { model: 'kimi-k3', phase: 'turn_metadata', provider: 'kimi-code', usage },
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();
+ it('omits the model from the event when the wire log did not record one', () => {
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 = adapter.buildPostRunUsageEvents({
+ usage: {
+ inputCacheMissTokens: 7,
+ totalInputTokens: 7,
+ totalOutputTokens: 3,
+ totalTokens: 10,
+ },
+ });
- 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({
@@ -257,20 +220,5 @@ describe('KimiCodeAdapter', () => {
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 df805980436..fdc63bccdb6 100644
--- a/packages/heterogeneous-agents/src/adapters/kimiCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/kimiCode.ts
@@ -3,11 +3,10 @@ import type {
AgentEventAdapter,
HeterogeneousAgentEvent,
HeterogeneousToolResultImage,
- PostRunUsageOptions,
+ PostRunUsage,
ToolCallPayload,
ToolResultData,
} from '../types';
-import { readKimiCodeSessionUsage } from '../utils/kimiCodeUsage';
const KIMI_CODE_IDENTIFIER = 'kimi-code';
@@ -104,27 +103,21 @@ export class KimiCodeAdapter implements AgentEventAdapter {
/**
* 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
+ * does, and the spawn pipeline reads it after exit. 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 [];
- }
+ buildPostRunUsageEvents(result: PostRunUsage): HeterogeneousAgentEvent[] {
+ 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,
+ }),
+ ];
}
flush(): HeterogeneousAgentEvent[] {
diff --git a/packages/heterogeneous-agents/src/browserSafeRoot.test.ts b/packages/heterogeneous-agents/src/browserSafeRoot.test.ts
new file mode 100644
index 00000000000..f7652406b2d
--- /dev/null
+++ b/packages/heterogeneous-agents/src/browserSafeRoot.test.ts
@@ -0,0 +1,78 @@
+import { readFileSync } from 'node:fs';
+import { builtinModules } from 'node:module';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const NODE_BUILTINS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
+
+const FROM_SPECIFIER = /\bfrom\s*['"]([^'"]+)['"]/g;
+const SIDE_EFFECT_IMPORT = /^import\s*['"]([^'"]+)['"]/gm;
+
+/**
+ * Value (non type-only) module specifiers of a file's static imports and
+ * re-exports. Dynamic `import()` is skipped on purpose: it loads on call, so
+ * it cannot break the page just by being bundled.
+ */
+const staticValueImports = (source: string): string[] => {
+ const text = `\n${source}`;
+ const specifiers: string[] = [];
+ for (const match of text.matchAll(FROM_SPECIFIER)) {
+ const start = Math.max(
+ text.lastIndexOf('\nimport ', match.index),
+ text.lastIndexOf('\nexport ', match.index),
+ );
+ if (start < 0) continue;
+ // Type-only imports vanish at build time and cannot reach the browser.
+ if (/^\n(?:import|export) type[\s{]/.test(text.slice(start, start + 16))) continue;
+ specifiers.push(match[1]);
+ }
+ for (const match of source.matchAll(SIDE_EFFECT_IMPORT)) specifiers.push(match[1]);
+ return specifiers;
+};
+
+const resolveRelative = (from: string, specifier: string): string | undefined => {
+ const base = path.resolve(path.dirname(from), specifier);
+ for (const candidate of [`${base}.ts`, `${base}.tsx`, path.join(base, 'index.ts')]) {
+ try {
+ readFileSync(candidate);
+ return candidate;
+ } catch {
+ continue;
+ }
+ }
+};
+
+/** Every file reachable from `entry` through value imports, with the Node builtins each one pulls. */
+const collectNodeImports = (entry: string) => {
+ const seen = new Set<string>();
+ const offenders: string[] = [];
+ const queue = [entry];
+ while (queue.length > 0) {
+ const file = queue.pop()!;
+ if (seen.has(file)) continue;
+ seen.add(file);
+ for (const specifier of staticValueImports(readFileSync(file, 'utf8'))) {
+ if (NODE_BUILTINS.has(specifier)) {
+ offenders.push(`${path.relative(__dirname, file)} -> ${specifier}`);
+ } else if (specifier.startsWith('.')) {
+ const resolved = resolveRelative(file, specifier);
+ if (resolved) queue.push(resolved);
+ }
+ }
+ }
+ return offenders;
+};
+
+/**
+ * Regression: the package root is imported by the web app for labels and
+ * helpers, and it re-exports every adapter. An adapter that pulled in a
+ * `node:fs` reader put that module in the SPA's graph, where Vite's
+ * externalized stub throws on first access and the whole app rendered blank.
+ * Node-only code belongs behind a subpath entry (`./spawn`, `./rpc`, ...).
+ */
+describe('package root', () => {
+ it('reaches no Node built-in module', () => {
+ expect(collectNodeImports(path.join(__dirname, 'index.ts'))).toEqual([]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts b/packages/heterogeneous-agents/src/kimiCode/sessionUsage.test.ts
similarity index 56%
rename from packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts
rename to packages/heterogeneous-agents/src/kimiCode/sessionUsage.test.ts
index 4f4605c961b..4c271564ad4 100644
--- a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.test.ts
+++ b/packages/heterogeneous-agents/src/kimiCode/sessionUsage.test.ts
@@ -4,13 +4,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
-import {
- aggregateKimiCodeUsage,
- getKimiCodeHome,
- parseKimiCodeWireUsage,
- readKimiCodeSessionUsage,
- toKimiCodeUsageData,
-} from './kimiCodeUsage';
+import { getKimiCodeHome, readKimiCodeSessionUsage } from './sessionUsage';
const tempDirs: string[] = [];
@@ -37,7 +31,7 @@ const usageLine = (usage: Record<string, number>) =>
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', () => {
+describe('kimiCode sessionUsage', () => {
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
@@ -52,118 +46,6 @@ describe('kimiCodeUsage', () => {
});
});
- 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();
diff --git a/packages/heterogeneous-agents/src/kimiCode/sessionUsage.ts b/packages/heterogeneous-agents/src/kimiCode/sessionUsage.ts
new file mode 100644
index 00000000000..a31a89f9e97
--- /dev/null
+++ b/packages/heterogeneous-agents/src/kimiCode/sessionUsage.ts
@@ -0,0 +1,107 @@
+/**
+ * Reads a finished Kimi Code run's usage from its session wire log on disk.
+ * Node-only β€” keep it out of anything the browser bundle can reach (adapters,
+ * the package root). The spawn pipeline calls it after the CLI exits.
+ */
+import { readdir, readFile, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { KimiCodeSessionUsage } from './usage';
+import { aggregateKimiCodeUsage, parseKimiCodeWireUsage } from './usage';
+
+type KimiCodeEnv = Record<string, string | undefined>;
+
+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');
+};
+
+/**
+ * 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);
+ }
+};
diff --git a/packages/heterogeneous-agents/src/kimiCode/usage.test.ts b/packages/heterogeneous-agents/src/kimiCode/usage.test.ts
new file mode 100644
index 00000000000..507398373ed
--- /dev/null
+++ b/packages/heterogeneous-agents/src/kimiCode/usage.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+
+import { aggregateKimiCodeUsage, parseKimiCodeWireUsage, toKimiCodeUsageData } from './usage';
+
+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('kimiCode usage', () => {
+ 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 } },
+ ]);
+ });
+ });
+});
diff --git a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts b/packages/heterogeneous-agents/src/kimiCode/usage.ts
similarity index 62%
rename from packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts
rename to packages/heterogeneous-agents/src/kimiCode/usage.ts
index b0baf708ac8..72b73c64f73 100644
--- a/packages/heterogeneous-agents/src/utils/kimiCodeUsage.ts
+++ b/packages/heterogeneous-agents/src/kimiCode/usage.ts
@@ -1,11 +1,12 @@
-import { readdir, readFile, stat } from 'node:fs/promises';
-import os from 'node:os';
-import path from 'node:path';
-
+/**
+ * Kimi Code session usage β€” the wire-log format and how it maps to UsageData.
+ *
+ * Pure on purpose: nothing here touches the file system, so the adapter (which
+ * is also bundled for the browser) can import it. Reading the log from disk
+ * lives in `./sessionUsage`, which only the Node spawn pipeline loads.
+ */
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`).
@@ -34,26 +35,6 @@ export interface KimiCodeSessionUsage {
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;
@@ -165,77 +146,3 @@ export const parseKimiCodeWireUsage = (content: string): KimiCodeWireUsageRecord
}
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);
- }
-};
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 4612065d581..7859838d14b 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -197,6 +197,24 @@ describe('AgentStreamPipeline', () => {
await expect(pipeline.collectPostRunUsage()).resolves.toEqual([]);
});
+ it('no-ops for Kimi Code when the run has no session id or no wire log', async () => {
+ const kimiHome = await mkdtemp(path.join(os.tmpdir(), 'lobe-kimi-pipeline-'));
+ tempDirs.push(kimiHome);
+
+ const noSession = new AgentStreamPipeline({ agentType: 'kimi-code', operationId: 'op-1' });
+ await expect(
+ noSession.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } }),
+ ).resolves.toEqual([]);
+
+ const missingLog = new AgentStreamPipeline({ agentType: 'kimi-code', operationId: 'op-2' });
+ await missingLog.push(
+ `${JSON.stringify({ role: 'meta', session_id: 'nope', type: 'session.resume_hint' })}\n`,
+ );
+ await expect(
+ missingLog.collectPostRunUsage({ env: { KIMI_CODE_HOME: kimiHome } }),
+ ).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);
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
index d7b136f814c..1a6a6344fa5 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
@@ -11,6 +11,7 @@ import type {
} from '../types';
import { CodexFileChangeTracker } from './codexFileChangeTracker';
import { JsonlStreamProcessor } from './jsonlProcessor';
+import { readPostRunUsage } from './postRunUsage';
import { toStreamEvent } from './streamEvent';
/**
@@ -60,6 +61,7 @@ export interface AgentStreamPipelineOptions {
export class AgentStreamPipeline {
private readonly processor = new JsonlStreamProcessor();
private readonly adapter: AgentEventAdapter;
+ private readonly agentType: string;
private readonly operationId: string;
private readonly codexTracker?: CodexFileChangeTracker;
private readonly uploadImage?: UploadHeterogeneousImage;
@@ -67,6 +69,7 @@ export class AgentStreamPipeline {
constructor(options: AgentStreamPipelineOptions) {
this.adapter = createAdapter(options.agentType);
+ this.agentType = options.agentType;
this.operationId = options.operationId;
this.uploadImage = options.uploadImage;
this.codexTracker =
@@ -132,14 +135,17 @@ 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 `[]`.
+ * Read usage the CLI only wrote to disk (Kimi Code's session wire log) and
+ * let the adapter turn it into events. Call after {@link flush} and process
+ * exit. Always best-effort: agents without post-run usage, a missing log, or
+ * a failing read yield `[]`.
*/
async collectPostRunUsage(options?: PostRunUsageOptions): Promise<AgentStreamEvent[]> {
+ if (!this.adapter.buildPostRunUsageEvents) return [];
try {
- const events = (await this.adapter.collectPostRunUsage?.(options)) ?? [];
- return this.toStreamEvents(events);
+ const usage = await readPostRunUsage(this.agentType, this.adapter.sessionId, options);
+ if (!usage) return [];
+ return this.toStreamEvents(this.adapter.buildPostRunUsageEvents(usage));
} catch {
return [];
}
diff --git a/packages/heterogeneous-agents/src/spawn/postRunUsage.ts b/packages/heterogeneous-agents/src/spawn/postRunUsage.ts
new file mode 100644
index 00000000000..b766fffe086
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/postRunUsage.ts
@@ -0,0 +1,23 @@
+import { readKimiCodeSessionUsage } from '../kimiCode/sessionUsage';
+import type { PostRunUsage, PostRunUsageOptions } from '../types';
+
+type PostRunUsageReader = (
+ sessionId: string | undefined,
+ options: PostRunUsageOptions,
+) => Promise<PostRunUsage | undefined>;
+
+/**
+ * Agents whose token usage only lands on disk, keyed by agent type. Reading is
+ * the Node side's job β€” the adapter just turns the result into events β€” so a
+ * new entry here never pulls file-system code into the browser bundle.
+ */
+const POST_RUN_USAGE_READERS: Record<string, PostRunUsageReader> = {
+ 'kimi-code': (sessionId, { env }) => readKimiCodeSessionUsage(sessionId, { env }),
+};
+
+/** Best-effort: unknown agent types and missing logs resolve to `undefined`. */
+export const readPostRunUsage = async (
+ agentType: string,
+ sessionId: string | undefined,
+ options: PostRunUsageOptions = {},
+): Promise<PostRunUsage | undefined> => POST_RUN_USAGE_READERS[agentType]?.(sessionId, options);
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 1a79ef79e4d..d6c4a99b95c 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -386,14 +386,20 @@ export interface HeterogeneousTerminalErrorData {
* 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
+ * Options for reading a run's usage after the CLI exits. `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>;
}
+/** Token usage a CLI only records outside stdout, read once the run has exited. */
+export interface PostRunUsage {
+ model?: string;
+ usage: UsageData;
+}
+
export interface AgentEventAdapter {
/**
* Convert a single raw event into zero or more HeterogeneousAgentEvents.
@@ -401,12 +407,13 @@ export interface AgentEventAdapter {
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.
+ * Turn usage read after exit into events, for agents whose token usage never
+ * appears on stdout (e.g. Kimi Code logs it only to the session's
+ * wire.jsonl). Pure: the spawn pipeline reads the usage from disk and hands
+ * it over, because adapters are also bundled for the browser and must not
+ * touch the file system.
*/
- collectPostRunUsage?: (options?: PostRunUsageOptions) => Promise<HeterogeneousAgentEvent[]>;
+ buildPostRunUsageEvents?: (usage: PostRunUsage) => HeterogeneousAgentEvent[];
/**
* Flush any buffered events (call at end of stream).