agenthook

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const (
	EventPreToolUse = "PreToolUse"
	EventSessionEnd = "SessionEnd"
)

Event names of the Claude Code hooks TokenHound installs.

View Source
const (
	FieldCommand   = "command"
	FieldMatcher   = "matcher"
	FieldTimeout   = "timeout"
	FieldDuplicate = "duplicate"
)

Fields an Updated change can name.

View Source
const (
	ClaudeCodeSettingsSurface   = "claude-code"
	ClaudeCodeTranscriptSurface = "claude-code-transcripts"
)

ClaudeCodeSettingsSurface and ClaudeCodeTranscriptSurface are the registry surface ids the SessionEnd scan reads its files with.

View Source
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.

View Source
const ClaudeConfigDirEnv = surface.ClaudeConfigDirEnv

ClaudeConfigDirEnv is the variable that moves Claude Code's user configuration (see surface.ClaudeConfigDirEnv).

View Source
const Program = "tokenhound"

Program is the bare program name used when no lasting tokenhound binary is found.

View Source
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

View Source
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.

View Source
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, or those files under CLAUDE_CONFIG_DIR when getenv sets it.

func ClaudeCodeFound

func ClaudeCodeFound(claudeDir string, paths []string) bool

ClaudeCodeFound reports whether Claude Code is installed for the user: claudeDir (from ClaudeDir) 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 ClaudeDir added in v1.0.0

func ClaudeDir(goos, home string, getenv func(string) string) (dir string, moved bool)

ClaudeDir returns Claude Code's user configuration directory as an OS path: the directory CLAUDE_CONFIG_DIR names when it is set to an absolute path (see surface.ClaudeConfigDirEnv for how Claude Code resolves it), else <home>/.claude. moved reports the first case.

func DisplayFile added in v1.0.0

func DisplayFile(abs, home, goos string) string

DisplayFile names the OS path abs for output: "~/..." when it lies below home, else abs with forward slashes.

func Ephemeral

func Ephemeral(p string) bool

Ephemeral reports whether p lies in a package runner cache.

func FindOnPath

func FindOnPath(pathList, name string) []string

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

func InstallLines(t Target, res Result) []string

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

func Quote(p string) string

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

func ResolveCommand(exe string, onPath []string) (command string, missing bool)

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 ResolveProgram added in v1.0.0

func ResolveProgram(exe string, onPath []string) string

ResolveProgram is the unquoted path ResolveCommand chooses, or "" when it falls back to the bare Program.

func UninstallLines

func UninstallLines(t Target, res Result) []string

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

func WithoutEvent(entries []Entry, event string) []Entry

WithoutEvent returns entries without the entries of event (for --no-session-scan).

func (Entry) Owns

func (e Entry) Owns(command string) bool

Owns reports whether command is this entry's TokenHound command.

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

type MalformedError struct {
	Line, Col int
	Problem   string
}

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

func Install(path string, entries []Entry, command string) (Result, error)

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.

func Uninstall

func Uninstall(path string, entries []Entry) (Result, error)

Uninstall removes every TokenHound hook of entries from the settings file at path, and the hook groups, event lists and hooks object it leaves empty. A missing file, or one without TokenHound hooks, is not written.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL