Documentation
¶
Overview ¶
This file is the single assembly point for a session's tool gates: the trust gate, the workspace-boundary gate and the permission gate, composed once and installed on every run of the session — the main run, a /goal or /btw side run, and any sub-agent they dispatch.
Before this, each driver built the chain itself (seven assembly sites: tui/repl/goal/btw/headless/subagent_rpc/task-factory), which is how the TUI came to gate reads differently from the REPL and how a sub-agent ended up with fewer gates than the run that spawned it. With the chain defined here, "which gates a run has" is one decision, and a derived run inherits the session's answer instead of re-deciding it.
Two chains come out of one set of inputs. The interactive chain carries the driver's answer channels (stdin prompt or dialog callback); the derived chain has the same gates but NO channels, so a sub-agent thread cannot prompt — it fails closed with guidance, exactly as the read-scope gate has always done for children. That is deliberate: a child runs concurrently with its parent, and a dialog opened from under a running batch is not a question the user can answer without losing the thread of what they were reading.
This file holds chainEvent, the observer composition the gate assembly uses (#425): the SessionEnd/PreCompact hook notifier is chained onto whatever event seam the driver owns (HeadlessConfig.OnEvent, the DrainStream handler for the REPL/TUI).
The tool-execution and Stop seams, the SessionStart dispatch and that notifier used to be installed here by InstallDriverHooks, one of two entry points (#425 converged the six drivers onto it). Both entry points are gone: run.Gates.InstallDriver is now the single one, so a driver cannot wire its gates without also wiring the hook seams they belong beside.
This file provides the single cli-layer assembly helper that composes hook dispatch into a runtime.RunConfig. It lives in the cli layer (not runtime) to avoid a runtime→hooks→runtime import cycle: runtime stays hook-agnostic and only exposes the generic seams (BeforeToolCall/AfterToolCall/ShouldStopAfterTurn), while this helper knows about both the resolved Config.Hooks and the seams.
#419 establishes the skeleton: InstallHooks builds a Dispatcher (or short- circuits to nil when no hooks are configured, FR-18) and offers generic decorator combinators for the seams. The concrete per-event wiring is filled in by later issues (#420–#424); this file deliberately wires no event yet.
This file provides the cli-layer helper that runs the UserPromptSubmit hook event (US-007, FR-9) at the two prompt entry points (REPL + headless) before a prompt is submitted to the loop. It lives in the cli layer alongside the other hook assembly (hooks_install.go) because it bridges the resolved Dispatcher and the runtime.RunConfig, which runtime itself must not know about.
Two hook effects are supported, with block taking priority over injection:
- block (decision=block / exit 2): the prompt is NOT submitted. The caller decides how to surface the reason — the REPL returns to its input state and shows it, the headless driver exits non-zero. DispatchUserPromptSubmit only reports (block, reason); it does not itself abort.
- additionalContext: registered as a ONE-SHOT reminder on cfg.Reminders so the text is injected into THIS turn's provider context via the existing TransformContext seam, then never again. It is not written to the persisted message history (the reminder mechanism is ephemeral by construction).
This file provides the cli-layer helper that runs the SessionStart hook event (US-010, FR-1) synchronously at the run-start seam. It lives in the cli layer alongside the other hook assembly (hooks_install.go) because it bridges the resolved Dispatcher and the runtime.RunConfig, which runtime itself must not know about.
SessionStart is dispatched SYNCHRONOUSLY at run start rather than through the async OnEvent notifier: an async dispatch could land after the first turn's request is built, so its additionalContext would miss the first turn (SPEC §11.2). Dispatching inline before the loop starts guarantees the injected context is present for the very first turn.
Only injection is supported (there is nothing to block at session start): any additionalContext is registered as a ONE-SHOT reminder on cfg.Reminders so the text is injected into the first turn's provider context via the existing TransformContext seam, then never again. It is not written to the persisted message history (the reminder mechanism is ephemeral by construction).
This file provides the cli-layer decorator that runs the Stop and SubagentStop hook events (US-008/009, FR-10/12) at the loop's natural-end seam (runtime.RunConfig.OnStop). It lives in the cli layer because it bridges the resolved Dispatcher and runtime, which must not depend on hooks.
A Stop hook may block the run from ending and force a continuation, feeding its reason back as guidance. Left unchecked a hook that always blocks would loop forever, so the decorator holds a per-run consecutive-block counter and force-stops after maxConsecutiveStopBlocks (FR-12). The counter resets on any natural (non-blocking) stop, so an occasional block does not erode the budget.
Package run holds the run-assembly layer (US-005, #362): the shared setup that both the interactive REPL and the headless driver need — resolving the provider, building the tool set rooted at the working directory, discovering skills and plugins, and constructing the loop RunConfig. Pulling it out of cmd/golder lets the subpackages assemble a run through one exported API instead of duplicating the wiring.
Index ¶
- func ApplyToolPolicy(tools []agentcore.AgentTool, policy ToolPolicy) []agentcore.AgentTool
- func BuildDispatcher(set hooks.HookSet, deps HookDeps) *hooks.Dispatcher
- func BuiltinTools(cwd string, disabled bool) []agentcore.AgentTool
- func BuiltinToolsExcept(cwd string, disabled bool, except ...string) []agentcore.AgentTool
- func ChildToolSet(cwd string, policy ToolPolicy) []agentcore.AgentTool
- func ConfigDir() string
- func DispatchSessionStart(ctx context.Context, d *hooks.Dispatcher, cfg *runtime.RunConfig, ...)
- func DispatchUserPromptSubmit(ctx context.Context, d *hooks.Dispatcher, cfg *runtime.RunConfig, ...) (block bool, reason string)
- func ExecSessionsFromTools(tools []agentcore.AgentTool) *execsess.Manager
- func GrantWritableRoot(root string, persist bool) (made bool, why string)
- func InstallSeams(cfg *runtime.RunConfig, d *hooks.Dispatcher, deps HookDeps)
- func KillShellSessions(tools []agentcore.AgentTool)
- func LoadSkills(noSkills bool) ([]*runtime.Skill, error)
- func MemoryDir() string
- func MemoryRootFromTools(tools []agentcore.AgentTool) string
- func MemoryStoreFromTools(tools []agentcore.AgentTool) *memory.Store
- func NewConfig(model, providerName string, thinking agentcore.ThinkingLevel, ...) runtime.RunConfig
- func NewReviewer(model, providerName string, prov provider.Provider, ...) judge.Classifier
- func OpenMemoryStore(memEnabled bool) (*memory.Store, error)
- func PersistReadRoot(dir string) (made bool, why string)
- func PluginsDir() string
- func ReadableExtraRoots() []string
- func ResolveHookSet(cwd string, trusted bool) (hooks.HookSet, error)
- func ResolveThinkingLevel(cliLevel string) (agentcore.ThinkingLevel, error)
- func ReviewCheck(model, providerName string, stream provider.StreamFn, ...) judge.ReviewFunc
- func SandboxGate() func(toolName string) bool
- func SkillsDir() string
- func SnapshotRecorderFromTools(tools []agentcore.AgentTool) *agenttool.FileSnapshotRecorder
- func SplitToolNames(values []string) []string
- func TodoReminders(tools []agentcore.AgentTool) *runtime.ReminderRegistry
- func ToolRegistry(tools []agentcore.AgentTool) *agenttool.ToolRegistry
- func Trusted(cwd string) bool
- func ValidateToolPolicy(tools []agentcore.AgentTool, policy ToolPolicy) error
- func WireBashSandbox(tools []agentcore.AgentTool, cwd string)
- func WirePermissionState(tools []agentcore.AgentTool, state *permissions.State)
- type Env
- type Gates
- func (g *Gates) Authorization() agentcore.ToolAuth
- func (g *Gates) Chain() agentcore.BeforeToolCallFunc
- func (g *Gates) Install(cfg *runtime.RunConfig, d *hooks.Dispatcher, deps HookDeps)
- func (g *Gates) InstallDriver(ctx context.Context, cfg *runtime.RunConfig, set hooks.HookSet, deps HookDeps, ...) (*hooks.Dispatcher, func(agentcore.AgentEvent))
- func (g *Gates) InstallWith(cfg *runtime.RunConfig, seam agentcore.BeforeToolCallFunc, d *hooks.Dispatcher, ...)
- func (g *Gates) Seed(auth agentcore.ToolAuth) (refusedRoots int)
- type GatesOpts
- type HookDeps
- type ReviewNotes
- type ToolPolicy
- type ToolPolicyError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyToolPolicy ¶
func ApplyToolPolicy(tools []agentcore.AgentTool, policy ToolPolicy) []agentcore.AgentTool
ApplyToolPolicy narrows a tool set to the allow list and then removes the deny list. Both empty means no restriction and the input is returned unchanged, so the default path is a true no-op.
Deny runs after allow, which makes deny win when a name appears on both sides. That ordering is deliberate: the fail-closed reading of a contradictory policy is "do not run it".
This filters the set handed to the model, so it sits at the tool-registration layer — strictly before the BeforeToolCall confirmation gate. A removed tool is never advertised and never dispatchable, which is why --approve (which only waives per-call confirmation) cannot widen the boundary.
func BuildDispatcher ¶
func BuildDispatcher(set hooks.HookSet, deps HookDeps) *hooks.Dispatcher
BuildDispatcher builds the run's Dispatcher from the resolved hook set without touching a RunConfig. It is the entry point for the multi-turn drivers (REPL / TUI) that resolve hooks and fire SessionStart once per session, then install the per-turn seams (InstallSeams) on each turn's freshly-built RunConfig. It returns nil for an empty set (FR-18), so callers gate all hook work on non-nil.
func BuiltinTools ¶
BuiltinTools returns the default file/shell tool set rooted at cwd, or nil when tools are disabled. The todo tool is stateful: a single TodoStore is created here and held by the one TodoTool instance, so the task list persists across calls within a run (a later write replaces the plan).
func BuiltinToolsExcept ¶
BuiltinToolsExcept returns the default builtin tool set (BuiltinTools) with any tool whose name matches one of the except names removed. It backs the nesting guard for the generic task tool: a child sub-agent's registry is built with "task" excluded so a child can never spawn further sub-agents, capping delegation depth at one. With no except names it is equivalent to BuiltinTools.
func ChildToolSet ¶
func ChildToolSet(cwd string, policy ToolPolicy) []agentcore.AgentTool
ChildToolSet builds the tool set for a task sub-agent: the builtins with "task" removed (the nesting guard capping delegation depth at one), narrowed by the parent's policy.
Inheriting the policy is load-bearing, not a nicety. A child that ignored it would be a one-line escape from the boundary: under --disallowed-tools bash the model could dispatch a sub-agent and run bash there instead. Any future spawn path must route through here for the same reason.
func ConfigDir ¶
func ConfigDir() string
ConfigDir returns the directory golder reads its global config layer from: $GOLDER_HOME, or ~/.golder by default. An empty string is returned when the home directory cannot be resolved and no override is set (the caller then treats the global layer as absent).
func DispatchSessionStart ¶
func DispatchSessionStart(ctx context.Context, d *hooks.Dispatcher, cfg *runtime.RunConfig, deps HookDeps, source string)
DispatchSessionStart runs the SessionStart event once at run start. source is "startup" for a fresh run or "resume" when continuing an existing session; it is carried in the HookInput so hooks can differentiate. Any additionalContext returned by the hook is registered as a one-shot reminder on cfg.Reminders (allocating a registry when cfg.Reminders is nil) so it is injected into the first turn only.
A nil dispatcher (no hooks configured) is a no-op.
func DispatchUserPromptSubmit ¶
func DispatchUserPromptSubmit(ctx context.Context, d *hooks.Dispatcher, cfg *runtime.RunConfig, deps HookDeps, prompt string) (block bool, reason string)
DispatchUserPromptSubmit runs the UserPromptSubmit event for a prompt about to be submitted. It returns (block, reason): when block is true the caller must NOT submit the prompt and should surface reason. When block is false and the hook returned additionalContext, that context is registered as a one-shot reminder on cfg.Reminders (allocating a registry when cfg.Reminders is nil) so it is injected into this turn only. Block takes priority: a blocking decision never also injects.
A nil dispatcher (no hooks configured) is a no-op that returns (false, "").
func ExecSessionsFromTools ¶
ExecSessionsFromTools returns the shared shell-session manager backing the run's bash / write_stdin tools, or nil when the shell tool is disabled.
func GrantWritableRoot ¶ added in v1.2.17
GrantWritableRoot makes a directory writable inside the sandbox, for this session and — when persist is true — for every later one. It is the callback behind the REPL prompt's `w`/`s` answers, the twin of the TUI dialog's rows, and it lives here for the same reason PersistReadRoot does: judge is a leaf package that can reach neither the sandbox registry nor the managed store, and this assembly point can.
func InstallSeams ¶
func InstallSeams(cfg *runtime.RunConfig, d *hooks.Dispatcher, deps HookDeps)
InstallSeams wires the tool-execution and Stop hook points onto cfg from an already-built dispatcher. It is the shared body of InstallHooks and the per-turn install path for multi-turn drivers. A nil dispatcher is a no-op, so callers can invoke it unconditionally.
PreToolUse is CHAINED onto the existing BeforeToolCall seam (occupied by the trust gate) rather than replacing it: trust runs first and stays authoritative (a trust block short-circuits before the user hook runs). PostToolUse is chained onto AfterToolCall as a last-writer so it can append feedback to an already-executed tool's result without undoing it. The Stop hook is chained onto the loop's natural-end seam (FR-10), bounded by the decorator's consecutive-block counter (FR-12).
func KillShellSessions ¶
KillShellSessions terminates every still-running shell session in tools. It is the driver-exit hook: without it a long-running command handed back as a bash_id would be orphaned when the process quits. No-op when the shell tool is disabled.
func LoadSkills ¶
LoadSkills discovers skills from SkillsDir() once, for both prompt injection and /skill-name registration. Under --no-skills it is a no-op.
func MemoryDir ¶
func MemoryDir() string
MemoryDir returns the persistent memory root directory: $GOLDER_HOME/memory, or ~/.golder/memory by default (a single global store so cross-project "global" memories are searchable, mirroring the session store's ~/.golder base). It returns "" when the home directory cannot be resolved and no override is set.
func MemoryRootFromTools ¶
MemoryRootFromTools returns the persistent memory root the run's memory_search tool is backed by (its Store.Root()), or "" when persistent memory is not wired into this tool set (memory.enabled=false, --no-tools, or the store failed to open). It is the canonical source of the memory root for checkpoint persistence and context rebuild (<root>/sessions/<id>/checkpoint.md): callers resolve the root through the opened store rather than re-deriving it from the session store.
func MemoryStoreFromTools ¶
MemoryStoreFromTools returns the persistent memory Store backing the run's memory_search tool, or nil when persistent memory is not wired into this tool set. It lets status commands (/memory) inspect the live store without re-opening the database.
func NewConfig ¶
func NewConfig(model, providerName string, thinking agentcore.ThinkingLevel, prov provider.Provider, creds *provider.CredentialStore, reg *agenttool.ToolRegistry, reminders *runtime.ReminderRegistry, sched *agenttool.Schedule, budget *contextbudget.State) runtime.RunConfig
NewConfig builds the loop configuration shared by every driver: the provider stream, the dynamic API-key resolver, and the tool registry. It is the single definition of "how a run is wired", so the REPL (streamRun) and the headless driver cannot drift apart.
func NewReviewer ¶
func NewReviewer(model, providerName string, prov provider.Provider, creds *provider.CredentialStore, sessionID, cwd string, trusted bool) judge.Classifier
NewReviewer builds the model-backed classifier for one run: the static floor chained to the LLM reviewer, which grades calls with the session's active model. It is rebuilt per turn so a /model switch changes the reviewer with the conversation. A nil provider degrades to the static floor plus a fail-closed reviewer (never an allow).
func OpenMemoryStore ¶
OpenMemoryStore opens the persistent memory store under MemoryDir() (index DB at <root>/index.db). It returns (nil, nil) — not an error — when persistent memory is disabled (memEnabled=false) or the home dir is unresolvable, so the caller degrades to file-based auto-memory without treating the off state as a failure. A genuine open failure is returned as an error for the caller to log non-fatally.
func PersistReadRoot ¶ added in v1.2.17
PersistReadRoot writes a read grant to the managed store so it survives the process. It lives here, in the gate assembly, because that is where the two layers that need each other can meet: judge (which owns the read-scope gate and takes the answer) is a leaf package that cannot import the config layer, and the cli layer above this one imports run (host.go), so run cannot import cli.
alreadySeeded is not a failure: the grant is already permanent because config.toml carries it, and nothing is written — that file belongs to the user, and rewriting it would drop their comments.
func PluginsDir ¶
func PluginsDir() string
PluginsDir returns the directory external plugins are discovered from: $GOLDER_HOME/plugins, or ~/.golder/plugins by default. An empty string is returned when the home directory cannot be resolved and no override is set (Discover then treats it as "no plugins").
func ReadableExtraRoots ¶
func ReadableExtraRoots() []string
ReadableExtraRoots returns trusted directories the file tools may reach beyond the workspace root. The skills directory is included so the model can load the absolute SKILL.md paths golder advertises in the system prompt, and author or update skills there (they otherwise resolve outside the workspace and are rejected). An empty skills dir is dropped, so this stays a no-op when the home directory cannot be resolved.
func ResolveHookSet ¶
ResolveHookSet resolves the effective hook set through the same layered config chain as ResolveThinkingLevel (default < global < project < env), with one difference required by FR-14: the project layer (./.golder/config.json under cwd) is only merged when the directory is trusted. An untrusted directory therefore contributes no hooks, so a checked-out repo cannot run arbitrary commands until the user trusts it. A malformed layer file is a hard error, surfaced to the caller. The returned set is empty (len 0) when no layer defines hooks, which InstallHooks treats as "no hooks" (FR-18).
func ResolveThinkingLevel ¶
func ResolveThinkingLevel(cliLevel string) (agentcore.ThinkingLevel, error)
ResolveThinkingLevel resolves the effective reasoning-effort level through the layered config chain (US-023): default < global < project < env < CLI flag. The global layer is $GOLDER_HOME/config.json (or ~/.golder/config.json); the project layer is ./.golder/config.json in the working directory. A malformed layer file or an invalid resolved value is a hard error, surfaced to the caller for exit-code mapping. cliLevel is the raw --thinking-level flag ("" = unset, so lower layers show through).
func ReviewCheck ¶
func ReviewCheck(model, providerName string, stream provider.StreamFn, creds *provider.CredentialStore, sessionID string) judge.ReviewFunc
ReviewCheck adapts the provider stream to judge.ReviewFunc: one system + user message, drained to a final text answer. Runtime failures (including a terminal error/abort) are returned as errors so the reviewer fails closed rather than reading an empty answer as approval.
func SandboxGate ¶
SandboxGate is the predicate the judge gate asks before failing a Sandbox-tier verdict closed: which tool calls this process can actually run isolated. It mirrors WireBashSandbox's decision exactly — bash runs under the platform sandbox (sandbox-exec on macOS, bubblewrap on Linux) when the mode allows it and the platform provides it, and (in auto mode) a grader is configured — so the gate never passes a call through to an execution layer that would run it unsandboxed. Nil means nothing can be sandboxed and the gate keeps its prompt/fail-closed behavior.
func SkillsDir ¶
func SkillsDir() string
SkillsDir returns the directory skills are loaded from. It defaults to ~/.agents/skills, overridable via GOLDER_SKILLS_DIR. An empty string is returned when the home directory cannot be resolved and no override is set.
func SnapshotRecorderFromTools ¶
func SnapshotRecorderFromTools(tools []agentcore.AgentTool) *agenttool.FileSnapshotRecorder
SnapshotRecorderFromTools returns the shared FileSnapshotRecorder backing the run's apply_patch tool, or nil when file tools are disabled (--no-tools). The REPL uses it to commit a per-turn restore point and to serve /rewind.
func SplitToolNames ¶
SplitToolNames normalizes raw --allowed-tools / --disallowed-tools values into a flat list of tool names. Each value may itself be a comma-separated list, so `--allowed-tools "read,grep"` and `--allowed-tools read --allowed-tools grep` are equivalent. Entries are lowercased and trimmed, and empty entries dropped, so `"read, ,grep"` yields [read grep]. Matching is case-insensitive on purpose: users coming from Claude Code write `Read`/`Bash`, which must hit golder's `read`/`bash`.
func TodoReminders ¶
func TodoReminders(tools []agentcore.AgentTool) *runtime.ReminderRegistry
TodoReminders builds the per-turn system-reminder registry for a tool set (US-002): it locates the stateful TodoTool and registers a TodoReminderProvider over its shared store, so the model is reminded of unfinished tasks each turn. It also registers a MemoryReminderProvider over the memory_search tool's store (issue #481) when present, so relevant persisted memory is recalled each turn (this is the recall channel used after auto-compaction), and the stateless BudgetReminderProvider, which reads the run's budget state from the context and reminds once per low-budget threshold crossing. Returns nil when no provider applies (e.g. --no-tools), leaving injection disabled.
func ToolRegistry ¶
func ToolRegistry(tools []agentcore.AgentTool) *agenttool.ToolRegistry
ToolRegistry builds a registry from the given tools (skipping any that fail to register, e.g. a bad schema, which should not happen for built-ins).
func Trusted ¶
Trusted reports whether cwd is a trusted directory per the shared trust store ($GOLDER_HOME/trust.json). It is the trust gate for the non-interactive drivers (headless / TUI / sub-agent) that have no live trust.Manager to consult, so ResolveHookSet can honor FR-14 uniformly. A missing or unreadable store is treated as untrusted (fail closed): a directory only runs project-layer hooks after the user has explicitly trusted it.
func ValidateToolPolicy ¶
func ValidateToolPolicy(tools []agentcore.AgentTool, policy ToolPolicy) error
ValidateToolPolicy checks every allow/deny entry against the assembled tool set. It must run AFTER the full set exists (builtins + memory + task + plugins), because plugin and memory tool names are only known at runtime; validating right after flag parsing would reject legitimate plugin names.
An empty tool set (--no-tools) skips validation entirely: there is nothing to constrain, and reporting every name as unknown would be noise.
func WireBashSandbox ¶
WireBashSandbox injects the sandbox runner into every BashTool in tools. It is called from BuiltinTools so every driver (REPL, TUI, headless, /btw side runs, task children, sub-agent RPC, webhook) inherits platform isolation without its own wiring. The reviewer is injected separately (per turn, by the driver) because it depends on the live model, which /model can switch.
The matrix is deliberately conservative:
- GOLDER_SANDBOX=off → no runner: sandbox-tier commands never execute (the gate fails closed) unless a human approved one explicitly.
- GOLDER_SANDBOX=auto (default) → sandbox-tier verdicts run under the platform sandbox when it provides one (sandbox-exec on macOS, bubblewrap on Linux).
- GOLDER_SANDBOX=enforce → every foreground command runs sandboxed and fails closed when no runner is available.
func WirePermissionState ¶
func WirePermissionState(tools []agentcore.AgentTool, state *permissions.State)
WirePermissionState attaches the live approval mode to every BashTool so the execution layer honors read-only/full-access and contains an auto-mode reviewer failure (see BashTool.sandboxRoute). Task-child tool sets are wired with the same state, so a sub-agent cannot outrun the parent's mode.
Types ¶
type Env ¶
type Env struct {
Cwd string
Tools []agentcore.AgentTool
Provider provider.Provider
ProviderName string
SysPrompt string
// Skills is the discovered skill set (loaded once here, empty under
// --no-skills). It is threaded into the REPL so each skill is registered as a
// /skill-name command, and the model-invocable subset is already injected into
// SysPrompt.
Skills []*runtime.Skill
// Prompt is the launch context the system prompt was built from. It is kept
// so a RESUMED session can rebuild its prompt through the same path: our own
// text (guide, environment, AGENTS.md, skills) comes from here, the session's
// recorded user inputs from the session header (see cli.ResumeSystemPrompt).
Prompt runtime.PromptInputs
// Plugins holds any loaded external plugins so the caller can Close them when
// the run ends. It is nil when no plugins were discovered.
Plugins *plugin.Manager
// Memory is the persistent memory store opened once for the run (issue #481),
// or nil when persistent memory is disabled (memory.enabled=false), tools are
// disabled (--no-tools), or the store could not be opened (a non-fatal
// failure). When non-nil the caller MUST Close it when the run ends. The store
// is also handed to the memory_search tool (in Tools) and, through it, the
// per-turn memory reminder provider, so this field exists mainly so the owner
// can close the DB — downstream wiring reaches the store via the tool.
Memory *memory.Store
// Schedule is the session-local reminder scheduler (issue #565), or nil when
// tools are disabled. Its schedule_* tools are already in Tools; the store is
// surfaced so run assembly can wire due-reminder delivery into the loop's
// GetFollowUpMessages seam (see NewConfig) and front-ends can reach it via
// agenttool.ScheduleFromTools.
Schedule *agenttool.Schedule
// Permissions is the live approval mode shared by every gate and bash tool
// assembled here. /permissions mutates it; a switch applies to the next
// tool call, even mid-run.
Permissions *permissions.State
// ReviewNotes is the announcement sink for mode decisions (approvals,
// sandbox routing, denials, read-only blocks). The parent gate and every
// task-child gate publish here; the active driver registers a handler so
// the notes reach its transcript.
ReviewNotes *ReviewNotes
// Budget is the session-scoped context-window budget shared by every run of
// the session. Tools and the low-budget reminder read it through the run
// context; keeping one object per session means the reminder ladder survives
// across prompts instead of restarting at every run.
Budget *contextbudget.State
}
Env is the environment every run shares: the working directory, the tool set rooted at it, the resolved provider, and the system prompt. It is assembled once (SetupEnv) and consumed by whichever driver runs.
func SetupEnv ¶
func SetupEnv(model, baseURL, protocol, providerName, apiKey string, noTools, noSkills bool, systemPrompt string, appendSystemPrompt []string, memEnabled bool, policy ToolPolicy) (Env, error)
SetupEnv resolves the provider for model/baseURL, builds the tool set rooted at the working directory, and constructs the system prompt — the setup the REPL and headless drivers both need. systemPrompt, when non-empty, replaces the default base instruction (mirrors pi's --system-prompt); appendSystemPrompt entries are each resolved (a path to an existing file is read, otherwise the value is literal text) and layered onto the end of the prompt (mirrors pi's --append-system-prompt). apiKey is the resolved credential (CLI --api-key or config.toml) used as the override for sub-agent credential resolution so dispatched task children authenticate the same way the parent does. policy is the --allowed-tools/--disallowed-tools boundary; it is validated against the fully assembled tool set and then applied, so an unknown tool name is a usage error rather than a silently ineffective boundary. It returns an error rather than exiting so the caller owns exit-code mapping.
type Gates ¶ added in v1.2.17
type Gates struct {
// contains filtered or unexported fields
}
Gates is a session's assembled gate chain. It is immutable after construction except for the trust state its Manager carries, and safe for concurrent use: Install is called per run (possibly from concurrent sub-agent goroutines), and it only reads shared state.
func NewGates ¶ added in v1.2.17
NewGates assembles the session's gates. It never returns nil: a Gates with no inputs still installs hooks and the authorization snapshot, and its chain is nil (an ungated run), which is what the callers previously expressed with a nil BeforeToolCall.
func (*Gates) Authorization ¶ added in v1.2.17
Authorization snapshots the session's decisions for a run that cannot share this chain: a process-isolated sub-agent. It reports what the session answered, not what it was asked: Trusted is true when the run has no trust gate at all (an explicit non-interactive invocation) or the directory is trusted, so the child proceeds exactly where the parent would have.
func (*Gates) Chain ¶ added in v1.2.17
func (g *Gates) Chain() agentcore.BeforeToolCallFunc
Chain returns the interactive gate chain on its own, for a driver that wraps it in its own transport (the REPL's remote-control bridge intercepts confirm requests before they reach the terminal). Drivers that do not wrap should call Install instead, which also wires hooks and the inherited chain.
func (*Gates) Install ¶ added in v1.2.17
Install wires the session's gates onto cfg: the interactive chain as the tool-execution seam, the hook seams when a dispatcher is resolved, and the derived (channel-less) chain as the chain a spawned sub-agent inherits.
d is the session's hook dispatcher (nil when no hooks are configured, FR-18), passed per call rather than held on Gates because a driver may resolve hooks after assembling its gates — the TUI defers hook loading until the first-run trust answer.
func (*Gates) InstallDriver ¶ added in v1.2.17
func (g *Gates) InstallDriver(ctx context.Context, cfg *runtime.RunConfig, set hooks.HookSet, deps HookDeps, source string, onEvent func(agentcore.AgentEvent)) (*hooks.Dispatcher, func(agentcore.AgentEvent))
InstallDriver wires the session's gates AND the resolved hook set onto cfg in one call: the interactive gate chain, the PreToolUse/PostToolUse seams, the Stop hook, the SessionStart dispatch, and the hook notifier chained onto onEvent. It is the single entry point a driver uses, so a driver cannot wire one half (gates) while forgetting the other (hooks), and the chain a spawned sub-agent inherits carries the tool-use hooks with it.
set is the already-resolved, trust-gated hook set (see ResolveHookSet). When it is empty NewDispatcher returns nil and this is a no-op beyond the gates, the hot path paying nothing (FR-18).
func (*Gates) InstallWith ¶ added in v1.2.17
func (g *Gates) InstallWith(cfg *runtime.RunConfig, seam agentcore.BeforeToolCallFunc, d *hooks.Dispatcher, deps HookDeps)
InstallWith is Install with a driver-supplied interactive seam: the REPL's remote-control bridge wraps the session's chain in its own transport (a paired browser answers instead of the terminal), so the driver passes the wrapped chain here rather than overwriting the seam after Install. The inherited chain, the hook seams and the Stop decorator are unchanged — whatever wraps the interactive chain, a sub-agent still inherits the session's gates rather than the wrapper.
func (*Gates) Seed ¶ added in v1.2.17
Seed applies a parent's authorization snapshot to this session's state, before any run is installed: the process-isolated sub-agent's side of Authorization. It never widens beyond what the parent held — the snapshot is the parent's decision — and it reports how many read roots were refused (too broad, or malformed), so the caller can note the difference.
type GatesOpts ¶ added in v1.2.17
type GatesOpts struct {
// Trust is the session trust store. Nil disables the trust gate, which is
// the right shape for an explicit non-interactive invocation (headless,
// whose authorization IS the invocation) and for the SDK.
Trust *trust.Manager
// Cwd is the directory the trust decision and the workspace boundary are
// about: never a tool argument, always the run's workspace.
Cwd string
// Perms is the live approval mode shared with the tool set; /permissions
// mutates it and the next call obeys.
Perms *permissions.State
// Notes receives one announcement per non-trivial decision.
Notes *ReviewNotes
// Sandboxed reports whether a Sandbox-tier call will actually be isolated
// by the execution layer (see SandboxGate).
Sandboxed func(toolName string) bool
// Classifier builds the reviewer for one chain build. It is a factory
// rather than a value because /model switches change the reviewer's model
// between runs; nil keeps the static floor and fails closed on gated calls.
Classifier func() judge.Classifier
// In/Out/Mu are the stdin answer channel (interactive line drivers).
In *bufio.Reader
Out io.Writer
Mu *sync.Mutex
// Confirm is the driver's own answer channel (the TUI dialog, a browser
// bridge). Used in preference to stdin when both are set.
Confirm func(ctx context.Context, req judge.ApprovalRequest) judge.ApprovalAnswer
// TrustConfirm, when set, answers trust questions instead of Confirm. The
// TUI uses it because a paired browser answers trust questions while local
// dialogs answer the rest (the pre-existing routing); nil keeps Confirm for
// every question.
TrustConfirm func(ctx context.Context, req judge.ApprovalRequest) judge.ApprovalAnswer
// ExtraRoots are read roots the session advertised itself (the skills
// directory), never asked about. See ReadableExtraRoots.
ExtraRoots []string
}
GatesOpts carries the session-scoped inputs of the gate chain. Every field is optional except Cwd; a zero Gates is the "no gates" run (an SDK session with nothing wired), not an error.
type HookDeps ¶
HookDeps carries the run-scoped context a Dispatcher needs: the session id and project directory that populate each HookInput / the hook process environment, and the writer that receives isolation warnings. WarnLog may be nil (defaults to os.Stderr), matching the plugin.EventNotifier convention.
type ReviewNotes ¶
type ReviewNotes struct {
// contains filtered or unexported fields
}
ReviewNotes is the concurrency-safe announcement sink for permission decisions. Gates publish notes from the run goroutine (including task-child runs); the active driver registers a single handler that forwards them to its transcript. A nil handler drops notes.
func (*ReviewNotes) Emit ¶
func (r *ReviewNotes) Emit(n judge.Note)
Emit delivers one note to the registered handler.
func (*ReviewNotes) Set ¶
func (r *ReviewNotes) Set(fn func(judge.Note))
Set replaces the handler. Passing nil drops subsequent notes.
type ToolPolicy ¶
ToolPolicy is the user-declared tool boundary for a run: the --allowed-tools whitelist and the --disallowed-tools blacklist, already normalized by SplitToolNames. It is passed as one value rather than two adjacent []string parameters so the two lists cannot be swapped at a call site — silently inverting a security boundary is exactly the bug that must be impossible.
The zero value means "no restriction" and every operation on it is a no-op.
func NewToolPolicy ¶
func NewToolPolicy(allowed, disallowed []string) ToolPolicy
NewToolPolicy normalizes raw flag values into a policy.
func (ToolPolicy) IsZero ¶
func (p ToolPolicy) IsZero() bool
IsZero reports whether the policy constrains nothing.
type ToolPolicyError ¶
type ToolPolicyError struct {
// UnknownAllowed and UnknownDisallowed are the unrecognized names from each
// flag. Both are reported in one error so a user with two typos fixes both in
// one round rather than one per run.
UnknownAllowed []string
UnknownDisallowed []string
// Available is the sorted set of names that would have been accepted.
Available []string
}
ToolPolicyError reports --allowed-tools / --disallowed-tools entries that name no existing tool. It is a usage error — the caller maps it to exit code 2 — because silently ignoring a typo is the worst outcome available: the user believes a boundary is in force when it is not.
func (*ToolPolicyError) Error ¶
func (e *ToolPolicyError) Error() string