tools

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 69 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 (
	FormPrefix = "prefix" // words: the command with any arguments
	FormGlob   = "glob"   // * and ?
	FormRegex  = "regex"  // re:
)

Command pattern forms, as CommandPatternForm reports them.

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 (
	SourceConfig  = "config"   // the settings files, global and the workspace's
	SourceProject = "project"  // the workspace's project files (.blitz/settings.toml)
	SourceBuiltIn = "built-in" // [permissions] read_only_defaults
	SourceFlag    = "flag"     // --allow, --deny
	SourceSession = "session"  // added for this session
)

Rule sources, as PermissionRule.Source says.

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 means the path is in the repository's .git directory, which 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 means the file is over the size the caller reads.

Functions

func Background

func Background(ctx context.Context) context.Context

Background marks ctx as a background task's run: what the workspace's rules and mode allow runs, and anything that would ask the person is refused instead, since nobody is asked for it (spec_background_agents_032 BGA-40).

func CallID

func CallID(ctx context.Context) string

CallID is the ID of the tool call ctx runs (the tool's context), or "".

func CommandPatternForm

func CommandPatternForm(p string) string

CommandPatternForm says how a command pattern matches.

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 ExportDocxOutputPath added in v0.6.0

func ExportDocxOutputPath(p, output string) string

ExportDocxOutputPath is where export_docx writes: output, or path with its extension replaced by .docx ("" with neither).

func ExportPDFOutputPath added in v0.2.1

func ExportPDFOutputPath(p, output string) string

ExportPDFOutputPath is where export_pdf writes: output, or path with its extension replaced by .pdf ("" with neither).

func IsBackground

func IsBackground(ctx context.Context) bool

IsBackground reports whether ctx is a background task's run.

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 NewBrowserTool

func NewBrowserTool(bt *browserTool) (tool.Tool, error)

NewBrowserTool is browser: the agent drives a real browser (spec_parity_027 PAR-TOOL-10..12).

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 NewExportDocxTool added in v0.6.0

func NewExportDocxTool(ws *Workspace, hooks *Hooks, pageSize string) (tool.Tool, error)

NewExportDocxTool writes a Markdown file as a Word document beside it (or at output), or Markdown given directly at output, as NewExportPDFTool does for PDFs (FS-75).

func NewExportPDFTool added in v0.2.1

func NewExportPDFTool(ws *Workspace, hooks *Hooks, pageSize string) (tool.Tool, error)

NewExportPDFTool typesets a Markdown file as a PDF beside it (or at output), or Markdown given directly as a PDF at output, so a PDF of something that isn't a file (a summary of the conversation) leaves no Markdown file behind. It goes through the same checks, approval and checkpoint as create_file. pageSize is a [pdf] page_size setting.

func NewGenerateAudioTool added in v0.2.1

func NewGenerateAudioTool(ws *Workspace, hooks *Hooks, s *speech, allowNetwork bool) (tool.Tool, error)

NewGenerateAudioTool reads text aloud with the [audio] speech model and writes the audio into the workspace: an audio overview of notes, a two-voice conversation about a paper. One approval covers the call (it sends the text to the provider) and the file it writes, which a checkpoint can undo.

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 NewLSPTool

func NewLSPTool(ws *Workspace, m *lsp.Manager) (tool.Tool, error)

NewLSPTool is lsp: go to definitions, find references, hover, search symbols and read diagnostics through the workspace's language servers.

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 NewMCPResourceTools

func NewMCPResourceTools(r *Registry) ([]tool.Tool, error)

NewMCPResourceTools creates list_mcp_resources and read_mcp_resource. Both only read; each server's use is approved as its tools are.

func NewManageBackgroundTool

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

NewManageBackgroundTool creates the tool for inspecting and stopping background processes.

func NewNotebookEditTool

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

NewNotebookEditTool is notebook_edit: a Jupyter cell replaced, inserted or deleted, through the file sandbox, approvals (with the diff) and checkpoints, as other edits.

func NewReadFileTool

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

NewReadFileTool creates an ADK tool for reading files.

func NewRememberTool

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

NewRememberTool is remember: the agent keeps a note for later sessions. Notes never hold secrets (they're redacted) and never grant permission.

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 NewSearchWorkspaceTool added in v0.3.0

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

NewSearchWorkspaceTool is search_workspace: ranked full-text search of the workspace's index, one passage per item.

func NewTaskTools

func NewTaskTools(hooks *Hooks) ([]tool.Tool, error)

NewTaskTools creates list_tasks, task_output and stop_task: the calling session's background tasks.

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 NewViewDocumentTool added in v0.2.1

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

NewViewDocumentTool lets the model read a PDF in the workspace as it is, pages, figures and tables, where the model can (as its text where it can't): papers, slides, scanned notes.

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 NewViewMediaTool added in v0.2.1

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

NewViewMediaTool lets a model that takes audio or video (Gemini) listen to or watch a file in the workspace: a lecture, a recording, a screen capture of a bug. Others are told it can't.

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 NotebookText added in v0.3.0

func NotebookText(data []byte) (string, error)

render is the notebook as its cells with their outputs, for read_file. NotebookText is a Jupyter notebook's cells as text, as read_file shows them, each headed "## Cell N [kind]" (workspace search indexes it).

func PromptID

func PromptID(ctx context.Context) string

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

func Speakable added in v0.2.1

func Speakable(md string) string

Speakable is Markdown as it should be read out: without front matter, heading and list marks, emphasis, link targets, rules and HTML tags. A "Name: line" stays as it is, for a conversation's speakers.

func SystemNode

func SystemNode() (string, error)

SystemNode is the node on PATH, as its real path, when it runs TypeScript (22.6 or later).

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 WithMode

WithMode runs ctx's actions in permission mode m instead of the workspace's (an agent's own permission_mode). The caller checks that bypass may be used.

func WithNotices added in v0.5.4

func WithNotices(ctx context.Context, f func(string)) context.Context

WithNotices sends what the tools tell the user during work under ctx to f: the turn's notices (runtime.WithTurnNotices sets it).

func WithOwnerSession

func WithOwnerSession(ctx context.Context, session string) context.Context

WithOwnerSession makes session the one a sub-agent's tool calls count for (their background processes and tasks): the session whose turn started the sub-agent, not its own.

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.

func WithTaskAsker

func WithTaskAsker(ctx context.Context, a TaskAsker) context.Context

WithTaskAsker routes ctx's approval requests and questions to a, instead of the workspace's approver (a background task's run).

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"`
	// Assets are the skill's declared resources (Castor's): what each is,
	// where it lives, and text it was turned into.
	Assets []SkillAsset `json:"assets,omitempty"`
	// WritesWorkspace means the scripts change the workspace's files, in a
	// copy; the user approves what they changed before it's kept.
	WritesWorkspace bool   `json:"writes_workspace,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; it takes effect only once saved.

func (*ApprovalStore) Has

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

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

func (*ApprovalStore) Path

func (s *ApprovalStore) Path() string

Path is the store's file.

func (*ApprovalStore) Reload

func (s *ApprovalStore) Reload() error

Reload reads the file again: another process (the service, a terminal) may have remembered or forgotten an approval. A missing file is empty.

func (*ApprovalStore) Remove

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

Remove deletes a rule; it reports whether it existed. The rule stays when saving fails.

func (*ApprovalStore) Rules

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

Rules returns all rules sorted by key.

type AskUserQuestionInput

type AskUserQuestionInput struct {
	Question    string   `json:"question,omitempty" jsonschema:"The question or clarification needed from the user"`
	Options     []string `json:"options,omitempty" jsonschema:"Optional list of multiple choice options"`
	MultiSelect bool     `json:"multi_select,omitempty" jsonschema:"The user may choose several of the options"`
	// Questions asks several at once, answered in turn.
	Questions []QuestionItem `json:"questions,omitempty" jsonschema:"Several questions to ask together, instead of question and options"`
}

AskUserQuestionInput defines arguments for asking the user: one question, or several at once.

type AskUserQuestionOutput

type AskUserQuestionOutput struct {
	Answer string `json:"answer,omitempty"`
	// Selected are the options chosen, for a multi-select question.
	Selected []string         `json:"selected,omitempty"`
	Answers  []QuestionAnswer `json:"answers,omitempty"`
	Error    string           `json:"error,omitempty"`
}

AskUserQuestionOutput holds the user's answer (or answers).

type BackgroundProcess

type BackgroundProcess struct {
	ID      int
	Command string
	// Session is the session whose turn started it ("" outside one).
	Session   string
	StartTime time.Time
	// contains filtered or unexported fields
}

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

type BrowserInput

type BrowserInput struct {
	Action   string `` /* 209-byte string literal not displayed */
	URL      string `json:"url,omitempty" jsonschema:"navigate: the http(s) address"`
	Selector string `` /* 137-byte string literal not displayed */
	Text     string `json:"text,omitempty" jsonschema:"type: the text to enter"`
	Append   bool   `json:"append,omitempty" jsonschema:"type: add to what the field holds instead of replacing it"`
	Submit   bool   `json:"submit,omitempty" jsonschema:"type: press Enter afterwards"`
	Value    string `json:"value,omitempty" jsonschema:"select: the option's value or text"`
	Script   string `json:"script,omitempty" jsonschema:"script: a JavaScript expression run in the page; its value (awaited) is returned"`
	FullPage bool   `json:"full_page,omitempty" jsonschema:"screenshot: the whole page, not just the viewport"`
}

BrowserInput is what the browser tool takes.

type BrowserOutput

type BrowserOutput struct {
	URL       string                `json:"url,omitempty"`
	Title     string                `json:"title,omitempty"`
	Text      string                `json:"text,omitempty"`
	Result    string                `json:"result,omitempty"`
	Truncated bool                  `json:"truncated,omitempty"`
	Console   []browser.ConsoleLine `json:"console,omitempty"`
	ImageURI  string                `json:"image_uri,omitempty"`
	MIME      string                `json:"mime_type,omitempty"`
	Refused   []string              `json:"refused,omitempty"`
	Recording string                `json:"recording,omitempty"`
	Frames    []string              `json:"frames,omitempty"`
	Note      string                `json:"note,omitempty"`
	Error     string                `json:"error,omitempty"`
}

BrowserOutput is what it returns.

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. When the index can't be loaded (unreadable, from a newer Blitz, or damaged, which is set aside), the store starts empty in memory and leaves o.Dir alone (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) BeginWorkerTurn

func (c *Checkpoints) BeginWorkerTurn(session, run, label string)

BeginWorkerTurn starts the turn of worker run run, in its session: its changes are kept apart from the interactive sessions' (BL-WK-01).

func (*Checkpoints) Created

func (c *Checkpoints) Created(session string) []string

Created returns the files session's latest turn created: absent before it, there after (absolute paths, in the order they were made).

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) RunFiles

func (c *Checkpoints) RunFiles(run string) []string

RunFiles are the files worker run run changed, sorted.

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.

func (*Checkpoints) UndoRun

func (c *Checkpoints) UndoRun(run string, force bool) (UndoResult, error)

UndoRun restores the files worker run run changed, as they were before it, refusing on conflicts as Undo does (BL-WK-02).

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 means 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:

  • words alone name a command and any arguments: "ls" matches "ls" and "ls -la", "git log" matches "git log --oneline" (not "git logs");
  • with "*" (any text) or "?" (one character) the pattern is a glob over the whole command, and a trailing " *" also matches the bare command ("git * --output*" matches "git log --output=x");
  • "re:" starts a regular expression (RE2), which must match the whole command: "re:git (log|show)( .*)?".

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 Credential

type Credential struct {
	Env  string
	Path func() string
}

Credential is a file a process gets a copy of: Path gives the file as the process starts ("" for none), and Env is set to the copy's path.

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
	// Credentials are files each process gets its own copy of, named by an
	// environment variable, while the originals stay blocked: the sign-in
	// Blitz itself uses (Google's ADC), for commands that need it too.
	Credentials []Credential
}

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 ExportInput added in v0.6.0

type ExportInput struct {
	Path      string `json:"path,omitempty" jsonschema:"The Markdown file to export (.md or .markdown); or give markdown instead"`
	Markdown  string `` /* 190-byte string literal not displayed */
	Output    string `` /* 142-byte string literal not displayed */
	Overwrite bool   `json:"overwrite,omitempty" jsonschema:"Replace the document if it already exists"`
}

ExportInput defines arguments for export_pdf and export_docx.

type ExportOutput added in v0.6.0

type ExportOutput struct {
	Path    string `json:"path"`
	Output  string `json:"output,omitempty"`
	Pages   int    `json:"pages,omitempty"`
	Bytes   int    `json:"bytes,omitempty"`
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

ExportOutput holds an export's result.

type ExportPDFInput added in v0.2.1

type ExportPDFInput = ExportInput

ExportPDFInput and ExportPDFOutput are export_pdf's input and output.

type ExportPDFOutput added in v0.2.1

type ExportPDFOutput = ExportOutput

ExportPDFInput and ExportPDFOutput are export_pdf's input and output.

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 GenerateAudioInput added in v0.2.1

type GenerateAudioInput struct {
	Text      string         `json:"text,omitempty" jsonschema:"The text to read aloud (or text_path)"`
	TextPath  string         `json:"text_path,omitempty" jsonschema:"A workspace file whose text to read aloud, such as a script in Markdown"`
	Path      string         `` /* 129-byte string literal not displayed */
	Voice     string         `json:"voice,omitempty" jsonschema:"The voice for one speaker, by the provider's name for it"`
	Speakers  []SpeakerInput `` /* 138-byte string literal not displayed */
	Overwrite bool           `json:"overwrite,omitempty" jsonschema:"Replace the file if it already exists"`
}

GenerateAudioInput defines arguments for generate_audio.

type GenerateAudioOutput added in v0.2.1

type GenerateAudioOutput struct {
	Path    string  `json:"path"`
	Bytes   int     `json:"bytes,omitempty"`
	Seconds float64 `json:"seconds,omitempty"`
	Model   string  `json:"model,omitempty"`
	Note    string  `json:"note,omitempty"`
	Success bool    `json:"success"`
	Error   string  `json:"error,omitempty"`
}

GenerateAudioOutput describes the audio written.

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 HookFailure

type HookFailure struct {
	Time  time.Time
	Error string
}

HookFailure is a hook's failed run.

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) EndCall

func (h *Hooks) EndCall(id string)

EndCall forgets the call's grant.

func (*Hooks) GrantCall

func (h *Hooks) GrantCall(id string)

GrantCall lets the call id through its approvals (a pre_tool hook's allow); EndCall forgets it.

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) SetReviewer

func (h *Hooks) SetReviewer(r Reviewer)

SetReviewer supplies the auto mode's reviewer.

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) SetTaskRunner

func (h *Hooks) SetTaskRunner(r TaskRunner)

SetTaskRunner supplies what runs background tasks (invoke_agent with background: true, list_tasks, task_output, stop_task).

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"`
	// Background runs it beside this turn as a task.
	// Isolation runs a background task in its own git worktree.
	Isolation  string `` /* 187-byte string literal not displayed */
	Background *bool  `` /* 300-byte string literal not displayed */
}

InvokeAgentInput defines arguments for invoke_agent.

type InvokeAgentOutput

type InvokeAgentOutput struct {
	AgentName string `json:"agent_name"`
	Response  string `json:"response"`
	// TaskID and Status: a background task, started.
	TaskID string `json:"task_id,omitempty"`
	Status string `json:"status,omitempty"`
	Error  string `json:"error,omitempty"`
}

InvokeAgentOutput holds result of invoking an agent.

type Judge

type Judge func(ctx context.Context, model, prompt string, event []byte) (string, error)

Judge has a model decide a prompt hook: it reads prompt (the user's criteria) and the event, and answers like a hook's JSON reply (the engine supplies it).

type LSPInput

type LSPInput struct {
	Operation string `json:"operation" jsonschema:"definition, references, hover, symbols (in the workspace, by query) or diagnostics (of a file)"`
	Path      string `json:"path" jsonschema:"The file: for symbols, any file of the language to ask"`
	Line      int    `json:"line,omitempty" jsonschema:"1-based line (definition, references, hover)"`
	Column    int    `json:"column,omitempty" jsonschema:"1-based column, in characters, on the symbol (definition, references, hover)"`
	Query     string `json:"query,omitempty" jsonschema:"symbols: the name, or part of it"`
}

LSPInput is what the lsp tool takes.

type LSPOutput

type LSPOutput struct {
	Locations   []lsp.Location   `json:"locations,omitempty"`
	Hover       string           `json:"hover,omitempty"`
	Symbols     []lsp.Symbol     `json:"symbols,omitempty"`
	Diagnostics []lsp.Diagnostic `json:"diagnostics,omitempty"`
	Note        string           `json:"note,omitempty"`
	Error       string           `json:"error,omitempty"`
}

LSPOutput is what it returns.

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 ListMCPResourcesInput

type ListMCPResourcesInput struct {
	Server string `json:"server,omitempty" jsonschema:"An MCP server's name; empty lists every server's resources"`
}

ListMCPResourcesInput optionally names a server.

type ListMCPResourcesOutput

type ListMCPResourcesOutput struct {
	Resources []MCPResource `json:"resources"`
	Error     string        `json:"error,omitempty"`
}

ListMCPResourcesOutput lists resources.

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 ListTasksOutput

type ListTasksOutput struct {
	Tasks []TaskSummary `json:"tasks"`
	Error string        `json:"error,omitempty"`
}

ListTasksOutput lists this session's tasks.

type MCPManager

type MCPManager struct {
	Warn func(string)
	// Ask puts a server's elicitation to whoever the tool call's run asks.
	Ask func(ctx context.Context, question string, options []string) (string, error)
	// 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) GetPrompt

func (m *MCPManager) GetPrompt(ctx context.Context, server, name string, args map[string]string) (string, error)

GetPrompt runs prompt name of server with args and returns its messages as the text of a turn.

func (*MCPManager) Lookup

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

Lookup reports which server serves toolName.

func (*MCPManager) Prompts

func (m *MCPManager) Prompts(ctx context.Context, wait time.Duration) []MCPPrompt

Prompts lists every server's prompts, each server waiting at most wait.

func (*MCPManager) ReadResource

func (m *MCPManager) ReadResource(ctx context.Context, server, uri string) (string, error)

ReadResource returns the text of server's resource uri (binary content described, not included).

func (*MCPManager) ResourceMention

func (m *MCPManager) ResourceMention(ctx context.Context, mention string) (text string, ok bool, err error)

ResourceMention reads "@server:uri" for a prompt: the resource's text and whether server is an MCP server (else it isn't a resource mention).

func (*MCPManager) Resources

func (m *MCPManager) Resources(ctx context.Context, server string) ([]MCPResource, error)

Resources lists the resources of server (every server when "").

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 MCPPrompt

type MCPPrompt struct {
	Server      string
	Name        string
	Description string
	// Arguments are its arguments' names, in order; Required those that
	// must be given.
	Arguments []string
	Required  []string
}

MCPPrompt is a prompt an MCP server offers, as the slash command /mcp__<server>__<name>.

func (MCPPrompt) Command

func (p MCPPrompt) Command() string

Command is the prompt's slash command name.

type MCPResource

type MCPResource struct {
	Server      string `json:"server"`
	URI         string `json:"uri"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	MIMEType    string `json:"mime_type,omitempty"`
}

MCPResource is a resource an MCP server offers.

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 MediaCheck added in v0.2.1

type MediaCheck func(name, mime string, size int64) error

MediaCheck refuses an attachment the model about to take it can't (its media type and size; the workspace's, from the active agent's model).

type NodeEnv

type NodeEnv struct {
	Key      string    `json:"key"`
	Node     string    `json:"node"` // the runtime (real path)
	Deps     []string  `json:"deps"`
	Registry string    `json:"registry"`
	Created  time.Time `json:"created"`
	LastUsed time.Time `json:"last_used"`
	Skills   []string  `json:"skills"`
	Dir      string    `json:"-"`
}

NodeEnv describes one environment.

func (NodeEnv) Modules

func (e NodeEnv) Modules() string

Modules is the environment's node_modules.

type NodeEnvs

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

NodeEnvs manages npm package environments for TypeScript skill scripts (BL-SK-01), one per distinct set of dependencies, in ~/.blitz/node-envs/<key>, as PyEnvs does for Python: built inside the script sandbox (network on, writes only to the environment and npm's cache), never running packages' install scripts, and used only once its marker file is written.

func NewNodeEnvs

func NewNodeEnvs(dir string, p config.NPMPolicy) *NodeEnvs

NewNodeEnvs manages environments in dir (default ~/.blitz/node-envs) under the npm package policy.

func (*NodeEnvs) Ensure

func (m *NodeEnvs) Ensure(ctx context.Context, box ScriptBox, node, skill string, deps []string) (NodeEnv, error)

Ensure returns the environment for deps, building it in box first if needed (the caller has approved the install).

func (*NodeEnvs) InstallCommand

func (m *NodeEnvs) InstallCommand(deps []string) string

InstallCommand describes how Ensure installs deps, for the approval.

func (*NodeEnvs) Key

func (m *NodeEnvs) Key(node string, deps []string) string

Key identifies the environment for deps.

func (*NodeEnvs) Lookup

func (m *NodeEnvs) Lookup(node string, deps []string) (NodeEnv, bool)

Lookup returns the environment for deps and whether it's ready.

type NoteSaver

type NoteSaver func(ctx context.Context, kind, text string) (string, error)

NoteSaver keeps a note the agent remembers across sessions and returns its name (spec_parity_027 PAR-MEM-10); the engine supplies it.

type NotebookEditInput

type NotebookEditInput struct {
	Path     string `json:"path" jsonschema:"The notebook (.ipynb)"`
	Cell     string `` /* 140-byte string literal not displayed */
	Action   string `json:"action" jsonschema:"replace (the cell's source), insert (a new cell after cell), or delete"`
	Source   string `json:"source,omitempty" jsonschema:"The cell's new source (replace, insert)"`
	CellType string `json:"cell_type,omitempty" jsonschema:"code or markdown (insert; replace keeps the cell's unless given)"`
}

NotebookEditInput is what notebook_edit takes.

type NotebookEditOutput

type NotebookEditOutput struct {
	Path  string `json:"path"`
	Cell  string `json:"cell,omitempty"` // the cell changed or made (its id, or index)
	Cells int    `json:"cells,omitempty"`
	Error string `json:"error,omitempty"`
}

NotebookEditOutput is what it returns.

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 means 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
	// UpdatedArgs replace a tool call's arguments (pre_tool).
	UpdatedArgs map[string]any
}

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. With read_only_defaults on, the built-in read-only commands are allowed and their writing options ask (source SourceBuiltIn).

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) ReplaceConfigured

func (p *PermissionRules) ReplaceConfigured(cfg config.PermissionsConfig) error

ReplaceConfigured puts cfg's rules, and the built-in ones it asks for, in place of those from the settings: after the settings change while a session runs. Session and flag rules stay. Read rules are blocked paths, fixed when the workspace opens, so theirs apply from the next start.

func (*PermissionRules) ReplaceProject

func (p *PermissionRules) ReplaceProject(cfg config.PermissionsConfig) error

ReplaceProject puts cfg's rules in place of the project files' (their deny and ask rules, which only tighten), after a project file changed.

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 {
	// Notice receives what watched processes report: their exit and
	// matching lines, for their session (nil: nothing is reported).
	Notice func(session, text string)
	// 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) ListIn

func (m *ProcessManager) ListIn(sessions []string) []api.ProcessInfo

ListIn returns the tracked processes started for any of sessions, 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) SessionOf

func (m *ProcessManager) SessionOf(id int) (string, error)

SessionOf is the session process id was started for.

func (*ProcessManager) Shutdown

func (m *ProcessManager) Shutdown()

Shutdown kills every running process and refuses new ones.

func (*ProcessManager) Start

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

Start launches command in cwd as a background process for session (the session whose turn asked for it; "" for none).

func (*ProcessManager) StartWatched

func (m *ProcessManager) StartWatched(session, command, cwd string, watch *Watch) (*BackgroundProcess, error)

StartWatched is Start with what the process reports as it runs (nil: nothing).

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 QuestionAnswer

type QuestionAnswer struct {
	Question string   `json:"question"`
	Answer   string   `json:"answer"`
	Selected []string `json:"selected,omitempty"`
}

QuestionAnswer is the answer to one of several questions.

type QuestionItem

type QuestionItem struct {
	Question    string   `json:"question" jsonschema:"The question"`
	Options     []string `json:"options,omitempty" jsonschema:"Suggested answers"`
	MultiSelect bool     `json:"multi_select,omitempty" jsonschema:"The user may choose several options"`
}

QuestionItem is one of several questions.

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"`
	Note       string `json:"note,omitempty"`
	Error      string `json:"error,omitempty"`
}

ReadFileOutput holds the result of reading a file.

type ReadMCPResourceInput

type ReadMCPResourceInput struct {
	Server string `json:"server" jsonschema:"The MCP server's name"`
	URI    string `json:"uri" jsonschema:"The resource's URI, from list_mcp_resources"`
}

ReadMCPResourceInput names a resource.

type ReadMCPResourceOutput

type ReadMCPResourceOutput struct {
	Text  string `json:"text,omitempty"`
	Error string `json:"error,omitempty"`
}

ReadMCPResourceOutput is a resource's text.

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) CommandPolicy

func (r *Registry) CommandPolicy() *CommandPolicy

CommandPolicy is the policy shell commands are checked against, with the permission rules' shell patterns.

func (*Registry) EditDiagnostics

func (r *Registry) EditDiagnostics(ctx context.Context, tool string, args, result map[string]any) []lsp.Diagnostic

EditDiagnostics are the problems a language server reports in the file an edit tool call changed, when that language's server runs.

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) LSP added in v0.5.0

func (r *Registry) LSP() *lsp.Manager

LSP is the workspace's language servers (nil when the registry has none), which the editor shares with the agent's lsp tool.

func (*Registry) LoadImage

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

LoadImage reads an attachment from the workspace (an image, a PDF, a text file, audio or video) through the workspace sandbox (so blocked and out-of-workspace paths are refused), checks the model takes it, prepares it and stores it; audio and video are streamed, however large. The audit log records the path and hash, not the content.

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) SetMediaCheck added in v0.2.1

func (r *Registry) SetMediaCheck(c MediaCheck)

SetMediaCheck sets what refuses attachments the model can't take (spec_images_011); nil accepts every supported type.

func (*Registry) SetNoteSaver

func (r *Registry) SetNoteSaver(s NoteSaver)

SetNoteSaver supplies the remember tool's saver; nil turns it off.

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) SetSearchBilling

func (r *Registry) SetSearchBilling(f func(ctx context.Context, session, provider string, queries int))

SetSearchBilling sets what hears of the queries a search provider bills per query (Google's grounding): the session the search was for (its tool call's, or the owner WithOwnerSession names), the provider and the count. Nothing without a search provider.

func (*Registry) SetSearcher added in v0.3.0

func (r *Registry) SetSearcher(s Searcher)

SetSearcher supplies the search_workspace tool's searcher; nil turns it off.

func (*Registry) SetSpeaker added in v0.2.1

func (r *Registry) SetSpeaker(s Speaker, err error, cfg config.AudioConfig, billed SpeechBilling)

SetSpeaker gives generate_audio its speech model (nil: none), or why it can't be used (err), with the [audio] settings and what hears of each call's usage. Agents have generate_audio only while there's a speaker.

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) SpeakerErr added in v0.2.1

func (r *Registry) SpeakerErr() error

SpeakerErr is why the [audio] model can't be used; nil when it can, or when there's none.

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 RememberInput

type RememberInput struct {
	Note string `` /* 141-byte string literal not displayed */
	Kind string `` /* 138-byte string literal not displayed */
}

RememberInput is what the remember tool takes.

type RememberOutput

type RememberOutput struct {
	Saved string `json:"saved,omitempty"`
	Error string `json:"error,omitempty"`
}

RememberOutput is what it returns.

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 Reviewer

type Reviewer func(ctx context.Context, req api.ApprovalRequest) (allowed bool, reason string, err error)

Reviewer decides, in the auto mode, what would otherwise ask the user: allowed, or not with the reason.

type RuleCheck

type RuleCheck struct {
	Rule    string // canonical: kind(pattern), or a tool name
	Kind    string
	Pattern string
	// Form is FormPrefix, FormGlob or FormRegex for shell rules; "path" for
	// read, write and delete; "name" for the rest.
	Form string
	// Tested and Matches: whether the sample (a command, path or name)
	// was checked, and whether the rule covers it (an allow rule every
	// command in it, an ask or deny rule any).
	Tested, Matches bool
	// Redirect is a file the sample command writes through a redirection:
	// an allow rule that matches it still asks.
	Redirect string
}

RuleCheck describes a rule without adding it: its canonical form, how its pattern matches, and whether a sample matched.

func CheckPermissionRule

func CheckPermissionRule(effect Effect, text, sample string) (RuleCheck, error)

CheckPermissionRule parses a rule and, given a sample, says whether the rule applies to it.

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"`
	// Notify and NotifyPattern (background only) tell the agent about the
	// process as it runs (spec_parity_027 PAR-TOOL-04).
	Notify        bool   `` /* 142-byte string literal not displayed */
	NotifyPattern string `` /* 161-byte string literal not displayed */
}

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"`
	// Changed are the workspace files a writes_workspace script changed,
	// kept once approved.
	Changed []string `json:"changed_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)
	// Notify shows a hook's system_message to the user (nil: logged only).
	Notify func(ctx context.Context, msg string)
	// Judge decides prompt hooks (nil: they fail).
	Judge Judge
	// HTTP posts http hooks' events.
	HTTP *http.Client
	// 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) List

func (s *ScriptHooks) List() []api.HookInfo

List is every configured hook with its recent failures, by 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) Outcome

PreTool runs pre_tool hooks: a block (or deny), a decision, arguments to use instead, and context for the agent.

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 SearchWorkspaceHit added in v0.3.0

type SearchWorkspaceHit struct {
	Source  string   `json:"source"`
	Where   string   `json:"where"`
	Title   string   `json:"title,omitempty"`
	Section string   `json:"section,omitempty"`
	Snippet string   `json:"snippet"`
	Summary string   `json:"summary,omitempty"`
	Tags    []string `json:"tags,omitempty"`
}

SearchWorkspaceHit is one item found: where (path:line for files), what section of it (a PDF's page), and the lines around the match.

type SearchWorkspaceInput added in v0.3.0

type SearchWorkspaceInput struct {
	Query   string   `json:"query" jsonschema:"Words and \"quoted phrases\" to find; identifiers and parts of names match too"`
	Sources []string `` /* 133-byte string literal not displayed */
	Limit   int      `json:"limit,omitempty" jsonschema:"Most results (default 20)"`
	Mode    string   `` /* 161-byte string literal not displayed */
}

SearchWorkspaceInput is what search_workspace takes.

type SearchWorkspaceOutput added in v0.3.0

type SearchWorkspaceOutput struct {
	Hits  []SearchWorkspaceHit `json:"hits"`
	Error string               `json:"error,omitempty"`
}

SearchWorkspaceOutput is search_workspace's result, best first.

type Searcher added in v0.3.0

type Searcher func(ctx context.Context, q api.SearchQuery) (api.SearchResult, error)

Searcher searches the workspace's index (spec_search_035); the engine supplies it.

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 SkillAsset

type SkillAsset struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	Category    string `json:"category,omitempty"`
	MimeType    string `json:"mime_type,omitempty"`
	// URL is where to fetch it (web_fetch), when it has one.
	URL       string `json:"url,omitempty"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	// Content is its inline text; Summary and Text what it was interpreted
	// as (Text only when the skill asks it to go with the instructions).
	Content string `json:"content,omitempty"`
	Summary string `json:"summary,omitempty"`
	Text    string `json:"text,omitempty"`
}

SkillAsset is one of a skill's declared resources, for the model.

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.

func (*SkillScripts) SetWeb

func (s *SkillScripts) SetWeb(cfg WebFetchConfig)

SetWeb lets scripts come from storage_uri, fetched under cfg.

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 SpeakRequest added in v0.2.1

type SpeakRequest struct {
	Text     string
	Voice    string
	Speakers []config.SpeakerConfig
}

SpeakRequest is text to read aloud: in one voice, or as a conversation between Speakers whose lines start "Name: ".

type Speaker added in v0.2.1

type Speaker interface {
	// Model names the speech model, "provider/model".
	Model() string
	// Host is the API's host, for web permission rules.
	Host() string
	// Ext is the extension of the files it makes: ".wav" or ".mp3".
	Ext() string
	// Speak returns req's text as audio.
	Speak(ctx context.Context, req SpeakRequest) (*Speech, error)
}

Speaker reads text aloud with a speech model (runtime.NewSpeaker).

type SpeakerInput added in v0.2.1

type SpeakerInput struct {
	Name  string `json:"name" jsonschema:"The speaker's name, as each of their lines starts"`
	Voice string `json:"voice,omitempty" jsonschema:"The provider's voice name"`
}

SpeakerInput is one voice in a conversation.

type Speech added in v0.2.1

type Speech struct {
	Data    []byte
	MIME    string  // audio/wav or audio/mpeg
	Seconds float64 // 0 when unknown
	// Usage is what the model reported, for /cost (nil: none).
	Usage *genai.GenerateContentResponseUsageMetadata
}

Speech is spoken audio.

type SpeechBilling added in v0.2.1

type SpeechBilling func(ctx context.Context, session, model string, usage *genai.GenerateContentResponseUsageMetadata)

SpeechBilling hears what a speech call used: the session it was for, the model and its usage (nil when the provider reports none).

type StopTaskInput

type StopTaskInput struct {
	TaskID string `json:"task_id" jsonschema:"The task's ID"`
}

StopTaskInput names the task to stop.

type StopTaskOutput

type StopTaskOutput struct {
	ID    string `json:"id"`
	State string `json:"state"`
	Error string `json:"error,omitempty"`
}

StopTaskOutput is the task once stopped.

type TaskAsker

type TaskAsker struct {
	Approve api.Approver
	Ask     api.UserPromptFunc
}

TaskAsker is who a background task's approval requests and questions go to: its session's people, whenever one of them answers (spec_background_agents_032 BGA-41).

type TaskOutputInput

type TaskOutputInput struct {
	TaskID      string `json:"task_id" jsonschema:"The task's ID, from invoke_agent or list_tasks"`
	WaitSeconds int    `` /* 127-byte string literal not displayed */
}

TaskOutputInput names a task, and how long to wait for it.

type TaskOutputOutput

type TaskOutputOutput struct {
	TaskSummary
	RecentEvents []string `json:"recent_events,omitempty"`
	Error        string   `json:"error,omitempty"`
}

TaskOutputOutput is a task, its result once finished, and its latest events while it runs.

type TaskRunner

type TaskRunner interface {
	// StartTask starts one; isolation "worktree" gives it its own git
	// worktree and branch.
	StartTask(ctx context.Context, agent, prompt, isolation string) (api.TaskInfo, error)
	ListTasks(sessions []string) []api.TaskInfo
	// WaitTask returns the task with its latest events, once it has
	// finished or wait has passed (0: at once).
	WaitTask(ctx context.Context, sessions []string, id string, wait time.Duration) (api.TaskInfo, []string, error)
	StopTask(sessions []string, id string) (api.TaskInfo, error)
}

TaskRunner runs background tasks: sub-agents invoke_agent starts with background: true (spec_background_agents_032). The engine supplies it; every call names the sessions whose tasks it may see.

type TaskSummary

type TaskSummary struct {
	ID             string  `json:"id"`
	Agent          string  `json:"agent"`
	State          string  `json:"state"`
	Prompt         string  `json:"prompt"`
	RuntimeSeconds int64   `json:"runtime_seconds"`
	CostUSD        float64 `json:"cost_usd"`
	Result         string  `json:"result,omitempty"`
	Error          string  `json:"error,omitempty"`
}

TaskSummary is a task as the agent's task tools report it.

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"`
	// Run is the worker run that made the turn: its changes are the run's
	// own (blitz workers undo), not the interactive sessions' /undo.
	Run     string        `json:"run,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 ViewDocumentInput added in v0.2.1

type ViewDocumentInput struct {
	Path string `json:"path" jsonschema:"The absolute or workspace-relative path of a PDF"`
}

ViewDocumentInput defines arguments for view_document.

type ViewDocumentOutput added in v0.2.1

type ViewDocumentOutput struct {
	Path     string `json:"path"`
	ImageURI string `json:"image_uri,omitempty"`
	Pages    int    `json:"pages,omitempty"`
	Bytes    int    `json:"bytes,omitempty"`
	Note     string `json:"note,omitempty"`
	Error    string `json:"error,omitempty"`
}

ViewDocumentOutput describes the PDF; the document itself follows the result.

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 ViewMediaInput added in v0.2.1

type ViewMediaInput struct {
	Path string `json:"path" jsonschema:"The absolute or workspace-relative path of an audio or video file"`
}

ViewMediaInput defines arguments for view_media.

type ViewMediaOutput added in v0.2.1

type ViewMediaOutput struct {
	Path     string  `json:"path"`
	ImageURI string  `json:"image_uri,omitempty"`
	MIME     string  `json:"mime_type,omitempty"`
	Seconds  float64 `json:"seconds,omitempty"`
	Bytes    int     `json:"bytes,omitempty"`
	Note     string  `json:"note,omitempty"`
	Error    string  `json:"error,omitempty"`
}

ViewMediaOutput describes the audio or video; the file 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 Watch

type Watch struct {
	Exit  bool           // its exit, with its last output
	Lines *regexp.Regexp // output lines matching this (maxWatchedLines)
}

Watch is what a background process reports as it runs.

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-4-argon)
	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(ctx context.Context, 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(ctx context.Context, 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(ctx context.Context, 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