run

package
v1.5.148 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 35 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

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.

BuildDispatcher builds a dispatcher (or short-circuits to nil when no hooks are configured, FR-18) and InstallSeams wires the per-event seams the issues #420–#424 landed: PrepareArguments/PreToolUse, AfterToolCall/PostToolUse and the Stop family.

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 managed extension sources, 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

Constants

View Source
const DefaultJevEndpoint = "https://api.typesafe.ai/v1/systemone"

DefaultJevEndpoint is TypeSafe's evaluation endpoint.

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

func BuiltinTools(cwd string, disabled bool) []agentcore.AgentTool

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

func BuiltinToolsExcept(cwd string, disabled bool, except ...string) []agentcore.AgentTool

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 golder state root, which is where the global config layer lives. An empty string means the root cannot be resolved (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

func ExecSessionsFromTools(tools []agentcore.AgentTool) *execsess.Manager

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

func GrantWritableRoot(root string, persist bool) (made bool, why string)

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 and the TUI dialog's rows.

One row is the whole answer: the sandbox's profile builders read the table directly (seatbelt.WritableRoots delegates to it), so there is no second store to mirror into and no window where the two disagree.

func InstallExtensions added in v1.5.15

func InstallExtensions(cfg *runtime.RunConfig, m *extensions.Manager, prompt runtime.PromptInputs)

InstallExtensions publishes a complete catalog at turn boundaries, on the loop goroutine. Both model declarations and execution see the same registry.

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 install body every driver and the per-turn install path for multi-turn drivers use. A nil dispatcher is a no-op, so callers can invoke it unconditionally.

PreToolUse runs at PrepareArguments: its rewrite is schema-validated and then the trust, boundary and authorization gates see the final input exactly ONCE. A hook block stops the call before any gate. 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 JevRouter added in v1.3.0

func JevRouter(fallback judge.Classifier, creds *provider.CredentialStore, cwd string, trusted bool) judge.Classifier

JevRouter wraps a reviewer with the decision-model fast path. It returns the reviewer unchanged when the feature is off or no credential exists, so the caller gets byte-for-byte the behaviour it had before — an absent key must never add a failed round trip to every gated call.

func KillShellSessions

func KillShellSessions(tools []agentcore.AgentTool)

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

func LoadSkills(noSkills bool) ([]*runtime.Skill, error)

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: memory/ under the golder state root (a single global store so cross-project "global" memories are searchable, mirroring the session store's location). It returns "" when the root cannot be resolved.

func MemoryRootFromTools

func MemoryRootFromTools(tools []agentcore.AgentTool) string

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

func MemoryStoreFromTools(tools []agentcore.AgentTool) *memory.Store

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 classifier the approval gate consults for one run:

static floor → the routine grader → session model

The routine grader is ONE of two things, never both:

the decision model (JEV)  when a credential for it resolves
the local rule table      otherwise

They are alternatives because they answer the same question — "is this call routine enough to settle here?" — and a run wants one answer, from one place, with the calls neither can settle going to the session model. Chaining them would also mean the decision model's escalations landed in the table, which is not what an escalation means: it is that layer saying the call deserves a model's judgment, not a cheaper one's.

It is rebuilt per turn so a /model switch changes the last stage with the conversation. A nil provider degrades to the static floor plus a fail-closed reviewer (never an allow). See judge.Local for what the table asserts.

func OpenMemoryStore

func OpenMemoryStore(memEnabled bool) (*memory.Store, error)

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

func PersistReadRoot(dir string) (made bool, why string)

PersistReadRoot writes a read grant into the authorization table as a remembered row, 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 owns the boundary gate and takes the answer, and this layer opens the managed file the row has to reach.

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

func ResolveHookSet(cwd string, trusted bool) (hooks.HookSet, error)

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 config.json in the golder state root; 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

func SandboxGate() func(toolName string) bool

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

func SplitToolNames(values []string) []string

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.

The memory provider is wired with the memory recall policy: it ships DISABLED (config.DefaultMemoryRecall), and when enabled it is guarded by a minimum query size, a relevance overlap, and a throttled index reconcile — see MemoryRecallSettings.

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

func Trusted(cwd string) bool

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 + extensions), because extension and memory tool names are only known at runtime; validating right after flag parsing would reject legitimate external 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

func WireBashSandbox(tools []agentcore.AgentTool, cwd string)

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.

func WritableAt added in v1.3.0

func WritableAt(path string) bool

WritableAt reports whether a path is already writable for this session, straight from the authorization table. The boundary gate asks it before putting a write question, so a patch into a directory a command may already write is not asked about again — the answer was given once, and the table is where it lives.

Types

type Env

type Env struct {
	Cwd          string
	Tools        []agentcore.AgentTool
	Provider     provider.Provider
	ProviderName string
	SysPrompt    string
	// Credentials is the one provider credential resolver shared by the driver,
	// model picker, reviewer and sub-agents. It carries no displayable value.
	Credentials *provider.CredentialStore

	// 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

	// Extensions owns managed CLI/MCP/legacy sources. Discovery never starts
	// third-party code. The caller closes it when the session ends.
	Extensions *extensions.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, setup ...SetupOptions) (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

func NewGates(opts GatesOpts) *Gates

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

func (g *Gates) Authorization() agentcore.ToolAuth

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) ChainAfterTrust added in v1.3.3

func (g *Gates) ChainAfterTrust() agentcore.BeforeToolCallFunc

ChainAfterTrust returns the same boundary → permission chain without the trust gate. A remote-control bridge uses it after the browser answered the trust question itself: the browser replaces the trust prompt, never the boundary or permission gates. Keeping this a named chain (rather than a context flag) makes the bypass impossible to reintroduce by accident.

func (*Gates) Install added in v1.2.17

func (g *Gates) Install(cfg *runtime.RunConfig, d *hooks.Dispatcher, deps HookDeps)

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 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) SandboxDenialAsker added in v1.3.1

func (g *Gates) SandboxDenialAsker() func(ctx context.Context, path, summary string) agenttool.SandboxDenialAnswer

SandboxDenialAsker builds the post-execution capability review for a denied path and applies an allow. It is deliberately NOT a second approval system:

  • auto: ReviewRecovery lets the reviewer decide whether to grant this one path. No Confirm and no stdin dialog is touched, so a denied command either retries contained or fails with a reason the model can act on;
  • ask: the same ReviewRecovery filters an outright reviewer denial and otherwise puts one capability question to the person;
  • read-only/full-access: no recovery question exists.

nil means there is no mode that can answer (or, for ask, no dialog channel): the denial keeps its labeling and the flow continues.

func (*Gates) Seed added in v1.2.17

func (g *Gates) Seed(auth agentcore.ToolAuth) (refusedRoots int)

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
	// OnPrompt, when set, is told the question just before a prompt is put to
	// the person and returns the function to call once it is answered. It is
	// how a session reports "this pane is waiting for a human" to the terminal
	// multiplexer around it (see internal/hostcompat): the gates own every
	// moment a person is asked something, which is exactly the moment a host's
	// rail, Inbox and phone alerts care about.
	//
	// It is called on the run goroutine and must not block; the chain passes it
	// to all three gates (trust, read scope, permission), so one hook covers
	// every prompt a session can show.
	OnPrompt func(question string) func()
	// 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

type HookDeps struct {
	SessionID  string
	ProjectDir string
	WarnLog    io.Writer
}

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 JevSettings added in v1.3.0

type JevSettings struct {
	// Enabled reports whether the cheap judge participates. It is ON by
	// default: a run that has a TypeSafe credential gets the fast path, and a
	// run without one behaves exactly as it did before this layer existed.
	Enabled bool
	// Endpoint is where evaluations are sent.
	Endpoint string
	// Timeout bounds one evaluation.
	Timeout time.Duration
}

JevSettings is the decision-model reviewer's resolved configuration.

func JevSettingsFromEnv added in v1.3.0

func JevSettingsFromEnv(getenv func(string) string) JevSettings

JevSettingsFromEnv resolves the settings. GOLDER_JEV=off (or 0/false/no/ disabled) turns the cheap judge off entirely; GOLDER_JEV_ENDPOINT and GOLDER_JEV_TIMEOUT_MS override the endpoint and the per-call timeout.

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 NewReviewNotes

func NewReviewNotes() *ReviewNotes

NewReviewNotes returns an empty sink.

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 SetupOptions added in v1.5.15

type SetupOptions struct {
	NoExtensions bool
	// NoTuios excludes the terminal multiplexer tools, including from task
	// children, even when the process inherited a tuios environment.
	NoTuios bool
	// Cwd overrides the process working directory for this assembled environment
	// without calling os.Chdir. Desktop projects use it to keep multiple project
	// roots in one process; CLI callers leave it empty.
	Cwd string
}

type ToolPolicy

type ToolPolicy struct {
	Allow []string
	Deny  []string
}

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) AllowsName added in v1.5.15

func (p ToolPolicy) AllowsName(name string) bool

AllowsName also applies to tools discovered after startup. A new catalog cannot widen the operator's allow/deny boundary.

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

Jump to

Keyboard shortcuts

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