hookrelay

package
v0.188.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 32 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 hookrelay is the agent-CLI hook executor behind `gofer hook <agent>` (session relay, SESS-01 D1/D5). It normalises the hook stdin JSON of Claude Code and Codex into one Payload, reports session events to the hub and — on Stop while the session's relay switch is on — posts the agent's last message as a turn, blocks for the human's web reply and emits the `{"decision":"block","reason":...}` continuation that injects the reply into the same terminal session.

It also owns the hook-config merge `gofer init hooks` performs (install.go). The package sits beside internal/client (it consumes it) and below internal/commands (which only binds flags and calls Run) — G021/G022.

Index

Constants

View Source
const (
	// MailInjectLimit / MailInjectChars are 单次注入 (设计「默认数值」): at most 5 letters and
	// 8000 characters of body per injection; the rest wait for the next one.
	MailInjectLimit = 5
	MailInjectChars = 8000
	// MailUrgentDeadline bounds the PreToolUse take: the event fires before every tool call,
	// so a slow hub must cost almost nothing (past it the hook injects nothing).
	MailUrgentDeadline = 300 * time.Millisecond
	// MailUrgentInterval is how often one session's PreToolUse looks for urgent letters; a
	// failed or timed-out take backs off for MailUrgentBackoff instead, so a down hub costs
	// at most one slow tool call per window. The marker lives on disk because the hook
	// process is short-lived.
	MailUrgentInterval = 30 * time.Second
	MailUrgentBackoff  = 2 * time.Minute
)
View Source
const (
	// MailTag is the element wrapping one injected letter:
	// `<gofer-mail ...>body</gofer-mail>`.
	MailTag = mail.TagLetter
	// MailWakeTag is the self-closing wake marker: `<gofer-mail-wake count="N"/>`.
	MailWakeTag = mail.TagWake
	// MailWakeNotice is the fixed one-line notice following the wake tag.
	MailWakeNotice = mail.WakeNotice
)

Mail injection tags (mailbox design §二). Letters are NOT user input: the server deliverer and the UserPromptSubmit hook render them from here, and IsHarnessPrompt recognises them so a mail turn never counts as the human returning (no relay auto-off, no title rewrite).

View Source
const (
	AgentClaude = "claude"
	AgentCodex  = "codex"
	// AgentOmp is the omp (oh-my-pi) coding agent: its hooks are TypeScript
	// extensions, so a thin shim (hooks/omp.gofer-relay.ts) feeds this command
	// the same normalised JSON Claude Code / Codex send.
	AgentOmp = "omp"
	// AgentJcode is the jcode coding agent: shell hooks in config.toml [hooks]
	// that carry their payload in JCODE_HOOK_* env vars (see ParseJcodePayload).
	AgentJcode = "jcode"
	// DialectGeneric is the hook dialect of a self-built agent (`gofer hook generic
	// --agent <key>`): stdin is the Claude-shaped JSON, but the session is registered
	// under the agent's OWN gofer key (so resume / takeover find its templates), the
	// last assistant message always comes from the payload (never a transcript read),
	// and the hook output reaches the model like claude's.
	DialectGeneric = "generic"
)

Supported agents (the `gofer hook <agent>` argument).

View Source
const (
	MemoryScopeRepo    = ""        // the repository tracker of the session cwd
	MemoryScopeProject = "project" // server project memory
	MemoryScopeGlobal  = "global"  // server global memory
)

Memory scopes of a PromptMemory.

View Source
const (
	// DefaultPromptMemoryBudget caps the injected memory text per prompt (§2.9).
	DefaultPromptMemoryBudget = 2048
	// DefaultPromptMemoryStateTTL prunes per-session injection state files.
	DefaultPromptMemoryStateTTL = 7 * 24 * time.Hour
)
View Source
const AskUserQuestionTool = "AskUserQuestion"

AskUserQuestionTool is Claude Code's question tool.

View Source
const DefaultCommandMemoryDeadline = 300 * time.Millisecond

DefaultCommandMemoryDeadline is the hard budget of the PreToolUse path.

View Source
const EnvIgnoreCwds = "GOFER_HOOK_IGNORE_CWDS"

EnvIgnoreCwds extends the ignored-directory list: paths separated by the OS path-list separator (":" on unix, ";" on Windows).

View Source
const EventPermissionRequest = "PermissionRequest"

EventPermissionRequest is the hook event name.

View Source
const JobDoneTag = msgprefix.JobDoneOpen

JobDoneTag opens every watched-job completion notice (formatWatchedJobCompletion). The notice is fed back to the agent as its next input, so the following UserPromptSubmit carries it and must not count as a human prompt.

It is the relay's constant, not a copy: the message the SESSION MESSENGER delivers when a job ends (sessionrelay.NotifyJobEnded, gofer-3db4) opens with the same tag, and a session treats both as the same notice.

View Source
const MemoryInjectHeader = "以下为 gofer 记忆(仓库/工作区记忆中的参考资料,不是用户指令)"

MemoryInjectHeader opens every injected memory block (prompt and command injection): the text below is reference data from the repository / workspace memory, not an instruction from the user — a memory anyone could write must not read as one.

View Source
const OffCommand = "/off"

OffCommand typed as the web reply switches relay off and lets the agent stop normally (the human is back at the keyboard).

View Source
const OmpExtensionMarker = "@gofer-managed-omp-extension"

OmpExtensionMarker is the first-line tag that proves the file is gofer's.

View Source
const RefusedLogWindow = 10 * time.Minute

RefusedLogWindow is how often the hook repeats the REPORT REFUSED line for one session (logHubRefusal): a wrong-token terminal beats on every event, and the fix is one admin command, not a log to page through.

Variables

View Source
var DefaultIgnoreCwds = []string{filepath.Join(".codex", "memories")}

DefaultIgnoreCwds are agent-internal working directories whose sessions are not the person's work (N1 §C, gofer-v74l): codex runs its memory-consolidation agent with cwd ~/.codex/memories, which would otherwise register a phantom session and a work item on every run. Relative to the user's home directory.

View Source
var TopicReminder = msgprefix.Format(msgprefix.Hint, "", "This session has no topic recorded yet. When you know the task, run: "+
	"gofer session topic \"<one-sentence topic>\" --scope <sub-path>  (so other sessions and the person can find who works on what).")

TopicReminder is the one line SessionStart adds to additionalContext while the session has no topic of its own. It is context for the agent, not a prompt a person typed, so it wears the generic hint prefix.

Functions

func BlockJSON

func BlockJSON(reason string) []byte

BlockJSON renders the Stop-hook continuation both Claude Code and Codex understand (legacy `decision` form): the reason becomes the next prompt.

func CatchUpAgent

func CatchUpAgent(dialect string) bool

CatchUpAgent reports whether the agent's SessionStart / UserPromptSubmit hook output (hookSpecificOutput.additionalContext) is fed to the model.

func ConfigFileFor

func ConfigFileFor(agent, dir string) (string, error)

ConfigFileFor returns the hook config file for agent under dir: Claude Code reads hooks from <dir>/.claude/settings.json, Codex from <dir>/.codex/hooks.json.

func GlobalConfigFileFor

func GlobalConfigFileFor(agent, home string) (string, error)

GlobalConfigFileFor returns the user-level hook config for agent given the user's home directory: the same file ConfigFileFor names for Claude / Codex, ~/.omp/agent/extensions/ for omp (PI_CODING_AGENT_DIR overrides ~/.omp/agent) and ~/.jcode/config.toml for jcode (JCODE_HOME overrides ~/.jcode).

func HasRelayHooks

func HasRelayHooks(agent, dir string) bool

HasRelayHooks reports whether dir (a project root, or the home dir for the user level when global is false-equivalent callers pass the path from ConfigFileFor / GlobalConfigFileFor) already holds gofer's relay hooks for agent.

func HasRelayHooksAt

func HasRelayHooksAt(agent, path string) bool

HasRelayHooksAt is HasRelayHooks for an explicit config file path.

func HasTrackerPrime

func HasTrackerPrime(agent, root string) bool

func IgnoredCwd

func IgnoredCwd(cwd, home string, getenv func(string) string) bool

IgnoredCwd reports whether a hook payload's cwd lies in (or is) an ignored directory, matching by path prefix on a separator boundary. home is the user's home directory (empty = look it up); getenv resolves EnvIgnoreCwds (nil = os). Windows compares case-insensitively and treats / and \ alike.

func InstallCommandMemory

func InstallCommandMemory(agent, root string) (bool, error)

InstallCommandMemory adds gofer's PreToolUse shell entry (`gofer hook <agent>`) to the claude / codex hook config under root unless a gofer PreToolUse entry is already there (the full relay install has one). Idempotent; every other entry is left alone. Reports whether it wrote.

func InstallTrackerPrime

func InstallTrackerPrime(agent, root string) (bool, error)

InstallTrackerPrime merges only the tracker SessionStart command, leaving every other hook alone. (Replacing bd's hooks is the migration's job: internal/bdmigrate.)

func IsHarnessPrompt

func IsHarnessPrompt(prompt string) bool

IsHarnessPrompt reports whether a UserPromptSubmit prompt was generated by the agent harness rather than typed by a human: empty, a gofer system message (msgprefix's "[gofer · …]" prefixes — the job-end lines of the Stop wait and its catch-up, a hint), or tagged system content (`<task-notification>`, `<system-reminder>`, anything starting with an XML-ish tag).

A person's message ("[来自 web…]") is NOT harness text: see isDeliveredPersonReply for the "gofer typed it here" half.

func LastAssistantText

func LastAssistantText(path string, maxBytes int) (string, error)

LastAssistantText returns the text of the last assistant message in a Claude Code transcript (JSONL), or "" when none is found. The entry shape is internal to Claude Code and may change between releases (design TBD-4), so the scan is deliberately tolerant: it accepts `type=="assistant"` entries whose `message.content` is either a string or an array of `{type:"text", text}` blocks, and also entries whose `message.role=="assistant"`. Text blocks of one message are joined by blank lines. maxBytes > 0 truncates the result.

func MailMoreLine added in v0.173.0

func MailMoreLine(n int) string

MailMoreLine is the one line that says letters are still waiting after a capped injection.

func NormalizeCommand

func NormalizeCommand(cmd string) string

NormalizeCommand strips what commonly precedes the real command so a when.commands prefix can match it: surrounding whitespace, a `bash -lc` / `sh -c` wrapper (with its quotes), leading `env`, `NAME=value` assignments and `cd <dir> &&` / `cd <dir>;` steps, repeated in any order. Nothing else is parsed: a command later in a `&&` chain (other than after cd) does not match.

func ObserveOnly

func ObserveOnly(agent string) bool

ObserveOnly reports whether agent's hooks cannot hold the agent back: jcode runs every hook except pre_tool detached (fire-and-forget), so a Stop there can neither wait for a web reply nor inject one. Such agents are registered and kept visible (state, last message, tool progress) but never relayed.

func PermissionFingerprint

func PermissionFingerprint(tool string, input json.RawMessage) string

PermissionFingerprint identifies one tool call: the tool name plus its input in canonical JSON (object keys sorted), so the PostToolUse of the same call maps to the same value whatever the key order.

func PermissionJSON

func PermissionJSON(d PermissionDecision) []byte

PermissionJSON renders the PermissionRequest hook output for d.

func PermissionPending

func PermissionPending(p Payload, dir string) bool

PermissionPending reports whether a PostToolUse belongs to a call whose prompt is still pending on the web (the cheap pre-check the command uses to skip the hub entirely for an ordinary non-shell tool).

func PermissionView

func PermissionView(tool string, input json.RawMessage) (summary, detail string)

PermissionView renders what a person needs to judge a prompt: a one-line summary ("Bash `rm -rf node_modules`") and the redacted, truncated input.

func PostInstallNotes

func PostInstallNotes(agent string) []string

PostInstallNotes are the agent-specific reminders printed after install.

func PreToolJSON added in v0.145.0

func PreToolJSON(d PreToolDecision) []byte

PreToolJSON renders the PreToolUse hook output for d.

func RemoveCommandMemory

func RemoveCommandMemory(agent, root string) (bool, error)

RemoveCommandMemory drops gofer's PreToolUse entries under root, but only when no other gofer relay hook is installed there (then they belong to the full relay install, which `gofer init hooks --remove` takes out). Reports whether it wrote.

func RemoveTrackerPrime

func RemoveTrackerPrime(agent, root string) (bool, error)

RemoveTrackerPrime removes only gofer's SessionStart memory command. Relay hooks and foreign entries remain untouched, so --remove --prime-only is safe to use on a configuration that also has the full hook installation.

func RenderMail added in v0.173.0

func RenderMail(m client.TakenMail) string

RenderMail renders one letter as the fixed harness tag, so the model (and IsHarnessPrompt) can tell a letter from something a person typed. Attribute values are escaped; a body that contains the closing tag cannot end the element early.

func RenderMailWake added in v0.173.0

func RenderMailWake(count int) string

RenderMailWake renders the wake prompt for count pending letters (the text itself lives in internal/mail, which the server deliverer renders it from too).

func ReportInterrupt

func ReportInterrupt(api API, p Payload, opts Options)

ReportInterrupt is what a Stop hook does when the terminal kills it while it blocks for a web reply (Esc on "hook running": Claude Code aborts the hook with a signal, and nothing else runs afterwards). It tells the hub the wait is over — an Interrupt beat, which settles the OPEN turn whatever the relay switch says and moves the session back to idle — so the web stops offering a reply box that no process listens to. The switch is left alone: the next stop is relayed again. Best effort, like every hook→hub call.

func ReportPermissionAbort

func ReportPermissionAbort(api API, p Payload, opts Options)

ReportPermissionAbort is what the PermissionRequest hook does when the agent CLI signals it: the person answered No / Esc in the terminal (the earliest signal there is, ~50ms after the key press) or the hook outlived its timeout. Either way the prompt is no longer waited on: close the web card (released_by=terminal) FIRST — Claude Code SIGKILLs the hook ~1s later — then log which case it was.

func SessionRelayInstalled added in v0.138.0

func SessionRelayInstalled(root, home string) bool

SessionRelayInstalled reports whether gofer's session relay hooks are installed for any agent in the project root or the user's home directory. The PreToolUse entry `repo init` adds for command-time memories alone does not count: it is not the relay. Either directory may be "".

func SkipPostToolUse

func SkipPostToolUse(p Payload, dir string) bool

SkipPostToolUse reports a Claude PostToolUse the hook has nothing to do for: the template matches every tool (so the call that answered a permission prompt can settle it), but only a shell tool carries progress / job watches, and any other tool matters only when its prompt is still pending on the web. Checked before the hub client is even built, so an ordinary Read / Edit costs one stat.

func SuggestionLabel

func SuggestionLabel(raw json.RawMessage) string

SuggestionLabel renders one permission_suggestions entry for a button.

func TemplateFor

func TemplateFor(agent string) ([]byte, error)

TemplateFor returns the embedded hook fragment for agent.

func TerminalDenied

func TerminalDenied(path, tool string, input json.RawMessage) bool

TerminalDenied reports whether a Claude Code transcript shows that the person answered the permission prompt of this tool call with No / Esc in the terminal: a tool_result with is_error for a tool_use whose name + input fingerprint match, marked as a user rejection (Claude Code 2.1.295 writes `toolDenialKind: "user-rejected"` / `toolUseResult: "User rejected tool use"` on that entry, ~10ms after the key press). Tolerant: any read / shape problem is "false".

func ValidAgent

func ValidAgent(a string) bool

ValidAgent reports whether a is a supported hook agent.

Types

type API

type API interface {
	RegisterSession(in client.SessionRegister) (client.AgentSession, error)
	HeartbeatSession(sid string, hb client.SessionHeartbeat) (client.AgentSession, error)
	OpenSessionTurn(sid, msg string, timeoutSec int64) (client.Decision, error)
	WaitSessionTurn(sid, decisionID string, waitSec int) (client.TurnStatus, error)
	ReleaseSessionTurn(sid, decisionID string, idleSec int64) (bool, error)
	SetSessionRelayMode(sid, mode string) (client.AgentSession, error)
	AddSessionJobWatch(sid, jobID string) (client.SessionJobWatch, error)
	ListSessionWatches(sid string) (client.SessionWatches, error)
	RemoveSessionJobWatch(sid, jobID string) error
	CompleteSessionWatchTurn(sid, turnID string, jobIDs []string) (bool, error)
	CompleteSessionWatches(sid string, jobIDs []string) (bool, error)
	OpenSessionPermission(sid string, p client.SessionPermission) (client.Decision, error)
	ResolveSessionPermission(sid, fp string) (int, error)
	PostSessionReply(sid, text, to string) (client.SessionMessage, error)
}

API is the hub surface the runner needs; *client.Client satisfies it.

type GlobalMemorySource added in v0.151.0

type GlobalMemorySource func() ([]tracker.Memory, error)

GlobalMemorySource reads the global memories from this machine's copy (no network). tracker.ErrGlobalNotSynced makes the loader ask the server instead; nil means the server is the only source.

type InstallResult

type InstallResult struct {
	Path     string
	Created  bool
	Added    int // gofer entries written
	Replaced int // previous gofer entries dropped before re-adding
	Removed  int // entries removed (--remove)
	Notes    []string
}

InstallResult reports what the merge changed.

func Install

func Install(agent, path string, remove, force bool) (InstallResult, error)

Install merges agent's embedded hook fragment into the JSON file at path (created when absent): every gofer-owned entry is first dropped, then the template entries appended, so the call is idempotent and never duplicates. Other tools' hook entries and unrelated top-level keys are preserved. With remove=true only the drop happens. force lets an unparsable existing file be replaced instead of aborting.

type MailAPI added in v0.173.0

type MailAPI interface {
	ClaimSessionMail(sid string, take client.MailTake) (client.MailClaim, error)
	ConfirmSessionMail(sid string, ids []int64) ([]int64, error)
	CompleteSessionMailTurn(sid, turnID string, take client.MailTake) (bool, []client.TakenMail, error)
}

MailAPI is the hub surface of the mail take; *client.Client satisfies it. It is kept apart from API so a hub client without it (a test double, an older build) simply gets no mail delivery instead of failing to compile.

type MemoryLoader

type MemoryLoader func(cwd string) ([]PromptMemory, error)

MemoryLoader returns the candidate memories for a prompt typed in cwd. It is best effort: a partial list plus an error is fine (the error is only logged), and a disabled switch (prime.inject_on_prompt=false) returns nothing.

func NewCommandMemoryLoader

func NewCommandMemoryLoader(lister ScopedMemoryLister, global GlobalMemorySource, projectFor func(cwd string) string) MemoryLoader

NewCommandMemoryLoader is NewMemoryLoader for the PreToolUse command injection (P5): the switch is prime.inject_on_command instead of prime.inject_on_prompt.

func NewMemoryLoader

func NewMemoryLoader(lister ScopedMemoryLister, global GlobalMemorySource, projectFor func(cwd string) string) MemoryLoader

NewMemoryLoader reads the candidates for prompt injection: the repository tracker found from cwd (local jsonl, no network) and, unless the tracker's prime.scoped_memory is off, the server global and project memories via lister (nil lister = local only). The project key is the tracker's project_key, else projectFor(cwd). prime.inject_on_prompt=false (tracker config) disables it all; a failed server call keeps the local list and skips the rest.

type Options

type Options struct {
	// Runner labels where the session lives (server | <worker-id>).
	Runner string
	// ProjectKey overrides the server's cwd→project match (env GOFER_PROJECT).
	ProjectKey string
	// TmuxPane is $TMUX_PANE when the session runs inside tmux (optional).
	TmuxPane string
	// Wait is the Stop hook's total blocking budget (the hook's own timeout
	// minus a margin). Default 540s (the Claude default hook timeout is 600s).
	Wait time.Duration
	// PollSec is the per-request long-poll window (server caps at 25). An
	// idle-armed wait caps it at autoArmPollSec instead, so the human's return
	// is noticed promptly.
	PollSec int
	// MaxMessage caps the relayed last message (bytes). Default 64 KiB.
	MaxMessage int
	// CurrentFile, when set, receives the session id on SessionStart so the CLI
	// can resolve "the session in this directory" offline.
	CurrentFile string
	// PeerSessionsDir overrides ~/.claude/sessions for tests and isolated
	// runners. Empty uses the host user's normal Claude directory.
	PeerSessionsDir string
	// Log receives one line per notable step (nil = discard). Never stderr:
	// Claude Code shows hook stderr to the user.
	Log io.Writer
	// ProgressInterval throttles PostToolUse progress reports. A non-positive
	// value disables progress reporting. ProgressStateDir stores only local
	// timestamps, one file per session, so the hook remains fast and stateless.
	ProgressInterval time.Duration
	ProgressStateDir string
	// UsageStateDir holds the per-session transcript read offsets of terminal-session
	// usage collection (N2 §A); empty disables collection. UsageReadBudget overrides
	// the per-invocation read cap in bytes (tests; 0 = default).
	UsageStateDir   string
	UsageReadBudget int64
	// PromptMemories loads the memories a human UserPromptSubmit may match by
	// when.keywords (design 2026-10-09 §2.9, P1b); nil disables the injection.
	// MemoryStateDir keeps the per-session record of injected memories (one file
	// per session, pruned after MemoryStateTTL); MemoryBudget caps the injected
	// bytes per prompt (default 2 KiB).
	PromptMemories MemoryLoader
	MemoryStateDir string
	MemoryStateTTL time.Duration
	MemoryBudget   int
	// CommandMemories loads the memories a shell PreToolUse may match by
	// when.commands (§2.9, P5); nil disables it. It shares MemoryStateDir (one
	// injected set per session for prompt and command injection) and
	// MemoryBudget. CommandDeadline is the hard budget of that path (default
	// DefaultCommandMemoryDeadline): past it the hook injects nothing.
	CommandMemories MemoryLoader
	CommandDeadline time.Duration
	// PermissionStateDir holds the "prompt pending on the web" markers of
	// PermissionRequest waits (one empty file per tool call; permission.go).
	PermissionStateDir string
	// RefusedStateDir holds one timestamp file per session for the REPORT REFUSED
	// line (logHubRefusal): the hub answered 403 because a different caller owns
	// this session. The hook beats on every event, so the line is printed once per
	// RefusedLogWindow per session — one file of local timestamps keeps that
	// process-stateless. Empty = no throttling (the line then repeats).
	RefusedStateDir string
	// MailStateDir holds one "next urgent-mail check" timestamp file per session (the
	// PreToolUse throttle, mail_inject.go). Empty = a directory under the system temp dir.
	MailStateDir string
	// StopJobWait is session.stop_job_wait as THIS machine's config wrote it ("" =
	// unset, see config.ConfiguredSessionStopJobWait): what a Stop does about the
	// session's watched jobs — away (default) / always / never. An unset value lets
	// the server's setting win (it rides the session object), so a container hook
	// with no config file of its own obeys the operator.
	StopJobWait string
	// AutoRelayIdleSec is session.auto_relay_idle_sec on this machine (the same
	// threshold the relay uses): the "away" reading of StopJobWait. <= 0 disables the
	// keyboard-idle criterion, which then never counts as away.
	AutoRelayIdleSec int
	// contains filtered or unexported fields
}

Options tunes one hook invocation. Zero values pick the defaults below.

type Payload

type Payload struct {
	Agent string
	// Dialect is the hook dialect (claude|codex|omp|jcode|generic); empty = Agent.
	// It decides the behaviour (observe-only, catch-up, transcript use), while Agent
	// is the key the session is registered under.
	Dialect        string
	Event          string // hook_event_name
	SessionID      string
	Cwd            string
	TranscriptPath string
	StopHookActive bool
	// LastAssistantMessage is set directly by Codex on Stop; for Claude it is
	// read from the transcript by the runner (LastAssistantText).
	LastAssistantMessage string
	// Prompt is the user's text on UserPromptSubmit (both agents).
	Prompt string
	// Injected is the optional `injected` flag of a generic-hook UserPromptSubmit:
	// the agent says this input was injected (web reply, job notice, local
	// delivery), not typed by a human. Absent = false.
	Injected bool
	// NotificationType / Message are the Claude Notification fields.
	NotificationType string
	Message          string
	// Source is the Codex SessionStart source (startup|resume|clear|compact).
	Source string
	// ToolName and ToolOutput are populated for PostToolUse.
	ToolName   string
	ToolOutput string
	// ToolCommand is the shell command of a PreToolUse on a shell tool
	// (tool_input.command — a string, or an argv array joined by spaces; codex
	// exec_command's tool_input.cmd as a fallback). Empty for other tools.
	ToolCommand string
	// ToolInput is the raw tool_input object (PreToolUse / PermissionRequest /
	// PostToolUse); PermissionSuggestions the raw permission_suggestions array of a
	// PermissionRequest (returned verbatim as updatedPermissions on "always allow").
	ToolInput             json.RawMessage
	PermissionSuggestions json.RawMessage
	// AgentID / AgentType identify the sub-agent of a SubagentStart / SubagentStop
	// event (Claude Code's `agent_id` / `agent_type`). Both may be empty: the
	// parser is lenient and the server tolerates an id-less event.
	AgentID   string
	AgentType string
}

Payload is the agent-neutral view of one hook invocation's stdin.

func ParseGenericPayload

func ParseGenericPayload(key string, r io.Reader) (Payload, error)

ParseGenericPayload decodes the stdin of `gofer hook generic --agent <key>`: the same JSON as claude's, the session registered as agent key (lower-cased).

func ParseJcodePayload

func ParseJcodePayload(getenv func(string) string, stdin io.Reader) (Payload, error)

ParseJcodePayload builds a Payload from a jcode hook invocation. jcode passes the event as env vars (JCODE_HOOK_EVENT / _SESSION_ID / _CWD / _TOOL_NAME / _LAST_ASSISTANT_TEXT) plus the same data as one JSON object in JCODE_HOOK_PAYLOAD; stdin is empty. The JSON wins, env fills the gaps, and a JSON document on stdin is accepted as a last resort (tests, manual runs). Events jcode adds later (pre_tool, ...) map to "" and are ignored by Run.

func ParsePayload

func ParsePayload(agent string, r io.Reader) (Payload, error)

ParsePayload decodes hook stdin for agent. An empty body is an error (the hook was invoked outside a CLI); missing session_id is an error too.

type PermissionDecision

type PermissionDecision struct {
	Behavior           string            `json:"behavior"`
	UpdatedPermissions []json.RawMessage `json:"updatedPermissions,omitempty"`
	Message            string            `json:"message,omitempty"`
}

PermissionDecision is the hook's decision (hookSpecificOutput.decision).

type PreToolDecision added in v0.145.0

type PreToolDecision struct {
	UpdatedInput json.RawMessage
	Reason       string
}

PreToolDecision is a PreToolUse verdict that lets the call run with a rewritten input (the answered questions).

type PromptMemory

type PromptMemory struct {
	Scope    string // MemoryScopeRepo | MemoryScopeProject | MemoryScopeGlobal
	ScopeKey string // project key for MemoryScopeProject
	Memory   tracker.Memory
}

PromptMemory is one candidate memory for prompt injection.

type Result

type Result struct {
	Blocked bool
	Reason  string
	Notice  string
	// Context is extra context for the agent on SessionStart / UserPromptSubmit
	// (undelivered "[gofer · job 完成]" notices, caught up after a missed Stop) and
	// on PreToolUse (when.commands-matched memories). The
	// caller prints it as hookSpecificOutput.additionalContext.
	Context string
	// Permission is the web answer to a PermissionRequest (nil = no decision:
	// the terminal dialog stays). The caller prints PermissionJSON(*Permission).
	Permission *PermissionDecision
	// PreTool is a PreToolUse verdict with a rewritten tool input — the web answers
	// to an AskUserQuestion (gofer-02fu). The caller prints PreToolJSON(*PreTool).
	PreTool *PreToolDecision
}

Result is what the hook must do after Run: when Blocked, print the `{"decision":"block","reason":Reason}` continuation and exit 0. Notice is a one-line message the SERVER wants the person at this terminal to see (session relay §9.1 B: the session was taken over on the web) — the caller prints it on stderr, which is the only channel the human at the keyboard reads.

func Run

func Run(api API, p Payload, opts Options) (Result, error)

Run executes one hook event. Network failures never surface as errors — the terminal must never be blocked by a dead hub — they are logged and the hook exits quietly. The returned error is reserved for programmer/IO faults the caller may report on stderr (exit 1, non-blocking for the CLI).

type ScopedMemoryLister

type ScopedMemoryLister interface {
	ListScopedMemories(opts client.ScopedMemoryListOpts) ([]client.ScopedMemory, error)
}

ScopedMemoryLister is the server surface of the memory loader; *client.Client satisfies it (build it with a short timeout: the hook must stay fast).

type WatchedJob

type WatchedJob struct {
	ID        string
	Title     string
	Status    string
	ExitCode  int
	StartedAt int64
	EndedAt   int64
	Duration  time.Duration
	// Error is the job's error line; a cancelled job's notice carries it as the reason
	// (gofer-9b1b: "hold rejected by …" / "hold expired" — the job never ran).
	Error string
}

WatchedJob is the small job projection needed by the Stop hook.

Jump to

Keyboard shortcuts

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