guard

package
v0.170.6 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: 40 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 guard keeps builds from taking the machine down. Run takes one of the machine's build slots and runs a command in a memory-capped systemd scope; Hook is the PreToolUse hook that routes build, test, lint and lab commands through it and refuses a third kind lab.

The slots are memcap's: flock files <slotDir>/<i>.lock with a <i>.holder record in memcap's format, so beekeeper and the memcap shell wrapper share them. A slot is a slice too, capped like one run: a session's runs share the slot it holds, and its cap, instead of taking a second one.

Index

Constants

View Source
const (
	CreateForm = "`beekeeper app create <name>` or `beekeeper app create <installation> --manifest <file>`"
	DeleteForm = "`beekeeper app allow <name> --delete --word \"<the person's words>\"`"
)

CreateForm is how a creation is run, DeleteForm how a deletion the person asked for is recorded.

View Source
const (
	Allow = decisionAllow
	Deny  = decisionDeny
)

Allow and Deny are the decisions.

View Source
const (
	Drawn    = "drawn"
	NotDrawn = "not drawn"
)

drawOpen opens DrawCheck's answer; Drawn and NotDrawn are its verdicts.

View Source
const (
	PostToolUseEvent = "PostToolUse"
	PreToolUseEvent  = "PreToolUse"
)

PostToolUseEvent is the hook event a ToolResult names; PreToolUseEvent the one before a call.

View Source
const (
	// ExitBusy: no slot, or not enough memory for the cap, within the wait.
	ExitBusy = 75
	// ExitNotFound: the command could not be started.
	ExitNotFound = 127
)

Exit codes Run returns besides the command's own.

View Source
const (
	ForegroundWait = "8m"
	BackgroundWait = "60m"
	BackgroundEnv  = "MEMCAP_BACKGROUND"
)

The wait for a slot when neither --wait nor MEMCAP_WAIT sets one: a foreground call's fits within the Bash tool's 10 minutes, a background call's, which no tool limit stops, is longer. The PreToolUse hook exports BackgroundEnv=1 into every background Bash call, so a run it reaches directly, after a cd or export chain or through a script gets the background wait.

View Source
const (
	WaitFromForeground = "the foreground default"
	WaitFromBackground = "the background default"
	WaitFromEnv        = "MEMCAP_WAIT"
	WaitFromFlag       = "--wait"
)

Where a run's wait came from (Options.WaitFrom).

View Source
const (
	VerbStart = "run.start"
	VerbEnd   = "run.end"
)

The event log verbs of a capped run. Their detail is "<scope> <facts>: <command>": the scope's unit name exactly as the kernel prints it in an OOM kill's memcg path, then the slot and the cap (start) or the exit code, the duration and the cap's victims (end), then CommandHead.

View Source
const (
	ScopePrefix     = "memcap-"
	TestScopePrefix = "memcap-test-"
)

A capped run's scope is <ScopePrefix><pid>-<n>.scope in memcap.slice. A test's run (Options.Test) takes TestScopePrefix instead, so that the cap kill it provokes on purpose reads as a test kill, never as a build's.

View Source
const (
	ClassBuild     = "build"
	ClassBenchmark = "benchmark"
	ClassLab       = "lab"
)

The classes of a run (Options.Class). A build, test or lint takes a build slot. A benchmark and a lab proof are long by design and wait on their model or their lab, not on the cores: they take no slot, only their own cap in memcap.slice once the memory for it is there, so builds run beside them and memory stays the bound.

View Source
const (
	RoleSupervisor = "supervisor"
	RoleGuide      = "guide"
)

Roles a message can address by name instead of by session.

View Source
const (
	SOPSRef = "sops://"
	OpRef   = "op://"
)

Reference prefixes of the values a source indexes; a rebuild drops them.

View Source
const AllowForm = "`beekeeper app allow <name> --client-id <id> --word \"<the person's words>\"`"

AllowForm is how a consent for an App the person owns and asked for is recorded.

View Source
const AskTool = "AskUserQuestion"

AskTool is Claude Code's tool that puts a question to the person and blocks the session until the person answers.

View Source
const CallbackForm = "`beekeeper app allow <name> --callback-url <url> --word \"<the person's words>\"`"

CallbackForm is how one callback URL of an App the person owns and asked for is recorded.

View Source
const CaptureMask = "[masked by beekeeper secret page]"

CaptureMask stands for a token run, or the captured value, in a capture turn's result and transcript.

View Source
const DrawCheck = "'" + drawOpen + "' + ((await new Promise(done => { const late = setTimeout(() => done(false), 4000); " +
	"requestAnimationFrame(() => requestAnimationFrame(() => { clearTimeout(late); done(true); })); })) ? '" + Drawn + "' : '" +
	NotDrawn + "') + ', visibility ' + document.visibilityState"

DrawCheck asks a tab whether Chrome draws it: two animation frames within four seconds. A window the compositor does not draw (on a workspace not shown, minimised, under another) produces no frame while its document.visibilityState still says visible; a consent page there keeps its Authorize button disabled (its clickjacking guard waits on a drawn frame) and a click on it does nothing. A drawn window whose frame callbacks stall (the shared Chrome on the off-screen output) still draws, on Chrome's own fallback of about one frame a second: two frames take up to two seconds there, which four seconds leave room for. It is one expression, which a second run on the same page evaluates again without a declaration clash.

View Source
const FrozenRenderer = "renderer may be frozen"

FrozenRenderer is in the error of a screenshot of a tab whose window the compositor does not draw: the capture times out.

View Source
const GitLabForm = "" /* 129-byte string literal not displayed */

GitLabForm is how a consent for a self-hosted GitLab's OAuth application the person owns and asked for is recorded.

View Source
const GitLabFormScript = `(() => {
  const forms = [...document.querySelectorAll('form')].filter(f => { const a = new URL(f.action, location.href);
    return a.origin === location.origin && a.pathname === '` + gitlabAuthorize + `' && !f.querySelector('input[name=_method]') && f.querySelector('input[name=client_id]'); });
  if (forms.length !== 1) return '` + gitlabFormOpen + `none: ' + forms.length + ' authorize forms';
  return '` + gitlabFormOpen + `application ' + forms[0].querySelector('input[name=client_id]').value;
})()`

GitLabFormScript reads the client id of a GitLab authorize page's consent form, which the Chrome tools redact everywhere else (the tab's URL, the hidden inputs of read_page and find): the one form on the page's own origin that posts to /oauth/authorize (the Cancel form's _method is delete), its hidden client_id. GitLab assigns the id; the application's owner chooses nothing of the answer.

View Source
const GoogleForm = "`beekeeper app allow <name> --google --callback <host> --account <address> --word \"<the person's words>\"`"

GoogleForm is how a consent for a Google OAuth client the person owns and asked for is recorded.

View Source
const LeaveDisarm = "window.onbeforeunload = null; " +
	"BeforeUnloadEvent.prototype.preventDefault = function () {}; " +
	"Object.defineProperty(BeforeUnloadEvent.prototype, 'returnValue', { configurable: true, get() { return ''; }, set() {} }); " +
	"'" + leaveAnswer + "'"

LeaveDisarm takes a page's leave-page prompt ("Leave site? Changes you made may not be saved") away before its tab closes: a page with an unsaved form asks it on close, nobody answers, and the close hangs with the tab left open in the shared Chrome. It drops the page's onbeforeunload and makes every beforeunload listener's request for the prompt a no-op, whatever order the page registered them in.

View Source
const LogPrefix = "beekeeper run: "

LogPrefix starts every line Run writes, the cap's victim line included.

View Source
const MemcapSlice = "memcap.slice"

MemcapSlice is the slice every capped run sits under; a run that takes no slot sits in it directly, under its own cap.

View Source
const MinSecretLen = 12

MinSecretLen is the default shortest value the index takes: shorter ones (ports, flags, words) would match ordinary output.

View Source
const ModeAcceptEdits = "acceptEdits"

ModeAcceptEdits is the mode Claude Desktop turns a bypassPermissions session into when it imports it (claude://resume).

View Source
const NotDrawnLine = "window not drawn"

NotDrawnLine is the line a browse turn's report names a page Chrome did not draw with.

View Source
const NotShared = "Refused: not shared for upload: "

NotShared opens the hook's refusal of a file_upload of a path the caller did not share with the browse turn.

View Source
const OAuthForm = "`beekeeper app allow <name> --oauth <host> --client-id <id> --account <address> --word \"<the person's words>\"`"

OAuthForm is how a consent to a third party's OAuth client, as the person's own account there, is recorded.

View Source
const PermissionEvent = "PermissionRequest"

PermissionEvent is the hook event a Request names.

View Source
const PermissionForm = "`beekeeper app allow <name> --permission \"<scope>: <level>\" --word \"<the person's words>\"`"

PermissionForm is how one permission change of an App the person owns and asked for is recorded.

View Source
const PostTool = "slack_send_message"

PostTool is the suffix of the tool that posts a report: the Slack connector's slack_send_message.

View Source
const ReadsBudget = 10000

ReadsBudget bounds the context one repository's reads add to a call, in bytes.

View Source
const SendMessageTool = "SendMessage"

SendMessageTool is the tool one Claude session messages another with.

View Source
const SharedEnv = "BEEKEEPER_BROWSE_SHARED"

SharedEnv names, in a browse turn's environment, the files the caller shared with it for upload (beekeeper browse --file): their copies' paths, joined by the path list separator, empty when it shared none. Its presence marks the session a browse turn.

View Source
const SlackForm = "" /* 150-byte string literal not displayed */

SlackForm is how the install consent of a Slack app the person owns and asked for is recorded.

View Source
const SubscriptionControls = "a subscription, watch, star or notification control"

SubscriptionControls names the controls a browser call never clicks; a refusal's reason carries it, which a browse report reads.

View Source
const TaskStopTool = "TaskStop"

TaskStopTool is the tool a session stops one of its background tasks with.

View Source
const UploadTargetLabel = "beekeeper upload target"

UploadTargetLabel is the accessible name the upload-target check gives the input it marks, which find reads.

View Source
const UploadTargetScript = `(() => {
  const label = '` + UploadTargetLabel + `';
  document.querySelectorAll('input[type=file]').forEach(e => { if (e.getAttribute('aria-label') === label) e.removeAttribute('aria-label'); });
  const root = scope ? document.querySelector(scope) : document;
  if (!root) return label + ': none: no element matches the scope ' + scope;
  const name = e => { const f = e.form || e.closest('form'); return 'input' + (e.id ? '#' + e.id : '') + (e.name ? '[name=' + e.name + ']' : '') +
    (f ? ' in form' + (f.id ? '#' + f.id : '') + (f.getAttribute('action') ? ' (' + f.getAttribute('action') + ')' : '') : ''); };
  const shown = e => !e.disabled && !!e.parentElement && e.parentElement.checkVisibility({ visibilityProperty: true }) && !e.parentElement.closest('[hidden],[inert]');
  const all = [...root.querySelectorAll('input[type=file]')];
  const ok = all.filter(shown);
  if (ok.length === 1) { ok[0].setAttribute('aria-label', label); ok[0].parentElement.scrollIntoView({ block: 'center' });
    return label + ': marked ' + name(ok[0]) + ' (' + (all.length - 1) + ' other file inputs hidden or disabled); find "' + label + '" for its ref'; }
  if (ok.length > 1) return label + ': none: ' + ok.length + ' visible file inputs (' + ok.map(name).join('; ') + '): run again with scope set to the intended form';
  return label + ': none: ' + all.length + ' file inputs, every one hidden or disabled' + (all.length ? ' (' + all.map(name).join('; ') + ')' : '');
})()`

UploadTargetScript is the upload-target check after its scope line: in the scope (a selector of the intended form or comment box, "" for the page) it clears the label of every file input, marks the one input that is enabled and whose box is rendered (no ancestor display:none, visibility:hidden, hidden or inert) and scrolls it into view; several such inputs or none mark nothing and say which there are.

Variables

View Source
var BlindReads = []string{
	chromePageText, chromeReadPage, "read_network_requests", "read_console_messages",
	"gif_creator", "upload_image", "file_upload", "shortcuts_execute", chromeBatch,
}

BlindReads are the Claude in Chrome tools a capture turn goes without: each answers the page's text, its traffic, its pixels or a file, where a value the page shows once would reach the model, or (a batch) runs such a call past the hook. The turn finds its controls with find, clicks them by ref, and runs one script, the reader.

Classes are the classes a run may declare, the default first.

View Source
var SecretFiles = []string{
	"~/.omp/agent/models.yml",
	"~/.omp/agent/config.yml",
	"~/.omp/agent/agent.db",
	"~/.claude/.credentials.json",
	"~/.config/gh/hosts.yml",
	"~/.docker/config.json",
	"~/.netrc",
	"~/.git-credentials",
}

SecretFiles are the files every session's hook guards, globs allowed, ~/ for the home directory; secret.files adds to them.

View Source
var ThirdPartyClients = []ThirdPartyClient{
	{Host: "auth.openai.com", ClientID: "app_EMoamEEZ73f0CkXaXp7hrann", Consent: "/sign-in-with-chatgpt/codex/consent", DeviceCode: "/deviceauth/callback", Name: "OpenAI's Codex sign-in with ChatGPT"},
}

ThirdPartyClients are the third parties' clients a consent is recorded for: a client not here has no consent page the hook knows, so none is recorded.

View Source
var TmpEnv = []string{"GOTMPDIR", "TMPDIR"}

TmpEnv are the temporary directory variables a run points off tmpfs: GOTMPDIR, where the go command writes its work directories (go-build*), and TMPDIR, every other tool's and a test's (t.TempDir).

View Source
var VaultVar = regexp.MustCompile("^(?:" + vaultEnv + ")$")

VaultVar matches the name of a variable that carries a vault credential.

Functions

func AppSlug added in v0.125.0

func AppSlug(name string) string

AppSlug is the slug GitHub gives an App's name: lower case, every run of other characters one hyphen, none at the ends.

func AwaitSlot added in v0.146.3

func AwaitSlot(o Options, what string) (ok bool, ahead int, err error)

AwaitSlot waits in the slot queue for a start that builds, within o.Wait: its turn comes once fewer waiters than slots are ahead of it and a slot is free, and it leaves the queue then without holding the slot, which the next waiter takes. One line when the wait starts and one when it ends, on o.Stderr. It reports whether the turn came; ahead is how many waited ahead of it when the wait ran out.

func Brokered added in v0.104.0

func Brokered(gh string, path []string) bool

Brokered reports whether gh, the gh a session resolves, is one of the agent's own programs: it lies in a directory of path (agents.shell.path). With no such directories every gh is the agent's.

func BrowseStop added in v0.146.1

func BrowseStop(input []byte) []byte

BrowseStop is a browse turn's Stop hook's answer for the event, nil to let the turn end: while tabs the turn opened are still open in its group, the turn goes on once to close them, the group's first tab last. A turn that went on once already ends; browse names the tabs it left.

func CanonicalCallback added in v0.151.0

func CanonicalCallback(raw string) bool

CanonicalCallback reports whether raw is a callback URL as a record keeps it: http(s), a host, no user info, a path and query of URL-safe characters, written as Go's URL parser writes it back.

func CapturePage added in v0.150.0

func CapturePage(input []byte, c Capture) []byte

CapturePage is a capture turn's hook (beekeeper hook capturepage, in the turn's --settings alone). On PreToolUse it refuses every Chrome call but those captureTools and captureActions allow: no screenshot, zoom, page read, batch, drag or triple click, no key but a plain one (captureKeys), no navigate but to an http or https page, no script but the reader. On PostToolUse it delivers the one distinct match of the pattern a result carries, and answers every result with images dropped, every match of the pattern and every token run masked, so the value reaches the model neither as pixels nor as text. A result with several distinct matches delivers none: its answer says the page is ambiguous. Every other event, and a result with nothing to drop, gets no answer.

func CommandHead added in v0.11.0

func CommandHead(argv []string) string

CommandHead is the command a run's events name, at most 100 characters (commandHead).

func Commands added in v0.66.2

func Commands(cmd string) [][]string

Commands splits a shell command line into the words of its simple commands, quotes removed, comments and here-document bodies left out.

func CredentialShapes added in v0.148.0

func CredentialShapes(text string) []string

CredentialShapes are the ids of the token rules text matches, once each: the shapes of a credential (a private key, a token's prefix), none for a public value. A gitleaks:allow marker exempts nothing here.

func CurrentContext added in v0.33.0

func CurrentContext(kubeconfig string) string

CurrentContext is the machine kubeconfig's current context, "" when it has none or cannot be read.

func DecideUnsandboxed added in v0.154.0

func DecideUnsandboxed(input []byte) []byte

DecideUnsandboxed is the PreToolUse answer for a session the policy does not hold while sandbox.required is set: every call is refused but a SendMessage, by which the session says why it stopped. Malformed input passes.

func DefaultClass added in v0.158.0

func DefaultClass(argv []string) string

DefaultClass is the class of a run that declares none: ClassLab for a lab command (agentlab) that runs no build, ClassBuild for the rest.

func DrawVerdict added in v0.155.12

func DrawVerdict(text string) string

DrawVerdict is the verdict a result's text of DrawCheck gives, "" for none.

func FirstLine added in v0.70.0

func FirstLine(s string) string

FirstLine is a tool's first stderr line, cut short and stripped of what a pattern would redact.

func GoogleCallback added in v0.147.0

func GoogleCallback(u *url.URL) string

GoogleCallback is the callback host of the Google authorization request u carries: its redirect_uri's host, or that of the request its continue URL carries; "" for none.

func HolderText added in v0.158.0

func HolderText(raw string, now time.Time) string

HolderText states a slot's holder for a waiter's line: who holds it, since when and for how long by now, and the command; a record it cannot read as it is.

func IndexSOPS added in v0.64.0

func IndexSOPS(ctx context.Context, ix *Index, files []string) (int, error)

IndexSOPS adds every string value of each SOPS file, decrypted with sops -d, under sops://<file>#<key path>. A file sops cannot decrypt is named in the error and the others are still indexed.

func IndexVault added in v0.64.0

func IndexVault(ctx context.Context, ix *Index, vault string, env []string) (int, error)

IndexVault adds the concealed fields (passwords, credentials, keys) of every item in the 1Password vault, read with op item list and op item get --reveal, under op://<vault>/<item>/<field>. env is added to op's environment: the service account's token for the shared vault.

func IsProduction added in v0.96.0

func IsProduction(name, production string) bool

IsProduction reports whether a context or cluster name has production as one of its components.

func IsTestScope added in v0.15.3

func IsTestScope(unit string) bool

IsTestScope reports whether a scope's unit name is a test run's.

func KubeGuardOff added in v0.47.0

func KubeGuardOff(production string) string

KubeGuardOff says why the kube guard is off, "" while it is on.

func LabCluster added in v0.92.0

func LabCluster(dir string) (string, bool)

LabCluster is the kind cluster of the agentlab lab in dir, its agentlab.yaml's clusterName (agentlab's default without one), and whether dir holds an agentlab.yaml at all.

func Loopback added in v0.152.4

func Loopback(host string) bool

Loopback reports whether host is the machine itself: localhost and its subdomains, a loopback address (127.0.0.0/8, ::1), and a nip.io name whose address is one, which every agentlab binds its own of (*.127.0.0.1.nip.io, *.lab2.127.0.0.2.nip.io).

func MandatoryReads added in v0.32.0

func MandatoryReads(repo string, budget int) string

MandatoryReads gathers repo's instructions for an agent that did not start in it: CLAUDE.md and AGENTS.md with their @imports, .claude/rules, the hooks and permissions of .claude/settings.json, and the files these name as mandatory reading; within budget bytes, "" when the repository has none. Only regular text files inside repo are read, never a secret name; repo is a RepoRoot, its symlinks resolved.

func Message added in v0.112.1

func Message(s string) string

Message is a tool's whole stderr on one line, stripped of what a pattern would redact: a refusal's reason is often past its first line.

func Owned added in v0.73.1

func Owned(cmd string) bool

Owned reports whether cmd runs one of the devctl commands the gate runs outside its caller, whose outcome reaches its owner unheard or not.

func ParseClass added in v0.158.0

func ParseClass(s string) (string, error)

ParseClass checks a declared class; "" is ClassBuild.

func ParseSize

func ParseSize(s string) (int64, error)

ParseSize parses a systemd size with base-1024 suffixes into KiB.

func ParseWait

func ParseWait(s string) (time.Duration, error)

ParseWait parses a duration ("8m", "90s", "1h"); a bare number is seconds.

func PathFirst added in v0.104.0

func PathFirst(first []string, path string) string

PathFirst is path, a PATH, as writePath leaves it: each directory of first not on it yet put ahead, in their order.

func PeekSlot added in v0.148.0

func PeekSlot(o Options) (free bool, wait string, err error)

PeekSlot reports how a start that builds would find the build slots now, judged as AwaitSlot judges its turn, without joining the queue or holding a slot: free when fewer waiters than slots are queued and a slot is free. Otherwise wait says what the start would wait for: the slots' holders and the waiters ahead of it, one indented line each.

func PermissionDecision added in v0.63.0

func PermissionDecision(behavior, message string) []byte

PermissionDecision is the hook's answer with behavior ("allow" or "deny") and, for a deny, the message the model reads.

func PostToolUse added in v0.64.0

func PostToolUse(input []byte, ix *Index) ([]byte, ToolResult, []Finding)

PostToolUse scans a tool's result for indexed values and token patterns before the model sees it. With a hit it returns the hook's answer, which replaces the result with the same result, every hit replaced by a marker naming its reference or rule, and the findings; otherwise nil. Malformed input, or any other event, gets no answer.

func Prelude added in v0.60.0

func Prelude(unalias []string, literalGlobs bool, path, drop []string, unheld string) string

Prelude is the shell code an agent shell runs before each command, in zsh and bash alike: it removes the aliases and shell functions of unalias, so each name runs the tool on PATH, and with literalGlobs an unmatched glob stays as written instead of failing the command. Claude Code sources it before parsing the command, so a removed alias is not expanded in it. The directories of path go first on PATH, in their order, each once (a leading ~/ is the home directory): an agent's own programs, such as a gh that acts with a short-lived token, shadow the person's. The directories of drop leave PATH wherever they are, one an inherited PATH carries included: in the agent sandbox an agent's gh link to devctl would read a keychain the sandbox closes. With unheld, the shell picks per command: a command the sandbox runtime holds ($SANDBOX_RUNTIME) leaves drop, any other runs unheld, the shell lines that put an unheld environment back on the host, and puts path first: Claude Code can apply the sandbox policy's environment without its sandbox. It always drops the vault credentials of vaultEnv from the environment: no agent command runs with a vault session or token. Every line ends with exit status 0.

func ProcList added in v0.156.0

func ProcList(pids []int, t *proc.Table) string

ProcList names the processes, "4711 (kube-apiserver), 4712 (etcd)" by the table t (nil: their ids only), at most maxProcs of them and the count of the rest.

func ReaderScript added in v0.150.0

func ReaderScript(pattern string) string

ReaderScript is the one script a capture turn runs (javascript_tool): it answers the distinct matches of pattern in the page's text and in its fields' values, as JSON. Its result reaches beekeeper's hook, which takes the value and hands the model the result masked.

func RepoRoot added in v0.32.0

func RepoRoot(p string) string

RepoRoot is the top of the git repository or worktree holding p, "" when p is in none. It reads only the file system, never runs git.

func ReportCheck added in v0.27.0

func ReportCheck(input []byte, check func(string) []string) []byte

ReportCheck decides one PreToolUse event of a reporter session: a post whose message check finds wrong (post.Report) is denied, with what to fix as the reason. Any other tool passes, nil; a post without a message is denied.

func Resolve added in v0.104.0

func Resolve(name, path string) string

Resolve is the program a shell runs for name on path, a PATH: the first executable file of that name, "" when there is none.

func ResolveWait added in v0.137.1

func ResolveWait(flag string, flagSet bool) (wait, from string, background bool)

ResolveWait returns a run's wait, where it came from (WaitFrom…) and whether the run is part of a background Bash call: flag when set, else $MEMCAP_WAIT, else BackgroundWait with BackgroundEnv=1, else ForegroundWait.

func RoleOf added in v0.60.0

func RoleOf(to string) (string, bool)

RoleOf reads a SendMessage target that names a role: "the supervisor", "supervisor", "The Guide".

func Run

func Run(o Options, argv []string) int

Run runs argv in a capped scope and returns its exit code: the command's, 128+signal when a signal ended it, ExitBusy when the wait ran out. Without a user systemd, or inside a capped scope already, it execs argv. In the agent sandbox (o.Sandbox), which keeps the user systemd out of reach, the host's broker caps it; without a broker it refuses, 1. A run of a session that holds a slot already joins that slot at once: its scope goes into the slot's slice and shares the slot's cap.

func RunCommand added in v0.11.0

func RunCommand(detail string) string

RunCommand is the command a run event names.

func RunScope added in v0.11.0

func RunScope(detail string) string

RunScope is the scope a run event names.

func Scratchpad added in v0.166.0

func Scratchpad(project, session string) string

Scratchpad is the scratchpad Claude Code gives the session id started in the project directory: <tmp>/claude-<uid>/<project>/<session>/scratchpad.

func SessionDirs added in v0.166.0

func SessionDirs(session string) []string

SessionDirs are the directories Claude Code keeps for the session id under <tmp>/claude-<uid>/<project>/, whichever project it runs in.

func ShellQuote

func ShellQuote(s string) string

ShellQuote quotes s for a POSIX shell as Python's shlex.quote does.

func SlackChannel added in v0.168.0

func SlackChannel(name string) string

SlackChannel is a webhook channel's name as a record keeps it: lower case, without its "#"; "" for a name Slack gives no channel.

func SlackConsentURL added in v0.168.0

func SlackConsentURL(rawURL string) bool

SlackConsentURL reports whether rawURL is Slack's install consent page.

func Under added in v0.70.1

func Under(dirs []string, paths ...string) bool

Under reports whether any of paths (absolute; empty ones skipped) is one of dirs or lies below one: the directory part of the hooks' scope.

func UnsandboxedStart added in v0.154.0

func UnsandboxedStart() []byte

UnsandboxedStart is the SessionStart answer for such a session: the refusal as its context, before its first call.

func UploadTargetCheck added in v0.148.0

func UploadTargetCheck(scope string) string

UploadTargetCheck is the upload-target check as a session runs it, its scope line first; the hook knows the check by UploadTargetScript.

func WithPrelude added in v0.60.0

func WithPrelude(env, prelude string) string

WithPrelude is env, a session's environment file, with prelude in place of the one an earlier start wrote; the rest of the file stays.

func WritePrelude added in v0.60.0

func WritePrelude(path, prelude string) error

WritePrelude puts prelude into the environment file at path, written only when it changes.

func Yours added in v0.102.0

func Yours(message string, resources []string) []string

Yours returns the resources a message hands over with the supervisor's word: `yours <resource>`, `<resource> yours` or `<resource> is yours`, in the order said, each once, as resources spells them. Only a resource of resources counts, so "yours" in any other sense names nothing; the punctuation around the words (backticks, quotes, a comma or colon) is ignored.

Types

type App added in v0.120.0

type App struct {
	// Name is the App's name as GitHub's consent page titles it.
	Name string
	// ClientID is the OAuth client id the consent URL carries, "" for a
	// record without a consent.
	ClientID string
	// Callbacks are the hosts the consent page's redirect may go to, none
	// for a record without a consent.
	Callbacks []string
	// Org is the organisation whose settings pages the record covers, the
	// owner of the declaring repository.
	Org string
	// Permission is the one change of the App's permissions the person
	// asked for, "<scope>: <level>"; "" for a record without one.
	Permission string
	// CallbackURL is the one callback URL the person asked to add to the
	// App's settings, on a callback host its manifest declares; "" for a
	// record without one (appcallback.go).
	CallbackURL string
	// Delete says the person asked for the App's deletion (applife.go).
	Delete bool
	// Google says the App is a Google OAuth client whose consent is on
	// Google's sign-in (google.go), not a GitHub App.
	Google bool
	// Account is the Google account a Google App's sign-in chooses on
	// Google's account chooser, "" for any.
	Account string
	// GitLab is the host of the self-hosted GitLab whose OAuth application
	// this is, its consent on that host's authorize page (gitlab.go); "" for
	// any other App.
	GitLab string
	// OAuth is the sign-in host of a third party's OAuth client a consent
	// is recorded for as the person's Account there (thirdparty.go); "" for
	// any other App.
	OAuth string
	// Slack is the workspace host (<workspace>.slack.com) of a Slack app of
	// the person's whose install consent is on record there, SlackApp its
	// app id and Channel the webhook channel its install keeps, lower case
	// without "#" ("" for an app without one) (slack.go); Slack is "" for
	// any other App.
	Slack, SlackApp, Channel string
	// Run is the running `beekeeper app create` of the App whose listener
	// answers, nil for none; Created is beekeeper's ledger entry of the App
	// it created, nil for none (applife.go).
	Run     *CreateRun
	Created *Created
	// Declared is where the organisation declares the App.
	Declared string
	// Word is the person's words that asked for the grant, By whom and At
	// when they were recorded.
	Word, By string
	At       time.Time
}

App is an App the person owns and asked a consent, or one permission change, for.

type Capture added in v0.150.0

type Capture struct {
	Pattern *regexp.Regexp
	// Deliver hands the value to the waiting beekeeper secret page.
	Deliver func(value string) error
}

Capture is what a capture turn's hook knows: the pattern of the value, the reader script built from it, and where the one value goes.

type CreateRun added in v0.133.0

type CreateRun struct {
	Listener, By string
	At           time.Time
}

CreateRun is a running `beekeeper app create` of an App: its loopback listener, who runs it and since when.

type Created added in v0.133.0

type Created struct {
	Slug   string
	ID     int64
	Stored string
	At     time.Time
}

Created is beekeeper's ledger entry of an App its app create created: the slug GitHub gave it, its id, where its credentials went ("" for nowhere), and when.

type Decision added in v0.120.0

type Decision struct {
	Decision, Reason string
}

Decision is the hook's answer for a call acting on a page: Allow, Deny or "" for no decision, and why.

func Click added in v0.125.0

func Click(apps []App, page Page, words string) Decision

Click decides a call that acts on page (a click, a key, a typed text, a form value), in the call's own words, from the Apps on record.

func Navigation(apps []App, rawURL string) Decision

Navigation decides a navigation to rawURL from the Apps on record: the permissions page of an App on record for a permission change is allowed, the permissions page of any other App refused; the Advanced page of an App whose deletion is answered (applife.go) and the settings page of an App on record for a callback URL (appcallback.go) are allowed; every other URL gets no decision.

type Exposure added in v0.55.0

type Exposure struct {
	Path, What string
}

Exposure is a credential left exposed on disk: the file and what is wrong with it, never its content.

func Sweep added in v0.55.0

func Sweep(roots []string, depth int) []Exposure

Sweep walks each root depth levels deep for world-readable private key files and git repositories whose remote URL carries a credential. Symlinks are not followed; unreadable directories are passed over.

type Finding added in v0.64.0

type Finding struct {
	// Ref is the indexed reference; empty for a pattern hit.
	Ref string `json:"ref,omitempty"`
	// Rule is the token pattern's rule id; empty for an index hit.
	Rule  string `json:"rule,omitempty"`
	Count int    `json:"count"`
}

A Finding is what a text carried: an indexed reference or a token pattern's rule id, and how often.

func (Finding) Name added in v0.64.0

func (f Finding) Name() string

Name is the reference, or "pattern <rule>".

type Holder added in v0.158.0

type Holder struct {
	PID     int
	Session string
	// Name is the holding session's name, "" when its run had none.
	Name string
	Cmd  string
	// Since is when the slot was taken, zero when the record has none.
	Since time.Time
}

Holder is a slot's holder record as read: who holds it, since when and with what.

func ParseHolder added in v0.158.0

func ParseHolder(raw string) (Holder, bool)

ParseHolder reads a slot's raw holder record (memcap's JSON line); false when it is none.

func (Holder) Who added in v0.158.0

func (h Holder) Who() string

Who names the holder: its session's name, else its session id, and its process.

type Hook

type Hook struct {
	// Self is the absolute path of the beekeeper binary a rewrite names.
	Self string
	// UnlockCommands are the person's own vault unlock helpers
	// (secret.unlockCommands), refused like op signin.
	UnlockCommands []string
	// SecretFiles are the files known to hold secret values the config adds
	// to the built-in SecretFiles (secret.files), globs allowed; no session
	// reads them whole.
	SecretFiles []string
	// ConfigErr is why the configuration did not load: every Bash call is
	// refused with it, since the guards it configures cannot run.
	ConfigErr error
	// Shell is the shell a rewritten command runs in (sh -c semantics).
	Shell string
	// GoCache and GoModCache are the Go build and module caches the
	// machine's builds share, which only beekeeper cache clear go clears;
	// empty, that cache is not guarded.
	GoCache, GoModCache string
	// MaxLabs is how many kind clusters the machine runs at most; read
	// only for a command that creates one.
	MaxLabs func() int
	// Production is the installation the kube guard protects; empty, the
	// guard is off.
	Production string
	// ContextHint is how a refusal writes an installation's context
	// ("login.example.com-<installation>"); empty, "<context>".
	ContextHint string
	// Clusters lists the running kind clusters.
	Clusters func() []string
	// Leases lists the held leases.
	Leases func() []lease.Holder
	// Guide reports whether the session is the guide's, and the person the
	// guide asks; read only for an AskUserQuestion call and a call that
	// does work (guide.go).
	Guide func(session string) (bool, string)
	// CheckQuestion names what one of the guide's questions lacks for its
	// person to answer it, as `note add` checks a note; nil checks nothing.
	CheckQuestion func(Question) []string
	// Role names the session a message to a role (RoleOf) goes to: the
	// name its running CLI takes messages under, else its desktop session
	// id; an error (no holder, an ambiguous name) refuses the send. Nil
	// leaves a role's name as written.
	Role func(role string) (string, error)
	// Holds names the role a message by name addresses: a name the role's
	// holder carries or carried on the roster ("Supervisor run 82" for a
	// holder its desktop has since titled "klaus-lab-14"), or its session
	// id; "" when it holds none. Such a message goes where Role sends it.
	// Nil reads every name as written.
	Holds func(name string) string
	// Peer names the running CLI of a desktop session id, "" when none
	// runs; an error refuses the send. Nil passes every SendMessage.
	Peer func(host string) (string, error)
	// Absent says why a message by name reaches nobody: the name is a
	// roster agent's whose CLI does not run (its headless turn ended, its
	// import waits); "" passes the send. Nil passes every one.
	Absent func(name string) string
	// Agent names where a message by name goes while several running CLIs
	// carry it and the roster agent of that name is one of them (a
	// hand-over's follow-up beside the session it replaces): that CLI's own
	// socket; "" leaves the name as written, an error refuses the send.
	// Nil reads every name as written.
	Agent func(name string) (string, error)
	// Yours records a `yours <resource>` in a message from the session
	// holding the supervisor role as the resource's grant to the message's
	// target (to, after the hook's own redirects) and returns what the
	// sender is told: the grant recorded, or why none was; "" says nothing.
	// Nil records nothing.
	Yours func(session, to, message string) string
	// Project is the session's own project ($CLAUDE_PROJECT_DIR), whose
	// instructions Claude Code loads itself; "" takes the call's cwd.
	Project string
	// Reads reports whether a call is the session's first write in the
	// repository, and records it; nil adds no repository reads.
	Reads func(session, repo string) bool
	// Kubeconfig is the kubeconfig list the session's commands use by
	// default ($KUBECONFIG, else MachineKubeconfig).
	Kubeconfig string
	// MachineKubeconfig is the machine kubeconfig (~/.kube/config), which
	// keeps no current context.
	MachineKubeconfig string
	// ModelServer reads the host's model server, whose loads need its
	// lease; called only for a command that may load a model, nil guards
	// nothing.
	ModelServer func() ModelServer
	// Outbound is the outbound secret guard's configuration; its token
	// patterns apply without one.
	Outbound Outbound
	// Upstream is the upstream guard's configuration (upstream.go); without
	// organizations it refuses nothing.
	Upstream Upstream
	// Refused records the upstream guard's refusal of a session's command
	// (a hook.refused event) with the repository it aimed at; nil records
	// nothing.
	Refused func(session, command, repo string)
	// Sandbox is the agent sandbox's policy, which the file tools are held
	// to; nil in a session no sandbox holds.
	Sandbox *sandbox.Policy
	// Labs lists the held leases of kind labs, unnamed (a lease file read,
	// no process scan); nil, none.
	Labs func() []lease.Holder
	// FreshLabs brings the kubeconfigs in the given lab leases up to date
	// with their clusters, before a Bash command of the session holding
	// them; nil, never.
	FreshLabs func(labs []string)
	// Started reports whether beekeeper agents start started the session
	// in bypassPermissions; read only for a browser call in acceptEdits,
	// nil refuses no browser call.
	Started func(session string) bool
	// Apps lists the Apps the person owns and asked a consent for, what a
	// Chrome call on a consent page is decided from (consent.go); read only
	// for a browser call that acts on a page, nil decides no consent page.
	Apps func() []App
	// Shared reports whether the session is a browse turn and the files
	// its caller shared with it for upload (SharedEnv); nil, none is.
	Shared func() (files []string, browse bool)
	// GraphQL is the GraphQL budget as beekeeper last read it, for a
	// board-read refusal; nil or "", unknown.
	GraphQL func() string
	// PersonFolders are the person's folders (hooks.personFolders, absolute
	// globs): no file is created directly in one, nor an untracked one in the
	// main working tree of a checkout that sits directly in one (folders.go);
	// empty, the guard is off.
	PersonFolders []string
	// StopTask ends the gate a TaskStop of the session's task runs and says
	// what it ended, "" for nothing; nil ends nothing.
	StopTask func(session, task string) string
}

Hook decides one PreToolUse event.

func (Hook) Decide

func (h Hook) Decide(input []byte) []byte

Decide returns the hook's JSON answer for the event, nil to let the call pass unchanged. Malformed input passes. A call the hook does not refuse that is the session's first write in another repository carries that repository's instructions as additional context.

func (Hook) DecideSandbox added in v0.80.0

func (h Hook) DecideSandbox(input []byte) []byte

DecideSandbox is Decide for a session out of the hooks' scope: only the sandbox's hold on the file tools applies.

type Index added in v0.64.0

type Index struct {

	// MinLen is the shortest value Add takes.
	MinLen int
	// contains filtered or unexported fields
}

Index is the fingerprint index in its directory.

func LoadIndex added in v0.64.0

func LoadIndex(dir string) (*Index, error)

LoadIndex reads the index in dir without creating anything: with no key yet, the index is empty and matches nothing.

func OpenIndex added in v0.64.0

func OpenIndex(dir string) (*Index, error)

OpenIndex reads the index in dir, creating its key on first use. The key and the index are readable by the user only.

func (*Index) Add added in v0.64.0

func (ix *Index) Add(ref, value string) int

Add indexes value under ref: the value itself, its base64 forms, each of its lines, and for a value that is base64 text its decoded form. It returns the number of forms added; a value shorter than MinLen adds none.

func (*Index) Built added in v0.64.0

func (ix *Index) Built() time.Time

Built is when the index was last saved.

func (*Index) Drop added in v0.64.0

func (ix *Index) Drop(prefixes ...string)

Drop removes every entry whose reference starts with one of prefixes.

func (*Index) Fingerprint added in v0.70.0

func (ix *Index) Fingerprint(s string) string

Fingerprint is the keyed hash of s, comparable only through beekeeper; empty while the index has no key.

func (*Index) Len added in v0.64.0

func (ix *Index) Len() int

Len is the number of fingerprints in the index.

func (*Index) Redact added in v0.64.0

func (ix *Index) Redact(s string) (string, []Finding)

Redact replaces every indexed value and every token pattern match in s with a marker naming its reference or rule, and returns what it found. A line marked gitleaks:allow keeps its pattern matches, not its indexed values. A base64 run whose decoding carries either is replaced whole. An Index without a key matches patterns only.

func (*Index) Refs added in v0.64.0

func (ix *Index) Refs() []string

Refs are the distinct references in the index, sorted.

func (*Index) Save added in v0.64.0

func (ix *Index) Save(now time.Time) error

Save writes the index, readable by the user only.

func (*Index) ValueFingerprint added in v0.73.0

func (ix *Index) ValueFingerprint(ref string) (string, bool)

ValueFingerprint is the fingerprint of ref's value when it was indexed (Index.Fingerprint of the value itself); false when ref was not.

type Leak added in v0.64.0

type Leak struct {
	Finding
	Files int      `json:"files"`
	Paths []string `json:"paths"`
}

A Leak is one reference or rule found in the transcripts: how often, in how many files and which. It never carries the value or where in a file it was.

type ModelServer added in v0.40.0

type ModelServer struct {
	// URL is ollama's API, LemonadeURL Lemonade Server's; "" guards
	// neither.
	URL         string
	LemonadeURL string
	// LabTests are the agentlab subcommands that run turns on its models.
	LabTests []string
}

ModelServer is what the hook knows of the host's model servers.

type Options

type Options struct {
	// Max is the scope's MemoryMax, a systemd size ("12G").
	Max string
	// Swap is the scope's MemorySwapMax; "0": a build does not swap.
	Swap string
	// CPUQuota and CPUWeight are memcap.slice's CPU budget, which every
	// slot shares (platform.Cap).
	CPUQuota  string
	CPUWeight int
	// Wait bounds the wait for a slot and for the memory the cap needs;
	// WaitFrom names where it came from (WaitFromForeground, …), for the
	// lines that state it.
	Wait     time.Duration
	WaitFrom string
	// Background: the run is part of a background Bash call (BackgroundEnv).
	Background bool
	SlotDir    string
	Slots      int
	Stderr     io.Writer
	// Record appends a run event (VerbStart, VerbEnd) to the event log; nil
	// records nothing. It must not fail or block the run: it swallows its
	// own errors and bounds its wait.
	Record func(verb, detail string)
	// Test names the scope TestScopePrefix…: a test's run, whose cap kill
	// snapshot and watch report as a test kill.
	Test bool
	// Sandbox caps the run when the agent sandbox keeps the service
	// manager out of reach (the host's broker); nil outside the sandbox.
	Sandbox platform.Capper
	// GoCache is the Go build cache the command compiles with
	// (gocache.Dir); "" for none. The run holds its use lock shared for the
	// length of the command, so no trim removes an entry the compile reads.
	GoCache string
	// TmpDir holds each run's own temporary directory, which GOTMPDIR and
	// TMPDIR name for the command (runTmp), off the tmpfs /tmp whose files
	// take RAM; "" leaves the caller's. The run removes it after the
	// command.
	TmpDir string
	// Class is the run's class (ClassBuild, …); "" is ClassBuild. Only a
	// build takes a slot.
	Class string
}

Options configure one capped run.

func (Options) SlotSlice added in v0.80.0

func (o Options) SlotSlice(n int) string

SlotSlice is the slice of the run's slot n under memcap.slice (systemd nests a slice by the dashes in its name, so the rest has none), named by the slot directory: a scratch state's slot never shares a cap with the machine's slot of the same number. A test's run (Test) takes one slice per slot number for every test, so that the temporary slot directories of tests leave no slice behind each.

type Outbound added in v0.55.0

type Outbound struct {
	// Phrases never leave the machine (case-insensitive).
	Phrases []string
	// Paths are globs of the files whose Write and Edit are outbound; a
	// directory covers what is under it.
	Paths []string
	// StoreDeny are the secret-store writes refused.
	StoreDeny []StoreRule
	// Git runs git in dir and returns its output, at most pushLimit bytes;
	// nil runs the git binary.
	Git func(dir string, args ...string) ([]byte, error)
}

Outbound is what the outbound guard checks beyond the built-in patterns.

type Page added in v0.120.0

type Page struct {
	URL, Title string
	Flow       string
	Form       string
	Picked     string
}

Page is a tab's page: its URL and title, on Google's sign-in the callback host of the OAuth flow the tab's earlier pages there named, and on a GitLab authorize page the client id its consent form carries, as GitLabFormScript read it while the tab was at that URL; on Slack's install consent page the channel the last call on the tab that named one named there (slack.go).

type Question added in v0.57.0

type Question struct {
	Text, StatusQuo, Why, Checked string
	Options                       []string
}

Question is one question of the guide's AskUserQuestion call, in the parts `note add` checks: the text up to its first label, the "Status quo:", "Why:" and "Checked:" labelled parts, and each option as "<label>: <description>", the description its consequence.

type ReadsMarker added in v0.32.0

type ReadsMarker struct {
	Dir string
}

ReadsMarker records which repositories a session was given, one empty file per session and repository under Dir.

func (ReadsMarker) First added in v0.32.0

func (m ReadsMarker) First(session, repo string) bool

First reports whether this is the session's first call for repo, and records it: the marker is created exclusively, so of two concurrent calls only one is first. Any error reads as not first: the reads are extra.

type Request added in v0.22.0

type Request struct {
	Event   string          `json:"hook_event_name"`
	Session string          `json:"session_id"`
	Mode    string          `json:"permission_mode"`
	Tool    string          `json:"tool_name"`
	Input   json.RawMessage `json:"tool_input"`
}

Request is the part of a PermissionRequest event the hook reads.

func Permission added in v0.22.0

func Permission(input []byte, started func(session string) bool) ([]byte, Request)

Permission decides one PermissionRequest event. It allows the request only when the session runs in acceptEdits and started reports it as a session beekeeper started in bypassPermissions; any other event, malformed input included, gets no decision (nil) and the person gets the normal card. started is asked only for an acceptEdits request, so every other request is decided without reading beekeeper's state.

type StoreRule added in v0.55.0

type StoreRule struct{ Vault, Item string }

StoreRule refuses a secret-store write whose vault and item match the globs; an empty glob matches any.

type SweepReport added in v0.64.0

type SweepReport struct {
	Files int    `json:"files"`
	Bytes int64  `json:"bytes"`
	Leaks []Leak `json:"leaks"`
}

SweepReport is what SweepTranscripts read and found.

func SweepTranscripts added in v0.64.0

func SweepTranscripts(dir string, ix *Index) (SweepReport, error)

SweepTranscripts scans every transcript under dir (Claude Code's projects directory): the sessions' and subagents' .jsonl files, each line's strings decoded, and the spilled tool results (.txt) as they are. It counts what ix.Redact finds; it never writes.

type Tabs added in v0.146.1

type Tabs struct {
	Opened, Closed, Group []string
	Anchor                string
}

Tabs are the Chrome tabs a session opened, as its transcript's tool results show them: a tabs_context result lists the tabs of the session's own tab group, which the session made, a tabs_create result names the tab it created, a tabs_close result the tab it closed, and every result ends with the tabs its group holds now. Anchor is the tab the session's current group was made with: the Claude in Chrome extension keys the group by it, so closing it while other tabs remain dissolves the group and leaves them open outside it, where no call of the session reaches them.

func ReadTabs added in v0.146.1

func ReadTabs(transcript string) Tabs

ReadTabs reads the tabs of the session's transcript; none for a transcript that cannot be read.

func (Tabs) Open added in v0.146.1

func (t Tabs) Open() []string

Open are the tabs the session opened and did not close, in the order it opened them.

func (Tabs) Reachable added in v0.146.1

func (t Tabs) Reachable() []string

Reachable are the open tabs still in the session's group, which its calls reach; Stray the open tabs outside it, which they no longer reach.

func (Tabs) Stray added in v0.146.1

func (t Tabs) Stray() []string

Stray are the open tabs outside the session's group.

type ThirdPartyClient added in v0.161.0

type ThirdPartyClient struct {
	Host, ClientID, Consent, DeviceCode, Name string
}

ThirdPartyClient is a third party's OAuth client whose consent page the hook knows: the sign-in host, the client id, the path of its consent page and of its device-code entry page ("" for a client with none).

func ThirdPartyClientOf added in v0.161.0

func ThirdPartyClientOf(host, id string) (ThirdPartyClient, bool)

ThirdPartyClientOf is the known client of id on host; false for none.

type ToolResult added in v0.64.0

type ToolResult struct {
	Event    string          `json:"hook_event_name"`
	Session  string          `json:"session_id"`
	Tool     string          `json:"tool_name"`
	Response json.RawMessage `json:"tool_response"`
}

ToolResult is the part of a PostToolUse event the hook reads.

type Upstream added in v0.137.0

type Upstream struct {
	// Orgs are the GitHub organizations and accounts an agent writes to
	// (github.allowedOrgs); empty, the guard is off.
	Orgs []string
	// Review is where an upstream candidate is queued (github.upstreamReview),
	// named in the refusal; "" names the team's upstream review list.
	Review string
	// Git runs git in dir and returns its output; nil runs the git binary.
	Git func(dir string, args ...string) ([]byte, error)
	// Getenv reads the hook's environment (GH_REPO); nil reads os.Getenv.
	Getenv func(string) string
}

Upstream is the upstream guard's configuration.

Jump to

Keyboard shortcuts

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