Documentation
¶
Overview ¶
Package cli houses entry points for the AI-agent hooks domain: `hooks install`, `hooks uninstall`, and the hidden `_hook` runtime.
The runtime entry point intentionally lives outside internal/cli so the hot path can bypass cli.Parse and logger construction — agents invoke `_hook` on every event and a non-zero exit is treated as a hook failure / block. RunHook calls config.Load itself for the upload gate; the bypass is everything else in main's startup path. Fail-open is a hard contract enforced here.
Index ¶
- Constants
- Variables
- func AppendError(stage, code, message, eventID string)
- func ChownToTarget(exec executor.Executor, paths []string, target TargetUser)
- func ErrorLogPath() string
- func Resolve() (string, error)
- func RunHook(stdin io.Reader, stdout, stderr io.Writer, args []string) int
- func RunInstall(ctx context.Context, exec executor.Executor, agent string, ...) int
- func RunUninstall(ctx context.Context, exec executor.Executor, agent string, ...) int
- type ErrorEntry
- type TargetUser
Constants ¶
const ErrorLogFilename = "ai-agent-hook-errors.jsonl"
ErrorLogFilename is the basename of the per-user errors log. It lives directly under ~/.stepsecurity/.
const MaxErrorLogBytes = 5 * 1024 * 1024
MaxErrorLogBytes triggers a truncate-and-restart before each append. At 5 MiB, individual entries < 4 KiB remain atomic on POSIX `O_APPEND` writes without advisory locks.
Variables ¶
var SupportedAgents = []string{ claudecode.AgentName, codex.AgentName, }
SupportedAgents is the canonical list of agent names accepted by `--agent`. Order matters for user-facing diagnostics (the `unsupported agent` error lists them in this order) and for the default fan-out in selectAdapters.
Adding a new agent means: append here, add a case in adapterForAgent, add the constructor case in allAdapters, and add the adapter package. No other changes are needed in this layer.
Functions ¶
func AppendError ¶
func AppendError(stage, code, message, eventID string)
AppendError writes a single JSONL entry to the errors log. The call is best-effort: any failure (no $HOME, mkdir denied, marshal error, open denied, partial write) is silently dropped — the hot path's allow response must never be blocked by logging.
The message is run through redact.String before being written to disk so a stray secret in an error message never lands in the on-disk log.
func ChownToTarget ¶
func ChownToTarget(exec executor.Executor, paths []string, target TargetUser)
ChownToTarget chowns each path to the target user's UID/GID. It's a best-effort helper: any individual chown failure is logged to the errors file and the loop continues — an unchown'd file is still a working install, just one the target user can't tidy up themselves.
No-op on Windows (chown is a Unix concept) and when the caller is not root (chown to a different UID requires CAP_CHOWN). Empty paths in the slice are skipped silently so callers can pass `WriteResult.BackupPath` without first checking for "".
func ErrorLogPath ¶
func ErrorLogPath() string
ErrorLogPath returns the absolute path of the errors log for the current user (or the test override). Exposed for diagnostics paths that want to surface the location to the user.
func Resolve ¶
Resolve returns the absolute, fully symlink-resolved path of the running DMG binary. The result is what `hooks install` writes into agent settings as the hook command prefix.
Symlinks are evaluated so the recorded path is canonical — Homebrew, for example, installs binaries under `/opt/homebrew/Cellar/...` and links `/opt/homebrew/bin/<name>` to them. Recording the Cellar path means a `brew upgrade` that swaps the symlink target still leaves a valid hook command (until the Cellar path itself is removed).
On Windows, EvalSymlinks resolves directory junctions and reparse points the same way it resolves Unix symlinks.
func RunHook ¶
RunHook is the hidden `_hook <agent> <event>` entry point.
Contract (enforced by hook_test.go and main_test.go):
- returns 0 on every code path, including malformed args, unknown agents, unparseable stdin, and internal panics
- writes nothing to stdout unless emitting a valid agent-allow response
- writes nothing to stderr on the success path
args is os.Args[2:] — i.e., everything after the `_hook` verb. Two positional args are required (agent, hookEvent) and any additional or missing args fail-open silently.
func RunInstall ¶
func RunInstall(ctx context.Context, exec executor.Executor, agent string, stdout, stderr io.Writer) int
RunInstall is the entry point for `hooks install`.
agent is the --agent flag value; "" means "every detected agent". stdout/stderr are the writers main wires from os.Stdout/os.Stderr.
Returns the desired process exit code:
- 0 on success, idempotent no-op, no agents detected, or the root-with-no-console-user no-op.
- 1 on enterprise-config gate failure, self-path resolution failure, unsupported --agent, or any adapter Install error.
Flow:
- enterprise-config gate (all three credentials present and non-placeholder)
- resolve target user (root + no console user → log + exit 0)
- resolve absolute, symlink-resolved DMG binary path
- select adapters per --agent or detection on $PATH
- per-adapter Install, then chown all outputs to target user under root
- emit per-adapter summary to stdout
Adapter Install errors don't abort the loop — the remaining adapters still get a chance. The aggregate exit code is 1 if any adapter failed.
func RunUninstall ¶
func RunUninstall(ctx context.Context, exec executor.Executor, agent string, stdout, stderr io.Writer) int
RunUninstall is the entry point for `hooks uninstall`.
agent is the --agent flag value; "" means "every detected agent". stdout/stderr are wired from os.Stdout/os.Stderr by main.
Returns the desired process exit code:
- 0 on success, no-op (no DMG-owned entries found), no agents detected, or the root-with-no-console-user no-op.
- 1 on self-path resolution failure, unsupported --agent, or any adapter Uninstall error.
Flow:
- resolve target user (root + no console user → log + exit 0)
- resolve absolute, symlink-resolved DMG binary path (the uninstall matcher needs it to identify DMG-owned entries)
- select adapters per --agent or detection on $PATH
- per-adapter Uninstall, then chown rewritten outputs to target user under root
- emit per-adapter summary to stdout
No enterprise-config gate: uninstall must work even after the customer has revoked credentials or rotated keys — otherwise we'd trap users with hook entries pointing at a binary that can no longer authenticate.
Adapter Uninstall errors don't abort the loop — the remaining adapters still get a chance. The aggregate exit code is 1 if any adapter failed.
Types ¶
type ErrorEntry ¶
type ErrorEntry struct {
Timestamp string `json:"ts"`
Stage string `json:"stage"`
Code string `json:"code"`
Message string `json:"message"`
EventID string `json:"event_id,omitempty"`
}
ErrorEntry is the JSONL shape of a single line in the errors log. Field tags are short to keep the file compact when something goes wrong on the hot path; eventID is omitted when not correlated to an upload.
type TargetUser ¶
TargetUser identifies the user whose home `hooks install` should target. UID/GID are split out so `ChownToTarget` doesn't have to re-parse them on each path.
func ResolveTargetUser ¶
ResolveTargetUser determines whose home directory the install should modify. It's the only sanctioned way for install handlers to obtain a user — in particular, callers must NOT walk /etc/passwd or read $SUDO_USER directly.
Behavior:
- non-root caller: returns the calling user; ok=true.
- root caller, console user resolved: returns the console user; ok=true.
- root caller, no console user resolved: writes a one-line note to stderr, appends an entry to the errors log, and returns ok=false. The caller MUST exit 0 in this case — multi-user machines without an active console session aren't a hook-install error, just a no-op.