cli

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 20 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 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

View Source
const ErrorLogFilename = "ai-agent-hook-errors.jsonl"

ErrorLogFilename is the basename of the per-user errors log. It lives directly under ~/.stepsecurity/.

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

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

func Resolve() (string, error)

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

func RunHook(stdin io.Reader, stdout, stderr io.Writer, args []string) int

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:

  1. enterprise-config gate (all three credentials present and non-placeholder)
  2. resolve target user (root + no console user → log + exit 0)
  3. resolve absolute, symlink-resolved DMG binary path
  4. select adapters per --agent or detection on $PATH
  5. per-adapter Install, then chown all outputs to target user under root
  6. 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:

  1. resolve target user (root + no console user → log + exit 0)
  2. resolve absolute, symlink-resolved DMG binary path (the uninstall matcher needs it to identify DMG-owned entries)
  3. select adapters per --agent or detection on $PATH
  4. per-adapter Uninstall, then chown rewritten outputs to target user under root
  5. 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

type TargetUser struct {
	User    *user.User
	UID     int
	GID     int
	HomeDir string
}

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

func ResolveTargetUser(exec executor.Executor, stderr io.Writer) (TargetUser, bool)

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.

Jump to

Keyboard shortcuts

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