π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): emit a resumed Claude Code run's own cost, not the session total (#20439)
Arvin Xu3918141d424e
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 401671975db..9b738b3a100 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -92,6 +92,7 @@ import {isDevinAcpSessionNotFoundError,isDroidAcpSessionNotFoundError,normalizeImage,+ readClaudeCodeSessionCost,readCodexSessionModel,resolveClaudeCodeTranscriptPath,resolveCliSpawnPlan,@@ -1908,6 +1909,7 @@ export default class HeterogeneousAgentCtr {let traceSession;let cwd: string;let initialCumulativeUsage: UsageData | undefined;+ let initialSessionCostUsd: number | undefined;let resolvedCliSpawnPlan;let spawnEnv: NodeJS.ProcessEnv;try {@@ -1970,6 +1972,15 @@ export default class HeterogeneousAgentCtr {}}+ if (session.agentType === 'claude-code' && session.agentSessionId) {+ initialSessionCostUsd = await readClaudeCodeSessionCost({+ configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,+ cwd,+ home: spawnEnv.HOME,+ sessionId: session.agentSessionId,+ });+ }+traceSession = await this.createCliTraceSession({cliArgs: spawnPlan.args,cwd,@@ -2045,6 +2056,7 @@ export default class HeterogeneousAgentCtr {resolve,session,initialCumulativeUsage,+ initialSessionCostUsd,spawnEnv,startedAt,traceSession,@@ -2103,6 +2115,7 @@ export default class HeterogeneousAgentCtr {const sdkSession = new ClaudeAgentSdkSession({args: session.args,commandPath,+ configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,cwd,env: spawnEnv,onEvents: async (events) => {@@ -3164,6 +3177,7 @@ export default class HeterogeneousAgentCtr {private handleSpawnedAgentProcess({cwd,initialCumulativeUsage,+ initialSessionCostUsd,intervention,params,proc,@@ -3184,6 +3198,7 @@ export default class HeterogeneousAgentCtr {resolve: () => void;session: AgentSession;initialCumulativeUsage?: UsageData | undefined;+ initialSessionCostUsd?: number | undefined;spawnEnv: NodeJS.ProcessEnv;spawnPlan: HeterogeneousAgentBuildPlan;/** ISO time taken before the spawn β see `recordInflightRun`. */@@ -3243,6 +3258,7 @@ export default class HeterogeneousAgentCtr {initialCumulativeUsage,initialModel: session.model,startedAt: startedAt ? Date.parse(startedAt) : undefined,+ initialSessionCostUsd,operationId: params.operationId,uploadImage: this.uploadResultImage,});diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 7aea1fe02fe..525408fa11d 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -251,8 +251,9 @@ const {piRpcSessionRunMock: vi.fn(),}));-const { ensureResumeTranscriptMock } = vi.hoisted(() => ({+const { ensureResumeTranscriptMock, readClaudeCodeSessionCostMock } = vi.hoisted(() => ({ensureResumeTranscriptMock: vi.fn(async () => ({ path: '', written: false })),+ readClaudeCodeSessionCostMock: vi.fn(async (): Promise<number | undefined> => undefined),}));vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {@@ -601,6 +602,7 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {return {...actual,ensureClaudeCodeResumeTranscript: ensureResumeTranscriptMock,+ readClaudeCodeSessionCost: readClaudeCodeSessionCostMock,ClaudeAgentSdkSession: MockClaudeAgentSdkSession,CodexAppServerClient: MockCodexAppServerClient,CodexThreadSession: MockCodexThreadSession,@@ -1758,6 +1760,32 @@ describe('HeterogeneousAgentCtr', () => {expect(cliArgs[cliArgs.indexOf('--model') + 1]).toBe('gpt-5.4');});+ it("emits a resumed run's own cost over the session baseline", async () => {+ const send = vi.fn();+ mockGetAllWindows.mockReturnValue([{ isDestroyed: () => false, webContents: { send } }]);+ readClaudeCodeSessionCostMock.mockResolvedValueOnce(69.67);++ const { options } = await runSendPrompt('carry on', { resumeSessionId: 'sess-live' }, [+ `${JSON.stringify({ session_id: 'sess-live', subtype: 'init', type: 'system' })}\n`,+ `${JSON.stringify({+ is_error: false,+ result: 'done',+ total_cost_usd: 76.43,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ })}\n`,+ ]);++ expect(readClaudeCodeSessionCostMock).toHaveBeenCalledWith(+ expect.objectContaining({ home: options.env.HOME, sessionId: 'sess-live' }),+ );+ const resultUsage = send.mock.calls+ .filter(([channel]) => channel === 'heteroAgentEvent')+ .map(([, payload]) => payload.event)+ .find((event) => event.type === 'step_complete' && event.data?.phase === 'result_usage');+ expect(resultUsage?.data.costUsd).toBeCloseTo(6.76);+ });+it('captures the Claude Code session id from stream-json init events', async () => {const { ctr, sessionId } = await runSendPrompt('hello', {}, [`${JSON.stringify({ session_id: 'sess_cc_123', subtype: 'init', type: 'system' })}\n`,diff --git a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.tsindex c97314d6f01..370e02fd637 100644--- a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts+++ b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts@@ -52,6 +52,19 @@ interface HeteroSessionUsage {const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined);+/**+ * Every hetero step is one model turn: a turn that calls tools is retyped+ * `call_tool` but still made the LLM call, so counting `call_llm` steps alone+ * reported one call for a 284-step run.+ */+const isModelTurn = (step: StepSnapshot): boolean =>+ step.stepType === 'call_llm' ||+ !!step.toolsCalling?.length ||+ !!step.content ||+ !!step.reasoning ||+ step.inputTokens !== undefined ||+ step.outputTokens !== undefined;+/*** Hetero-native execution-trace recorder. Unlike the built-in* {@link OperationTraceRecorder} β which is coupled to the homogeneous runtime's@@ -209,7 +222,7 @@ export class HeteroTraceRecorder {await this.store.removePartial(operationId);return {- llmCalls: steps.filter((s) => s.stepType === 'call_llm').length,+ llmCalls: steps.filter(isModelTurn).length,model: partial.model ?? null,provider: partial.provider ?? null,stepCount: steps.length,diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.tsindex b23c1dfe3ce..2e508eda4c8 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts@@ -156,7 +156,8 @@ describe('HeteroTraceRecorder', () => {});expect(totals).toMatchObject({- llmCalls: 1,+ // both steps are model turns; step 0 just went on to call a tool+ llmCalls: 2,// resolved from stream_start, so heteroFinish can backfill the op rowmodel: 'sonnet',provider: 'anthropic',diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 82239f2c484..5968f864f12 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -3,6 +3,39 @@ import { describe, expect, it } from 'vitest';import { ClaudeCodeAdapter, ClaudeCodeSdkAdapter } from './claudeCode';describe('ClaudeCodeAdapter', () => {+ describe('run cost', () => {+ // CC restores the session's cost tally on `--resume`, so `total_cost_usd`+ // covers every earlier run of the session, not just this one.+ const resultCost = (adapter: ClaudeCodeAdapter, totalCostUsd: number) =>+ adapter+ .adapt({+ is_error: false,+ result: 'done',+ total_cost_usd: totalCostUsd,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ })+ .find((e) => e.type === 'step_complete' && e.data?.phase === 'result_usage')?.data.costUsd;++ it('emits only what a resumed run added to the session total', () => {+ const adapter = new ClaudeCodeAdapter();+ expect(adapter.adapt({ initialSessionCostUsd: 69.67, type: 'session_configured' })).toEqual(+ [],+ );++ expect(resultCost(adapter, 76.43)).toBeCloseTo(6.76);+ });++ it('keeps the reported total without a usable baseline', () => {+ expect(resultCost(new ClaudeCodeAdapter(), 4)).toBeCloseTo(4);++ // a total below the baseline means CC did not restore that tally+ const reset = new ClaudeCodeAdapter();+ reset.adapt({ initialSessionCostUsd: 9, type: 'session_configured' });+ expect(resultCost(reset, 2)).toBeCloseTo(2);+ });+ });+describe('lifecycle', () => {it('emits stream_start on init system event', () => {const adapter = new ClaudeCodeAdapter();diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex 7f466879ba9..19d94fd7b23 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -1026,6 +1026,13 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {private readonly profile: ClaudeCompatibleAdapterProfile;sessionId?: string;private pendingRateLimitInfo?: HeterogeneousRateLimitInfo;+ /**+ * What the resumed session had already spent before this run (from its+ * transcript's last `cost-state`). CC restores that tally on `--resume`, so+ * its `result.total_cost_usd` is session-cumulative; subtracting this makes+ * the emitted `costUsd` this run's own spend.+ */+ private sessionCostBaseline?: number;/** Pending tool_use ids awaiting their tool_result */private pendingToolCalls = new Set<string>();@@ -1290,6 +1297,12 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {case 'result': {return this.handleResult(raw);}+ case 'session_configured': {+ if (typeof raw.initialSessionCostUsd === 'number') {+ this.sessionCostBaseline = raw.initialSessionCostUsd;+ }+ return [];+ }default: {return [];}@@ -2091,6 +2104,19 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {return synthesizeTaskPluginState(this.claudeCodeTasks);}+ /**+ * This run's spend out of CC's session-cumulative `total_cost_usd`. A total+ * below the baseline means CC did not restore the tally (the transcript's+ * cost-state was not the one it resumed from), so the total stands alone.+ */+ private toRunCost(sessionTotal: unknown): number | undefined {+ if (typeof sessionTotal !== 'number') return undefined;+ const baseline = this.sessionCostBaseline;+ return baseline !== undefined && baseline <= sessionTotal+ ? sessionTotal - baseline+ : sessionTotal;+ }+private handleResult(raw: any): HeterogeneousAgentEvent[] {// Resuming a session whose previous run left background tasks behind makes// CC first report them as orphaned (`task_notification` ΓN), then close that@@ -2108,7 +2134,7 @@ export class ClaudeCompatibleStreamAdapter implements AgentEventAdapter {if (usage) {events.push(this.makeEvent('step_complete', {- costUsd: raw.total_cost_usd,+ costUsd: this.toRunCost(raw.total_cost_usd),phase: 'result_usage',usage,}),diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.tsindex 5136d8d9c25..b698926c51b 100644--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts@@ -382,3 +382,28 @@ describe('AgentStreamPipeline', () => {});});});++describe('AgentStreamPipeline β resumed Claude Code cost', () => {+ it("emits the run's own cost when given the session's prior total", async () => {+ const pipeline = new AgentStreamPipeline({+ agentType: 'claude-code',+ initialSessionCostUsd: 69.67,+ operationId: 'op-cost',+ });++ const events = await pipeline.push(+ `${init()}${JSON.stringify({+ is_error: false,+ result: 'done',+ total_cost_usd: 76.43,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ })}\n`,+ );++ const resultUsage = events.find(+ (e) => e.type === 'step_complete' && (e.data as any)?.phase === 'result_usage',+ );+ expect((resultUsage?.data as any).costUsd).toBeCloseTo(6.76);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.tsindex 8443f491865..7ebb9b52594 100644--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts@@ -39,6 +39,8 @@ export interface AgentStreamPipelineOptions {initialCumulativeUsage?: UsageData | undefined;/** Host-known model to emit before the CLI's first stdout payload. */initialModel?: string | undefined;+ /** Claude Code session's cumulative cost before a resumed run starts. */+ initialSessionCostUsd?: number | undefined;/** Operation id to stamp onto every emitted `AgentStreamEvent`. */operationId: string;/** Invocation start, recorded before spawning the CLI. */@@ -86,10 +88,15 @@ export class AgentStreamPipeline {this.codexTracker =options.agentType === 'codex' ? new CodexFileChangeTracker(options.cwd) : undefined;- if (options.initialModel || options.initialCumulativeUsage) {+ if (+ options.initialModel ||+ options.initialCumulativeUsage ||+ options.initialSessionCostUsd !== undefined+ ) {this.queuedEvents.push(...this.configureSession({initialCumulativeUsage: options.initialCumulativeUsage,+ initialSessionCostUsd: options.initialSessionCostUsd,model: options.initialModel,}),);@@ -125,6 +132,7 @@ export class AgentStreamPipeline {configureSession(data: {initialCumulativeUsage?: UsageData | undefined;+ initialSessionCostUsd?: number | undefined;model?: string | undefined;}): AgentStreamEvent[] {return this.toStreamEvents(diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.tsindex 0f68a136249..b56c9c5cb11 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts@@ -1,11 +1,22 @@import { EventEmitter } from 'node:events';+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { resolveClaudeSdkExecutablePath, spawnClaudeCodeCliProcess } from './claudeAgentSdkSession';+import {+ ClaudeAgentSdkSession,+ resolveClaudeSdkExecutablePath,+ spawnClaudeCodeCliProcess,+} from './claudeAgentSdkSession';+import { resolveClaudeCodeTranscriptPath } from './ensureResumeTranscript';const resolveCliSpawnPlanMock = vi.hoisted(() => vi.fn());const spawnMock = vi.hoisted(() => vi.fn());+const sdkQueryMock = vi.hoisted(() => vi.fn());++vi.mock('@anthropic-ai/claude-agent-sdk', () => ({ query: sdkQueryMock }));vi.mock('./cliSpawn', () => ({ resolveCliSpawnPlan: resolveCliSpawnPlanMock }));vi.mock('node:child_process', async (importOriginal) => ({@@ -132,3 +143,73 @@ describe('spawnClaudeCodeCliProcess', () => {expect(onStderr).toHaveBeenCalledWith('boom');});});++describe('ClaudeAgentSdkSession resume cost', () => {+ const tempDirs: string[] = [];++ afterEach(async () => {+ sdkQueryMock.mockReset();+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));+ });++ it('emits a resumed run its own cost, using the profile dir the CLI resumes from', async () => {+ const configDir = await mkdtemp(path.join(os.tmpdir(), 'lobe-sdk-profile-'));+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'lobe-sdk-cwd-'));+ tempDirs.push(configDir, cwd);+ const sessionId = '72f65fa9-0355-45d3-b903-8f41027ed5f2';+ const transcript = (await resolveClaudeCodeTranscriptPath({ configDir, cwd, sessionId }))!;+ await mkdir(path.dirname(transcript), { recursive: true });+ await writeFile(+ transcript,+ `${JSON.stringify({ sessionId, totalCostUSD: 69.67, type: 'cost-state' })}\n`,+ );++ const messages = [+ { model: 'claude-sonnet-4-6', session_id: sessionId, subtype: 'init', type: 'system' },+ {+ is_error: false,+ result: 'done',+ session_id: sessionId,+ subtype: 'success',+ total_cost_usd: 76.43,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ },+ ];+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {+ yield* messages;+ },+ close: vi.fn(),+ }));++ const events: any[] = [];+ const session = new ClaudeAgentSdkSession({+ args: [],+ commandPath: 'claude',+ configDir,+ cwd,+ env: {} as NodeJS.ProcessEnv,+ onEvents: (batch) => {+ events.push(...batch);+ },+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-sdk-resume',+ resumeSessionId: sessionId,+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({+ message: { content: 'continue', role: 'user' },+ type: 'user',+ })}\n`,+ });+ await session.run();++ const resultUsage = events.find(+ (e) => e.type === 'step_complete' && e.data?.phase === 'result_usage',+ );+ expect(resultUsage?.data.costUsd).toBeCloseTo(6.76);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex fc24c64348a..9e7d4ae4e07 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -12,6 +12,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { spawnManaged } from '@lobechat/utils/managedProcess';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';+import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { resolveCliSpawnPlan } from './cliSpawn';const CLAUDE_SDK_DISALLOWED_TOOLS = ['AskUserQuestion', 'Monitor', 'ScheduleWakeup'] as const;@@ -156,6 +157,8 @@ export interface HeterogeneousAgentRuntimeStatus {export interface ClaudeAgentSdkSessionOptions {args: string[];commandPath: string;+ /** Claude profile root the transcript lives under; defaults to `env.CLAUDE_CONFIG_DIR`. */+ configDir?: string;cwd: string;env: NodeJS.ProcessEnv;onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;@@ -246,6 +249,17 @@ export class ClaudeAgentSdkSession {this.armInactivityTimer();try {+ if (this.options.resumeSessionId) {+ this.pipeline.configureSession({+ initialSessionCostUsd: await readClaudeCodeSessionCost({+ configDir: this.options.configDir ?? this.options.env.CLAUDE_CONFIG_DIR,+ cwd: this.options.cwd,+ home: this.options.env.HOME,+ sessionId: this.options.resumeSessionId,+ }),+ });+ }+const { query } = await import('@anthropic-ai/claude-agent-sdk');const userMessage = buildClaudeSdkUserMessageFromStreamJson(this.options.stdinPayload);diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.test.tsnew file mode 100644index 00000000000..d1fc75ed2d3--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.test.ts@@ -0,0 +1,98 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { readClaudeCodeSessionCost, readTranscriptSessionCost } from './claudeCodeSessionCost';+import { resolveClaudeCodeTranscriptPath } from './ensureResumeTranscript';++const SESSION_ID = '72f65fa9-0355-45d3-b903-8f41027ed5f2';++const costState = (totalCostUSD: number) =>+ JSON.stringify({ sessionId: SESSION_ID, totalCostUSD, type: 'cost-state' });+const turn = (text: string) =>+ JSON.stringify({ message: { content: text, role: 'user' }, type: 'user' });++let dir: string;++beforeEach(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'cc-cost-'));+});++afterEach(async () => {+ await rm(dir, { force: true, recursive: true });+});++const writeTranscript = async (lines: string[]) => {+ const file = path.join(dir, 'session.jsonl');+ await writeFile(file, `${lines.join('\n')}\n`);+ return file;+};++describe('readTranscriptSessionCost', () => {+ it('returns the newest cost-state the session ended a run with', async () => {+ const file = await writeTranscript([+ turn('a'),+ costState(4.01),+ turn('b'),+ costState(38.09),+ turn('c'),+ ]);++ expect(await readTranscriptSessionCost(file)).toBe(38.09);+ });++ it('finds a cost-state far behind the tail and across chunk boundaries', async () => {+ // ~400KB of later records pushes the cost-state several 64KB chunks back;+ // odd-sized lines make a chunk boundary land inside the record.+ const filler = Array.from({ length: 3000 }, (_, i) => turn(`${'x'.repeat(100 + (i % 37))}`));+ const file = await writeTranscript([turn('start'), costState(12.5), ...filler]);++ expect(await readTranscriptSessionCost(file)).toBe(12.5);+ });++ it('reaches a cost-state behind a single multi-megabyte record', async () => {+ // An interrupted run can leave one huge tool-result line after the last+ // cost-state; it is stepped over by offset, never accumulated.+ const huge = JSON.stringify({ content: 'y'.repeat(5 * 1024 * 1024), type: 'user' });+ const file = await writeTranscript([costState(7.25), huge]);++ expect(await readTranscriptSessionCost(file)).toBe(7.25);+ });++ it('reads a cost-state on the first line without a trailing newline', async () => {+ const file = path.join(dir, 'single.jsonl');+ await writeFile(file, costState(1.5));++ expect(await readTranscriptSessionCost(file)).toBe(1.5);+ });++ it('returns undefined for a transcript without cost-state or a missing file', async () => {+ // a transcript LobeHub rebuilt after CC's GC carries no cost-state+ const file = await writeTranscript([turn('a'), turn('b')]);++ expect(await readTranscriptSessionCost(file)).toBeUndefined();+ expect(await readTranscriptSessionCost(path.join(dir, 'missing.jsonl'))).toBeUndefined();+ });+});++describe('readClaudeCodeSessionCost', () => {+ it('reads the transcript `--resume` loads for the session', async () => {+ const cwd = path.join(dir, 'repo');+ await mkdir(cwd);+ const configDir = path.join(dir, 'profile');+ const file = (await resolveClaudeCodeTranscriptPath({+ configDir,+ cwd,+ sessionId: SESSION_ID,+ }))!;+ await mkdir(path.dirname(file), { recursive: true });+ await writeFile(file, `${costState(69.67)}\n`);++ expect(await readClaudeCodeSessionCost({ configDir, cwd, sessionId: SESSION_ID })).toBe(69.67);+ expect(+ await readClaudeCodeSessionCost({ configDir, cwd, sessionId: '../../escape' }),+ ).toBeUndefined();+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.tsnew file mode 100644index 00000000000..ba97c42351f--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeSessionCost.ts@@ -0,0 +1,124 @@+import { open } from 'node:fs/promises';++import { resolveClaudeCodeTranscriptPath } from './ensureResumeTranscript';++/** Tail window read per step while scanning backwards for the last cost-state. */+const CHUNK_BYTES = 64 * 1024;++/**+ * A cost-state record is a few hundred bytes. Any longer line (a large tool+ * result, a pasted file) cannot be one, so it is skipped by offset without+ * ever being buffered.+ */+const MAX_COST_STATE_LINE_BYTES = 16 * 1024;++const COST_STATE_MARKER = Buffer.from('"type":"cost-state"');++const NEWLINE = 0x0a;++/**+ * Match the marker on raw bytes so lines that cannot be a cost-state are never+ * decoded: a transcript without one (rebuilt, or written by an older CLI) is+ * walked end to end on every resume.+ */+const parseCostState = (line: Buffer): number | undefined => {+ if (!line.includes(COST_STATE_MARKER)) return undefined;+ try {+ const record = JSON.parse(line.toString('utf8'));+ return record?.type === 'cost-state' && typeof record.totalCostUSD === 'number'+ ? record.totalCostUSD+ : undefined;+ } catch {+ return undefined;+ }+};++/**+ * Read the last `cost-state.totalCostUSD` from a Claude Code transcript.+ *+ * CC appends a `cost-state` record at the end of every run and restores the+ * newest one on `--resume`, which is why a resumed run's `total_cost_usd`+ * includes everything the session spent before. The record sits near the tail,+ * so the file is scanned backwards in fixed chunks for line boundaries instead+ * of loading a transcript that can reach tens of megabytes. Only short lines+ * carrying the marker are decoded; memory stays bounded by one chunk plus one+ * candidate line however long the records behind the tail are.+ */+export const readTranscriptSessionCost = async (filePath: string): Promise<number | undefined> => {+ let handle;+ try {+ handle = await open(filePath, 'r');+ } catch {+ return undefined;+ }++ try {+ const fileHandle = handle;+ const chunk = Buffer.alloc(CHUNK_BYTES);+ let chunkStart = 0;+ let chunkEnd = 0;++ /** Decode `[start, end)` if it is short enough to be a cost-state record. */+ const readLine = async (start: number, end: number): Promise<number | undefined> => {+ const length = end - start;+ if (length <= 0 || length > MAX_COST_STATE_LINE_BYTES) return undefined;+ if (start >= chunkStart && end <= chunkEnd) {+ return parseCostState(chunk.subarray(start - chunkStart, end - chunkStart));+ }+ // The line straddles a chunk boundary: read just its bytes.+ const line = Buffer.alloc(length);+ await fileHandle.read(line, 0, length, start);+ return parseCostState(line);+ };++ const { size } = await fileHandle.stat();+ // Exclusive end of the line currently being walked back over.+ let lineEnd = size;+ let position = size;++ while (position > 0) {+ const length = Math.min(CHUNK_BYTES, position);+ position -= length;+ await fileHandle.read(chunk, 0, length, position);+ chunkStart = position;+ chunkEnd = position + length;++ for (let i = length - 1; i >= 0; i -= 1) {+ if (chunk[i] !== NEWLINE) continue;+ const lineStart = position + i + 1;+ const cost = await readLine(lineStart, lineEnd);+ if (cost !== undefined) return cost;+ lineEnd = position + i;+ }+ }++ return await readLine(0, lineEnd);+ } catch {+ return undefined;+ } finally {+ await handle.close();+ }+};++/**+ * The cumulative cost a Claude Code session had reached before this run, read+ * from the transcript `--resume` will load. Undefined when the transcript or+ * its cost-state is missing (a rebuilt transcript has none β CC then restores+ * nothing and its total is already per-run). Never throws: a missing baseline+ * only means the reported total is kept as is.+ */+export const readClaudeCodeSessionCost = async (params: {+ /** Claude profile root selected through CLAUDE_CONFIG_DIR. */+ configDir?: string;+ cwd: string;+ /** The child's effective HOME, where `~/.claude` resolves without a config dir. */+ home?: string;+ sessionId: string;+}): Promise<number | undefined> => {+ try {+ const filePath = await resolveClaudeCodeTranscriptPath(params);+ return filePath ? await readTranscriptSessionCost(filePath) : undefined;+ } catch {+ return undefined;+ }+};diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex afacf7348e7..0582fc9dc05 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -150,6 +150,7 @@ export {sanitizeClaudeCodeDirectArgs,sanitizeClaudeCodeDirectEnv,} from './claudeCodeDirectEnv';+export { readClaudeCodeSessionCost } from './claudeCodeSessionCost';export {ensureClaudeCodeResumeTranscript,type EnsureResumeTranscriptReason,diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.tsindex 1f816cced20..bff4ec42693 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.test.ts@@ -1006,6 +1006,117 @@ describe('spawnAgent', () => {expect(spawnCalls[0].args).toContain('--include-partial-messages');});+ it("charges a resumed claude run against the transcript under the child's HOME", async () => {+ // The child gets an overridden HOME, so the transcript `--resume` loads+ // (and its last cost-state) lives there, not under the parent's homedir.+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobe-cc-home-'));+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'lobe-cc-cwd-'));+ tempDirs.push(home, cwd);+ const sessionId = '72f65fa9-0355-45d3-b903-8f41027ed5f2';+ const { resolveClaudeCodeTranscriptPath } = await import('./ensureResumeTranscript');+ const transcript = (await resolveClaudeCodeTranscriptPath({ cwd, home, sessionId }))!;+ await mkdir(path.dirname(transcript), { recursive: true });+ await writeFile(+ transcript,+ `${JSON.stringify({ sessionId, totalCostUSD: 69.67, type: 'cost-state' })}\n`,+ );++ const result = `${JSON.stringify({+ is_error: false,+ result: 'done',+ total_cost_usd: 76.43,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ })}\n`;+ const fake = createFakeProc({ stdoutChunks: [ccInit, result] });+ nextFakeProc = fake.proc;+ const configDir = process.env.CLAUDE_CONFIG_DIR;+ delete process.env.CLAUDE_CONFIG_DIR;++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'claude-code',+ cwd,+ env: { HOME: home },+ operationId: 'op-home',+ prompt: 'continue',+ resumeSessionId: sessionId,+ });+ fake.start();++ const events: any[] = [];+ for await (const event of handle.events) events.push(event);+ await handle.exit;++ const resultUsage = events.find(+ (e) => e.type === 'step_complete' && e.data?.phase === 'result_usage',+ );+ expect(resultUsage?.data.costUsd).toBeCloseTo(6.76);+ } finally {+ if (configDir !== undefined) process.env.CLAUDE_CONFIG_DIR = configDir;+ }+ });++ it('reads the cost baseline from the env the child actually receives', async () => {+ // options.env unsets CLAUDE_CONFIG_DIR for the child, so the CLI resumes from+ // HOME/.claude; the parent's config dir holds an unrelated transcript.+ const home = await mkdtemp(path.join(os.tmpdir(), 'lobe-cc-home-'));+ const parentConfigDir = await mkdtemp(path.join(os.tmpdir(), 'lobe-cc-parent-'));+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'lobe-cc-cwd-'));+ tempDirs.push(home, parentConfigDir, cwd);+ const sessionId = '72f65fa9-0355-45d3-b903-8f41027ed5f2';+ const { resolveClaudeCodeTranscriptPath } = await import('./ensureResumeTranscript');+ const writeCostState = async (params: { configDir?: string; home?: string }, cost: number) => {+ const transcript = (await resolveClaudeCodeTranscriptPath({ ...params, cwd, sessionId }))!;+ await mkdir(path.dirname(transcript), { recursive: true });+ await writeFile(+ transcript,+ `${JSON.stringify({ sessionId, totalCostUSD: cost, type: 'cost-state' })}\n`,+ );+ };+ await writeCostState({ home }, 69.67);+ await writeCostState({ configDir: parentConfigDir }, 50);++ const result = `${JSON.stringify({+ is_error: false,+ result: 'done',+ total_cost_usd: 76.43,+ type: 'result',+ usage: { input_tokens: 10, output_tokens: 5 },+ })}\n`;+ const fake = createFakeProc({ stdoutChunks: [ccInit, result] });+ nextFakeProc = fake.proc;+ const configDir = process.env.CLAUDE_CONFIG_DIR;+ process.env.CLAUDE_CONFIG_DIR = parentConfigDir;++ try {+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'claude-code',+ cwd,+ // JS callers can spread an unset key; the child then has no config dir.+ env: { CLAUDE_CONFIG_DIR: undefined as unknown as string, HOME: home },+ operationId: 'op-child-env',+ prompt: 'continue',+ resumeSessionId: sessionId,+ });+ fake.start();++ const events: any[] = [];+ for await (const event of handle.events) events.push(event);+ await handle.exit;++ const resultUsage = events.find(+ (e) => e.type === 'step_complete' && e.data?.phase === 'result_usage',+ );+ expect(resultUsage?.data.costUsd).toBeCloseTo(6.76);+ } finally {+ if (configDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;+ else process.env.CLAUDE_CONFIG_DIR = configDir;+ }+ });+it('appends --resume <id> for claude when resuming a session', async () => {nextFakeProc = createFakeProc().proc;const { spawnAgent } = await import('./spawnAgent');diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 68bba83cd11..fb4a1de7baa 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -9,6 +9,7 @@ import { spawnManaged } from '@lobechat/utils/managedProcess';import type { AskUserBridge } from '../askUser/AskUserBridge';import { resolveHeterogeneousAgentCommand } from '../config';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';+import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { isPathLikeCommand, resolveCliSpawnPlan } from './cliSpawn';import { readCodexSessionModel, resolveCodexInitialModel } from './codexModel';import { buildCursorAcpPrompt, CursorAcpSession } from './cursorAcpSession';@@ -709,7 +710,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentinputArgs: inputPlan.args,resumeSessionId: options.resumeSessionId,});- const childEnv = {+ const childEnv: NodeJS.ProcessEnv = {...process.env,...(options.agentType === 'codebuddy' ? { CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS: '1' } : {}),...options.env,@@ -723,6 +724,17 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent? await readCodexSessionModel(options.resumeSessionId, { env: childEnv }): undefined;const initialCumulativeUsage = resumedCodexSession?.cumulativeUsage;+ const initialSessionCostUsd =+ options.agentType === 'claude-code' && options.resumeSessionId+ ? await readClaudeCodeSessionCost({+ configDir: childEnv.CLAUDE_CONFIG_DIR,+ cwd,+ // Resolve from the child's environment: an overridden HOME moves the+ // transcript the CLI resumes from.+ home: childEnv.HOME,+ sessionId: options.resumeSessionId,+ })+ : undefined;const cliSpawnPlan = await resolveCliSpawnPlan(command, args);const detached = platform() !== 'win32' && (options.detached ?? true);@@ -740,6 +752,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgentenv: childEnv,initialCumulativeUsage,initialModel,+ initialSessionCostUsd,operationId: options.operationId,startedAt,uploadImage: options.uploadImage,diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex d6c4a99b95c..70bb7da3086 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -327,7 +327,11 @@ export interface UsageData {* - `result_usage`: authoritative grand total at the end of a session*/export interface StepCompleteData {- /** Total session cost in USD (only on `result_usage`, if the CLI reports it). */+ /**+ * This run's cost in USD (only on `result_usage`, if the CLI reports it).+ * Adapters whose CLI reports a session-cumulative figure across resume+ * (Claude Code) convert it to the run's own spend before emitting.+ */costUsd?: number;/** Model id for this turn (only meaningful on `turn_metadata`). */model?: string;