Implement the following plan: Refactor CalculateTokenUsage to accept []byte and use…
- User
Implement the following plan:
Refactor
CalculateTokenUsageto accept[]byteand use canonical interfaceContext
TokenCalculator.CalculateTokenUsagecurrently takes a file path (sessionRef string) and each agent reads the file internally. Meanwhile, the condensation code in the strategy package has its owncalculateTokenUsagehelper that dispatches byagentTypeto package-level functions, bypassing the interface entirely. This refactoring:- Changes the interface to accept
data []byteso callers that already have bytes (condensation) don't need file I/O - Makes the strategy's helper use the canonical
TokenCalculatorinterface viaagent.GetByAgentType
Changes
1. Interface signature (
cmd/entire/cli/agent/agent.go:169)go// Before CalculateTokenUsage(sessionRef string, fromOffset int) (*TokenUsage, error) // After CalculateTokenUsage(data []byte, fromOffset int) (*TokenUsage, error)2. Claude Code implementation (
cmd/entire/cli/agent/claudecode/lifecycle.go:131-138)Replace file-based delegation with bytes-based parsing:
gofunc (c *ClaudeCodeAgent) CalculateTokenUsage(data []byte, fromOffset int) (*agent.TokenUsage, error) { lines, err := transcript.ParseFromBytes(data) if err != nil { return nil, fmt.Errorf("failed to parse transcript: %w", err) } if fromOffset > 0 && fromOffset < len(lines) { lines = lines[fromOffset:] } return CalculateTokenUsage(lines), nil }Note: This does NOT include subagent tokens. The subagent-aware path is handled separately by
SubagentAwareExtractor.CalculateTotalTokenUsagewhich lifecycle.go already prefers. That interface is not changed.3. Gemini CLI implementation (
cmd/entire/cli/agent/geminicli/lifecycle.go:99-102)Delegate to the existing bytes-based package-level function:
go - Changes the interface to accept
Assistant
I'll start by reading all the files that need to be modified in parallel.
Assistant
Let me check a few more things - the opencode
CalculateTokenUsageFromBytesfunction and the imports in the condensation file.Assistant
Let me check the remaining usages of these imports in the condensation file, and also the
transcriptimport.Assistant
Good. The
transcriptimport is used at line 229 too, and the agent sub-package imports are used elsewhere. Now let me also check the Claude Code lifecycle.go imports to understand what I need to add.Assistant
Now I have all the context I need. Let me also quickly check the
GetByAgentTypefunction exists.Assistant
Now let me implement all the changes. I'll start with the interface and implementations, then the callers and tests.
Assistant
Now update the lifecycle.go caller and the condensation helper.
Assistant
Now check if the
transcriptimport in the condensation file is still needed (it was also used at line 229).Assistant
The
transcriptimport is still used at line 229 and theclaudecodeimport is no longer used. Let me check for remaining usage ofclaudecodein the file more broadly.Assistant
The
claudecodeimport is now unused. I need to remove it.Assistant
Now update the OpenCode tests. I need to update the three test functions that use file paths.
Assistant
Now let me check if
osis still used in the opencode transcript.go after my change (I removed the only method that usedos.IsNotExist).Assistant
Good,
osis still used. Now let me run the format, lint, and tests.Assistant
The test failure is expected —
CalculateTokenUsageFromBytesreturns an empty&agent.TokenUsage{}for nil/empty data, notnil. Let me fix the test to match the actual behavior.Assistant
Right —
CalculateTokenUsageFromBytesreturns&agent.TokenUsage{}for nil/empty data, nevernil. The old method-level code returnednilfor nonexistent files. Now with the bytes-based interface, empty/nil data returns a zero-valued usage. Update the test accordingly.Assistant
All passing. Here's a summary of the changes:
Interface (
agent/agent.go): ChangedCalculateTokenUsage(sessionRef string, ...)toCalculateTokenUsage(data []byte, ...)Implementations:
- Claude Code (
claudecode/lifecycle.go): Parses bytes withtranscript.ParseFromBytes, slices by offset, delegates to package-levelCalculateTokenUsage(lines) - Gemini CLI (
geminicli/lifecycle.go): Delegates directly to package-levelCalculateTokenUsage(data, fromOffset)which already accepts bytes - OpenCode (
opencode/transcript.go): Delegates to existingCalculateTokenUsageFromBytes(data, fromOffset)
Callers:
- lifecycle.go: Passes
transcriptData(already loaded) instead oftranscriptRef - manual_commit_condensation.go: Replaced switch-dispatch with canonical
agent.GetByAgentType→TokenCalculatorinterface. Removed unused import.
- Claude Code (
- User
in manual_commit_condensation.go, if the agent does not implement agent.TokenCalculator we should return nil, not &agent.TokenUsage{}
Assistant
Let me check how callers use the return value to understand if returning
nilthere could cause issues.Assistant
Callers just assign to
data.TokenUsage—nilis fine there. The fix is straightforward:Assistant
All green. The
!okbranch now returnsnilinstead of an empty&agent.TokenUsage{}.- User
how do the new changes affect subagent token usage calculation, especially for claude?
Assistant
Good question. Let me trace the two call sites.
Assistant
Here's how it works across the two call sites:
1.
lifecycle.go(live hook path) — no change in behaviorThe code checks
SubagentAwareExtractorfirst (line 350). SinceClaudeCodeAgentimplements that interface, it always takes the first branch, callingCalculateTotalTokenUsage(transcriptRef, ...)which is still file-path-based and includes subagent tokens. TheTokenCalculatorfallback on line 357 is only reached for agents that don't implementSubagentAwareExtractor(Gemini, OpenCode). So Claude's subagent tokens are unaffected here.2.
manual_commit_condensation.go(condensation path) — already didn't include subagentsThe old switch-dispatch called
claudecode.CalculateTokenUsage(lines)— the same package-level function that computes main-transcript-only tokens. The new code callsClaudeCodeAgent.CalculateTokenUsage(data, offset)which does the same thing (parse bytes → slice →CalculateTokenUsage(lines)). So this path was already main-transcript-only, and remains so.- User
can we refactor away SubagentAwareExtractor.CalculateTotalTokenUsage and instead just rely on using ExtractAllModifiedFiles.ExtractAllModifiedFiles to get the file content and then feeding it to TokenCalculator.CalculateTokenUsage?
Assistant
Let me understand the full picture first.
Assistant
Now let me check what
ExtractAllModifiedFilesreturns and how the lifecycle caller already gets subagent data.Assistant
Now let me look at the lifecycle code that handles subagent transcripts being saved separately.
Assistant
Now let me understand what data is available. The key issue is: can we get the subagent transcript bytes at the point where we compute tokens?
Assistant
Now I have the full picture. Here's the issue with what you're proposing:
ExtractAllModifiedFilesandCalculateTotalTokenUsagedo different things with the subagent transcripts — one extracts file paths, the other sums token counts. They both independently:- Parse the main transcript to find spawned agent IDs (
ExtractSpawnedAgentIDs) - Read each subagent transcript file from disk
- Process each one differently
The idea of "feeding subagent content to
TokenCalculator.CalculateTokenUsage" would work, but we can't piggyback onExtractAllModifiedFilesfor that — it returns file paths, not transcript bytes. What we can do is:- Remove
CalculateTotalTokenUsagefrom theSubagentAwareExtractorinterface - In
lifecycle.go, after we already know the subagent IDs (from the modified-files extraction), read each subagent transcript and callTokenCalculator.CalculateTokenUsageon it
But there's a subtlety — the subagent IDs are discovered by parsing the main transcript.
ExtractAllModifiedFilesdoes this internally but doesn't expose the IDs. We'd need to be accessible.- Parse the main transcript to find spawned agent IDs (
Assistant
Understood, we'll leave
SubagentAwareExtractor.CalculateTotalTokenUsageas-is.I notice the Gemini lifecycle.go was modified externally — the
CalculateTokenUsagemethod was removed. Let me check the current state.Assistant
The
CalculateTokenUsagemethod got removed entirely, which breaks the compile-time interface assertion. Let me verify.Assistant
It compiles — so the method must still exist. Let me search more carefully.
Assistant
Ah — it was moved to
transcript.goinstead of being inlifecycle.go. Let me check what it looks like there.Assistant
The method was moved to
transcript.goby the user. Let me check whether the package-levelCalculateTokenUsagefunction still exists alongside the method.Assistant
The user already merged the package-level function into the method — the old package-level
CalculateTokenUsageis gone. Let me verify the condensation file still compiles since it was callinggeminicli.CalculateTokenUsage(data, startOffset)in the old code, but that call was removed by our refactor.Assistant
The tests reference the old package-level
CalculateTokenUsagewhich the user removed. These tests need to call through the method instead.Assistant
These tests call the now-removed package-level
CalculateTokenUsage. Since the user merged it into the method, I'll update the tests to call through the method. The method returns(*agent.TokenUsage, error)instead of*agent.TokenUsage, so I also need to handle the error return.Assistant
Now fix the
StartIndextest.Assistant
Wait — let me check the actual method behavior on invalid JSON. The method returns
errfromjson.Unmarshal.Assistant
Returns
&agent.TokenUsage{}, erron invalid JSON. The test was previously checking thatAPICallCount == 0which still holds. But now we get an error too. Let me fix the test properly — it should expect an error.Assistant
Now the last test — MissingTokensField.
Assistant
Now let me also check if
CalculateTokenUsageFromFilestill exists and whether it's used anywhere, since the condensation code no longer calls the package-level function.Assistant
The user already removed
CalculateTokenUsageFromFiletoo. Let me verify nothing else references it.Assistant
Good. Now run the full check.
Assistant
The user's change introduced a
wrapchecklint error — thejson.Unmarshalerror needs wrapping.Assistant
Check if
fmtis already imported.Assistant
Good,
fmtis imported. Let me run the checks again.Assistant
All clean — 0 lint issues, all tests passing.