tools

package
v0.1.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: Apache-2.0 Imports: 57 Imported by: 1 module, 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 tools is everything the agent can do and the rules it does it under: file tools through the workspace's sandbox (with checkpoints for undo), shell commands under the command policy and the OS sandbox, approvals and permission rules, web fetch and search, MCP servers, skill scripts, images, the task list and questions to the user (spec_filetools_006, spec_shell_007, spec_approvals_005).

Index

Constants

View Source
const (
	RuleShell  = "shell"  // a command, with the command policy's pattern syntax
	RuleRead   = "read"   // a path glob (deny only: it becomes a blocked path)
	RuleWrite  = "write"  // a path glob for creates and edits
	RuleDelete = "delete" // a path glob for deletions
	RuleWeb    = "web"    // a host glob; *.example.com also matches example.com
	RuleSearch = "search" // a web search provider
	RuleMCP    = "mcp"    // server:tool, globs allowed
	RuleSkill  = "skill"  // a skill name
	RuleAgent  = "agent"  // an agent name, for invoke_agent
	RuleTool   = "tool"   // a bare tool name, e.g. web_search
)

Rule kinds: what a rule's pattern is matched against.

View Source
const (
	TaskPending    = "pending"
	TaskInProgress = "in_progress"
	TaskDone       = "done"
)

Task statuses in the todo list.

View Source
const DefaultMaxFileSize int64 = 10 * 1024 * 1024

DefaultMaxFileSize bounds how much of a single file the tools will load into memory.

View Source
const (

	// SkillOutputDir is where scripts write, relative to the workspace.
	SkillOutputDir = ".blitz/skill-output"
)

Variables

View Source
var (
	// ErrOutsideWorkspace is returned when a path is not under any sandbox root.
	ErrOutsideWorkspace = errors.New("path is outside the workspace")
	// ErrReadOnlyPath is returned when writing under a read-only root.
	ErrReadOnlyPath = errors.New("path is read-only")
	// ErrBlockedPath is returned when a path matches a blocked-path pattern.
	ErrBlockedPath = errors.New("path is blocked by sandbox policy")
)
View Source
var ErrBlockedAddress = errors.New("destination address is not allowed")

ErrBlockedAddress is returned when a request targets a non-public address.

View Source
var ErrGitDir = errors.New("the .git directory can't be opened here")

ErrGitDir: the repository's .git directory is never read or written.

View Source
var ErrNoScriptBox = errors.New("no sandbox is available for scripts")

ErrNoScriptBox means no sandbox is available, so scripts can't run.

View Source
var ErrNotApproved = errors.New("action not approved")

ErrNotApproved is returned when an action is denied or cannot be approved.

View Source
var ErrNothingToUndo = errors.New("nothing to undo")

ErrNothingToUndo is returned when no checkpoint has changes to restore.

View Source
var ErrTooLarge = errors.New("file too large")

ErrTooLarge: the file is over the size the caller reads.

Functions

func DefaultShellWritableDirs

func DefaultShellWritableDirs() []string

DefaultShellWritableDirs returns scratch locations commands commonly need: the temp dirs and the user cache dir (e.g. the Go build cache).

func MountsFor

func MountsFor(python string) []string

MountsFor returns the directories an interpreter needs mounted, beyond the system directories every sandbox gets: its installation prefix when it lives elsewhere (e.g. /opt/python3.13).

func NewActivateSkillTool

func NewActivateSkillTool(provider *skills.Provider, policy *config.SkillPolicy) (tool.Tool, error)

NewActivateSkillTool creates an ADK tool for activating a skill. policy (nil: the defaults) decides which of its scripts may run.

func NewApplyPatchTool

func NewApplyPatchTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewApplyPatchTool creates the apply_patch tool. The whole patch is validated before anything is written, and it is applied all-or-nothing: if any write fails, files already changed are restored.

func NewAskUserQuestionTool

func NewAskUserQuestionTool(hooks *Hooks) (tool.Tool, error)

NewAskUserQuestionTool creates an ADK tool for asking user questions. The prompt is delegated to hooks so it shares the host's stdin reader instead of competing with it for buffered input.

func NewCreateFileTool

func NewCreateFileTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewCreateFileTool creates an ADK tool for creating files.

func NewDeleteFileTool

func NewDeleteFileTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewDeleteFileTool creates an ADK tool for deleting files.

func NewDeleteSnippetTool

func NewDeleteSnippetTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewDeleteSnippetTool creates an ADK tool for removing code snippets.

func NewEnterPlanModeTool

func NewEnterPlanModeTool(hooks *Hooks) (tool.Tool, error)

NewEnterPlanModeTool lets the agent choose to plan before changing anything ([blitz] plan_review = "agent-decides").

func NewExitPlanModeTool

func NewExitPlanModeTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewExitPlanModeTool shows the agent's plan to the user, who carries it out (in the default or accept-edits mode), asks for changes, or keeps planning. An approved plan is saved under .blitz/plans in the workspace and ends the planning: the workspace then asks the agent to carry it out.

func NewGlobTool

func NewGlobTool(ws *Workspace) (tool.Tool, error)

NewGlobTool creates glob: find files by name pattern.

func NewGrepTool

func NewGrepTool(ws *Workspace) (tool.Tool, error)

NewGrepTool creates an ADK tool for workspace grep searching.

func NewInvokeAgentTool

func NewInvokeAgentTool(registry *agents.Registry, hooks *Hooks) (tool.Tool, error)

NewInvokeAgentTool creates an ADK tool for subagent delegation. The actual invocation is supplied at runtime through hooks.SetSubagentInvoker.

func NewListAgentsTool

func NewListAgentsTool(registry *agents.Registry) (tool.Tool, error)

NewListAgentsTool creates an ADK tool for listing agents.

func NewListFilesTool

func NewListFilesTool(ws *Workspace) (tool.Tool, error)

NewListFilesTool creates an ADK tool for listing directory files.

func NewListSkillsTool

func NewListSkillsTool(provider *skills.Provider) (tool.Tool, error)

NewListSkillsTool creates an ADK tool for searching skills.

func NewManageBackgroundTool

func NewManageBackgroundTool(pm *ProcessManager) (tool.Tool, error)

NewManageBackgroundTool creates the tool for inspecting and stopping background processes.

func NewReadFileTool

func NewReadFileTool(ws *Workspace) (tool.Tool, error)

NewReadFileTool creates an ADK tool for reading files.

func NewReplaceInFileTool

func NewReplaceInFileTool(ws *Workspace, hooks *Hooks) (tool.Tool, error)

NewReplaceInFileTool creates an ADK tool for targeted search-and-replace.

func NewRunShellCommandTool

func NewRunShellCommandTool(cfg ShellConfig) (tool.Tool, error)

NewRunShellCommandTool creates an ADK tool for running shell commands.

func NewRunSkillScriptTool

func NewRunSkillScriptTool(s *SkillScripts) (tool.Tool, error)

NewRunSkillScriptTool creates run_skill_script.

func NewTodoTool

func NewTodoTool() (tool.Tool, error)

NewTodoTool keeps the agent's task list for a multi-step job; front ends show it as a checklist (see TodoItems). It changes nothing else, so it works in plan mode too.

func NewUniversalConstructorTool

func NewUniversalConstructorTool(toolsDir string, hooks *Hooks, env *ExecEnv, policy *CommandPolicy) (tool.Tool, error)

NewUniversalConstructorTool creates the Helios Universal Constructor tool. Forged tools are stored in toolsDir (default ~/.blitz/uc_tools), which is created lazily on the first create. Runs go through the command policy as "universal_constructor <tool> <args...>" and the OS sandbox.

func NewViewImageTool

func NewViewImageTool(r *Registry) (tool.Tool, error)

NewViewImageTool lets the model look at an image in the workspace: screenshots, diagrams, UI mock-ups, test output.

func NewWebFetchTool

func NewWebFetchTool(cfg WebFetchConfig, hooks *Hooks) (tool.Tool, error)

NewWebFetchTool creates web_fetch: it retrieves a public web page and returns readable text. Domains outside web.allow_domains need approval.

func NewWebSearchTool

func NewWebSearchTool(cfg WebSearchConfig, hooks *Hooks) (tool.Tool, error)

NewWebSearchTool creates web_search for a configured provider.

func PromptID

func PromptID(ctx context.Context) string

PromptID returns the ID WithPromptID set ("" if none).

func SystemPython

func SystemPython() (string, error)

SystemPython is the python3 on PATH, as its real path (so it names the installed version, and so the directories it lives in can be mounted).

func Unattended

func Unattended(ctx context.Context, decide api.Approver) context.Context

Unattended marks ctx as an unattended run (a worker): approvals in it go only to decide, bypassing auto-approval, remembered and saved rules and the interactive approver, and nothing decided is remembered; questions to the user are refused. The run gets exactly what decide permits.

func UserPath

func UserPath(p string) (string, error)

UserPath cleans a workspace-relative path from the user ("" is the workspace itself).

func WithFetchGrants

func WithFetchGrants(ctx context.Context, urls []string) context.Context

WithFetchGrants lets web_fetch read exactly these URLs without asking, for calls made with ctx (one turn). The user picked them (/search web); any other URL, including links found on these pages and redirects to another host, still needs approval.

func WithPlanGate

func WithPlanGate(ctx context.Context, g *PlanGate) context.Context

WithPlanGate gives a turn its plan state.

func WithPromptID

func WithPromptID(ctx context.Context, id string) context.Context

WithPromptID tags a turn's context with its prompt's ID, for hooks.

Types

type ActivateSkillInput

type ActivateSkillInput struct {
	SkillName string `json:"skill_name" jsonschema:"Name of the skill to activate"`
}

ActivateSkillInput defines arguments for activating a skill.

type ActivateSkillOutput

type ActivateSkillOutput struct {
	SkillName    string   `json:"skill_name"`
	Instructions string   `json:"instructions"`
	Resources    []string `json:"resources"`
	// Scripts can be run with run_skill_script, when allowed.
	Scripts []SkillScriptInfo `json:"scripts,omitempty"`
	Error   string            `json:"error,omitempty"`
}

ActivateSkillOutput holds skill instructions.

type AgentSummary

type AgentSummary struct {
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	Description string `json:"description"`
}

AgentSummary provides summary info for list_agents.

type ApplyPatchInput

type ApplyPatchInput struct {
	Patch string `` /* 175-byte string literal not displayed */
}

ApplyPatchInput defines arguments for apply_patch.

type ApplyPatchOutput

type ApplyPatchOutput struct {
	Success bool          `json:"success"`
	Files   []PatchedFile `json:"files,omitempty"`
	Error   string        `json:"error,omitempty"`
}

ApplyPatchOutput holds the result of apply_patch.

type ApprovalRule

type ApprovalRule struct {
	Key   string    `json:"key"`
	Label string    `json:"label,omitempty"`
	Added time.Time `json:"added"`
}

ApprovalRule is a persisted "always allow" decision.

type ApprovalStore

type ApprovalStore struct {
	// contains filtered or unexported fields
}

ApprovalStore persists "always allow" rules in a JSON file (owner-only). Deny rules and the sandbox are always checked first, so a saved rule can never unlock something policy forbids.

func OpenApprovalStore

func OpenApprovalStore(path string) (*ApprovalStore, error)

OpenApprovalStore loads rules from path; a missing file is an empty store.

func (*ApprovalStore) Add

func (s *ApprovalStore) Add(key, label string) error

Add persists a rule.

func (*ApprovalStore) Has

func (s *ApprovalStore) Has(key string) bool

Has reports whether key is allowed. A nil store has no rules.

func (*ApprovalStore) Remove

func (s *ApprovalStore) Remove(key string) (bool, error)

Remove deletes a rule; it reports whether it existed.

func (*ApprovalStore) Rules

func (s *ApprovalStore) Rules() []ApprovalRule

Rules returns all rules sorted by key.

type AskUserQuestionInput

type AskUserQuestionInput struct {
	Question string   `json:"question" jsonschema:"The question or clarification needed from the user"`
	Options  []string `json:"options,omitempty" jsonschema:"Optional list of multiple choice options"`
}

AskUserQuestionInput defines arguments for asking the user a question.

type AskUserQuestionOutput

type AskUserQuestionOutput struct {
	Answer string `json:"answer"`
	Error  string `json:"error,omitempty"`
}

AskUserQuestionOutput holds the user's answer.

type BackgroundProcess

type BackgroundProcess struct {
	ID        int
	Command   string
	StartTime time.Time
	// contains filtered or unexported fields
}

BackgroundProcess is a command running (or finished) in the background.

type CheckpointOptions

type CheckpointOptions struct {
	// MaxBytes bounds the snapshots kept; the oldest turns go first, and the
	// latest is always kept.
	MaxBytes int64
	// Dir keeps the checkpoints on disk, so they outlive the process: an
	// index and content-addressed blobs, owner-only. "" keeps them in memory.
	Dir string
	// MaxAge drops persisted turns older than this (0: 30 days).
	MaxAge time.Duration
}

CheckpointOptions configure a checkpoint store.

type Checkpoints

type Checkpoints struct {
	// contains filtered or unexported fields
}

Checkpoints snapshots files before tools modify them so changes can be undone turn by turn. Only changes made through the file tools are tracked; shell commands are not (their effects are detected as conflicts).

func NewCheckpoints

func NewCheckpoints(ws *Workspace, maxBytes int64) *Checkpoints

NewCheckpoints attaches an in-memory checkpoint store to ws.

func OpenCheckpoints

func OpenCheckpoints(ws *Workspace, o CheckpointOptions) (*Checkpoints, error)

OpenCheckpoints attaches a checkpoint store to ws, loading what an earlier process persisted in o.Dir. A damaged index is set aside and the store starts empty (the error says so).

func (*Checkpoints) Begin

func (c *Checkpoints) Begin(label string)

Begin starts a new turn; later changes are grouped under it.

func (*Checkpoints) BeginTurn

func (c *Checkpoints) BeginTurn(session string, prompt int, label string)

BeginTurn starts a new turn for the prompt at index prompt of session's transcript.

func (*Checkpoints) Detach

func (c *Checkpoints) Detach(session string, prompt int)

Detach marks session's turns from transcript index prompt on as made before whatever prompt comes next at that index, once the conversation was rewound without the files: a later rewind to an earlier prompt still restores them, one to the new prompt doesn't.

func (*Checkpoints) List

func (c *Checkpoints) List() []TurnSummary

List returns turns with changes, newest first.

func (*Checkpoints) Rewind

func (c *Checkpoints) Rewind(session string, prompt int, force bool) (UndoResult, error)

Rewind restores the files session's prompts changed from the prompt at transcript index prompt on, newest first: the workspace as it was before that prompt, as far as the file tools changed it. It refuses on conflicts as Undo does. Other sessions' changes are left alone (if they changed the same files, that shows as a conflict).

func (*Checkpoints) SessionDiff

func (c *Checkpoints) SessionDiff(session string) string

SessionDiff returns a unified diff of every file session's turns changed ("" for every session), from its earliest snapshot to its current content.

func (*Checkpoints) Undo

func (c *Checkpoints) Undo(force bool) (UndoResult, error)

Undo reverts the most recent turn that changed files. Unless force is set, it refuses when a file no longer matches what the tools wrote, so edits made afterwards (by the shell or the user) aren't silently discarded.

type CommandDecision

type CommandDecision struct {
	Verdict  Verdict
	Reason   string   // why it was denied or not auto-approved
	Commands []string // every simple command found, as evaluated
	// MustAsk: a permission ask rule matched (or couldn't be ruled out), so
	// the user is asked even in a mode or with a saved approval that would
	// let the command through.
	MustAsk bool
}

CommandDecision explains a policy verdict.

type CommandPolicy

type CommandPolicy struct {
	// contains filtered or unexported fields
}

CommandPolicy decides whether shell commands may run. Every simple command is checked: pipelines, lists, subshells, command substitutions, functions, "bash -c" strings, find -exec, and wrappers such as env, nohup, timeout and xargs are all unpacked.

This is a guardrail, not a security boundary: an allowed interpreter or script can still do anything. Use it with the OS sandbox.

func NewCommandPolicy

func NewCommandPolicy(cfg CommandPolicyConfig) (*CommandPolicy, error)

NewCommandPolicy compiles the configured allow, deny and auto-approve patterns into a policy; an invalid pattern is an error.

func (*CommandPolicy) Describe

func (p *CommandPolicy) Describe() []string

Describe summarises the policy for display.

func (*CommandPolicy) Evaluate

func (p *CommandPolicy) Evaluate(script string) CommandDecision

Evaluate checks a shell script against the policy. A nil policy requires approval.

func (*CommandPolicy) SetRules

func (p *CommandPolicy) SetRules(r *PermissionRules)

SetRules makes the policy apply permission rules' shell patterns.

type CommandPolicyConfig

type CommandPolicyConfig struct {
	Allow       []string // if non-empty, only matching commands may run
	Deny        []string // never run; wins over Allow and AutoApprove
	AutoApprove []string // run without prompting
}

CommandPolicyConfig lists command patterns. A pattern is matched against a simple command with its words joined by single spaces: "*" matches any text, "?" one character, and a trailing " *" also matches the bare command ("git *" matches "git" and "git status"). A command given by path also matches by its base name ("/bin/rm -rf x" matches "rm *").

type CreateFileInput

type CreateFileInput struct {
	Path      string `json:"path" jsonschema:"The path to create"`
	Content   string `json:"content" jsonschema:"The complete content to write"`
	Overwrite bool   `json:"overwrite,omitempty" jsonschema:"Whether to overwrite if file already exists"`
}

CreateFileInput defines arguments for creating a file.

type CreateFileOutput

type CreateFileOutput struct {
	Path         string `json:"path"`
	Success      bool   `json:"success"`
	BytesWritten int    `json:"bytes_written"`
	Error        string `json:"error,omitempty"`
}

CreateFileOutput holds file creation result.

type DeleteFileInput

type DeleteFileInput struct {
	Path string `json:"path" jsonschema:"Path of file to delete"`
}

DeleteFileInput defines arguments for deleting a file.

type DeleteFileOutput

type DeleteFileOutput struct {
	Path    string `json:"path"`
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

DeleteFileOutput holds result of deleting a file.

type DeleteSnippetInput

type DeleteSnippetInput struct {
	Path    string `json:"path" jsonschema:"The file path"`
	Snippet string `json:"snippet" jsonschema:"The exact snippet to remove"`
}

DeleteSnippetInput defines arguments for deleting a code snippet.

type DeleteSnippetOutput

type DeleteSnippetOutput struct {
	Path    string `json:"path"`
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

DeleteSnippetOutput holds result of delete_snippet.

type Effect

type Effect string

Effect is what a permission rule does.

const (
	// EffectAllow lets a matching action run without asking.
	EffectAllow Effect = "allow"
	// EffectAsk makes a matching action ask even when a mode, a
	// remembered approval or an allow rule would let it through.
	EffectAsk Effect = "ask"
	// EffectDeny refuses a matching action, in every mode.
	EffectDeny Effect = "deny"
)

type EnterPlanModeInput

type EnterPlanModeInput struct {
	Reason string `json:"reason,omitempty" jsonschema:"Why this task needs a plan first"`
}

EnterPlanModeInput is enter_plan_mode's argument.

type ExecEnv

type ExecEnv struct {
	Sandbox *OSSandbox
	// ScrubEnv lists environment variable names (globs allowed, e.g.
	// "*_API_KEY") removed from every child process, so commands the model
	// runs can't read Blitz's own credentials.
	ScrubEnv []string
	// Dir is where commands run unless they set their own directory: the
	// workspace root, never the process's working directory.
	Dir string
}

ExecEnv builds every process Blitz runs on the model's behalf: shell commands, background processes, and forged tools. Each process is placed in its own process group, optionally wrapped in the OS sandbox, and guarded so the group is killed if Blitz exits for any reason.

type ExitPlanModeInput

type ExitPlanModeInput struct {
	Plan string `` /* 134-byte string literal not displayed */
}

ExitPlanModeInput is exit_plan_mode's argument.

type FileEntry

type FileEntry struct {
	Path  string `json:"path"`
	IsDir bool   `json:"is_dir"`
	Size  int64  `json:"size_bytes"`
}

FileEntry represents a file in directory listing.

type GlobInput

type GlobInput struct {
	Pattern    string `` /* 143-byte string literal not displayed */
	Path       string `json:"path,omitempty" jsonschema:"Directory to search from (default: the workspace)"`
	MaxResults int    `json:"max_results,omitempty" jsonschema:"Maximum files to return (default 200, max 1000)"`
}

GlobInput defines arguments for glob.

type GlobOutput

type GlobOutput struct {
	Files     []string `json:"files"`
	Count     int      `json:"count"`
	Truncated bool     `json:"truncated,omitempty"`
	Error     string   `json:"error,omitempty"`
}

GlobOutput holds the matching files, newest first.

type GrepInput

type GrepInput struct {
	Query           string `json:"query" jsonschema:"The search term or regex pattern"`
	Path            string `json:"path,omitempty" jsonschema:"Optional directory or file path to search in"`
	IsRegex         bool   `json:"is_regex,omitempty" jsonschema:"Whether query is a regex pattern"`
	CaseInsensitive bool   `json:"case_insensitive,omitempty" jsonschema:"Whether search is case insensitive"`
	MaxMatches      int    `json:"max_matches,omitempty" jsonschema:"Max results to return"`
}

GrepInput defines arguments for grep search.

type GrepMatch

type GrepMatch struct {
	File       string `json:"file"`
	LineNumber int    `json:"line_number"`
	Content    string `json:"content"`
}

GrepMatch holds a single search match.

type GrepOutput

type GrepOutput struct {
	Matches      []GrepMatch `json:"matches"`
	TotalMatches int         `json:"total_matches"`
	Error        string      `json:"error,omitempty"`
}

GrepOutput holds grep search results.

type HookEvent

type HookEvent struct {
	Event     string         `json:"event"` // pre_tool, post_tool, prompt_submit
	SessionID string         `json:"session_id,omitempty"`
	Workspace string         `json:"workspace"`
	Tool      string         `json:"tool,omitempty"`
	Args      map[string]any `json:"args,omitempty"`
	Result    map[string]any `json:"result,omitempty"`
	Error     string         `json:"error,omitempty"`
	Prompt    string         `json:"prompt,omitempty"`

	// Context for every event.
	PromptID       string `json:"prompt_id,omitempty"`
	TranscriptPath string `json:"transcript_path,omitempty"`
	PermissionMode string `json:"permission_mode,omitempty"`
	Agent          string `json:"agent,omitempty"`
	Cwd            string `json:"cwd,omitempty"`

	// Event-specific.
	Reason         string   `json:"reason,omitempty"`           // session_start/end, compaction trigger
	StopHookActive bool     `json:"stop_hook_active,omitempty"` // stop: already continued by a stop hook
	Type           string   `json:"type,omitempty"`             // notification type
	Message        string   `json:"message,omitempty"`          // notification text
	Kind           string   `json:"kind,omitempty"`             // permission_request: the action kind
	Detail         string   `json:"detail,omitempty"`           // permission_request: what will happen
	Targets        []string `json:"targets,omitempty"`          // permission_request
	Subagent       string   `json:"subagent,omitempty"`         // subagent_start/stop
	Output         string   `json:"output,omitempty"`           // subagent_stop: its reply
}

HookEvent is the JSON document a hook receives on stdin.

type HookInfo

type HookInfo struct {
	PromptID, TranscriptPath, PermissionMode, Agent string
}

HookInfo is session context added to every hook event.

type Hooks

type Hooks struct {
	// contains filtered or unexported fields
}

Hooks holds callbacks injected by the host application (TUI, engine) and the approval rules remembered for this session or persisted across sessions.

func NewHooks

func NewHooks(policy Policy) *Hooks

NewHooks creates hooks with the given approval policy.

func (*Hooks) Approve

func (h *Hooks) Approve(ctx context.Context, req api.ApprovalRequest) error

Approve decides whether a tool call may proceed, and records the decision in the audit log. A deny rule refuses it in any mode. An unattended run (a worker) decides by its own permissions and can't ask anyone. Otherwise an ask rule goes straight to the approver; else an allow rule, the bypass mode, auto-approved commands, or an approval remembered for the session or stored for good let it through; else the approver is asked, and its answer may be remembered. It returns nil to proceed, or an error wrapping ErrNotApproved.

func (*Hooks) Audit

func (h *Hooks) Audit() *audit.Logger

Audit returns the audit logger (possibly nil, which is a no-op).

func (*Hooks) Mode

func (h *Hooks) Mode() api.PermissionMode

Mode returns the permission mode.

func (*Hooks) Notify

func (h *Hooks) Notify(ctx context.Context, typ, message string)

Notify fires notification hooks (e.g. a question waiting for the user).

func (*Hooks) RevokeSession

func (h *Hooks) RevokeSession(key string) bool

RevokeSession forgets a session rule; it reports whether one existed.

func (*Hooks) Rules

func (h *Hooks) Rules() *PermissionRules

Rules returns the permission rules (nil when none are attached).

func (*Hooks) SessionRules

func (h *Hooks) SessionRules() []string

SessionRules returns the keys allowed for this session, sorted.

func (*Hooks) SetApprover

func (h *Hooks) SetApprover(a api.Approver)

SetApprover sets who answers approval requests (the front end's UI).

func (*Hooks) SetAudit

func (h *Hooks) SetAudit(l *audit.Logger)

SetAudit attaches the audit log.

func (*Hooks) SetEventHooks

func (h *Hooks) SetEventHooks(perm func(context.Context, api.ApprovalRequest) Outcome, notify func(ctx context.Context, typ, message string))

SetEventHooks connects the gate to permission_request and notification hooks.

func (*Hooks) SetRules

func (h *Hooks) SetRules(r *PermissionRules)

SetRules attaches the permission rules the gate applies.

func (*Hooks) SetStore

func (h *Hooks) SetStore(s *ApprovalStore)

SetStore attaches the persistent "always allow" rules.

func (*Hooks) SetSubagentInvoker

func (h *Hooks) SetSubagentInvoker(i InvokeAgentFunc)

SetSubagentInvoker sets how the invoke_agent tool runs a sub-agent.

func (*Hooks) SetUserPrompter

func (h *Hooks) SetUserPrompter(p api.UserPromptFunc)

SetUserPrompter sets who answers the agent's questions (ask_user).

func (*Hooks) Store

func (h *Hooks) Store() *ApprovalStore

Store returns the persistent rule store (may be nil).

type InvokeAgentFunc

type InvokeAgentFunc func(ctx context.Context, agentName, prompt string) (string, error)

InvokeAgentFunc runs a registered sub-agent with a prompt and returns its reply.

type InvokeAgentInput

type InvokeAgentInput struct {
	AgentName string `json:"agent_name" jsonschema:"The name of the agent to invoke (e.g. qa, helios, planning-agent)"`
	Prompt    string `json:"prompt" jsonschema:"The specific task instruction for the delegated agent"`
}

InvokeAgentInput defines arguments for invoke_agent.

type InvokeAgentOutput

type InvokeAgentOutput struct {
	AgentName string `json:"agent_name"`
	Response  string `json:"response"`
	Error     string `json:"error,omitempty"`
}

InvokeAgentOutput holds result of invoking an agent.

type ListAgentsInput

type ListAgentsInput struct {
	Filter string `json:"filter,omitempty" jsonschema:"Optional substring filter for agent names"`
}

ListAgentsInput defines input for listing agents.

type ListAgentsOutput

type ListAgentsOutput struct {
	Agents []AgentSummary `json:"agents"`
}

ListAgentsOutput holds registered agents.

type ListFilesInput

type ListFilesInput struct {
	Directory  string `json:"directory,omitempty" jsonschema:"Directory path relative to workspace or absolute"`
	Recursive  bool   `json:"recursive,omitempty" jsonschema:"Whether to list files recursively"`
	MaxEntries int    `json:"max_entries,omitempty" jsonschema:"Maximum number of file entries to return"`
}

ListFilesInput defines arguments for listing directory files.

type ListFilesOutput

type ListFilesOutput struct {
	Directory  string      `json:"directory"`
	Files      []FileEntry `json:"files"`
	TotalCount int         `json:"total_count"`
	Error      string      `json:"error,omitempty"`
}

ListFilesOutput holds listed files.

type ListSkillsInput

type ListSkillsInput struct {
	Query string `json:"query,omitempty" jsonschema:"Optional keyword query to filter skills by name, description, or tags"`
}

ListSkillsInput defines arguments for listing or searching skills.

type ListSkillsOutput

type ListSkillsOutput struct {
	Skills []SkillSummary `json:"skills"`
	Count  int            `json:"count"`
	Error  string         `json:"error,omitempty"`
}

ListSkillsOutput holds discovered skills.

type MCPManager

type MCPManager struct {
	Warn func(string)
	// contains filtered or unexported fields
}

MCPManager owns the configured MCP servers and knows which tool names each one serves, so tool calls can be approved per server.

func NewMCPManager

func NewMCPManager(cfgs []config.MCPServerConfig, env *ExecEnv, reserved []string) (*MCPManager, error)

NewMCPManager validates configs and prepares toolsets. Servers connect lazily when their tools are first listed. Stdio servers run through env (process guard, scrubbed environment and, unless disabled per server, the OS sandbox).

func NewMCPManagerFromToolsets

func NewMCPManagerFromToolsets(servers []MCPToolset, reserved []string) *MCPManager

NewMCPManagerFromToolsets builds a manager over existing toolsets.

func (*MCPManager) Close

func (m *MCPManager) Close()

Close ends every server session and stops stdio server processes.

func (*MCPManager) Lookup

func (m *MCPManager) Lookup(toolName string) (server string, autoApprove, ok bool)

Lookup reports which server serves toolName.

func (*MCPManager) Servers

func (m *MCPManager) Servers() []string

Servers returns configured server names.

func (*MCPManager) Toolsets

func (m *MCPManager) Toolsets() []tool.Toolset

Toolsets returns one toolset per server for the primary agent.

func (*MCPManager) ToolsetsFor

func (m *MCPManager) ToolsetsFor(agent string, primary bool) []tool.Toolset

ToolsetsFor returns the toolsets offered to agent. Servers without an agents list go to the primary agent only; "*" matches every agent.

type MCPToolset

type MCPToolset struct {
	Config  config.MCPServerConfig
	Toolset tool.Toolset
}

MCPToolset pairs a server configuration with an already-connected toolset, for embedding applications (and tests) that manage transports themselves. Command and URL in Config are ignored.

type ManageBackgroundInput

type ManageBackgroundInput struct {
	Action    string `json:"action" jsonschema:"One of: list, output, kill"`
	ProcessID int    `json:"process_id,omitempty" jsonschema:"Background process ID (for output and kill)"`
}

ManageBackgroundInput defines arguments for manage_background_process.

type ManageBackgroundOutput

type ManageBackgroundOutput struct {
	Processes []api.ProcessInfo `json:"processes,omitempty"`
	Process   *api.ProcessInfo  `json:"process,omitempty"`
	Output    string            `json:"output,omitempty"`
	Error     string            `json:"error,omitempty"`
}

ManageBackgroundOutput holds the result of manage_background_process.

type OSSandbox

type OSSandbox struct {
	// contains filtered or unexported fields
}

OSSandbox wraps command argv so they run under the platform sandbox.

func NewOSSandbox

func NewOSSandbox(spec OSSandboxSpec) (*OSSandbox, error)

NewOSSandbox sets up the shell sandbox. In "required" mode an unavailable sandbox is an error, so the CLI fails closed at startup rather than silently running commands unconfined.

func (*OSSandbox) Active

func (s *OSSandbox) Active() bool

Active reports whether shell commands run sandboxed.

func (*OSSandbox) Status

func (s *OSSandbox) Status() string

Status describes the sandbox state for users.

type OSSandboxSpec

type OSSandboxSpec struct {
	Mode         ShellSandboxMode
	WritableDirs []string // canonical absolute directories
	ReadOnlyDirs []string // never writable, even when inside a writable dir
	Blocked      *PathMatcher
	AllowNetwork bool
}

OSSandboxSpec describes what sandboxed commands may do. Reads are allowed everywhere except blocked paths; writes only under WritableDirs.

type Outcome

type Outcome struct {
	// Blocked (exit 2 or {"decision":"block"}), with the reason.
	Blocked bool
	Reason  string
	// Decision is "allow", "deny" or "ask" from {"decision": …}
	// (permission_request, pre_tool).
	Decision string
	// Continue: a stop hook asks the agent to keep going (Reason says why).
	Continue bool
	// Context is text for the agent: plain stdout on session_start and
	// prompt_submit, or additional_context.
	Context string
}

Outcome is what synchronous hooks decided together.

type PatchedFile

type PatchedFile struct {
	Path    string `json:"path"`
	Op      string `json:"op"`
	MovedTo string `json:"moved_to,omitempty"`
	Added   int    `json:"added"`
	Removed int    `json:"removed"`
}

PatchedFile summarises one file's change.

type PathMatcher

type PathMatcher struct {
	// contains filtered or unexported fields
}

PathMatcher matches absolute paths against blocked-path glob patterns.

Pattern forms (all match the path itself and everything beneath it):

  • "name" or "*.pem" (no slash): a file or directory name at any depth
  • "~/.ssh", "/etc/x" (absolute): that exact location
  • "config/prod/*.yaml" (relative with slash): relative to every sandbox root

"*" matches within one path segment, "**" across segments, "?" one character.

func NewPathMatcher

func NewPathMatcher(patterns []string, roots []string) (*PathMatcher, error)

NewPathMatcher compiles patterns; relative patterns containing "/" are anchored at each of roots.

func (*PathMatcher) Match

func (m *PathMatcher) Match(abs string) (string, bool)

Match returns the pattern that blocks abs, if any.

func (*PathMatcher) Patterns

func (m *PathMatcher) Patterns() []string

Patterns returns the configured patterns (deduplicated, in order).

type PermissionRule

type PermissionRule struct {
	Effect  Effect
	Kind    string
	Pattern string // "" for a bare tool name
	// Source says where the rule came from: "config", "flag", "session".
	Source string
	// contains filtered or unexported fields
}

PermissionRule is one allow, ask or deny rule.

func ParsePermissionRule

func ParsePermissionRule(effect Effect, text, source string) (PermissionRule, error)

ParsePermissionRule reads "kind(pattern)" or a bare tool name. "Bash" and "Edit"/"Write" are accepted for shell and write, as Claude Code spells them.

func (PermissionRule) String

func (r PermissionRule) String() string

String is the rule as written: kind(pattern), or the bare tool name.

type PermissionRules

type PermissionRules struct {
	// contains filtered or unexported fields
}

PermissionRules are the rules in force, from configuration, flags and the session. They are safe for concurrent use and can change while a session runs.

func NewPermissionRules

func NewPermissionRules(cfg config.PermissionsConfig, source string) (*PermissionRules, error)

NewPermissionRules parses the configured rules; source labels them.

func (*PermissionRules) Add

func (p *PermissionRules) Add(effect Effect, text, source string) error

Add adds a rule (a duplicate is ignored).

func (*PermissionRules) Decide

func (p *PermissionRules) Decide(kind string, targets []string) (Effect, *PermissionRule)

Decide returns the effect for an action of kind on targets: deny if any target matches a deny rule, else ask if any matches an ask rule, else allow if every target matches an allow rule, else "" (no rule applies). The rule that decided is returned too.

func (*PermissionRules) List

func (p *PermissionRules) List() []PermissionRule

List returns the rules, deny first, then ask, then allow.

func (*PermissionRules) Patterns

func (p *PermissionRules) Patterns(kind string, effect Effect) []string

Patterns returns the patterns of kind with effect (e.g. read denies, which become blocked paths).

func (*PermissionRules) Remove

func (p *PermissionRules) Remove(text string, effect Effect) int

Remove removes the rules written as text (any effect unless one is given) and reports how many.

func (*PermissionRules) ToolDenied

func (p *PermissionRules) ToolDenied(tool string, args map[string]any) *PermissionRule

ToolDenied returns the deny rule that refuses a tool call outright (by tool name, or a skill or agent it names), or nil.

type PlanGate

type PlanGate struct {
	// contains filtered or unexported fields
}

PlanGate is one turn's plan state, shared by the plan tools and the front end's workspace: whether the agent is planning (only reading), and what the user decided about its plan.

func NewPlanGate

func NewPlanGate(planning bool) *PlanGate

NewPlanGate starts a turn's plan state; planning is whether it plans first.

func PlanGateFrom

func PlanGateFrom(ctx context.Context) *PlanGate

PlanGateFrom returns the turn's plan state (nil outside a turn).

func (*PlanGate) Planning

func (g *PlanGate) Planning() bool

Planning reports whether the agent is planning: tools that change anything are refused.

func (*PlanGate) Take

func (g *PlanGate) Take() (plan, path string, mode api.PermissionMode, ok bool)

Take returns the approved plan, the file it was saved to and the mode to carry it out in (ok is false when none was approved), and clears the approval, so each plan is carried out once.

type Policy

type Policy struct {
	// Mode is the permission mode ("" is ModeDefault). NewRegistry sets
	// it from [blitz] permission_mode and auto_approve.
	Mode                api.PermissionMode
	AutoApproveCommands bool // tools.auto_approve_commands
}

Policy controls which actions skip the approval prompt.

type ProcessManager

type ProcessManager struct {
	// contains filtered or unexported fields
}

ProcessManager owns background processes: it caps how many run at once, bounds their lifetime and captured output, and kills them on shutdown. Processes are guarded (see ExecEnv) so none survive Blitz exiting.

func NewProcessManager

func NewProcessManager(maxRunning int, maxLifetime time.Duration) *ProcessManager

NewProcessManager creates a manager; zero values select defaults.

func (*ProcessManager) Kill

func (m *ProcessManager) Kill(id int) (api.ProcessInfo, error)

Kill terminates a process and its descendants, waiting briefly for exit.

func (*ProcessManager) List

func (m *ProcessManager) List() []api.ProcessInfo

List returns all tracked processes ordered by ID.

func (*ProcessManager) Output

func (m *ProcessManager) Output(id int) (string, api.ProcessInfo, error)

Output returns captured output and status for a process.

func (*ProcessManager) Running

func (m *ProcessManager) Running() []api.ProcessInfo

Running returns the processes that have not exited, ordered by ID.

func (*ProcessManager) Shutdown

func (m *ProcessManager) Shutdown()

Shutdown kills every running process and refuses new ones.

func (*ProcessManager) Start

func (m *ProcessManager) Start(command, cwd string) (*BackgroundProcess, error)

Start launches command in cwd as a background process.

func (*ProcessManager) WaitAll

func (m *ProcessManager) WaitAll(ctx context.Context) error

WaitAll blocks until every running process exits or ctx is done.

type PyEnv

type PyEnv struct {
	Key        string    `json:"key"`
	Python     string    `json:"python"` // base interpreter (real path)
	Deps       []string  `json:"deps"`
	Index      string    `json:"index"`
	WheelsOnly bool      `json:"wheels_only"`
	Created    time.Time `json:"created"`
	LastUsed   time.Time `json:"last_used"`
	Skills     []string  `json:"skills"`
	Dir        string    `json:"-"`
	Ready      bool      `json:"-"` // built completely
	Size       int64     `json:"-"`
}

PyEnv describes one environment.

func (PyEnv) Interpreter

func (e PyEnv) Interpreter() string

Interpreter is the environment's Python.

type PyEnvs

type PyEnvs struct {
	// contains filtered or unexported fields
}

PyEnvs manages isolated Python environments for skill scripts, one per distinct set of requirements, in ~/.blitz/envs/<key>. An environment is built inside the script sandbox (network on, writes only to the environment and the package cache), and is only used once its marker file is written, so an interrupted build is rebuilt rather than used.

func NewPyEnvs

func NewPyEnvs(dir string, p config.PackagePolicy) *PyEnvs

NewPyEnvs manages environments in dir (default ~/.blitz/envs) under the package policy.

func (*PyEnvs) Ensure

func (m *PyEnvs) Ensure(ctx context.Context, box ScriptBox, python, skill string, deps []string) (PyEnv, error)

Ensure returns the environment for deps, building it in box first if needed (the caller has approved the install). skill is recorded as a user of the environment.

func (*PyEnvs) InstallCommands

func (m *PyEnvs) InstallCommands(deps []string) string

InstallCommands describes how Ensure installs deps, for the approval prompt.

func (*PyEnvs) Key

func (m *PyEnvs) Key(python string, deps []string) string

Key identifies the environment for deps under this manager's policy.

func (*PyEnvs) List

func (m *PyEnvs) List() []PyEnv

List returns every environment, complete or not, newest use first.

func (*PyEnvs) Lookup

func (m *PyEnvs) Lookup(python string, deps []string) (PyEnv, bool)

Lookup returns the environment for deps and whether it is ready to use.

func (*PyEnvs) Remove

func (m *PyEnvs) Remove(key string) error

Remove deletes an environment.

type ReadFileInput

type ReadFileInput struct {
	Path      string `json:"path" jsonschema:"The absolute or workspace-relative path to the file"`
	StartLine int    `json:"start_line,omitempty" jsonschema:"Optional 1-indexed starting line number"`
	EndLine   int    `json:"end_line,omitempty" jsonschema:"Optional 1-indexed ending line number"`
}

ReadFileInput defines arguments for reading a file.

type ReadFileOutput

type ReadFileOutput struct {
	Path       string `json:"path"`
	Content    string `json:"content"`
	TotalLines int    `json:"total_lines"`
	Truncated  bool   `json:"truncated,omitempty"`
	Error      string `json:"error,omitempty"`
}

ReadFileOutput holds the result of reading a file.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry manages initialized ADK tools and the resources they share. Tools are registered once at construction and never mutated afterwards.

func NewRegistry

func NewRegistry(cfg *config.Config, agentReg *agents.Registry, skillProv *skills.Provider) (*Registry, error)

NewRegistry initializes all standard Blitz tools. Call Close when done to stop background processes and release the workspace handle.

func (*Registry) AddImage

func (r *Registry) AddImage(name string, data []byte) (*images.Image, error)

AddImage prepares and stores image bytes that didn't come from a file (the clipboard). name is only for display.

func (*Registry) ApproveMCP

func (r *Registry) ApproveMCP(ctx context.Context, toolName string, args map[string]any) error

ApproveMCP gates an MCP tool call; it returns nil for non-MCP tools.

func (*Registry) CanFetch

func (r *Registry) CanFetch() bool

CanFetch reports whether web_fetch is available to agents.

func (*Registry) Checkpoints

func (r *Registry) Checkpoints() *Checkpoints

Checkpoints returns the file snapshot store (nil when disabled).

func (*Registry) Close

func (r *Registry) Close() error

Close kills background processes and MCP servers and releases the workspace root.

func (*Registry) GetAllTools

func (r *Registry) GetAllTools() []tool.Tool

GetAllTools returns all registered tools (aliases de-duplicated).

func (*Registry) GetToolsForAgent

func (r *Registry) GetToolsForAgent(toolNames []string) []tool.Tool

GetToolsForAgent returns the subset of tools configured for a given agent.

func (*Registry) Hooks

func (r *Registry) Hooks() *Hooks

Hooks returns the callbacks the host uses to wire approvals, prompts and sub-agents.

func (*Registry) Images

func (r *Registry) Images() *images.Store

Images returns the image store, or nil when images are disabled.

func (*Registry) LoadImage

func (r *Registry) LoadImage(path string) (*images.Image, error)

LoadImage reads an image file through the workspace sandbox (so blocked and out-of-workspace paths are refused), prepares it for the model and stores it. The audit log records the path and hash, not the picture.

func (*Registry) MCP

func (r *Registry) MCP() *MCPManager

MCP returns the MCP server manager.

func (*Registry) ModeNote

func (r *Registry) ModeNote() error

ModeNote is why the configured permission mode wasn't used, or nil.

func (*Registry) Processes

func (r *Registry) Processes() *ProcessManager

Processes returns the background process manager.

func (*Registry) Rules

func (r *Registry) Rules() *PermissionRules

Rules are the permission rules in force; they can change while a session runs (read rules only take effect at the next start).

func (*Registry) SandboxSummary

func (r *Registry) SandboxSummary() []string

SandboxSummary describes the active file, command, and OS sandbox policy.

func (*Registry) ScriptHooks

func (r *Registry) ScriptHooks() *ScriptHooks

ScriptHooks returns the configured lifecycle hooks.

func (*Registry) SearchError

func (r *Registry) SearchError() error

SearchError reports why the configured search provider can't be used.

func (*Registry) SearchProvider

func (r *Registry) SearchProvider() string

SearchProvider names the configured search provider ("" if none).

func (*Registry) SetAudit

func (r *Registry) SetAudit(l *audit.Logger)

SetAudit attaches the audit log to approvals and hooks.

func (*Registry) SetMCP

func (r *Registry) SetMCP(m *MCPManager)

SetMCP replaces the MCP server manager (e.g. with in-process toolsets).

func (*Registry) SetPermissionMode

func (r *Registry) SetPermissionMode(m api.PermissionMode) error

SetPermissionMode changes the permission mode, refusing bypass unless the OS sandbox is active.

func (*Registry) SetWarn

func (r *Registry) SetWarn(warn func(string))

SetWarn routes non-fatal warnings (MCP server failures, hook errors).

func (*Registry) ShellSandbox

func (r *Registry) ShellSandbox() *OSSandbox

ShellSandbox returns the OS sandbox used for commands.

func (*Registry) SkillScripts

func (r *Registry) SkillScripts() *SkillScripts

SkillScripts runs skills' scripts; nil when skills are disabled.

func (*Registry) WebSearch

func (r *Registry) WebSearch(ctx context.Context, query string, n int) (WebSearchOutput, error)

WebSearch runs a search the user asked for (/search web). It isn't an agent action, so it doesn't ask for approval; it is audited.

func (*Registry) WorkflowTools

func (r *Registry) WorkflowTools() []tool.Tool

WorkflowTools returns the workflow tools that are registered.

func (*Registry) Workspace

func (r *Registry) Workspace() *Workspace

Workspace returns the confined workspace the file tools operate in.

type ReplaceInFileInput

type ReplaceInFileInput struct {
	Path               string `json:"path" jsonschema:"The file path to edit"`
	TargetContent      string `json:"target_content" jsonschema:"The exact text snippet to replace"`
	ReplacementContent string `json:"replacement_content" jsonschema:"The new text content to substitute"`
	AllowMultiple      bool   `json:"allow_multiple,omitempty" jsonschema:"Whether to replace multiple occurrences if found"`
}

ReplaceInFileInput defines arguments for targeted search-and-replace.

type ReplaceInFileOutput

type ReplaceInFileOutput struct {
	Path              string `json:"path"`
	Success           bool   `json:"success"`
	ReplacementsCount int    `json:"replacements_count"`
	Error             string `json:"error,omitempty"`
}

ReplaceInFileOutput holds result of replace_in_file.

type RunShellCommandInput

type RunShellCommandInput struct {
	Command        string `json:"command" jsonschema:"The shell command to execute"`
	Cwd            string `json:"cwd,omitempty" jsonschema:"Optional working directory inside the workspace"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty" jsonschema:"Timeout in seconds (default 120, max 1800)"`
	Background     bool   `json:"background,omitempty" jsonschema:"Run asynchronously; inspect or stop it with manage_background_process"`
}

RunShellCommandInput defines arguments for executing shell commands.

type RunShellCommandOutput

type RunShellCommandOutput struct {
	Output       string `json:"output"`
	ExitCode     int    `json:"exit_code"`
	DurationMs   int64  `json:"duration_ms"`
	IsBackground bool   `json:"is_background"`
	ProcessID    int    `json:"process_id,omitempty"`
	Truncated    bool   `json:"truncated,omitempty"`
	Error        string `json:"error,omitempty"`
}

RunShellCommandOutput holds command execution results.

type RunSkillScriptInput

type RunSkillScriptInput struct {
	Skill  string   `json:"skill" jsonschema:"Skill name"`
	Script string   `json:"script" jsonschema:"Script name, as listed by activate_skill"`
	Args   []string `json:"args,omitempty" jsonschema:"Command-line arguments for the script"`
}

RunSkillScriptInput is the run_skill_script request.

type RunSkillScriptOutput

type RunSkillScriptOutput struct {
	ExitCode  int      `json:"exit_code"`
	Stdout    string   `json:"stdout,omitempty"`
	Stderr    string   `json:"stderr,omitempty"`
	TimedOut  bool     `json:"timed_out,omitempty"`
	Sandbox   string   `json:"sandbox,omitempty"`
	Tier      string   `json:"tier,omitempty"`
	OutputDir string   `json:"output_dir,omitempty"` // workspace-relative; read results with read_file
	Files     []string `json:"output_files,omitempty"`
	Error     string   `json:"error,omitempty"`
}

RunSkillScriptOutput is how the script ran.

type ScriptBox

type ScriptBox interface {
	// Name is "gvisor" or "os".
	Name() string
	Run(ctx context.Context, req ScriptRequest) (ScriptResult, error)
}

ScriptBox runs commands in isolation.

func NewScriptBox

func NewScriptBox(cfg ScriptBoxConfig) (box ScriptBox, note string, err error)

NewScriptBox returns the configured backend. With "auto" it also returns why gVisor isn't used, for doctor.

type ScriptBoxConfig

type ScriptBoxConfig struct {
	// Mode is "gvisor", "os" or "auto" (gVisor if it works, else the OS
	// sandbox); skills.policy.sandbox.
	Mode string
	// Blocked are paths no script may read, on backends that can hide
	// them (the OS sandbox; gVisor doesn't mount them at all).
	Blocked *PathMatcher
	// StateDir holds gVisor's container state and bundles
	// (~/.blitz/sandboxes).
	StateDir string
}

ScriptBoxConfig selects and configures a ScriptBox.

type ScriptHooks

type ScriptHooks struct {

	// Info adds session context (prompt ID, transcript, mode, agent) to
	// events; nil adds none.
	Info func(ctx context.Context, session string) HookInfo

	// Warn reports hook failures that don't block (defaults to no-op).
	Warn func(string)
	// contains filtered or unexported fields
}

ScriptHooks runs user-configured commands at lifecycle points. Hooks run through the same ExecEnv as shell commands (sandboxed, guarded, scrubbed environment) in the workspace directory.

func NewScriptHooks

func NewScriptHooks(cfg config.HooksConfig, env *ExecEnv, workspace string, log *audit.Logger) (*ScriptHooks, error)

NewScriptHooks validates and prepares hooks.

func (*ScriptHooks) Async

func (s *ScriptHooks) Async(ctx context.Context, event, tool string, ev HookEvent)

Async queues an observe-only event for the background worker, in order, and returns at once (tool names filter by each hook's match). Events are encoded now, so later changes to their maps can't alter what hooks see.

func (*ScriptHooks) Close

func (s *ScriptHooks) Close()

Close stops accepting post_tool events and lets queued hooks finish for up to postDrainTimeout, then kills any still running. Safe to call more than once.

func (*ScriptHooks) Empty

func (s *ScriptHooks) Empty() bool

Empty reports whether no hooks are configured.

func (*ScriptHooks) Has

func (s *ScriptHooks) Has(event string) bool

Has reports whether any hook handles event.

func (*ScriptHooks) PostTool

func (s *ScriptHooks) PostTool(ctx context.Context, session, tool string, args, result map[string]any, toolErr error)

PostTool queues post_tool hooks for the background worker and returns immediately. The hooks observe; they can't change the result. Events are delivered in order. If hooks fall so far behind that the queue fills, the event is dropped and reported rather than slowing the agent.

func (*ScriptHooks) PreTool

func (s *ScriptHooks) PreTool(ctx context.Context, session, tool string, args map[string]any) string

PreTool runs pre_tool hooks; a non-empty reason means the call is blocked.

func (*ScriptHooks) PromptSubmit

func (s *ScriptHooks) PromptSubmit(ctx context.Context, session, prompt string) string

PromptSubmit runs prompt_submit hooks; a non-empty reason blocks the prompt.

func (*ScriptHooks) PromptSubmitContext

func (s *ScriptHooks) PromptSubmitContext(ctx context.Context, session, prompt string) Outcome

PromptSubmitContext runs prompt_submit hooks and returns their outcome: a block, or context text for the agent.

func (*ScriptHooks) Run

func (s *ScriptHooks) Run(ctx context.Context, event, tool string, ev HookEvent) Outcome

Run runs an event's hooks synchronously and returns their outcome (for session_start, stop and permission_request; tool filters by match).

type ScriptRequest

type ScriptRequest struct {
	Argv []string
	// Dir is the working directory; it must be one of the mounted paths.
	Dir string
	// Env is the whole environment besides PATH, HOME, TMPDIR and LANG,
	// which the box sets. Nothing is inherited from Blitz's own.
	Env []string
	// Network gives the command the host's network; otherwise it has none.
	Network bool
	// ReadOnly and Writable are host paths mounted at the same path.
	ReadOnly, Writable []string
	Stdin              io.Reader
	Stdout, Stderr     io.Writer
	Timeout            time.Duration // 0: no limit besides ctx
}

ScriptRequest is one command to run in isolation.

type ScriptResult

type ScriptResult struct {
	ExitCode int
	TimedOut bool
	Elapsed  time.Duration
}

ScriptResult is how a command ended.

type SearchResult

type SearchResult struct {
	Title   string `json:"title"`
	URL     string `json:"url"`
	Snippet string `json:"snippet,omitempty"`
}

SearchResult is one web search hit.

type ShellConfig

type ShellConfig struct {
	Workspace      *Workspace
	Hooks          *Hooks
	Processes      *ProcessManager
	Policy         *CommandPolicy // nil: every command needs approval
	Exec           *ExecEnv       // nil: no OS sandbox
	DefaultTimeout time.Duration
}

ShellConfig configures the run_shell_command tool.

type ShellSandboxMode

type ShellSandboxMode string

ShellSandboxMode selects OS-level sandboxing for shell commands.

const (
	// SandboxAuto sandboxes shell commands when the platform supports it.
	SandboxAuto ShellSandboxMode = "auto"
	// SandboxRequired refuses to start unless shell commands can be sandboxed.
	SandboxRequired ShellSandboxMode = "required"
	// SandboxOff runs shell commands without an OS sandbox.
	SandboxOff ShellSandboxMode = "off"
)

type SkillScriptInfo

type SkillScriptInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Allowed     bool   `json:"allowed"`
	// Why the host's skills policy doesn't allow it.
	Blocked string `json:"blocked,omitempty"`
}

SkillScriptInfo describes one of a skill's scripts for the model.

type SkillScripts

type SkillScripts struct {
	// contains filtered or unexported fields
}

SkillScripts runs skills' scripts: each is checked against skills.policy, approved by its tier, given its Python environment, and run in the script sandbox. Scripts can read the workspace but never write it; they write into their own output directory, and the agent applies any changes with the file tools (so diffs, approvals and /undo still work).

func NewSkillScripts

func NewSkillScripts(provider *skills.Provider, policy config.SkillPolicy, ws *Workspace, hooks *Hooks, envs *PyEnvs, boxCfg ScriptBoxConfig) *SkillScripts

NewSkillScripts sets up script runs for the skills of provider.

func (*SkillScripts) Box

func (s *SkillScripts) Box() (ScriptBox, error)

Box returns the script sandbox, set up on first use (a gVisor test run takes a moment).

func (*SkillScripts) Envs

func (s *SkillScripts) Envs() *PyEnvs

Envs is the environment manager.

func (*SkillScripts) Run

Run runs one script.

type SkillSummary

type SkillSummary struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Tags        []string `json:"tags"`
	Version     string   `json:"version"`
}

SkillSummary represents a skill in search results.

type TodoInput

type TodoInput struct {
	Items []TodoItem `json:"items" jsonschema:"Every task, in order, with its current status"`
}

TodoInput is the whole list, replacing the previous one.

type TodoItem

type TodoItem struct {
	Content string `json:"content" jsonschema:"What to do, in a few words"`
	Status  string `json:"status" jsonschema:"pending, in_progress or done"`
}

TodoItem is one task in the agent's list.

func TodoItems

func TodoItems(result map[string]any) []TodoItem

TodoItems reads the list from a todo tool result (nil if it isn't one).

type Turn

type Turn struct {
	ID int `json:"id"`
	// Session is the session the prompt belongs to, and Prompt the index of
	// its message in the transcript (-1 when unknown), so a rewind can find
	// the changes made from a prompt on.
	Session string        `json:"session,omitempty"`
	Prompt  int           `json:"prompt"`
	Label   string        `json:"label"`
	Started time.Time     `json:"started"`
	Changes []*fileChange `json:"changes"`
	// contains filtered or unexported fields
}

Turn is the set of file changes made while handling one user prompt.

type TurnSummary

type TurnSummary struct {
	ID      int
	Session string
	Prompt  int
	Label   string
	Time    time.Time
	Files   []string
}

TurnSummary describes a checkpoint for display.

type UCToolMetadata

type UCToolMetadata struct {
	Name        string `json:"name"`
	Language    string `json:"language"`
	Description string `json:"description"`
	Path        string `json:"path"`
}

UCToolMetadata holds metadata about a dynamically forged tool.

type UndoResult

type UndoResult struct {
	Turn     TurnSummary
	Restored []string
}

UndoResult reports what an undo restored.

type UniversalConstructorInput

type UniversalConstructorInput struct {
	Action      string `json:"action" jsonschema:"Action to perform: create, run, list, or delete"`
	ToolName    string `json:"tool_name,omitempty" jsonschema:"Name of tool to create or run (letters, digits, '-' and '_')"`
	Language    string `json:"language,omitempty" jsonschema:"Programming language (go, python, bash)"`
	Code        string `json:"code,omitempty" jsonschema:"Source code of tool to create"`
	Description string `json:"description,omitempty" jsonschema:"Description of what tool does"`
	Args        string `json:"args,omitempty" jsonschema:"Whitespace-separated arguments to pass when running tool"`
}

UniversalConstructorInput defines arguments for the universal constructor.

type UniversalConstructorOutput

type UniversalConstructorOutput struct {
	Success bool     `json:"success"`
	Result  string   `json:"result"`
	Tools   []string `json:"tools,omitempty"`
	Error   string   `json:"error,omitempty"`
}

UniversalConstructorOutput holds result of universal constructor.

type Verdict

type Verdict int

Verdict is the outcome of evaluating a command against the policy.

const (
	// VerdictNeedsApproval means the user must approve (subject to global auto-approve settings).
	VerdictNeedsApproval Verdict = iota
	// VerdictAutoApprove means every command matched an auto_approve pattern.
	VerdictAutoApprove
	// VerdictDeny means the command must not run.
	VerdictDeny
)

type ViewImageInput

type ViewImageInput struct {
	Path string `json:"path" jsonschema:"The absolute or workspace-relative path of a PNG, JPEG, GIF or WebP image"`
}

ViewImageInput defines arguments for view_image.

type ViewImageOutput

type ViewImageOutput struct {
	Path     string `json:"path"`
	ImageURI string `json:"image_uri,omitempty"`
	MIME     string `json:"mime_type,omitempty"`
	Width    int    `json:"width,omitempty"`
	Height   int    `json:"height,omitempty"`
	Resized  bool   `json:"resized,omitempty"`
	Note     string `json:"note,omitempty"`
	Error    string `json:"error,omitempty"`
}

ViewImageOutput describes the image; the picture itself follows the result.

type WalkEntry

type WalkEntry struct {
	Path   string // display path: workspace-relative, or absolute outside it
	Entry  fs.DirEntry
	IsRoot bool // the starting path itself
	// contains filtered or unexported fields
}

WalkEntry is one entry visited by Walk.

func (WalkEntry) Open

func (e WalkEntry) Open() (fs.File, error)

Open opens the entry for reading.

type WebFetchConfig

type WebFetchConfig struct {
	AllowDomains []string // fetched without approval
	DenyDomains  []string // never fetched
	AllowPrivate bool     // permit loopback/private/link-local targets
	AllowNetwork bool     // mirrors sandbox.allow_network
	MaxBytes     int64
	Timeout      time.Duration
	// Rules are the permission rules: web(host) deny refuses, ask always
	// asks (even for allow_domains), allow skips the question.
	Rules *PermissionRules
}

WebFetchConfig configures web_fetch.

type WebFetchInput

type WebFetchInput struct {
	URL string `json:"url" jsonschema:"The http(s) URL to fetch"`
}

WebFetchInput defines arguments for web_fetch.

type WebFetchOutput

type WebFetchOutput struct {
	URL         string `json:"url"`
	FinalURL    string `json:"final_url,omitempty"`
	Status      int    `json:"status,omitempty"`
	ContentType string `json:"content_type,omitempty"`
	Content     string `json:"content,omitempty"`
	Truncated   bool   `json:"truncated,omitempty"`
	Error       string `json:"error,omitempty"`
}

WebFetchOutput holds the fetched page.

type WebSearchConfig

type WebSearchConfig struct {
	Provider     string // brave | tavily | searxng | google
	APIKey       string // brave/tavily/google; falls back to BRAVE_API_KEY / TAVILY_API_KEY / GEMINI_API_KEY
	BaseURL      string // searxng instance, or an override for the others
	Model        string // google: the Gemini model that runs the search (default gemini-3.8-flash)
	MaxResults   int
	DenyDomains  []string
	AllowNetwork bool
	Timeout      time.Duration
}

WebSearchConfig configures web_search.

type WebSearchInput

type WebSearchInput struct {
	Query      string `json:"query" jsonschema:"The search query"`
	MaxResults int    `json:"max_results,omitempty" jsonschema:"Number of results (default from config, max 20)"`
}

WebSearchInput defines arguments for web_search.

type WebSearchOutput

type WebSearchOutput struct {
	Query   string         `json:"query"`
	Results []SearchResult `json:"results"`
	// Answer is the provider's own summary with the results (google only).
	Answer string `json:"answer,omitempty"`
	Error  string `json:"error,omitempty"`
}

WebSearchOutput holds search results.

type Workspace

type Workspace struct {
	// contains filtered or unexported fields
}

Workspace is the file sandbox. Every file tool goes through it: paths must fall under one of its roots, writes need a writable root, and blocked patterns are refused even inside a root. Each root is an os.Root, which rejects ".." traversal and symlinks leaving the root at the OS level.

func NewWorkspace

func NewWorkspace(dir string, maxFileSize int64) (*Workspace, error)

NewWorkspace opens dir as a single read-write root with no blocked paths.

func OpenWorkspace

func OpenWorkspace(opts WorkspaceOptions) (*Workspace, error)

OpenWorkspace opens the workspace and any additional roots. Additional roots that don't exist are an error, so a typo can't silently widen or narrow the sandbox.

func (*Workspace) Abs

func (w *Workspace) Abs(p string) (string, error)

Abs resolves p for reading and returns its absolute path after verifying, through os.Root, that it exists and does not escape via symlinks.

func (*Workspace) AgentRule

func (w *Workspace) AgentRule(rel string) string

AgentRule is the agent's rule for the workspace-relative path rel: "blocked", "read_only", or "" when the agent may read and write it.

func (*Workspace) Blocked

func (w *Workspace) Blocked() *PathMatcher

Blocked returns the blocked-path matcher.

func (*Workspace) Close

func (w *Workspace) Close() error

Close releases all root handles.

func (*Workspace) CreateExclusive

func (w *Workspace) CreateExclusive(p string, data []byte) error

CreateExclusive creates a new file, failing with fs.ErrExist if it exists.

func (*Workspace) Describe

func (w *Workspace) Describe() []string

Describe summarises the sandbox for display.

func (*Workspace) Dir

func (w *Workspace) Dir() string

Dir returns the absolute workspace path.

func (*Workspace) MaxFileSize

func (w *Workspace) MaxFileSize() int64

MaxFileSize returns the per-file read limit in bytes.

func (*Workspace) Open

func (w *Workspace) Open(p string) (*os.File, error)

Open opens p for reading.

func (*Workspace) ReadFile

func (w *Workspace) ReadFile(p string) ([]byte, error)

ReadFile reads a regular file, refusing files over the size limit.

func (*Workspace) ReadFileLimit

func (w *Workspace) ReadFileLimit(p string, limit int64) ([]byte, error)

ReadFileLimit reads a regular file of at most limit bytes.

func (*Workspace) ReadOnlyDirs

func (w *Workspace) ReadOnlyDirs() []string

ReadOnlyDirs returns the read-only roots.

func (*Workspace) Rel

func (w *Workspace) Rel(p string) (string, error)

Rel resolves p for reading and returns its display form: relative to the workspace when inside it, otherwise absolute.

func (*Workspace) RemoveFile

func (w *Workspace) RemoveFile(p string) error

RemoveFile deletes a single non-directory entry.

func (*Workspace) RootDirs

func (w *Workspace) RootDirs() []string

RootDirs returns every root directory, workspace first.

func (*Workspace) Stat

func (w *Workspace) Stat(p string) (fs.FileInfo, error)

Stat stats p.

func (*Workspace) UserMkdir

func (w *Workspace) UserMkdir(rel string) error

UserMkdir creates the folder rel (and missing parents); it must not exist.

func (*Workspace) UserReadDir

func (w *Workspace) UserReadDir(rel string) ([]fs.DirEntry, error)

UserReadDir lists the directory rel.

func (*Workspace) UserReadFile

func (w *Workspace) UserReadFile(rel string, limit int64) ([]byte, fs.FileInfo, error)

UserReadFile reads the regular file rel if it's at most limit bytes; larger, it returns the file's information and ErrTooLarge.

func (*Workspace) UserRemove

func (w *Workspace) UserRemove(ctx context.Context, rel string) error

UserRemove deletes rel, a folder with everything in it.

func (*Workspace) UserRename

func (w *Workspace) UserRename(ctx context.Context, from, to string) error

UserRename moves from to to, which must not exist.

func (*Workspace) UserStat

func (w *Workspace) UserStat(rel string) (fs.FileInfo, error)

UserStat stats rel (following a symlink, which must stay in the workspace).

func (*Workspace) UserWriteFile

func (w *Workspace) UserWriteFile(ctx context.Context, rel string, data []byte, check func(current []byte, exists bool) error) error

UserWriteFile replaces rel with data atomically (its mode kept), or creates it, under the same per-path lock as the agent's edits. check, if set, runs under the lock with the file's current content (nil, false when it doesn't exist) and can refuse the write.

func (*Workspace) Walk

func (w *Workspace) Walk(p string, fn func(WalkEntry) error) error

Walk visits p and everything beneath it in lexical order, skipping blocked entries. fn may return fs.SkipDir or fs.SkipAll.

func (*Workspace) WritableDirs

func (w *Workspace) WritableDirs() []string

WritableDirs returns the roots that may be written to.

func (*Workspace) WritablePath

func (w *Workspace) WritablePath(p string) (string, error)

WritablePath resolves p for writing and returns its display form. Tools call it before asking for approval so users aren't asked to approve a write the sandbox would refuse anyway.

func (*Workspace) WriteFileAtomic

func (w *Workspace) WriteFileAtomic(p string, data []byte) error

WriteFileAtomic replaces p with data via a temp file and rename, so a crash or error never leaves a half-written file. An existing file's mode is kept. If p is itself a symlink, the target is rewritten in place (through os.Root, so it must stay inside the root) rather than replacing the link.

type WorkspaceOptions

type WorkspaceOptions struct {
	Dir           string   // the workspace (read-write); defaults to "."
	AllowedPaths  []string // additional read-write roots
	ReadOnlyPaths []string // additional read-only roots
	BlockedPaths  []string // glob patterns never readable or writable
	MaxFileSize   int64
}

WorkspaceOptions configures the file sandbox.

Jump to

Keyboard shortcuts

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