From 2ab301767feec8bcb479863bed5b4e206703ba59 Mon Sep 17 00:00:00 2001 From: Le He <8704175+AnnatarHe@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:24:12 +0000 Subject: [PATCH 1/4] feat(agenthook): capture token usage from Cursor and Antigravity hooks --- agenthook/antigravity.go | 2 + agenthook/antigravity_transcript.go | 144 ++++++++++++++++++++++++ agenthook/cursor.go | 47 ++++++++ agenthook/event.go | 8 ++ agenthook/normalize.go | 48 ++++++++ agenthook/tokens_test.go | 165 ++++++++++++++++++++++++++++ 6 files changed, 414 insertions(+) create mode 100644 agenthook/antigravity_transcript.go create mode 100644 agenthook/tokens_test.go diff --git a/agenthook/antigravity.go b/agenthook/antigravity.go index e4ff93c..e313903 100644 --- a/agenthook/antigravity.go +++ b/agenthook/antigravity.go @@ -60,6 +60,8 @@ func normalizeAntigravity(ev *Event, event string, p payload) { // Some builds leave content out ev.Response = p.str("content") p.setNumberMetadata(ev, "invocationNum", "invocation_num") + p.setNumberMetadata(ev, "initialNumSteps", "initial_num_steps") + applyAntigravityTranscriptUsage(ev, transcript, p) case strings.ToLower(AntigravityStop): ev.EventType = EventStop ev.Status = p.str("terminationReason") diff --git a/agenthook/antigravity_transcript.go b/agenthook/antigravity_transcript.go new file mode 100644 index 0000000..60efcf7 --- /dev/null +++ b/agenthook/antigravity_transcript.go @@ -0,0 +1,144 @@ +package agenthook + +import ( + "bytes" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" +) + +// maxAntigravityTranscriptBytes bounds how far back from the end of transcript.jsonl we +// scan during PostInvocation so long conversations never slow down the hook. +const maxAntigravityTranscriptBytes = 4 << 20 + +// applyAntigravityTranscriptUsage reads the current invocation's completed model step from +// Antigravity's transcript.jsonl (matching initialNumSteps to step_index) and fills token +// 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") + if !ok || transcriptPath == "" { + return + } + path := expandHomePath(transcriptPath) + if !strings.EqualFold(filepath.Ext(path), ".jsonl") { + return + } + row, found := readAntigravityStep(path, stepIndex) + if !found { + return + } + input, hasInput := row.nonNegInt("input_tokens") + output, hasOutput := row.nonNegInt("output_tokens") + if !hasInput || !hasOutput { + return + } + + // Antigravity's input_tokens excludes cache reads; output_tokens already includes thinking. + ev.InputTokens = intPtr(input) + ev.OutputTokens = intPtr(output) + if cacheRead, ok := row.nonNegInt("cache_read_tokens"); ok { + ev.CacheReadTokens = intPtr(cacheRead) + } + if cacheWrite, ok := firstNonNegInt(row, "cache_creation_input_tokens", "cache_write_tokens"); ok { + ev.CacheCreationTokens = intPtr(cacheWrite) + } + if thinking, ok := firstNonNegInt(row, "thinking_tokens", "reasoning_tokens"); ok { + ev.ReasoningTokens = intPtr(thinking) + } + if ev.Model == "" { + if m := row.str("model_name"); m != "" { + ev.Model = m + } else if m := row.str("modelName"); m != "" { + ev.Model = m + } + } +} + +func readAntigravityStep(path string, stepIndex int) (payload, bool) { + f, err := os.Open(path) + if err != nil { + return nil, false + } + defer f.Close() + + info, err := f.Stat() + if err != nil || info.IsDir() || info.Size() == 0 { + return nil, false + } + + offset := info.Size() - maxAntigravityTranscriptBytes + if offset < 0 { + offset = 0 + } + if offset > 0 { + if _, err := f.Seek(offset, io.SeekStart); err != nil { + return nil, false + } + } + data, err := io.ReadAll(io.LimitReader(f, maxAntigravityTranscriptBytes)) + if err != nil || len(data) == 0 { + return nil, false + } + if offset > 0 { + // Discard the partial first line when seeking into the middle of the file. + if idx := bytes.IndexByte(data, '\n'); idx >= 0 { + data = data[idx+1:] + } else { + return nil, false + } + } + + var matched payload + for _, line := range bytes.Split(data, []byte{'\n'}) { + line = bytes.TrimSpace(line) + if len(line) == 0 { + continue + } + var row payload + if err := json.Unmarshal(line, &row); err != nil || row == nil { + continue + } + idx, ok := row.nonNegInt("step_index") + if !ok || idx != stepIndex { + continue + } + if !isCompletedAntigravityModelStep(row) { + continue + } + if _, hasIn := row.nonNegInt("input_tokens"); !hasIn { + continue + } + if _, hasOut := row.nonNegInt("output_tokens"); !hasOut { + continue + } + matched = row + } + return matched, matched != nil +} + +func isCompletedAntigravityModelStep(row payload) bool { + if status := row.str("status"); status != "" && !strings.EqualFold(status, "DONE") { + return false + } + 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 +} diff --git a/agenthook/cursor.go b/agenthook/cursor.go index 6fa1922..750ca61 100644 --- a/agenthook/cursor.go +++ b/agenthook/cursor.go @@ -38,9 +38,13 @@ func normalizeCursor(ev *Event, event string, p payload, getenv func(string) str ev.SessionID = p.str("session_id") } ev.Model = p.str("model") + if ev.Model == "" { + ev.Model = p.str("model_id") + } ev.Workspace = firstWorkspace(p.strs("workspace_roots"), p.str("cwd"), getenv("CURSOR_PROJECT_DIR")) p.setStringMetadata(ev, "cursor_version", "cursor_version") p.setStringMetadata(ev, "generation_id", "generation_id") + p.setStringMetadata(ev, "model_id", "model_id") // A remote workspace may be a cloud agent's VM or one of the user's SSH hosts, so this is // kept apart from the cloud signals if getenv(cursorCodeRemoteEnvVar) == "true" { @@ -80,6 +84,9 @@ func normalizeCursor(ev *Event, event string, p payload, getenv func(string) str ev.EventType = EventStop ev.Status = p.str("status") p.setNumberMetadata(ev, "loop_count", "loop_count") + // Cursor reports the same turn token counts on both afterAgentResponse and stop + // for a given generation_id; read them only on stop so a turn is never counted twice. + applyCursorTokenUsage(ev, p) case strings.ToLower(CursorSessionStart): ev.EventType = EventSessionStart p.setBoolMetadata(ev, "is_background_agent", "is_background_agent") @@ -95,6 +102,46 @@ func normalizeCursor(ev *Event, event string, p payload, getenv func(string) str } } +// applyCursorTokenUsage extracts Cursor's per-turn token counts from a stop payload. +// Cursor's input_tokens includes cache_read_tokens and cache_write_tokens, so uncached input +// is computed as max(0, input_tokens - cache_read_tokens - cache_write_tokens). +func applyCursorTokenUsage(ev *Event, p payload) { + cacheRead, hasCacheRead := p.nonNegInt("cache_read_tokens") + cacheWrite, hasCacheWrite := firstNonNegInt(p, "cache_write_tokens", "cache_creation_tokens", "cache_creation_input_tokens") + rawInput, hasInput := p.nonNegInt("input_tokens") + output, hasOutput := p.nonNegInt("output_tokens") + reasoning, hasReasoning := p.nonNegInt("reasoning_tokens") + + if hasInput { + uncached := rawInput - cacheRead - cacheWrite + if uncached < 0 { + uncached = 0 + } + ev.InputTokens = intPtr(uncached) + } + if hasOutput { + ev.OutputTokens = intPtr(output) + } + if hasCacheRead { + ev.CacheReadTokens = intPtr(cacheRead) + } + if hasCacheWrite { + ev.CacheCreationTokens = intPtr(cacheWrite) + } + if hasReasoning { + ev.ReasoningTokens = intPtr(reasoning) + } +} + +func firstNonNegInt(p payload, keys ...string) (int, bool) { + for _, k := range keys { + if v, ok := p.nonNegInt(k); ok { + return v, true + } + } + return 0, false +} + // cursorSurface guesses whether a Cursor hook runs in the IDE or in cursor-agent. Cursor // names neither, so this is a heuristic: the IDE is a VS Code fork and passes VS Code's // environment to the commands it runs, which the CLI doesn't. diff --git a/agenthook/event.go b/agenthook/event.go index 0e513f2..711a279 100644 --- a/agenthook/event.go +++ b/agenthook/event.go @@ -77,6 +77,14 @@ type Event struct { Response string `json:"response,omitempty"` ToolInput string `json:"tool_input,omitempty"` + // Token counts for a model turn/invocation when reported. InputTokens excludes cache + // reads and cache writes (uncached input). + InputTokens *int `json:"input_tokens,omitempty"` + OutputTokens *int `json:"output_tokens,omitempty"` + CacheReadTokens *int `json:"cache_read_tokens,omitempty"` + CacheCreationTokens *int `json:"cache_creation_tokens,omitempty"` + ReasoningTokens *int `json:"reasoning_tokens,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` // YieldToUserHooks travels from hook-ingest to the daemon only, never to the server: the diff --git a/agenthook/normalize.go b/agenthook/normalize.go index 6c674a9..37755eb 100644 --- a/agenthook/normalize.go +++ b/agenthook/normalize.go @@ -210,6 +210,54 @@ func (p payload) number(key string) (float64, bool) { return 0, false } +// nonNegInt reads a non-negative integer field (JSON integer or ASCII decimal string). +// Booleans, floats with fractional parts, negative numbers and values that don't fit in int +// return false so bad counters never silently become zero. +func (p payload) nonNegInt(key string) (int, bool) { + raw, ok := p[key] + if !ok { + return 0, false + } + raw = bytes.TrimSpace(raw) + if len(raw) == 0 { + return 0, false + } + if raw[0] == '"' { + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return 0, false + } + if s == "" { + return 0, false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return 0, false + } + } + v, err := strconv.Atoi(s) + if err != nil || v < 0 { + return 0, false + } + return v, true + } + // Reject booleans, objects, arrays, null and decimals + for i := 0; i < len(raw); i++ { + if raw[i] < '0' || raw[i] > '9' { + return 0, false + } + } + v, err := strconv.Atoi(string(raw)) + if err != nil || v < 0 { + return 0, false + } + return v, true +} + +func intPtr(v int) *int { + return &v +} + func (p payload) boolean(key string) (bool, bool) { raw, ok := p[key] if !ok { diff --git a/agenthook/tokens_test.go b/agenthook/tokens_test.go new file mode 100644 index 0000000..345a708 --- /dev/null +++ b/agenthook/tokens_test.go @@ -0,0 +1,165 @@ +package agenthook + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCursorStopTokenUsage(t *testing.T) { + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + + t.Run("subtracts cache read and write from inclusive input_tokens", func(t *testing.T) { + stdin := []byte(`{ + "hook_event_name": "stop", + "conversation_id": "conv-1", + "generation_id": "gen-1", + "model": "cursor-grok-4.6-high-fast", + "model_id": "grok-4.6", + "status": "completed", + "loop_count": 0, + "input_tokens": 1180993, + "output_tokens": 8146, + "cache_read_tokens": 1007022, + "cache_write_tokens": 173957 + }`) + ev, err := Normalize("cursor", "", stdin, now, nil) + require.NoError(t, err) + assert.Equal(t, EventStop, ev.EventType) + assert.Equal(t, "cursor-grok-4.6-high-fast", ev.Model) + assert.Equal(t, "grok-4.6", ev.Metadata["model_id"]) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 14, *ev.InputTokens) + require.NotNil(t, ev.OutputTokens) + assert.Equal(t, 8146, *ev.OutputTokens) + require.NotNil(t, ev.CacheReadTokens) + assert.Equal(t, 1007022, *ev.CacheReadTokens) + require.NotNil(t, ev.CacheCreationTokens) + assert.Equal(t, 173957, *ev.CacheCreationTokens) + assert.Nil(t, ev.ReasoningTokens) + }) + + t.Run("clamps uncached input at zero when cache exceeds input", func(t *testing.T) { + stdin := []byte(`{ + "hook_event_name": "stop", + "conversation_id": "conv-2", + "model_id": "claude-4.5-sonnet", + "status": "completed", + "input_tokens": 100, + "output_tokens": 25, + "cache_read_tokens": 120 + }`) + ev, err := Normalize("cursor", "", stdin, now, nil) + require.NoError(t, err) + assert.Equal(t, "claude-4.5-sonnet", ev.Model) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 0, *ev.InputTokens) + require.NotNil(t, ev.OutputTokens) + assert.Equal(t, 25, *ev.OutputTokens) + require.NotNil(t, ev.CacheReadTokens) + assert.Equal(t, 120, *ev.CacheReadTokens) + assert.Nil(t, ev.CacheCreationTokens) + }) + + t.Run("afterAgentResponse does not double count tokens", func(t *testing.T) { + stdin := []byte(`{ + "hook_event_name": "afterAgentResponse", + "conversation_id": "conv-1", + "generation_id": "gen-1", + "text": "done", + "input_tokens": 5000, + "output_tokens": 200 + }`) + ev, err := Normalize("cursor", "", stdin, now, nil) + require.NoError(t, err) + assert.Equal(t, EventAgentResponse, ev.EventType) + assert.Nil(t, ev.InputTokens) + assert.Nil(t, ev.OutputTokens) + }) + + t.Run("omits token fields when absent or invalid", func(t *testing.T) { + stdin := []byte(`{ + "hook_event_name": "stop", + "conversation_id": "conv-3", + "status": "completed", + "input_tokens": -5, + "output_tokens": true + }`) + ev, err := Normalize("cursor", "", stdin, now, nil) + require.NoError(t, err) + assert.Nil(t, ev.InputTokens) + assert.Nil(t, ev.OutputTokens) + }) +} + +func TestAntigravityPostInvocationTranscriptUsage(t *testing.T) { + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + + t.Run("reads exact step_index matching initialNumSteps", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + lines := "" + + `{"step_index":0,"source":"USER","status":"DONE"}` + "\n" + + `{"step_index":1,"source":"MODEL","status":"DONE","model_name":"gemini-3.6-flash-medium","input_tokens":1000,"output_tokens":50,"cache_read_tokens":200}` + "\n" + + `{"step_index":4,"source":"MODEL","status":"IN_PROGRESS","input_tokens":50,"output_tokens":1}` + "\n" + + `{"step_index":4,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro-high","input_tokens":5225,"output_tokens":340,"cache_read_tokens":113928,"cache_creation_input_tokens":1200,"thinking_tokens":110}` + "\n" + require.NoError(t, os.WriteFile(transcript, []byte(lines), 0o600)) + + stdin := []byte(`{ + "conversationId": "agy-conv-1", + "transcriptPath": "` + filepath.ToSlash(transcript) + `", + "invocationNum": 2, + "initialNumSteps": 4, + "content": "Fixed it." + }`) + ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) + require.NoError(t, err) + assert.Equal(t, EventAgentResponse, ev.EventType) + assert.Equal(t, "gemini-3.1-pro-high", ev.Model) + assert.Equal(t, int64(4), ev.Metadata["initial_num_steps"]) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 5225, *ev.InputTokens) + require.NotNil(t, ev.OutputTokens) + assert.Equal(t, 340, *ev.OutputTokens) + require.NotNil(t, ev.CacheReadTokens) + assert.Equal(t, 113928, *ev.CacheReadTokens) + require.NotNil(t, ev.CacheCreationTokens) + assert.Equal(t, 1200, *ev.CacheCreationTokens) + require.NotNil(t, ev.ReasoningTokens) + assert.Equal(t, 110, *ev.ReasoningTokens) + }) + + t.Run("does not fall back to previous step when step_index not yet flushed", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + lines := `{"step_index":1,"source":"MODEL","status":"DONE","input_tokens":1000,"output_tokens":50}` + "\n" + require.NoError(t, os.WriteFile(transcript, []byte(lines), 0o600)) + + stdin := []byte(`{ + "conversationId": "agy-conv-1", + "transcriptPath": "` + filepath.ToSlash(transcript) + `", + "modelName": "gemini-3.6-flash-medium", + "initialNumSteps": 7 + }`) + ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) + require.NoError(t, err) + assert.Nil(t, ev.InputTokens) + assert.Nil(t, ev.OutputTokens) + }) + + t.Run("ignores non-jsonl paths and missing files", func(t *testing.T) { + stdin := []byte(`{ + "conversationId": "agy-conv-2", + "transcriptPath": "/nonexistent/transcript.db", + "initialNumSteps": 1 + }`) + ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) + require.NoError(t, err) + assert.Nil(t, ev.InputTokens) + assert.Nil(t, ev.OutputTokens) + }) +} From d9dac60125d87a917f2842e8a066c5c9a9a8e50b Mon Sep 17 00:00:00 2001 From: Le He <8704175+AnnatarHe@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:42:18 +0000 Subject: [PATCH 2/4] fix(agenthook): sum multi-step Antigravity usage with backward chunk scan and docs --- README.md | 4 +- agenthook/antigravity_transcript.go | 246 ++++++++++++++++++++-------- agenthook/normalize.go | 43 +++-- agenthook/tokens_test.go | 119 +++++++++++++- docs/CONFIG.md | 4 +- 5 files changed, 322 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index c493c71..6746c76 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,9 @@ The hooks go into each project's repository, the only place the agents' cloud ru Outside a repository the current folder counts as the project, but never your home folder. Hooks older versions put in `~/.cursor/hooks.json` or `~/.gemini/config/hooks.json` stay and keep tracking your other folders; a repository's own hooks leave events to them, so nothing is counted twice. `uninstall` takes ShellTime out of the repository's file and those. Restart the agent after installing. The hooks need macOS or Linux: `shelltime-daemon` doesn't run on Windows, and the install refuses there (a committed hook file fails on a Windows collaborator's machine, which Cursor logs and carries on from). -Each hook is one self-contained shell command, the same on every machine that checks the repository out: it records the event only where `shelltime` and `shelltime-daemon` are installed (on `PATH`, or in `~/.shelltime/bin`, `/opt/homebrew/bin` or `/usr/local/bin`, which an app started from the Dock may not have on its `PATH`), each to that machine's ShellTime account, and anywhere else just lets the agent carry on, so collaborators without ShellTime see no failing hooks. Events go to the daemon, which sends them in batches; while it isn't running they wait in `~/.shelltime/agent-hooks.pending.jsonl` until it sends them. The hooks send your prompts, the agent's responses, tool names and inputs (shell commands, file paths) and the workspace folder; tool output is never read. Data masking and your exclude patterns apply (an event whose shell command matches one is sent without the command, prompt, response, tool input or error), and `shelltime config disable agentHooks.sendContent` keeps the text of prompts, responses, tool input and errors, and the paths of files attached to prompts, out, so only the activity is sent. `shelltime doctor`, run in a repository, checks its hook file and that the hooks can find both binaries. +Each hook is one self-contained shell command, the same on every machine that checks the repository out: it records the event only where `shelltime` and `shelltime-daemon` are installed (on `PATH`, or in `~/.shelltime/bin`, `/opt/homebrew/bin` or `/usr/local/bin`, which an app started from the Dock may not have on its `PATH`), each to that machine's ShellTime account, and anywhere else just lets the agent carry on, so collaborators without ShellTime see no failing hooks. Events go to the daemon, which sends them in batches; while it isn't running they wait in `~/.shelltime/agent-hooks.pending.jsonl` until it sends them. The hooks send your prompts, the agent's responses, tool names and inputs (shell commands, file paths), per-turn token counts and the workspace folder; tool output is never read. Data masking and your exclude patterns apply (an event whose shell command matches one is sent without the command, prompt, response, tool input or error), and `shelltime config disable agentHooks.sendContent` keeps the text of prompts, responses, tool input and errors, and the paths of files attached to prompts, out, so only the activity and token usage are sent. `shelltime doctor`, run in a repository, checks its hook file and that the hooks can find both binaries. + +Token usage (used to calculate estimated USD cost on the server) is captured per turn: Cursor reports token counts directly on its `stop` hook payload, while Google Antigravity's `PostInvocation` hook reads completed model steps from the local `.jsonl` transcript file referenced by `transcriptPath` (when the file is missing, unreadable, or has no matching completed steps, activity is still recorded without token counts). ### Cloud agents diff --git a/agenthook/antigravity_transcript.go b/agenthook/antigravity_transcript.go index 60efcf7..988be2c 100644 --- a/agenthook/antigravity_transcript.go +++ b/agenthook/antigravity_transcript.go @@ -9,114 +9,222 @@ import ( "strings" ) -// maxAntigravityTranscriptBytes bounds how far back from the end of transcript.jsonl we -// scan during PostInvocation so long conversations never slow down the hook. -const maxAntigravityTranscriptBytes = 4 << 20 - -// applyAntigravityTranscriptUsage reads the current invocation's completed model step from -// Antigravity's transcript.jsonl (matching initialNumSteps to step_index) and fills token -// counts onto ev. Works across Antigravity App, IDE, and agy CLI. Missing, unreadable, or -// unmatched transcripts are silently ignored so hook recording never fails. +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 +) + +var ( + antigravityStepIndexNeedle = []byte(`"step_index"`) + antigravityTokensNeedle = []byte(`"input_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, or unmatched +// transcripts are silently ignored so hook recording never fails. func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload) { - stepIndex, ok := p.nonNegInt("initialNumSteps") + startStep, ok := p.nonNegInt("initialNumSteps") if !ok || transcriptPath == "" { return } + maxStep := -1 + if endStep, ok := firstNonNegInt(p, "finalNumSteps", "numSteps"); ok && endStep > startStep { + maxStep = endStep - 1 + } + path := expandHomePath(transcriptPath) if !strings.EqualFold(filepath.Ext(path), ".jsonl") { return } - row, found := readAntigravityStep(path, stepIndex) + usage, found := readAntigravityInvocationUsage(path, startStep, maxStep) if !found { return } - input, hasInput := row.nonNegInt("input_tokens") - output, hasOutput := row.nonNegInt("output_tokens") - if !hasInput || !hasOutput { - return - } // Antigravity's input_tokens excludes cache reads; output_tokens already includes thinking. - ev.InputTokens = intPtr(input) - ev.OutputTokens = intPtr(output) - if cacheRead, ok := row.nonNegInt("cache_read_tokens"); ok { - ev.CacheReadTokens = intPtr(cacheRead) + ev.InputTokens = intPtr(usage.input) + ev.OutputTokens = intPtr(usage.output) + if usage.hasCacheRead { + ev.CacheReadTokens = intPtr(usage.cacheRead) } - if cacheWrite, ok := firstNonNegInt(row, "cache_creation_input_tokens", "cache_write_tokens"); ok { - ev.CacheCreationTokens = intPtr(cacheWrite) + if usage.hasCacheWrite { + ev.CacheCreationTokens = intPtr(usage.cacheCreate) } - if thinking, ok := firstNonNegInt(row, "thinking_tokens", "reasoning_tokens"); ok { - ev.ReasoningTokens = intPtr(thinking) + if usage.hasReasoning { + ev.ReasoningTokens = intPtr(usage.reasoning) } - if ev.Model == "" { - if m := row.str("model_name"); m != "" { - ev.Model = m - } else if m := row.str("modelName"); m != "" { - ev.Model = m - } + if ev.Model == "" && usage.model != "" { + ev.Model = usage.model } } -func readAntigravityStep(path string, stepIndex int) (payload, bool) { +// 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), +// 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) if err != nil { - return nil, false + return antigravityStepUsage{}, false } defer f.Close() info, err := f.Stat() - if err != nil || info.IsDir() || info.Size() == 0 { - return nil, false + if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { + return antigravityStepUsage{}, false } - offset := info.Size() - maxAntigravityTranscriptBytes - if offset < 0 { - offset = 0 - } - if offset > 0 { - if _, err := f.Seek(offset, io.SeekStart); err != nil { - return nil, false - } - } - data, err := io.ReadAll(io.LimitReader(f, maxAntigravityTranscriptBytes)) - if err != nil || len(data) == 0 { - return nil, false - } - if offset > 0 { - // Discard the partial first line when seeking into the middle of the file. - if idx := bytes.IndexByte(data, '\n'); idx >= 0 { - data = data[idx+1:] - } else { - return nil, false - } - } + steps := map[int]antigravityStepUsage{} + latestStep := -1 + latestModel := "" + + pos := info.Size() + var scanned int64 + var carry []byte - var matched payload - for _, line := range bytes.Split(data, []byte{'\n'}) { + processLine := func(line []byte) (stop bool) { line = bytes.TrimSpace(line) - if len(line) == 0 { - continue + 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 + // when step_index falls below startStep, so skip full unmarshal when a line has no + // token fields unless we haven't checked its step_index yet. var row payload if err := json.Unmarshal(line, &row); err != nil || row == nil { - continue + return false } idx, ok := row.nonNegInt("step_index") - if !ok || idx != stepIndex { - continue + if !ok { + return false + } + if idx < startStep { + return true + } + if maxStep >= 0 && idx > maxStep { + return false + } + if !bytes.Contains(line, antigravityTokensNeedle) || !isCompletedAntigravityModelStep(row) { + return false + } + // Scanning backwards: the first completed row seen for a given step_index is the newest. + if _, exists := steps[idx]; exists { + return false } - if !isCompletedAntigravityModelStep(row) { - continue + input, hasInput := row.nonNegInt("input_tokens") + output, hasOutput := row.nonNegInt("output_tokens") + if !hasInput || !hasOutput { + return false + } + u := antigravityStepUsage{ + input: input, + output: output, + } + 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 { + 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 { + chunkSize := int64(antigravityTranscriptChunkBytes) + 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 + } + end = nl + } + } + + if len(steps) == 0 { + return antigravityStepUsage{}, false + } + + 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 _, hasIn := row.nonNegInt("input_tokens"); !hasIn { - continue + if u.hasCacheWrite { + total.cacheCreate += u.cacheCreate + total.hasCacheWrite = true } - if _, hasOut := row.nonNegInt("output_tokens"); !hasOut { - continue + if u.hasReasoning { + total.reasoning += u.reasoning + total.hasReasoning = true } - matched = row } - return matched, matched != nil + return total, true } func isCompletedAntigravityModelStep(row payload) bool { diff --git a/agenthook/normalize.go b/agenthook/normalize.go index 37755eb..38a20a3 100644 --- a/agenthook/normalize.go +++ b/agenthook/normalize.go @@ -227,31 +227,42 @@ func (p payload) nonNegInt(key string) (int, bool) { if err := json.Unmarshal(raw, &s); err != nil { return 0, false } - if s == "" { - return 0, false - } - for i := 0; i < len(s); i++ { - if s[i] < '0' || s[i] > '9' { - return 0, false - } + return parseNonNegIntBytes([]byte(strings.TrimSpace(s))) + } + return parseNonNegIntBytes(raw) +} + +func parseNonNegIntBytes(raw []byte) (int, bool) { + if len(raw) == 0 { + return 0, false + } + // Fast path: plain ASCII digits. + allDigits := true + for i := 0; i < len(raw); i++ { + if raw[i] < '0' || raw[i] > '9' { + allDigits = false + break } - v, err := strconv.Atoi(s) + } + if allDigits { + v, err := strconv.Atoi(string(raw)) if err != nil || v < 0 { return 0, false } return v, true } - // Reject booleans, objects, arrays, null and decimals - for i := 0; i < len(raw); i++ { - if raw[i] < '0' || raw[i] > '9' { - return 0, false - } + // Reject booleans, objects, arrays, null, and leading non-numeric tokens before float fallback. + if raw[0] < '0' || raw[0] > '9' { + return 0, false + } + f, err := strconv.ParseFloat(string(raw), 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || f < 0 || f >= float64(1<<53) || f != math.Trunc(f) { + return 0, false } - v, err := strconv.Atoi(string(raw)) - if err != nil || v < 0 { + if f > float64(math.MaxInt) { return 0, false } - return v, true + return int(f), true } func intPtr(v int) *int { diff --git a/agenthook/tokens_test.go b/agenthook/tokens_test.go index 345a708..697cfe9 100644 --- a/agenthook/tokens_test.go +++ b/agenthook/tokens_test.go @@ -1,6 +1,7 @@ package agenthook import ( + "encoding/json" "os" "path/filepath" "testing" @@ -151,15 +152,121 @@ func TestAntigravityPostInvocationTranscriptUsage(t *testing.T) { assert.Nil(t, ev.OutputTokens) }) - t.Run("ignores non-jsonl paths and missing files", func(t *testing.T) { + t.Run("sums all completed model steps >= initialNumSteps and deduplicates per step_index", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + lines := "" + + `{"step_index":2,"source":"MODEL","status":"DONE","model_name":"gemini-3.6-flash","input_tokens":900,"output_tokens":90}` + "\n" + + `{"step_index":4,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro","input_tokens":100,"output_tokens":10}` + "\n" + + `{"step_index":4,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro","input_tokens":500,"output_tokens":50,"cache_read_tokens":1000}` + "\n" + + `{"step_index":5,"source":"TOOL","status":"DONE"}` + "\n" + + `{"step_index":6,"step_type":"PLANNER_RESPONSE","status":"DONE","modelName":"gemini-3.1-pro-high","input_tokens":300,"output_tokens":40,"cache_read_tokens":2000,"cache_write_tokens":150,"reasoning_tokens":25}` + "\n" + require.NoError(t, os.WriteFile(transcript, []byte(lines), 0o600)) + stdin := []byte(`{ - "conversationId": "agy-conv-2", - "transcriptPath": "/nonexistent/transcript.db", - "initialNumSteps": 1 + "conversationId": "agy-conv-multi", + "transcriptPath": "` + filepath.ToSlash(transcript) + `", + "initialNumSteps": 4 }`) ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) require.NoError(t, err) - assert.Nil(t, ev.InputTokens) - assert.Nil(t, ev.OutputTokens) + assert.Equal(t, "gemini-3.1-pro-high", ev.Model) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 800, *ev.InputTokens) + require.NotNil(t, ev.OutputTokens) + assert.Equal(t, 90, *ev.OutputTokens) + require.NotNil(t, ev.CacheReadTokens) + assert.Equal(t, 3000, *ev.CacheReadTokens) + require.NotNil(t, ev.CacheCreationTokens) + assert.Equal(t, 150, *ev.CacheCreationTokens) + require.NotNil(t, ev.ReasoningTokens) + assert.Equal(t, 25, *ev.ReasoningTokens) }) + + t.Run("honors finalNumSteps upper bound and scans backwards across chunks", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + var buf []byte + // Write > 64 KiB of earlier steps so backward scanning crosses chunk boundaries. + pad := make([]byte, 2048) + for i := range pad { + pad[i] = 'a' + } + for step := 0; step < 45; step++ { + buf = append(buf, []byte(`{"step_index":0,"source":"USER","status":"DONE","blob":"`)...) + buf = append(buf, pad...) + buf = append(buf, []byte("\"}\n")...) + } + buf = append(buf, []byte(`{"step_index":10,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro","input_tokens":400,"output_tokens":60}`+"\n")...) + buf = append(buf, []byte(`{"step_index":11,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro","input_tokens":200,"output_tokens":30}`+"\n")...) + buf = append(buf, []byte(`{"step_index":12,"source":"MODEL","status":"DONE","model_name":"gemini-3.1-pro","input_tokens":9999,"output_tokens":9999}`+"\n")...) + require.NoError(t, os.WriteFile(transcript, buf, 0o600)) + + stdin := []byte(`{ + "conversationId": "agy-conv-chunks", + "transcriptPath": "` + filepath.ToSlash(transcript) + `", + "initialNumSteps": 10, + "finalNumSteps": 12 + }`) + ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) + require.NoError(t, err) + require.NotNil(t, ev.InputTokens) + assert.Equal(t, 600, *ev.InputTokens) + require.NotNil(t, ev.OutputTokens) + assert.Equal(t, 90, *ev.OutputTokens) + }) + + t.Run("ignores non-jsonl paths, directories, and missing files", func(t *testing.T) { + dir := t.TempDir() + dirNamedJSONL := filepath.Join(dir, "fake.jsonl") + require.NoError(t, os.Mkdir(dirNamedJSONL, 0o700)) + + for _, path := range []string{"/nonexistent/transcript.db", "/nonexistent/transcript.jsonl", dirNamedJSONL} { + stdin := []byte(`{ + "conversationId": "agy-conv-2", + "transcriptPath": "` + filepath.ToSlash(path) + `", + "initialNumSteps": 1 + }`) + ev, err := Normalize("agy", AntigravityPostInvocation, stdin, now, nil) + require.NoError(t, err) + assert.Nil(t, ev.InputTokens) + assert.Nil(t, ev.OutputTokens) + } + assert.Equal(t, "/abs/path.jsonl", expandHomePath("/abs/path.jsonl")) + assert.Contains(t, expandHomePath("~/transcript.jsonl"), "transcript.jsonl") + }) +} + +func TestPayloadNonNegInt(t *testing.T) { + cases := []struct { + name string + raw string + want int + ok bool + }{ + {"plain int", `{"n":42}`, 42, true}, + {"zero", `{"n":0}`, 0, true}, + {"string int", `{"n":"128"}`, 128, true}, + {"integral float", `{"n":1234.0}`, 1234, true}, + {"scientific notation", `{"n":1.2e3}`, 1200, true}, + {"string scientific", `{"n":"2.5e2"}`, 250, true}, + {"fractional float", `{"n":12.5}`, 0, false}, + {"negative", `{"n":-1}`, 0, false}, + {"boolean", `{"n":true}`, 0, false}, + {"null", `{"n":null}`, 0, false}, + {"empty string", `{"n":""}`, 0, false}, + {"non-numeric string", `{"n":"abc"}`, 0, false}, + {"object", `{"n":{}}`, 0, false}, + {"missing", `{}`, 0, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var p payload + require.NoError(t, json.Unmarshal([]byte(tc.raw), &p)) + got, ok := p.nonNegInt("n") + assert.Equal(t, tc.ok, ok) + assert.Equal(t, tc.want, got) + }) + } } diff --git a/docs/CONFIG.md b/docs/CONFIG.md index def3fe4..bae570d 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -341,11 +341,11 @@ You don't need to set it in a Claude Code cloud environment ([cloud.bash](https: ## Cursor and Antigravity Hooks -`shelltime cursor install` and `shelltime agy install` register ShellTime in the native hooks of Cursor (`.cursor/hooks.json`) and Google Antigravity (`.agents/hooks.json`) of the current repository, which is committed: the hooks record only on machines where `shelltime` and `shelltime-daemon` are installed. Each event goes to the daemon, which applies data masking and your exclude patterns before sending it. An event whose shell command matches an exclude pattern is sent without the command, its prompt, tool input, response or error. +`shelltime cursor install` and `shelltime agy install` register ShellTime in the native hooks of Cursor (`.cursor/hooks.json`) and Google Antigravity (`.agents/hooks.json`) of the current repository, which is committed: the hooks record only on machines where `shelltime` and `shelltime-daemon` are installed. Each event goes to the daemon, which applies data masking and your exclude patterns before sending it. An event whose shell command matches an exclude pattern is sent without the command, its prompt, tool input, response or error. Cursor reports per-turn token counts on its `stop` hook; Antigravity's `PostInvocation` hook reads completed model steps from the local `.jsonl` transcript file referenced by `transcriptPath` (silently falling back to activity-only tracking if the file is unavailable or has no matching completed step). | Option | Type | Default | Description | |--------|------|---------|-------------| -| `agentHooks.sendContent` | boolean | `true` | Send the text of prompts, agent responses, tool input and errors, and the paths of files attached to prompts. Off, only the activity is sent: event types, tool names, shell commands, the files tools worked on, the workspace and timing | +| `agentHooks.sendContent` | boolean | `true` | Send the text of prompts, agent responses, tool input and errors, and the paths of files attached to prompts. Off, only the activity and token usage are sent: event types, tool names, shell commands, the files tools worked on, token counts, the workspace and timing | ```yaml agentHooks: From 29936902eeb84d8948021e4089f51a157200e2ce Mon Sep 17 00:00:00 2001 From: Le He <8704175+AnnatarHe@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:54:07 +0000 Subject: [PATCH 3/4] fix(agenthook): stat before open, cheap step_index scan, and omit truncated totals --- agenthook/antigravity_transcript.go | 93 ++++++++++++++++++++++++----- 1 file changed, 78 insertions(+), 15 deletions(-) diff --git a/agenthook/antigravity_transcript.go b/agenthook/antigravity_transcript.go index 988be2c..6148faf 100644 --- a/agenthook/antigravity_transcript.go +++ b/agenthook/antigravity_transcript.go @@ -15,6 +15,9 @@ const ( 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 ( @@ -37,8 +40,8 @@ type antigravityStepUsage struct { // 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, or unmatched -// transcripts are silently ignored so hook recording never fails. +// 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 == "" { @@ -76,9 +79,16 @@ func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload } // 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), -// and stops as soon as a row with step_index < startStep is reached. +// 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) { + // 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) if err != nil { return antigravityStepUsage{}, false @@ -97,36 +107,50 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr 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 || !bytes.Contains(line, antigravityStepIndexNeedle) { - return false - } - // Fast check for non-usage lines that still carry step_index: we only need to stop - // when step_index falls below startStep, so skip full unmarshal when a line has no - // token fields unless we haven't checked its step_index yet. - var row payload - if err := json.Unmarshal(line, &row); err != nil || row == nil { + if len(line) == 0 { return false } - idx, ok := row.nonNegInt("step_index") + idx, ok := extractJSONNonNegInt(line, antigravityStepIndexNeedle) if !ok { return false } if idx < startStep { - return true + consecutiveBelow++ + if consecutiveBelow >= antigravityLowerStepThreshold { + return true + } + // Also stop immediately on a completed model step from an earlier invocation. + if bytes.Contains(line, antigravityTokensNeedle) { + var row payload + if err := json.Unmarshal(line, &row); err == nil && row != nil && isCompletedAntigravityModelStep(row) { + return true + } + } + return false } + consecutiveBelow = 0 + if maxStep >= 0 && idx > maxStep { return false } - if !bytes.Contains(line, antigravityTokensNeedle) || !isCompletedAntigravityModelStep(row) { + if !bytes.Contains(line, antigravityTokensNeedle) { 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 { @@ -202,6 +226,12 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr } } + // 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 } @@ -227,6 +257,39 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr return total, true } +// extractJSONNonNegInt scans a JSON object line for `"key": ` 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 From 1944cb66904c024b0d174f44532f571b3936be0f Mon Sep 17 00:00:00 2001 From: Le He <8704175+AnnatarHe@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:07:25 +0000 Subject: [PATCH 4/4] fix(agenthook): survive single out-of-order lower model row and omitted zero counters --- agenthook/antigravity_transcript.go | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/agenthook/antigravity_transcript.go b/agenthook/antigravity_transcript.go index 6148faf..01dee9b 100644 --- a/agenthook/antigravity_transcript.go +++ b/agenthook/antigravity_transcript.go @@ -22,7 +22,8 @@ const ( var ( antigravityStepIndexNeedle = []byte(`"step_index"`) - antigravityTokensNeedle = []byte(`"input_tokens"`) + antigravityInputNeedle = []byte(`"input_tokens"`) + antigravityOutputNeedle = []byte(`"output_tokens"`) ) type antigravityStepUsage struct { @@ -48,7 +49,10 @@ func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload return } maxStep := -1 - if endStep, ok := firstNonNegInt(p, "finalNumSteps", "numSteps"); ok && endStep > startStep { + if endStep, ok := firstNonNegInt(p, "finalNumSteps", "numSteps"); ok { + if endStep <= startStep { + return + } maxStep = endStep - 1 } @@ -120,24 +124,14 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr } if idx < startStep { consecutiveBelow++ - if consecutiveBelow >= antigravityLowerStepThreshold { - return true - } - // Also stop immediately on a completed model step from an earlier invocation. - if bytes.Contains(line, antigravityTokensNeedle) { - var row payload - if err := json.Unmarshal(line, &row); err == nil && row != nil && isCompletedAntigravityModelStep(row) { - return true - } - } - return false + return consecutiveBelow >= antigravityLowerStepThreshold } consecutiveBelow = 0 if maxStep >= 0 && idx > maxStep { return false } - if !bytes.Contains(line, antigravityTokensNeedle) { + 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. @@ -153,7 +147,7 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr } input, hasInput := row.nonNegInt("input_tokens") output, hasOutput := row.nonNegInt("output_tokens") - if !hasInput || !hasOutput { + if !hasInput && !hasOutput { return false } u := antigravityStepUsage{