hook

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 19 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 hook runs TokenHound as a coding agent pre-tool hook. One Adapter per agent parses the agent's payload into a Proposal (the content the agent wants to run or write) and speaks the agent's hook protocol; one shared policy (Decide) turns the scan of that content into allow, warn or block, so every adapter blocks and warns on exactly the same findings.

The pre-tool hook scans only the proposed content, through the public tokenhound API, as a Reader source. It never reads history, transcripts or other files.

RunSessionEnd is the Claude Code session-end scan: it reads only that session's Claude Code settings files and transcript (tokenhound.SurfaceFiles), reports keys new since its last run on stderr and keeps its state in the user tier (state.go).

Index

Constants

View Source
const (
	// ModeBlock blocks live and high-confidence unverified keys (the default).
	ModeBlock = "block"
	// ModeWarn turns every block into a warning.
	ModeWarn = "warn"
)

Modes of hook.mode.

View Source
const (
	// OnErrorWarnAllow lets the tool call through with a visible warning (the default).
	OnErrorWarnAllow = "warn-allow"
	// OnErrorBlock blocks the tool call on an internal failure.
	OnErrorBlock = "block"
)

Values of hook.on_error.

View Source
const (
	// CodePayloadInvalid: the agent's payload could not be read or parsed.
	CodePayloadInvalid = "payload_invalid"
	// CodeConfigInvalid: the user configuration or a hook flag is invalid.
	CodeConfigInvalid = "config_invalid"
	// CodeInternalPanic: the hook panicked.
	CodeInternalPanic = "internal_panic"
	// CodeScanFailed: the scan failed, did not finish within the backstop, or could
	// not read the whole proposal.
	CodeScanFailed = "scan_failed"
)

Warning codes of internal failures. Messages carry only these, never foreign error text (AD-3).

View Source
const (
	KindBash      = "Bash command"
	KindFileWrite = "file write"
	KindFileEdit  = "file edit"
	KindMCP       = "MCP call"
)

Tool kinds named in messages.

View Source
const (
	// VerifyDeadline ends verification, measured from the start of the scan; keys not
	// verified by then are unknown with status_reason deadline.
	VerifyDeadline = 3 * time.Second
	// Backstop bounds the whole scan; reaching it is a scan_failed internal failure.
	Backstop = 3400 * time.Millisecond
)

Timing of one hook run.

View Source
const (
	// CodeTimeout: the scan was cut short (partial results).
	CodeTimeout = tokenhound.CodeTimeout
	// CodeFileTooLarge: a file was over the size limit and skipped.
	CodeFileTooLarge = tokenhound.CodeFileTooLarge
	// CodeFileUnreadable: a session file exists but was not read (for example a
	// symlink, which is never followed).
	CodeFileUnreadable = tokenhound.CodeFileUnreadable
	// CodeStateInvalid: a state file cannot be parsed, read or written.
	CodeStateInvalid = "state_invalid"
	// CodeTranscriptOutside: the payload's transcript_path is not a .jsonl file under
	// ~/.claude/projects/ (or $CLAUDE_CONFIG_DIR/projects/), so it was not read.
	CodeTranscriptOutside = "transcript_outside_surface"
	// CodeConfigDirRelative: CLAUDE_CONFIG_DIR is set but not an absolute path, so the
	// ~/.claude files were read instead (Claude Code expects an absolute path).
	CodeConfigDirRelative = "config_dir_relative"
)

Warning codes the session-end scan records besides the internal failures (CodePayloadInvalid, CodeConfigInvalid, CodeScanFailed, CodeInternalPanic).

View Source
const (
	// SessionScanTimeout is Options.Timeout of the scan.
	SessionScanTimeout = 4 * time.Second
	// SessionBackstop is when the run returns at the latest, scan finished or not.
	SessionBackstop = 4700 * time.Millisecond
	// SessionMaxFileBytes is the largest file read (a whole transcript included).
	SessionMaxFileBytes = 64 << 20
)

Timing and limits of one session-end run. The whole run returns within 5 seconds.

View Source
const (
	// BaselineStateFile is the baseline v1 file (docs/schema/baseline.v1.json) of the
	// keys the session-end scan already reported.
	BaselineStateFile = "claude-code-baseline.json"
	// LastSessionFile holds the redacted new findings of the session-end scans and the
	// warning codes of the last run; it drives the reminder on the meta line of
	// tokenhound and tokenhound agents.
	LastSessionFile = "last-session-findings.json"
	// LastSessionSchemaVersion is the schema_version of LastSessionFile.
	LastSessionSchemaVersion = 1
)

State files of the Claude Code session-end scan. They live in the user tier, <user config dir>/tokenhound/state/, never in a repository.

View Source
const AgentClaudeCode = "claude-code"

AgentClaudeCode is the agent id of the Claude Code adapter.

View Source
const EventSessionEnd = "SessionEnd"

EventSessionEnd is the Claude Code hook event of the session-end scan.

View Source
const MaxPayloadBytes = 64 << 20

MaxPayloadBytes bounds the payload read from the agent.

Variables

View Source
var ErrState = errors.New("hook: session state file invalid")

ErrState is a state file that exists but cannot be read or parsed, or one that cannot be written. It carries no file content and no foreign error text.

Functions

func DisplayLocation

func DisplayLocation(loc tokenhound.Location, cwd, home string) string

DisplayLocation names a location's file relative to cwd when it is inside cwd, with a "~/" prefix when it is inside home, else by its absolute path; forward slashes, and ":<line>" when the line is known. Symbolic links of cwd and home are resolved too, so a resolved path still reads short.

func ErrorMessage

func ErrorMessage(code string, blocked bool) string

ErrorMessage is the one-line message of an internal failure.

func KeepPending

func KeepPending(dir string, keep func(f SessionFinding) bool) int

KeepPending drops from LastSessionFile in dir every finding for which keep is false (keep sees the stored finding: id and display location), rewriting the file only when something was dropped. It returns how many findings remain. A missing or unreadable file is left alone (0); the file is never created.

func MergeBaseline

func MergeBaseline(prev *tokenhound.Baseline, rep *tokenhound.Report) tokenhound.Baseline

MergeBaseline is prev (nil for none) united with the unsuppressed findings of rep, sorted by id: a key once seen stays known, so a partial scan never makes it new again.

func Message

func Message(d Decision, kind string, rep *tokenhound.Report) string

Message renders the one-line message of a warn or block decision for a proposal of kind, for example "Blocked: this Bash command contains a live OpenAI key (sk-pro...a1b2 (51)). Use $OPENAI_API_KEY instead and keep the key in your shell env or a secret manager." It shows only the redacted form of the key.

func ReadStateBaseline

func ReadStateBaseline(dir string) (*tokenhound.Baseline, error)

ReadStateBaseline reads BaselineStateFile in dir. A missing file gives (nil, nil); one that is not a valid baseline v1 is ErrState.

func Run

func Run(ctx context.Context, a Adapter, in io.Reader, cfg Config) (code int)

Run reads the agent's payload from in, scans the proposal and writes the decision through a. It returns a.ExitCode(). Every internal failure follows cfg.OnError.

func RunSessionEnd

func RunSessionEnd(ctx context.Context, stderr io.Writer, in io.Reader, cfg SessionConfig)

RunSessionEnd runs one Claude Code session-end scan: it reads the SessionEnd payload from in, scans the session's Claude Code files, prints a notice of at most two lines on stderr when keys are new since the last run, and records the state. It never writes stdout and never fails: every failure is one stderr line "TokenHound session scan warning: <code>." and a recorded code. The caller exits 0.

func ScanOptions

func ScanOptions(base tokenhound.Options, agent string, content io.Reader, deadline time.Duration) tokenhound.Options

ScanOptions returns base set up to scan content as the hook does: one Reader source named and targeted "hook:<agent>", inline tokenhound:allow ignored, verification ending at deadline, and no scan timeout of its own (the hook's backstop bounds it).

func SessionNotice

func SessionNotice(fresh []tokenhound.Finding, rep *tokenhound.Report, location func(tokenhound.Finding) string) []string

SessionNotice renders the notice of the new findings fresh (nil when there are none): one line for one key, two lines for more, naming the first in Report order. It shows only redacted keys.

func SessionWarningLine

func SessionWarningLine(code string) string

SessionWarningLine is the stderr line of a session-end failure.

func StateDir

func StateDir(dir string) string

StateDir is the state directory under the user config directory dir.

func WriteLastSession

func WriteLastSession(dir string, ls LastSession) error

WriteLastSession writes ls to LastSessionFile in dir (atomically, mode 0600).

func WriteStateBaseline

func WriteStateBaseline(dir string, b tokenhound.Baseline) error

WriteStateBaseline writes b to BaselineStateFile in dir, encoded as tokenhound baseline writes it.

Types

type Action

type Action int

Action is a policy decision.

const (
	ActionAllow Action = iota
	ActionWarn
	ActionBlock
)

Actions, least severe first.

func Classify

func Classify(f tokenhound.Finding, mode string) Action

Classify applies the policy to one finding. Suppressed findings, and findings the baseline already accepts, are silent. Live keys and high-confidence unverified keys (not-verified, unknown, rate-limited) block; dead keys and lower-confidence unverified keys warn. ModeWarn turns every block into a warning.

func (Action) String

func (a Action) String() string

String returns "allow", "warn" or "block".

type Adapter

type Adapter interface {
	// Name is the agent id, for example "claude-code". The scan target id is
	// "hook:" plus Name.
	Name() string
	// Parse reads the agent's payload and extracts the proposal.
	Parse(r io.Reader) (Proposal, error)
	// Allow lets the call through silently: the agent's own permission flow applies.
	Allow()
	// Warn lets the call through with msg shown to the user. It never grants
	// permission, so the user's own prompt still appears.
	Warn(msg string)
	// Block denies the call with msg.
	Block(msg string)
	// Error reports an internal failure that lets the call through (on_error
	// warn-allow), with msg shown to the user.
	Error(msg string)
	// Notice writes a diagnostic line that is not part of the decision (stderr).
	Notice(msg string)
	// ExitCode is the process exit code after the decision was written.
	ExitCode() int
}

Adapter speaks one agent's hook protocol.

type ClaudeCode

type ClaudeCode struct {
	// contains filtered or unexported fields
}

ClaudeCode is the Claude Code adapter (PreToolUse hook protocol, checked against Claude Code 2.1.325). The hook always exits 0 and answers in JSON on stdout: a block is hookSpecificOutput.permissionDecision "deny" with a reason, a warning is a top-level systemMessage only, and a clean call writes nothing. It never answers "allow", so the user's own permission prompt is never skipped.

func NewClaudeCode

func NewClaudeCode(stdout, stderr io.Writer) *ClaudeCode

NewClaudeCode returns the Claude Code adapter writing to stdout and stderr.

func (*ClaudeCode) Allow

func (c *ClaudeCode) Allow()

Allow writes nothing: the normal permission flow continues.

func (*ClaudeCode) Block

func (c *ClaudeCode) Block(msg string)

Block writes a PreToolUse deny decision with msg as the reason.

func (*ClaudeCode) Error

func (c *ClaudeCode) Error(msg string)

Error is Warn: an internal failure that lets the call through is shown to the user.

func (*ClaudeCode) ExitCode

func (c *ClaudeCode) ExitCode() int

ExitCode is always 0: Claude Code reads the decision from stdout.

func (*ClaudeCode) Name

func (c *ClaudeCode) Name() string

Name returns "claude-code".

func (*ClaudeCode) Notice

func (c *ClaudeCode) Notice(msg string)

Notice writes msg as one line on stderr.

func (*ClaudeCode) Parse

func (c *ClaudeCode) Parse(r io.Reader) (Proposal, error)

Parse reads a PreToolUse payload and extracts the proposed content: the Bash command, the Write content, the Edit new_string, every MultiEdit new_string, the NotebookEdit new_source, or every string value of an MCP tool's input. Other tools give a Proposal without Kind.

func (*ClaudeCode) Warn

func (c *ClaudeCode) Warn(msg string)

Warn writes a top-level systemMessage, shown to the user, and no decision.

type Config

type Config struct {
	// Mode is ModeBlock (also when empty) or ModeWarn.
	Mode string
	// OnError is OnErrorWarnAllow (also when empty) or OnErrorBlock.
	OnError string
	// ConfigInvalid makes the run a config_invalid failure before anything is read.
	ConfigInvalid bool
	// Notices are written through Adapter.Notice before the decision.
	Notices []string
	// Options are the base scan options (from config); Run sets the source, the
	// verify deadline and NoInlineAllow (see ScanOptions).
	Options tokenhound.Options
	// Scan runs the scan.
	Scan ScanFunc
	// Backstop replaces the Backstop constant when positive (tests).
	Backstop time.Duration
	// VerifyDeadline replaces the VerifyDeadline constant when positive (tests).
	VerifyDeadline time.Duration
}

Config configures one hook run.

type Decision

type Decision struct {
	Action Action
	// Finding is the most severe acting finding (nil for allow).
	Finding *tokenhound.Finding
	// More counts the other findings that warn or block.
	More int
}

Decision is the outcome of the policy for one Report.

func Decide

func Decide(rep *tokenhound.Report, mode string) Decision

Decide applies the policy to every finding of rep. The decision names the most severe finding: block before warn, then live before other statuses, then Report order.

type LastSession

type LastSession struct {
	SchemaVersion int              `json:"schema_version"`
	SessionID     string           `json:"session_id"`
	ScannedAt     string           `json:"scanned_at"`
	Findings      []SessionFinding `json:"findings"`
	Warnings      []string         `json:"warnings"`
}

LastSession is the content of LastSessionFile. It holds only ids, provider ids, statuses, redacted keys and display locations, never a key.

func ReadLastSession

func ReadLastSession(dir string) (ls LastSession, ok bool, err error)

ReadLastSession reads LastSessionFile in dir. ok is false when the file is missing; a file that cannot be parsed, or holds a malformed id, is ErrState.

type Proposal

type Proposal struct {
	// Tool is the agent's tool name, for example "Bash" or "mcp__github__create_issue".
	Tool string
	// Kind is the tool kind named in messages (KindBash, ...); empty means the tool
	// is not one the hook checks, and the call is allowed without a scan.
	Kind string
	// Content is the proposed content to scan: only what the call would run or write.
	Content string
}

Proposal is what an agent proposes to do.

type ScanFunc

type ScanFunc func(ctx context.Context, opts tokenhound.Options) (*tokenhound.Report, error)

ScanFunc runs one scan with opts and returns its final Report.

type SessionConfig

type SessionConfig struct {
	// Disabled (hook.session_scan false) makes the run do nothing.
	Disabled bool
	// ConfigInvalid makes the run a config_invalid failure before anything is read.
	ConfigInvalid bool
	// Options are the base scan options (user tier and environment only).
	Options tokenhound.Options
	// Scan runs the scan.
	Scan ScanFunc
	// Home is the user's home directory.
	Home string
	// ClaudeDir is Claude Code's configuration directory (<home>/.claude, or the one
	// CLAUDE_CONFIG_DIR names); the transcript must lie under its projects/. Empty
	// means <Home>/.claude.
	ClaudeDir string
	// ConfigDirRelative: CLAUDE_CONFIG_DIR is set but not an absolute path, so
	// ClaudeDir is <Home>/.claude; the run records CodeConfigDirRelative.
	ConfigDirRelative bool
	// HomeFiles are the literal machine paths of the claude-code surface.
	HomeFiles []string
	// StateDir is the state directory (StateDir of the user config directory); empty
	// when it is unknown, so nothing can be recorded.
	StateDir string
	// Now is the clock of scanned_at (time.Now when nil).
	Now func() time.Time
	// Backstop, Timeout and VerifyDeadline replace SessionBackstop,
	// SessionScanTimeout and VerifyDeadline when positive (tests).
	Backstop, Timeout, VerifyDeadline time.Duration
}

SessionConfig configures one session-end run.

type SessionFinding

type SessionFinding struct {
	ID       string `json:"id"`
	Provider string `json:"provider"`
	Status   string `json:"status"`
	Redacted string `json:"redacted"`
	Location string `json:"location"`
}

SessionFinding is one new finding of a session-end scan.

func PendingFindings

func PendingFindings(dir string) []SessionFinding

PendingFindings returns the findings of LastSessionFile in dir; nil when the file is missing or cannot be read (the reminder is silent on read errors).

type SessionPayload

type SessionPayload struct {
	SessionID      string `json:"session_id"`
	TranscriptPath string `json:"transcript_path"`
	Cwd            string `json:"cwd"`
	// Reason is why the session ended (clear, resume, logout, prompt_input_exit,
	// other); it does not change the scan.
	Reason string `json:"reason"`
}

SessionPayload is the part of a Claude Code SessionEnd payload the scan reads.

func ParseSessionEnd

func ParseSessionEnd(r io.Reader) (SessionPayload, error)

ParseSessionEnd reads a Claude Code SessionEnd payload. hook_event_name must be "SessionEnd".

type SessionPlan

type SessionPlan struct {
	// Settings are the Claude Code settings files: the user's, then the project's under
	// the payload cwd (missing files are skipped by the scan).
	Settings []string
	// Transcript is the session's transcript, resolved; empty when it is not read.
	Transcript string
	// Warnings are recorded warning codes (CodeTranscriptOutside).
	Warnings []string
}

SessionPlan is what one session-end run reads.

func PlanSessionFiles

func PlanSessionFiles(claudeDir string, homeFiles []string, p SessionPayload) SessionPlan

PlanSessionFiles decides the files of one run: homeFiles (the literal machine paths of the claude-code surface), <cwd>/.claude/settings.local.json and <cwd>/.claude/settings.json when cwd is an absolute directory, and the transcript when it is an absolute .jsonl path that, symlinks resolved, lies under <claudeDir>/projects/ (claudeDir is ~/.claude or CLAUDE_CONFIG_DIR). Nothing else is read.

Jump to

Keyboard shortcuts

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