Repository navigation
feat(agenthook): capture token usage from Cursor and Antigravity hooks #363
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
2ab3017
d9dac60
2993690
1944cb6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,309 @@ | ||
| package agenthook | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "io" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| ) | ||
|
|
||
| const ( | ||
| // antigravityTranscriptChunkBytes is read backwards from EOF one chunk at a time so | ||
| // short invocations only inspect the tail of transcript.jsonl (within the 50 ms hook budget). | ||
| antigravityTranscriptChunkBytes = 64 << 10 | ||
| // maxAntigravityTranscriptBytes bounds the maximum total bytes scanned from EOF. | ||
| maxAntigravityTranscriptBytes = 4 << 20 | ||
| // antigravityLowerStepThreshold stops the backward scan after this many consecutive | ||
| // rows below startStep, preventing a single out-of-order late update from cutting off earlier steps. | ||
| antigravityLowerStepThreshold = 3 | ||
| ) | ||
|
|
||
| var ( | ||
| antigravityStepIndexNeedle = []byte(`"step_index"`) | ||
| antigravityInputNeedle = []byte(`"input_tokens"`) | ||
| antigravityOutputNeedle = []byte(`"output_tokens"`) | ||
| ) | ||
|
|
||
| type antigravityStepUsage struct { | ||
| input int | ||
| output int | ||
| cacheRead int | ||
| hasCacheRead bool | ||
| cacheCreate int | ||
| hasCacheWrite bool | ||
| reasoning int | ||
| hasReasoning bool | ||
| model string | ||
| } | ||
|
|
||
| // applyAntigravityTranscriptUsage reads the current invocation's completed model steps from | ||
| // Antigravity's transcript.jsonl (all completed MODEL / PLANNER_RESPONSE steps with | ||
| // step_index >= initialNumSteps, deduplicated per step_index) and sums their token counts onto ev. | ||
| // Works across Antigravity App, IDE, and agy CLI. Missing, unreadable, non-regular, truncated, | ||
| // or unmatched transcripts are silently ignored so hook recording never fails or undercounts. | ||
| func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload) { | ||
| startStep, ok := p.nonNegInt("initialNumSteps") | ||
| if !ok || transcriptPath == "" { | ||
| return | ||
| } | ||
| maxStep := -1 | ||
| if endStep, ok := firstNonNegInt(p, "finalNumSteps", "numSteps"); ok { | ||
| if endStep <= startStep { | ||
| return | ||
| } | ||
| maxStep = endStep - 1 | ||
| } | ||
|
|
||
| path := expandHomePath(transcriptPath) | ||
| if !strings.EqualFold(filepath.Ext(path), ".jsonl") { | ||
| return | ||
| } | ||
| usage, found := readAntigravityInvocationUsage(path, startStep, maxStep) | ||
| if !found { | ||
| return | ||
| } | ||
|
|
||
| // Antigravity's input_tokens excludes cache reads; output_tokens already includes thinking. | ||
| ev.InputTokens = intPtr(usage.input) | ||
| ev.OutputTokens = intPtr(usage.output) | ||
| if usage.hasCacheRead { | ||
| ev.CacheReadTokens = intPtr(usage.cacheRead) | ||
| } | ||
| if usage.hasCacheWrite { | ||
| ev.CacheCreationTokens = intPtr(usage.cacheCreate) | ||
| } | ||
| if usage.hasReasoning { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (optional): the comment says Antigravity's Fix: don't send reasoning when output already includes it, or subtract it from |
||
| ev.ReasoningTokens = intPtr(usage.reasoning) | ||
| } | ||
| if ev.Model == "" && usage.model != "" { | ||
| ev.Model = usage.model | ||
| } | ||
| } | ||
|
|
||
| // 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). | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (optional): 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. |
||
| // 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) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (optional): when Fix: when an end bound is present and |
||
| // Stat before Open so a FIFO or device node named *.jsonl can never block Open. | ||
| statInfo, err := os.Stat(path) | ||
| if err != nil || !statInfo.Mode().IsRegular() || statInfo.Size() == 0 { | ||
| return antigravityStepUsage{}, false | ||
| } | ||
|
|
||
| f, err := os.Open(path) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: Fix: |
||
| if err != nil { | ||
| return antigravityStepUsage{}, false | ||
| } | ||
| defer f.Close() | ||
|
|
||
| info, err := f.Stat() | ||
| if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { | ||
| return antigravityStepUsage{}, false | ||
| } | ||
|
|
||
| steps := map[int]antigravityStepUsage{} | ||
| latestStep := -1 | ||
| latestModel := "" | ||
|
|
||
| pos := info.Size() | ||
| var scanned int64 | ||
| var carry []byte | ||
| consecutiveBelow := 0 | ||
|
|
||
| processLine := func(line []byte) (stop bool) { | ||
| line = bytes.TrimSpace(line) | ||
| if len(line) == 0 { | ||
| return false | ||
| } | ||
| idx, ok := extractJSONNonNegInt(line, antigravityStepIndexNeedle) | ||
| if !ok { | ||
| return false | ||
| } | ||
| if idx < startStep { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: the backward scan stops at the first row whose 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 |
||
| consecutiveBelow++ | ||
| return consecutiveBelow >= antigravityLowerStepThreshold | ||
| } | ||
| consecutiveBelow = 0 | ||
|
|
||
| if maxStep >= 0 && idx > maxStep { | ||
| return false | ||
| } | ||
| if !bytes.Contains(line, antigravityInputNeedle) && !bytes.Contains(line, antigravityOutputNeedle) { | ||
| return false | ||
| } | ||
| // Scanning backwards: the first completed row seen for a given step_index is the newest. | ||
| if _, exists := steps[idx]; exists { | ||
| return false | ||
| } | ||
| var row payload | ||
| if err := json.Unmarshal(line, &row); err != nil || row == nil { | ||
| return false | ||
| } | ||
| if !isCompletedAntigravityModelStep(row) { | ||
| return false | ||
| } | ||
| input, hasInput := row.nonNegInt("input_tokens") | ||
| output, hasOutput := row.nonNegInt("output_tokens") | ||
| if !hasInput && !hasOutput { | ||
| return false | ||
| } | ||
| u := antigravityStepUsage{ | ||
| input: input, | ||
| output: output, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: the backward scan stops at the first completed model row below Trigger: a late DONE rewrite of an earlier step (for example 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. |
||
| } | ||
| if cacheRead, ok := row.nonNegInt("cache_read_tokens"); ok { | ||
| u.cacheRead = cacheRead | ||
| u.hasCacheRead = true | ||
| } | ||
| if cacheWrite, ok := firstNonNegInt(row, "cache_creation_input_tokens", "cache_write_tokens"); ok { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Fix: don't stop on a count of lines. Stop only when a lower row is followed by none at or above |
||
| u.cacheCreate = cacheWrite | ||
| u.hasCacheWrite = true | ||
| } | ||
| if thinking, ok := firstNonNegInt(row, "thinking_tokens", "reasoning_tokens"); ok { | ||
| u.reasoning = thinking | ||
| u.hasReasoning = true | ||
| } | ||
| if m := row.str("model_name"); m != "" { | ||
| u.model = m | ||
| } else if m := row.str("modelName"); m != "" { | ||
| u.model = m | ||
| } | ||
| steps[idx] = u | ||
| if u.model != "" && idx > latestStep { | ||
| latestStep = idx | ||
| latestModel = u.model | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| stop := false | ||
| for pos > 0 && scanned < maxAntigravityTranscriptBytes && !stop { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Fix: when the cap is hit without reaching a row below |
||
| chunkSize := int64(antigravityTranscriptChunkBytes) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: a step is skipped unless both Fix: treat a missing counter as 0 when the other one is present, and have the pre-filter match either needle. |
||
| if chunkSize > pos { | ||
| chunkSize = pos | ||
| } | ||
| if remaining := int64(maxAntigravityTranscriptBytes) - scanned; chunkSize > remaining { | ||
| chunkSize = remaining | ||
| } | ||
| pos -= chunkSize | ||
| buf := make([]byte, chunkSize) | ||
| if _, err := f.ReadAt(buf, pos); err != nil && err != io.EOF { | ||
| break | ||
| } | ||
| scanned += chunkSize | ||
|
|
||
| if len(carry) > 0 { | ||
| buf = append(buf, carry...) | ||
| carry = nil | ||
| } | ||
|
|
||
| // Split lines from the end of buf; keep the leading fragment in carry when pos > 0. | ||
| end := len(buf) | ||
| for { | ||
| nl := bytes.LastIndexByte(buf[:end], '\n') | ||
| if nl < 0 { | ||
| if pos == 0 { | ||
| stop = processLine(buf[:end]) | ||
| } else { | ||
| carry = append([]byte(nil), buf[:end]...) | ||
| } | ||
| break | ||
| } | ||
| if processLine(buf[nl+1 : end]) { | ||
| stop = true | ||
| break | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Fix: keep the cap, but also record that usage was skipped (for example |
||
| } | ||
| end = nl | ||
| } | ||
| } | ||
|
|
||
| // If we hit the scan cap before reaching BOF or an earlier invocation boundary, | ||
| // omit usage rather than reporting a truncated partial sum as exact. | ||
| if pos > 0 && !stop { | ||
| return antigravityStepUsage{}, false | ||
| } | ||
|
|
||
| if len(steps) == 0 { | ||
| return antigravityStepUsage{}, false | ||
| } | ||
|
Comment on lines
+229
to
+231
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When an invocation's transcript spans more than 4 MiB, the backward scan can hit its byte limit before reaching Useful? React with 👍 / 👎. |
||
|
|
||
| var total antigravityStepUsage | ||
| total.model = latestModel | ||
| for _, u := range steps { | ||
| total.input += u.input | ||
| total.output += u.output | ||
| if u.hasCacheRead { | ||
| total.cacheRead += u.cacheRead | ||
| total.hasCacheRead = true | ||
| } | ||
| if u.hasCacheWrite { | ||
| total.cacheCreate += u.cacheCreate | ||
| total.hasCacheWrite = true | ||
| } | ||
| if u.hasReasoning { | ||
| total.reasoning += u.reasoning | ||
| total.hasReasoning = true | ||
| } | ||
| } | ||
| return total, true | ||
| } | ||
|
|
||
| // extractJSONNonNegInt scans a JSON object line for `"key": <int>` without full decoding. | ||
| func extractJSONNonNegInt(line, keyNeedle []byte) (int, bool) { | ||
| pos := bytes.Index(line, keyNeedle) | ||
| if pos < 0 { | ||
| return 0, false | ||
| } | ||
| rest := bytes.TrimSpace(line[pos+len(keyNeedle):]) | ||
| if len(rest) == 0 || rest[0] != ':' { | ||
| return 0, false | ||
| } | ||
| rest = bytes.TrimSpace(rest[1:]) | ||
| if len(rest) == 0 { | ||
| return 0, false | ||
| } | ||
| if rest[0] == '"' { | ||
| rest = rest[1:] | ||
| end := bytes.IndexByte(rest, '"') | ||
| if end <= 0 { | ||
| return 0, false | ||
| } | ||
| return parseNonNegIntBytes(bytes.TrimSpace(rest[:end])) | ||
| } | ||
| end := 0 | ||
| for end < len(rest) { | ||
| c := rest[end] | ||
| if c == ',' || c == '}' || c == ' ' || c == '\t' || c == '\r' || c == '\n' { | ||
| break | ||
| } | ||
| end++ | ||
| } | ||
| return parseNonNegIntBytes(rest[:end]) | ||
| } | ||
|
|
||
| func isCompletedAntigravityModelStep(row payload) bool { | ||
| if status := row.str("status"); status != "" && !strings.EqualFold(status, "DONE") { | ||
| return false | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (optional): 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 |
||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit (optional): Fix: unmarshal only the candidate lines, or at least check that the match is at brace depth 1. |
||
| source := row.str("source") | ||
| stepType := row.str("step_type") | ||
| if source != "" { | ||
| return strings.EqualFold(source, "MODEL") | ||
| } | ||
| if stepType != "" { | ||
| return strings.EqualFold(stepType, "PLANNER_RESPONSE") | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| func expandHomePath(p string) string { | ||
| if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, `~\`) { | ||
| if home, err := os.UserHomeDir(); err == nil && home != "" { | ||
| return filepath.Join(home, p[2:]) | ||
| } | ||
| } | ||
| return p | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.mdanddocs/CONFIG.mddo not explain token collection or that Antigravity usage requires a readable.jsonltranscript 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 inAGENTS.md.AGENTS.md reference: AGENTS.md:L55-L55
Useful? React with 👍 / 👎.