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
2 changes: 1 addition & 1 deletion CLAUDE.md

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,18 @@ Besides tokens and cost, both tools then send your prompts, tool details (shell

Cursor and Google Antigravity have no OpenTelemetry export, so ShellTime reads their native hooks instead: the agent runs `shelltime hook-ingest` for each event with the event's JSON on stdin, and ShellTime answers with the reply that lets the agent carry on. It never blocks, denies or changes anything the agent does.

The hooks go into each project's repository, the only place the agents' cloud runs read them from (Cursor Cloud Agents never read `~/.cursor/hooks.json`, and Antigravity runs a workspace's hooks ahead of its global file). Run the install in the repository, then commit the file:
The hooks go into each project's repository by default, the only place the agents' cloud runs read them from (Cursor Cloud Agents never read `~/.cursor/hooks.json`, and the Antigravity agent's Gemini API sandbox reads only the repository's `.agents/hooks.json`). Run the install in the repository, then commit the file:

- **Cursor**: `shelltime cursor install` registers `beforeSubmitPrompt`, `postToolUse`, `postToolUseFailure`, `afterAgentResponse`, `stop`, `sessionStart` and `sessionEnd` in `.cursor/hooks.json` at the repository's root. Your other hooks stay as they are.
- **Antigravity**: `shelltime agy install` adds a `shelltime` hook group (`SessionStart`, `PreInvocation`, `PostToolUse`, `PostInvocation`, `Stop`) to `.agents/hooks.json` at the repository's root. Antigravity ignores the whole file when it isn't strict JSON, so a file with comments, trailing commas or a byte order mark is left alone with an error, never rewritten.

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).
Outside a repository the current folder counts as the project, but never your home folder.

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.
To track every folder on this machine instead, add `--global`: `shelltime cursor install --global` writes `~/.cursor/hooks.json`, and `shelltime agy install --global` writes a `shelltime-global` group to `~/.gemini/config/hooks.json`, both of which the agent runs wherever you open it. Nothing is committed, and the cloud runs above don't read these files, so a repository whose cloud agents you want tracked still needs its own hooks. You can have both: a repository's hooks leave events to the global ones, so nothing is counted twice. `--global` also rewrites the hooks older versions put in those files (which named the `shelltime` binary by its path) into the self-contained command below.

`uninstall` takes ShellTime out of the repository's file and the global one; `uninstall --global` only out of the global one. 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), 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` checks the global hook files and, run in a repository, the repository's, 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).

Expand Down
2 changes: 1 addition & 1 deletion agenthook/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ type Event struct {
Metadata map[string]any `json:"metadata,omitempty"`

// YieldToUserHooks travels from hook-ingest to the daemon only, never to the server: the
// event came from a project's hook while an older version's user-level hook records it too,
// event came from a project's hook while the agent's user-level (global) hook records it too,
// so the daemon drops it unless the session is a cloud run (whose agent runs no user-level
// hooks), which only the daemon remembers across events.
YieldToUserHooks bool `json:"yield_to_user_hooks,omitempty"`
Expand Down
128 changes: 122 additions & 6 deletions commands/agent_hooks_cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,23 @@ func TestCursorInstallAndUninstallCommands(t *testing.T) {
path := filepath.Join(repo, ".cursor", "hooks.json")
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0755))
require.NoError(t, os.WriteFile(path, []byte(`{"version":1,"hooks":{"stop":[{"command":"say done"}]}}`), 0644))
// What an older version installed in the user's own file
// What an older version installed in the user's own file, first with its binary gone, which
// records nothing
userPath := filepath.Join(home, ".cursor", "hooks.json")
installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "/usr/local/bin/shelltime")
installUserHooksFor(t, userPath, "cursor", []string{"stop"}, filepath.Join(home, "gone", "shelltime"))
app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}}

out := captureColor(t)
require.NoError(t, app.Run([]string{"t", "cursor", "install"}))
assert.NotContains(t, stripANSI(out.String()), "keep recording your other folders")

installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "")
out.Reset()
require.NoError(t, app.Run([]string{"t", "cursor", "install"}))
text := stripANSI(out.String())
assert.Contains(t, text, "Cursor hooks installed in "+path)
assert.Contains(t, text, "The ShellTime hooks an older version put in "+userPath+" stay and keep recording your other folders")
assert.Contains(t, text, "`shelltime cursor uninstall` removes both.")
assert.Contains(t, text, "The ShellTime hooks in "+userPath+" keep recording your other folders")
assert.Contains(t, text, "nothing is counted twice. `shelltime cursor uninstall` removes both.")
assert.Contains(t, text, "Commit it: Cursor Cloud Agents run only the hooks in the repository.")
assert.Contains(t, text, "Restart Cursor")
assert.Contains(t, text, "SHELLTIME_CLOUD=true")
Expand Down Expand Up @@ -104,8 +110,118 @@ func TestCursorInstallCommand_RefusesTheHomeFolder(t *testing.T) {
out := captureColor(t)
err := app.Run([]string{"t", "cursor", "install"})
assert.ErrorIs(t, err, model.ErrHomeIsNotAProject)
assert.Contains(t, stripANSI(out.String()), "Failed to find the project")
assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json"), "Cursor's user-level file is never written")
text := stripANSI(out.String())
assert.Contains(t, text, "Failed to find the project")
assert.Contains(t, text, "To track Cursor in every folder on this machine, run `shelltime cursor install --global`.")
assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json"), "Cursor's user-level file isn't written without --global")
}

func TestCursorInstallCommand_Global(t *testing.T) {
home, repo := setupAgentHooksCommand(t)
t.Chdir(home)
userPath := filepath.Join(home, ".cursor", "hooks.json")
// What an older version installed there, next to the user's own hook
installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "/usr/local/bin/shelltime")
var file map[string]any
require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &file))
file["hooks"].(map[string]any)["stop"] = append([]any{map[string]any{"command": "say done"}}, file["hooks"].(map[string]any)["stop"].([]any)...)
data, err := json.Marshal(file)
require.NoError(t, err)
require.NoError(t, os.WriteFile(userPath, data, 0644))
app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}}

out := captureColor(t)
require.NoError(t, app.Run([]string{"t", "cursor", "install", "--global"}))
text := stripANSI(out.String())
assert.Contains(t, text, "Cursor hooks installed in "+userPath)
assert.Contains(t, text, "They record Cursor in every folder on this machine")
assert.Contains(t, text, "Cursor Cloud Agents run only a repository's .cursor/hooks.json")
assert.Contains(t, text, "Restart Cursor")
assert.Contains(t, text, "Privacy: the Cursor hooks send your prompts")
assert.NotContains(t, text, "Commit it", "nothing to commit")

status, err := model.NewCursorHooksService().Status()
require.NoError(t, err)
assert.Empty(t, status.MissingEvents)
assert.Equal(t, agenthook.CursorEvents, status.GlobalEvents)
assert.Equal(t, []string{model.ProjectHookCLI}, status.Binaries, "the older version's absolute path is replaced")
require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &file))
stop := file["hooks"].(map[string]any)["stop"].([]any)
require.Len(t, stop, 2)
assert.Equal(t, "say done", stop[0].(map[string]any)["command"], "the user's own hook stays first")
assert.Equal(t, model.CursorGlobalHookCommand("stop"), stop[1].(map[string]any)["command"])

// Both can be installed; --global uninstall leaves the repository's file
t.Chdir(repo)
out.Reset()
require.NoError(t, app.Run([]string{"t", "cursor", "install"}))
assert.Contains(t, stripANSI(out.String()), "The ShellTime hooks in "+userPath+" keep recording your other folders")
out.Reset()
require.NoError(t, app.Run([]string{"t", "cursor", "uninstall", "-g"}))
assert.Contains(t, stripANSI(out.String()), "Cursor hooks removed from "+userPath)
status, err = model.NewCursorHooksService().Status()
require.NoError(t, err)
assert.False(t, status.Present)
assert.JSONEq(t, `{"version":1,"hooks":{"stop":[{"command":"say done"}]}}`, string(mustReadFile(t, userPath)))
projectStatus, err := model.NewCursorProjectHooksService(repo).Status()
require.NoError(t, err)
assert.True(t, projectStatus.Installed, "the repository's hooks stay")

out.Reset()
require.NoError(t, app.Run([]string{"t", "cursor", "uninstall", "--global"}))
assert.Contains(t, stripANSI(out.String()), "No ShellTime hooks for Cursor to remove in "+userPath)
}

func TestCursorInstallCommand_GlobalRefusesWindows(t *testing.T) {
home, _ := setupAgentHooksCommand(t)
orig := agentHooksGOOS
agentHooksGOOS = "windows"
t.Cleanup(func() { agentHooksGOOS = orig })
app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}}

captureColor(t)
assert.ErrorIs(t, app.Run([]string{"t", "cursor", "install", "--global"}), model.ErrProjectHooksUnsupported)
assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json"))
}

func TestCursorUninstallCommand_GlobalInvalidFileIsAnError(t *testing.T) {
home, _ := setupAgentHooksCommand(t)
userPath := filepath.Join(home, ".cursor", "hooks.json")
require.NoError(t, os.MkdirAll(filepath.Dir(userPath), 0755))
require.NoError(t, os.WriteFile(userPath, []byte(`{"hooks":`), 0644))
app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}}

out := captureColor(t)
assert.ErrorIs(t, app.Run([]string{"t", "cursor", "uninstall", "--global"}), model.ErrHookFileInvalid)
assert.Contains(t, stripANSI(out.String()), "Failed to remove the Cursor hooks from "+userPath)
}

func TestAgyInstallCommand_Global(t *testing.T) {
home, _ := setupAgentHooksCommand(t)
userPath := filepath.Join(home, ".gemini", "config", "hooks.json")
require.NoError(t, os.MkdirAll(filepath.Dir(userPath), 0755))
// An older version's group between two of the user's
require.NoError(t, os.WriteFile(userPath, []byte(`{"a":{},"shelltime":{"Stop":[{"type":"command","command":"/usr/local/bin/shelltime hook-ingest --agent agy --event Stop","timeout":15}]},"z":{}}`), 0644))
app := &cli.App{Name: "t", Commands: []*cli.Command{AgyCommand}}

out := captureColor(t)
require.NoError(t, app.Run([]string{"t", "agy", "install", "--global"}))
text := stripANSI(out.String())
assert.Contains(t, text, "Antigravity hooks installed in "+userPath)
assert.Contains(t, text, "They record Antigravity in every folder on this machine")
assert.Contains(t, text, "Gemini API sandbox reads only a repository's .agents/hooks.json")
assert.Contains(t, text, "Privacy: the Antigravity hooks send")

var root map[string]json.RawMessage
require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &root))
assert.NotContains(t, root, model.AntigravityHookGroup, "the older version's group is replaced")
assert.Contains(t, root, model.AntigravityGlobalHookGroup)
status, err := model.NewAntigravityHooksService().Status()
require.NoError(t, err)
assert.Equal(t, agenthook.AntigravityEvents, status.GlobalEvents)

require.NoError(t, app.Run([]string{"t", "agy", "uninstall", "--global"}))
assert.JSONEq(t, `{"a":{},"z":{}}`, string(mustReadFile(t, userPath)))
}

func TestCursorUninstallCommand_OutsideAProjectCleansTheUserFile(t *testing.T) {
Expand Down
Loading
Loading