Documentation
¶
Overview ¶
Package agenthook installs and uninstalls TokenHound's coding agent hooks in the agent's own settings file (Claude Code's settings.json today).
The hooks TokenHound manages are data: a list of Entry values, one per agent event. Install, uninstall and the idempotency check loop over that list, so a new managed hook (Story 3.10's session-end entry) is one more Entry and no new code.
Settings are edited through an order-preserving JSON tree: object keys keep their order, scalars keep their literal bytes and a subtree TokenHound did not touch is written back exactly as it was read. Only the containers on the path of a change are re-rendered, in the file's own indent and newline style, so uninstall gives back the file's pre-install bytes. Writes are atomic (a temporary file plus a rename) and a run that changes nothing writes nothing.
Index ¶
- Constants
- Variables
- func ClaudeCodeFiles(reg *registry.Registry, goos, home string, getenv func(string) string) []string
- func ClaudeCodeFound(home string, paths []string) bool
- func ClaudeCodePaths(reg *registry.Registry, goos, home string, getenv func(string) string) []string
- func Ephemeral(p string) bool
- func FindOnPath(pathList, name string) []string
- func InstallLines(t Target, res Result) []string
- func MalformedLine(file string, e *MalformedError) string
- func Quote(p string) string
- func ResolveCommand(exe string, onPath []string) (command string, missing bool)
- func UninstallLines(t Target, res Result) []string
- type Change
- type Entry
- type Kind
- type MalformedError
- type Result
- type Target
Constants ¶
const ( EventPreToolUse = "PreToolUse" EventSessionEnd = "SessionEnd" )
Event names of the Claude Code hooks TokenHound installs.
const ( FieldCommand = "command" FieldMatcher = "matcher" FieldTimeout = "timeout" FieldDuplicate = "duplicate" )
Fields an Updated change can name.
const ( ClaudeCodeSettingsSurface = "claude-code" ClaudeCodeTranscriptSurface = "claude-code-transcripts" )
ClaudeCodeSettingsSurface and ClaudeCodeTranscriptSurface are the registry surface ids the SessionEnd scan reads its files with.
const ( // NotFoundLine: no Claude Code on this machine and no --force (exit 2). NotFoundLine = "Claude Code not found: no hook installed." // NotRepoLine: --project outside a git work tree (exit 2). NotRepoLine = "Not in a git repo: no Claude Code project hook installed." // NotOnPathLine: the running binary is in a package runner cache and no other // tokenhound is on PATH, so the hook runs the bare name (stderr, exit 0). NotOnPathLine = "Warning: tokenhound is not on PATH; install it so the hook keeps working" )
Fixed one-line messages of the Claude Code install verbs.
const Program = "tokenhound"
Program is the bare program name used when no lasting tokenhound binary is found.
const SessionEndTimeout = 10
SessionEndTimeout is the timeout of the SessionEnd hook in seconds. Claude Code gives SessionEnd hooks 1.5 seconds unless a hook sets a longer timeout (docs/adr/0005-claude-code-session-end-hook.md); the run itself ends within 5.
Variables ¶
var ( ErrRead = errors.New("agenthook: the settings file cannot be read") ErrWrite = errors.New("agenthook: the settings file cannot be written") )
Errors of reading and writing the settings file. They carry no file content and no foreign error text.
var EphemeralMarkers = []*regexp.Regexp{ regexp.MustCompile(`/_npx/`), regexp.MustCompile(`/pipx/\.cache/`), regexp.MustCompile(`/\.cache/uv/`), regexp.MustCompile(`/uv/cache/`), regexp.MustCompile(`/uv/archive-v`), regexp.MustCompile(`/pnpm/dlx/`), regexp.MustCompile(`/bunx-`), regexp.MustCompile(`/go-build[0-9]+/`), }
EphemeralMarkers match the paths (forward slashes, lower case) of package runner caches. A binary under one of them can be deleted at any time, so a hook must not point at it.
Functions ¶
func ClaudeCodeFiles ¶
func ClaudeCodeFiles(reg *registry.Registry, goos, home string, getenv func(string) string) []string
ClaudeCodeFiles resolves the literal (non-glob) machine-tier paths of the claude-code surface in reg for goos and home: ~/.claude/settings.json, ~/.claude/settings.local.json and ~/.claude.json on every OS today.
func ClaudeCodeFound ¶
ClaudeCodeFound reports whether Claude Code is installed for the user at home: ~/.claude is a directory or one of paths (from ClaudeCodePaths) exists.
func ClaudeCodePaths ¶
func ClaudeCodePaths(reg *registry.Registry, goos, home string, getenv func(string) string) []string
ClaudeCodePaths resolves the machine-tier paths of the Claude Code surfaces in reg for goos and home (the literal file or directory each pattern starts at).
func FindOnPath ¶
FindOnPath returns every executable called name in the directories of pathList (a PATH value), as absolute paths in PATH order. Relative and empty entries are skipped, so the current directory is never searched.
func InstallLines ¶
InstallLines renders an install Result: one line for the file changed then the Undo line, or one Already installed line per entry when nothing changed.
func MalformedLine ¶
func MalformedLine(file string, e *MalformedError) string
MalformedLine is the one line printed for a *MalformedError (exit 2). It names the file and a position or a settings key, never file content.
func Quote ¶
Quote returns p as it is when the shell reads it as one plain word, else in double quotes with ", \, $ and backtick escaped.
func ResolveCommand ¶
ResolveCommand chooses the program a hook runs: exe (the running binary, symlinks resolved) unless it is in a package runner cache, else the first of onPath (the absolute tokenhound paths found on PATH, in order) outside a cache, else the bare Program. missing reports the last case, where the caller warns that tokenhound is not on PATH. When an entry of onPath outside a cache is the same file as exe (a Homebrew, asdf, mise or nix link into a versioned directory), that entry is used, so the hook survives an upgrade. A path is quoted for the shell when it needs it.
func UninstallLines ¶
UninstallLines renders an uninstall Result: one line per entry removed, or Not installed.
Types ¶
type Change ¶
type Change struct {
Entry Entry
Kind Kind
// Field is set for Updated: FieldCommand, FieldMatcher, FieldTimeout or
// FieldDuplicate (the first that applies, in this order).
Field string
}
Change is the outcome for one entry.
type Entry ¶
type Entry struct {
Event string
Matcher string
Args string
// Summary completes "added the <Event> hook that ..." in install output.
Summary string
// When completes "runs tokenhound <Args> ..." in the Already installed line.
When string
// Timeout is the hook's "timeout" in seconds, written after "command"; 0 writes
// no timeout key (and leaves one the user set alone).
Timeout int
}
Entry is one hook TokenHound manages in an agent's settings: the agent event it runs on, the tool matcher (empty for events without one) and the arguments after the tokenhound command. A hook belongs to TokenHound when its command is a non-empty program followed by a space and Args, so a --command value or a moved binary is still recognised.
func ClaudeCodeEntries ¶
func ClaudeCodeEntries() []Entry
ClaudeCodeEntries are the hooks TokenHound installs in Claude Code settings: the PreToolUse check of proposed tool calls and the SessionEnd scan of the session's Claude Code files.
func WithoutEvent ¶
WithoutEvent returns entries without the entries of event (for --no-session-scan).
type Kind ¶
type Kind int
Kind is what install or uninstall did with one entry.
const ( // Added: the entry was not there and a new hook group was appended. Added Kind = iota + 1 // Updated: a TokenHound hook was rewritten in place (Field says what changed). Updated // Already: the entry is present with the same matcher and command. Already // Removed: uninstall removed the entry's TokenHound hooks. Removed // NotInstalled: uninstall found no TokenHound hook for the entry. NotInstalled )
Change kinds.
type MalformedError ¶
MalformedError is a settings file TokenHound cannot change safely. Line and Col are set for invalid JSON; Problem is fixed text naming at most a settings key.
func (*MalformedError) Error ¶
func (e *MalformedError) Error() string
type Result ¶
type Result struct {
// Created: the settings file did not exist and was written.
Created bool
// Wrote: the file was written (false when nothing changed).
Wrote bool
Changes []Change
}
Result is the outcome of one install or uninstall.
func Install ¶
Install adds every entry to the settings file at path, running command (the tokenhound program, already quoted) with the entry's Args. A missing file is created (mode 0600, its directory 0700). When every entry is already installed nothing is written. Errors are *MalformedError, ErrRead or ErrWrite; on error the file is unchanged.
type Target ¶
type Target struct {
// File is the display path, forward slashes ("~/.claude/settings.json").
File string
// Where is File with any qualifier, for install lines (".claude/settings.json
// (project settings in this repo)"); File when empty.
Where string
// Undo is the command that removes the hooks again.
Undo string
}
Target names a settings file in output.