Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions agenthook/antigravity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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 👍 / 👎.

case strings.ToLower(AntigravityStop):
ev.EventType = EventStop
ev.Status = p.str("terminationReason")
Expand Down
309 changes: 309 additions & 0 deletions agenthook/antigravity_transcript.go
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 {

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.

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).

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.

// 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.

// 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)

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.

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 {

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.

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,

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.

}
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 {

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.

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 {

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.

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.

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

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.

}
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

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 👍 / 👎.


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

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.

}

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.

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
}
Loading
Loading