Skip to content

feat(agenthook): capture token usage from Cursor and Antigravity hooks - #363

Merged
AnnatarHe merged 4 commits into
mainfrom
feat/agenthook-tokens
Nov 28, 2026
Merged

AnnatarHe merged 4 commits into
mainfrom
feat/agenthook-tokens

Conversation

@AnnatarHe

@AnnatarHe AnnatarHe commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Captures per-turn token usage from both Cursor and Google Antigravity (agy) hooks so the ShellTime backend can compute estimated USD cost and project turns into the unified Coding Agent pipeline.

Changes

  • Event schema (agenthook/event.go, agenthook/normalize.go): Added optional *int fields input_tokens (uncached), output_tokens, cache_read_tokens, cache_creation_tokens, and reasoning_tokens with strict integer parsing (nonNegInt).
  • Cursor (agenthook/cursor.go): Extracts token counts on stop only (never afterAgentResponse, avoiding double-counting per generation_id). Subtracts cache_read_tokens + cache_write_tokens from Cursor's inclusive input_tokens (clamped at 0) and preserves model_id fallback + metadata.
  • Antigravity (agenthook/antigravity.go, agenthook/antigravity_transcript.go): On PostInvocation, reads a bounded 4 MiB tail of transcriptPath (.jsonl), matches step_index == initialNumSteps on completed MODEL / PLANNER_RESPONSE steps (status == "DONE"), and extracts uncached input, output, cache read/creation, reasoning/thinking tokens, and model_name. Fails open without reusing older steps.
  • Tests (agenthook/tokens_test.go): Unit tests for Cursor stop extraction/clamping/deduplication and Antigravity transcript.jsonl step matching.

Test Plan

  • go build -o shelltime ./cmd/cli/main.go and go build -o shelltime-daemon ./cmd/daemon/main.go — passed
  • go vet ./... and gofmt -l agenthook/ — passed
  • go test -timeout 3m ./... — passed

Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-28T04:08:49.123170Z 1944cb6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Comment thread agenthook/antigravity_transcript.go Outdated
if _, hasOut := row.nonNegInt("output_tokens"); !hasOut {
continue
}
matched = row

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: Only one transcript row is ever used for a PostInvocation event, so the usage is probably undercounted. A single invocation usually spans several model steps (model, tool, model, ...), and only the row whose step_index equals initialNumSteps is matched; every later MODEL step in the same invocation is ignored. In a multi-tool-call invocation, the tokens of every model call after the first are never recorded. Fix: sum the completed MODEL rows with step_index >= initialNumSteps (up to the next invocation's start or the end of the file). If the hook payload gives a final step count, bound the sum by it. If one-row-per-invocation really is the intended semantics, say so in the doc comment.

Comment thread agenthook/antigravity_transcript.go Outdated
return nil, false
}

offset := info.Size() - maxAntigravityTranscriptBytes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: Every PostInvocation hook reads up to 4 MiB of the transcript. It then splits the data on newlines and runs json.Unmarshal into a map on every line, all synchronously inside the agent's hook process. CLAUDE.md treats hook-ingest latency as a hard constraint (the daemon ack has a 50 ms budget). Long conversations pay this on every invocation, and the work scales with transcript size. Fix: scan backwards from the end of the file in small chunks and stop at the first matching row. At minimum, do a cheap bytes.Contains(line, "\"step_index\":N") pre-filter before unmarshalling, and lower the window.

Comment thread agenthook/antigravity_transcript.go Outdated
// counts onto ev. Works across Antigravity App, IDE, and agy CLI. Missing, unreadable, or
// unmatched transcripts are silently ignored so hook recording never fails.
func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload) {
stepIndex, ok := p.nonNegInt("initialNumSteps")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): transcriptPath comes from the hook payload, and the code opens any path ending in .jsonl (including ~ expansion) with no check that it is a regular file or that it lives under the agent's transcript directory. Stat().IsDir() is checked, but a FIFO or device named *.jsonl would block ReadAll and hang the agent's hook. The row's model_name string also flows into ev.Model and is uploaded. Fix: require info.Mode().IsRegular(), and consider restricting the path to the ~/.gemini/antigravity* transcript roots, which antigravitySurface already knows.

Comment thread agenthook/cursor.go
reasoning, hasReasoning := p.nonNegInt("reasoning_tokens")

if hasInput {
uncached := rawInput - cacheRead - cacheWrite

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): The cache subtraction is applied inconsistently. If input_tokens is present but cache_read_tokens and cache_write_tokens are absent (for example, a Cursor build that names them differently), uncached is the full inclusive input and nothing marks it as unsplit, so the cached tokens are billed or reported as fresh input. When the cache exceeds the input, the clamp to 0 still reports the unclamped CacheReadTokens (the test asserts input 0 with cache 120), so the fields no longer add up. Fix: only report the split when at least one cache field is present, or add a metadata flag when the clamp or the missing cache fields were hit.

Comment thread agenthook/normalize.go Outdated
}
return v, true
}
// Reject booleans, objects, arrays, null and decimals

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): nonNegInt accepts only plain digit strings. A counter serialised as 1234.0 or 1.2e3 is rejected, so a whole event's usage is silently dropped. Cursor and Antigravity payloads come from JS or Go encoders that may emit floats, and payload.number just above already tolerates them. For the Antigravity transcript path the hasInput/hasOutput gate means one such field discards all token data for the step. Fix: parse numbers with json.Number or float64, and accept them when f == math.Trunc(f), f >= 0 and f < 1<<53.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2ab301767f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agenthook/antigravity.go
ev.Response = p.str("content")
p.setNumberMetadata(ev, "invocationNum", "invocation_num")
p.setNumberMetadata(ev, "initialNumSteps", "initial_num_steps")
applyAntigravityTranscriptUsage(ev, transcript, p)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the new hook token-collection behavior

This changes both agent integrations to upload token counts and additionally makes Antigravity hooks read a local transcript, but the commit does not update any user-facing documentation. The existing hook sections in README.md and docs/CONFIG.md do not explain token collection or that Antigravity usage requires a readable .jsonl transcript with a matching step, leaving users unable to distinguish unsupported or unavailable usage from successful tracking. Update the hook documentation in this commit, as required by the Documentation Maintenance guideline in AGENTS.md.

AGENTS.md reference: AGENTS.md:L55-L55

Useful? React with 👍 / 👎.

@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.82609% with 28 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
agenthook/antigravity_transcript.go 86.39% 23 Missing ⚠️
agenthook/normalize.go 87.87% 4 Missing ⚠️
agenthook/cursor.go 96.15% 1 Missing ⚠️
Flag Coverage Δ
unittests 88.02% <87.82%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
agenthook/antigravity.go 100.00% <100.00%> (ø)
agenthook/event.go 100.00% <ø> (ø)
agenthook/cursor.go 96.59% <96.15%> (-0.19%) ⬇️
agenthook/normalize.go 91.05% <87.87%> (-0.50%) ⬇️
agenthook/antigravity_transcript.go 86.39% <86.39%> (ø)

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

⏱️ shelltime track performance

✅ No significant change in shelltime track latency

Comparing main @ 48a978b → #363 @ 1944cb6. Each scenario execs the binary the way the shell hooks do; values are the median of 10 interleaved rounds. Lower is better.

Scenario base head Δ p
Startup/floor 308 µs ±2% 306 µs ±2% ~ 0.631 A/A
Startup/version 2.97 ms ±0% 2.96 ms ±1% ~ 0.481 ✅
Track/daemon/pre 3.14 ms ±2% 3.08 ms ±2% ~ 0.063 ✅
Track/daemon/post 3.13 ms ±1% 3.12 ms ±1% ~ 0.529 ✅
Track/direct/pre 3.14 ms ±1% 3.10 ms ±2% ~ 0.190 ✅
Track/direct/post 4.32 ms ±1% 4.30 ms ±1% ~ 0.089 ✅
Track/direct/post-sync 6.11 ms ±1% 6.14 ms ±1% ~ 0.353 ✅

Binary size: 19.5 MiB → 19.5 MiB (+0.1%).

CPU, tail latency and memory

Per exec, base → head (Δ when significant).

Scenario p95 wall user CPU sys CPU peak RSS
Startup/floor 370 µs → 368 µs 226 µs → 225 µs 46 µs → 48 µs 9.4 MiB → 9.3 MiB
Startup/version 3.18 ms → 3.16 ms 1.41 ms → 1.41 ms 1.92 ms → 1.90 ms 15.7 MiB → 15.8 MiB (+0.50%)
Track/daemon/pre 3.34 ms → 3.32 ms 1.51 ms → 1.59 ms 1.99 ms → 1.85 ms 16.3 MiB → 16.4 MiB (+0.86%)
Track/daemon/post 3.36 ms → 3.35 ms 1.57 ms → 1.48 ms 1.96 ms → 2.02 ms 16.2 MiB → 16.4 MiB (+0.87%)
Track/direct/pre 3.34 ms → 3.33 ms 1.50 ms → 1.47 ms 1.99 ms → 1.97 ms 16.2 MiB → 16.4 MiB (+1.64%)
Track/direct/post 4.58 ms → 4.52 ms (-1.27%) 2.56 ms → 2.53 ms 2.19 ms → 2.21 ms 16.8 MiB → 17.0 MiB (+0.80%)
Track/direct/post-sync 6.55 ms → 6.59 ms 4.39 ms → 4.38 ms 3.55 ms → 3.56 ms 19.4 MiB → 19.8 MiB (+1.74%)
benchstat
goos: linux
goarch: amd64
pkg: github.com/malamtime/cli/perf
cpu: Intel(R) Xeon(R) 6975P-C
                         │    base     │                head                │
                         │   sec/op    │   sec/op     vs base               │
Startup/floor-4            308.3µ ± 2%   306.2µ ± 2%       ~ (p=0.631 n=10)
Startup/version-4          2.966m ± 0%   2.959m ± 1%       ~ (p=0.481 n=10)
Track/daemon/pre-4         3.137m ± 2%   3.081m ± 2%       ~ (p=0.063 n=10)
Track/daemon/post-4        3.135m ± 1%   3.123m ± 1%       ~ (p=0.529 n=10)
Track/direct/pre-4         3.142m ± 1%   3.103m ± 2%       ~ (p=0.190 n=10)
Track/direct/post-4        4.315m ± 1%   4.303m ± 1%       ~ (p=0.089 n=10)
Track/direct/post-sync-4   6.112m ± 1%   6.136m ± 1%       ~ (p=0.353 n=10)
geomean                    2.572m        2.557m       -0.61%

                         │    base     │                head                │
                         │ p50-sec/op  │ p50-sec/op   vs base               │
Startup/floor-4            297.6µ ± 2%   295.3µ ± 2%       ~ (p=0.631 n=10)
Startup/version-4          2.943m ± 1%   2.945m ± 2%       ~ (p=0.853 n=10)
Track/daemon/pre-4         3.125m ± 2%   3.052m ± 2%       ~ (p=0.052 n=10)
Track/daemon/post-4        3.118m ± 1%   3.101m ± 1%       ~ (p=0.481 n=10)
Track/direct/pre-4         3.127m ± 2%   3.085m ± 2%       ~ (p=0.190 n=10)
Track/direct/post-4        4.292m ± 1%   4.281m ± 1%       ~ (p=0.315 n=10)
Track/direct/post-sync-4   6.124m ± 1%   6.140m ± 1%       ~ (p=0.247 n=10)
geomean                    2.550m        2.532m       -0.71%

                         │    base     │                head                │
                         │ p95-sec/op  │ p95-sec/op   vs base               │
Startup/floor-4            370.0µ ± 4%   368.0µ ± 6%       ~ (p=0.796 n=10)
Startup/version-4          3.184m ± 1%   3.163m ± 2%       ~ (p=0.393 n=10)
Track/daemon/pre-4         3.345m ± 3%   3.325m ± 1%       ~ (p=0.353 n=10)
Track/daemon/post-4        3.362m ± 1%   3.355m ± 2%       ~ (p=0.739 n=10)
Track/direct/pre-4         3.342m ± 1%   3.326m ± 2%       ~ (p=0.971 n=10)
Track/direct/post-4        4.581m ± 1%   4.523m ± 2%  -1.27% (p=0.011 n=10)
Track/direct/post-sync-4   6.547m ± 2%   6.591m ± 2%       ~ (p=0.631 n=10)
geomean                    2.794m        2.781m       -0.45%

                         │     base     │                head                 │
                         │  peak-rss-B  │  peak-rss-B   vs base               │
Startup/floor-4            9.371Mi ± 2%   9.328Mi ± 1%       ~ (p=0.516 n=10)
Startup/version-4          15.74Mi ± 0%   15.81Mi ± 0%  +0.50% (p=0.000 n=10)
Track/daemon/pre-4         16.31Mi ± 0%   16.45Mi ± 0%  +0.86% (p=0.000 n=10)
Track/daemon/post-4        16.23Mi ± 0%   16.37Mi ± 0%  +0.87% (p=0.000 n=10)
Track/direct/pre-4         16.18Mi ± 0%   16.45Mi ± 0%  +1.64% (p=0.000 n=10)
Track/direct/post-4        16.84Mi ± 0%   16.98Mi ± 0%  +0.80% (p=0.000 n=10)
Track/direct/post-sync-4   19.43Mi ± 0%   19.77Mi ± 0%  +1.74% (p=0.000 n=10)
geomean                    15.41Mi        15.54Mi       +0.85%

                         │     base     │                head                 │
                         │  sys-sec/op  │  sys-sec/op   vs base               │
Startup/floor-4            45.87µ ± 26%   48.50µ ± 22%       ~ (p=0.739 n=10)
Startup/version-4          1.920m ±  8%   1.897m ±  6%       ~ (p=0.529 n=10)
Track/daemon/pre-4         1.987m ±  6%   1.853m ±  8%       ~ (p=0.063 n=10)
Track/daemon/post-4        1.960m ±  5%   2.019m ±  8%       ~ (p=0.631 n=10)
Track/direct/pre-4         1.988m ±  7%   1.969m ± 11%       ~ (p=0.853 n=10)
Track/direct/post-4        2.188m ±  8%   2.206m ±  4%       ~ (p=0.971 n=10)
Track/direct/post-sync-4   3.547m ±  4%   3.562m ±  6%       ~ (p=0.631 n=10)
geomean                    1.269m         1.270m        +0.09%

                         │     base     │                head                 │
                         │ user-sec/op  │ user-sec/op   vs base               │
Startup/floor-4            226.2µ ±  4%   225.2µ ±  6%       ~ (p=1.000 n=10)
Startup/version-4          1.406m ± 10%   1.407m ±  7%       ~ (p=0.579 n=10)
Track/daemon/pre-4         1.508m ±  6%   1.593m ± 10%       ~ (p=0.247 n=10)
Track/daemon/post-4        1.566m ±  6%   1.482m ±  8%       ~ (p=0.315 n=10)
Track/direct/pre-4         1.498m ± 11%   1.474m ± 13%       ~ (p=0.631 n=10)
Track/direct/post-4        2.563m ±  6%   2.525m ±  2%       ~ (p=0.684 n=10)
Track/direct/post-sync-4   4.387m ±  3%   4.382m ±  6%       ~ (p=0.912 n=10)
geomean                    1.437m         1.430m        -0.52%

Δ compares medians; ~ means no significant difference (Mann-Whitney U, p ≥ 0.05). A scenario is flagged when it is more than 10% and more than 250µs slower with p < 0.05. Startup/floor runs true, not shelltime: it is an A/A check of runner noise. Runner: linux/amd64, Intel(R) Xeon(R) 6975P-C. go1.27.1, 10 rounds × 100 execs per scenario and binary.

if !ok {
return false
}
if idx < startStep {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: the backward scan stops at the first row whose step_index is below initialNumSteps, so an out-of-order row ends it early. A late status update to an earlier step, such as a tool step or a USER step finishing after later model steps were appended, is enough. Model steps further up are then never read, and the invocation's tokens are undercounted with no signal.

Fix: don't stop on one lower row. Either require several consecutive lower rows, or keep scanning to the bound and filter by index. Alternatively stop only on a row that is itself a completed model step below startStep.

// the latest completed model row for each step_index >= startStep (and <= maxStep when maxStep >= 0),
// and stops as soon as a row with step_index < startStep is reached.
func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigravityStepUsage, bool) {
f, err := os.Open(path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: os.Open on a path named *.jsonl that is a FIFO (or another blocking special file) blocks until a writer appears, and the IsRegular check only runs after the open. transcriptPath comes from the hook payload, so a stray FIFO hangs hook-ingest. That breaks the 50 ms budget and the promise that the hook always replies and exits 0.

Fix: os.Lstat/os.Stat the path first and reject non-regular files before opening. Or open with O_NONBLOCK and then check the mode.

Comment thread agenthook/antigravity_transcript.go Outdated
if len(line) == 0 || !bytes.Contains(line, antigravityStepIndexNeedle) {
return false
}
// Fast check for non-usage lines that still carry step_index: we only need to stop

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: every line in the invocation that contains "step_index" is fully json.Unmarshalled into a map, including tool-result rows with large blobs. The comment above says the unmarshal is skipped for non-usage lines, but the code doesn't do that. A long invocation can scan up to 4 MiB (maxAntigravityTranscriptBytes) with a full decode of each line, which can exceed the 50 ms hook budget CLAUDE.md states for hook-ingest.

Fix: cheaply extract step_index and check the input_tokens needle before decoding, so only model rows with usage are unmarshalled. Lower the scan cap, or run the scan under a deadline, and correct the stale comment.

}

stop := false
for pos > 0 && scanned < maxAntigravityTranscriptBytes && !stop {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: when the invocation's first step lies further back than 4 MiB, the loop ends at maxAntigravityTranscriptBytes. It then sums only the tail and reports it as the whole invocation, so a heavy invocation (large tool outputs) is silently undercounted. The same happens if the transcript hasn't flushed the last steps when PostInvocation fires, which the "not yet flushed" test accepts. Cost is understated with no marker and the event is not flagged as partial.

Fix: when the cap is hit without reaching a row below startStep, mark the usage as partial (for example a metadata flag) or skip it. Don't present a truncated sum as exact.

Comment thread agenthook/antigravity_transcript.go Outdated
return
}
maxStep := -1
if endStep, ok := firstNonNegInt(p, "finalNumSteps", "numSteps"); ok && endStep > startStep {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: the upper bound relies on finalNumSteps/numSteps payload fields that nothing here or in the docs shows Antigravity sending. Without them maxStep is -1, so every step at or after initialNumSteps is summed. If a PostInvocation for a nested invocation (a subagent or child) fires while an outer invocation's range overlaps it, or two PostInvocation events share a start, the same model steps are counted on both events. Tokens and cost are double-counted on the server.

Fix: confirm the real payload fields. Otherwise track the highest step already attributed per conversation and start there, instead of trusting initialNumSteps alone.

if usage.hasCacheWrite {
ev.CacheCreationTokens = intPtr(usage.cacheCreate)
}
if usage.hasReasoning {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): the comment says Antigravity's output_tokens already includes thinking, but the code also sends ReasoningTokens (from thinking_tokens/reasoning_tokens) as a separate field. If the server prices output + reasoning (as for the Codex backfill, which sends reasoning separately), Antigravity thinking tokens are billed twice.

Fix: don't send reasoning when output already includes it, or subtract it from OutputTokens, and say which convention Event uses in its field comment.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d9dac60125

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +205 to +207
if len(steps) == 0 {
return antigravityStepUsage{}, false
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject incomplete invocation totals when the scan limit is reached

When an invocation's transcript spans more than 4 MiB, the backward scan can hit its byte limit before reaching initialNumSteps, but this code still returns the collected suffix as successful invocation usage. For example, a completed model step with 1,000 input tokens, followed by a tool row larger than 4 MiB and another completed model step with 2,000 input tokens, reports only 2,000 instead of 3,000. This silently understates the token usage used for estimated cost. Track whether the invocation boundary was reached and omit usage when the scan is incomplete, or explicitly represent the counts as partial rather than publishing them as a complete total.

Useful? React with 👍 / 👎.

}
u := antigravityStepUsage{
input: input,
output: output,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: the backward scan stops at the first completed model row below startStep. The antigravityLowerStepThreshold comment says the scan should survive an out-of-order late update, but this branch defeats that.

Trigger: a late DONE rewrite of an earlier step (for example startStep-1) is appended after the current invocation's rows. The scan reaches it, returns stop=true, and never reads the current invocation's earlier rows. Their tokens are silently dropped, or the whole result is empty.

Fix: drop this immediate-stop branch and rely on the consecutive-below threshold. Or stop only when the below-start model row is also followed by lower rows.


stop := false
for pos > 0 && scanned < maxAntigravityTranscriptBytes && !stop {
chunkSize := int64(antigravityTranscriptChunkBytes)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: a step is skipped unless both input_tokens and output_tokens are present, and the cheap pre-filter requires the "input_tokens" needle. Protobuf-style JSON writers usually omit zero-valued fields. A completed model step with output_tokens omitted because it is 0 (a tool-call-only response), or with input_tokens omitted, is dropped without notice. The invocation total is then undercounted while looking exact.

Fix: treat a missing counter as 0 when the other one is present, and have the pre-filter match either needle.

// the latest completed model row for each step_index >= startStep (and <= maxStep when maxStep >= 0).
// Non-usage lines are filtered cheaply without full JSON unmarshalling. If the 4 MiB scan cap is
// reached before finding the invocation boundary, it returns false rather than reporting partial counts.
func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigravityStepUsage, bool) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): when finalNumSteps equals initialNumSteps (an invocation that added no steps), the endStep > startStep check fails and maxStep stays -1, meaning unbounded. The sum then runs to EOF and includes steps of any later invocation already in the transcript, so tokens are over-attributed to this event.

Fix: when an end bound is present and <= startStep, return without usage. Do not fall through to unbounded.


func isCompletedAntigravityModelStep(row payload) bool {
if status := row.str("status"); status != "" && !strings.EqualFold(status, "DONE") {
return false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): extractJSONNonNegInt takes the first "step_index" occurrence anywhere in the line, not the top-level key. A row that carries a nested object with its own step_index ahead of the real key (for example tool args or a nested step reference) gets the wrong index. That can trigger the early stop or misclassify a step.

Fix: decode the line when the needle appears more than once, or only accept the needle at brace depth 1.

Related: the 4 MiB backward scan and per-line json.Unmarshal run synchronously in hook-ingest on every PostInvocation. The tests do not cover the scan cap, the early-stop branch or the consecutive-below threshold.

Comment thread agenthook/cursor.go
reasoning, hasReasoning := p.nonNegInt("reasoning_tokens")

if hasInput {
uncached := rawInput - cacheRead - cacheWrite

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): uncached input is computed as max(0, input - cacheRead - cacheWrite), assuming Cursor's input_tokens always includes the cache counters. If a Cursor build or model reports input without the cache (the new "clamps at zero" test hints this can happen), the clamp silently turns real input into 0 and the cost is understated. Cursor's counts are also read only on stop, so a turn whose stop never fires, or older builds that put counts only on afterAgentResponse, record no usage.

Fix: when cacheRead + cacheWrite > rawInput, keep rawInput as-is, or omit the field and mark the event in metadata, instead of clamping to 0.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 29936902ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agenthook/antigravity_transcript.go Outdated
Comment on lines +129 to +130
if err := json.Unmarshal(line, &row); err == nil && row != nil && isCompletedAntigravityModelStep(row) {
return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid treating a late model update as the invocation boundary

When a completed model row from an earlier invocation is appended out of order, this immediate return defeats the scan's stated protection against late updates and silently publishes an incomplete total. For example, with initialNumSteps=4 and completed rows in file order 4 (1000 input), 1 (late update), 6 (2000 input), the backward scan returns 2000 instead of 3000. I reproduced this against the reader in an isolated test. Do not treat a single older completed row as proof that the invocation boundary has been reached; continue scanning or omit usage if completeness cannot be established.

Useful? React with 👍 / 👎.

}
if processLine(buf[nl+1 : end]) {
stop = true
break

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: Antigravity usage is silently dropped for long invocations, and the transcript read runs synchronously inside hook-ingest (budget about 50 ms). The scan is capped at 4 MiB from EOF, and when the invocation boundary isn't reached (line 259) the function returns false, so no tokens are recorded. The longest, most expensive invocations, with many tool outputs in the transcript, are therefore the ones that lose all usage. A 4 MiB read plus a json.Unmarshal per candidate line can also exceed the hook's latency budget.

Fix: keep the cap, but also record that usage was skipped (for example metadata.usage_truncated=true) so the server doesn't treat the missing counts as zero. Consider moving the scan to the daemon, or using a smaller time-bounded scan.

u.cacheRead = cacheRead
u.hasCacheRead = true
}
if cacheWrite, ok := firstNonNegInt(row, "cache_creation_input_tokens", "cache_write_tokens"); ok {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: The early-stop heuristic can undercount without any signal. Any 3 consecutive lines whose step_index is below startStep end the backward scan, whether or not they are model rows, and stop=true makes line 259 accept the partial sum. If three late rows of earlier steps are written after this invocation's first steps (late updates or checkpoints for parallel tools, or a backgrounded earlier step), steps >= startStep that sit further up the file are never read.

Fix: don't stop on a count of lines. Stop only when a lower row is followed by none at or above startStep within a bounded window, or scan to BOF within the byte cap.

}

// readAntigravityInvocationUsage scans path backwards in bounded chunks from EOF, collecting
// the latest completed model row for each step_index >= startStep (and <= maxStep when maxStep >= 0).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): finalNumSteps and numSteps are guessed payload field names that the tests don't match to any real Antigravity payload. If a build's numSteps is a different counter (the step count when the invocation started, or a total that doesn't count tool steps), then endStep <= startStep returns early and drops usage, or maxStep truncates the range and undercounts.

Fix: only apply the upper bound from a field that is confirmed in Antigravity's hook schema. Otherwise ignore it, since the PostInvocation hook already fires at the end of the invocation.

func isCompletedAntigravityModelStep(row payload) bool {
if status := row.str("status"); status != "" && !strings.EqualFold(status, "DONE") {
return false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): extractJSONNonNegInt takes the first "step_index" anywhere in the line, including inside a nested object that comes before the top-level key (for example "metadata":{"step_index":3} or a tool-call payload). That row is then bucketed under the wrong step, or counts as "below" and feeds the early-stop counter. It is also fooled by any JSON string value that contains the needle unescaped.

Fix: unmarshal only the candidate lines, or at least check that the match is at brace depth 1.

Comment thread agenthook/cursor.go
reasoning, hasReasoning := p.nonNegInt("reasoning_tokens")

if hasInput {
uncached := rawInput - cacheRead - cacheWrite

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): This path is also reached from NormalizeTruncated (payloads over 4 MiB), which keeps only the top-level fields before the cut. If input_tokens is in the prefix but cache_read_tokens and cache_write_tokens are cut, uncached = rawInput - 0 - 0 reports the whole cache-inclusive input as uncached. The server then prices the cache-heavy input at the full uncached rate, and nothing marks the counts as unreliable.

Fix: when ev.Metadata["truncated"] applies (or when input_tokens is present without the cache fields), skip the input and cache counts, or flag them as inexact.

@AnnatarHe
AnnatarHe merged commit 57b781d into main Nov 28, 2026
16 checks passed
@AnnatarHe
AnnatarHe deleted the feat/agenthook-tokens branch November 28, 2026 04:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant