api

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 7 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 api is the contract between Blitz's front ends and its engine: the Backend a front end drives, and the values, events and errors that cross it. The engine's Workspace implements Backend in process and the client implements it over the service's API, so the CLI, the desktop app and the service see the same types.

It depends on nothing else in Blitz except the shared config and images packages, and nothing here reaches into the engine.

Index

Constants

View Source
const (
	TrustNone     = "none"
	TrustNew      = "new"
	TrustChanged  = "changed"
	TrustTrusted  = "trusted"
	TrustDeclined = "declined"
)

The trust states of ProjectSettings.State.

View Source
const (
	TaskRunning = "running"
	TaskWaiting = "waiting" // for an answer to its approval request or question
	TaskDone    = "done"
	TaskFailed  = "failed"
	TaskStopped = "stopped"
)

The states of a task.

Variables

View Source
var (
	// ErrSessionBusy reports a rewind while a turn runs in the session.
	ErrSessionBusy = errors.New("a turn is running in this session")
	// ErrNotRewindPoint reports an index that isn't one of the session's
	// prompts.
	ErrNotRewindPoint = errors.New("not a prompt of this session")
	// ErrCantRewindConversation reports a prompt recorded without its place
	// in the conversation (by an older version).
	ErrCantRewindConversation = errors.New("this prompt's place in the conversation isn't known")
	// ErrUnknownRewindMode reports a mode that isn't one of RewindModes.
	ErrUnknownRewindMode = errors.New("unknown rewind mode")
)
View Source
var (
	ErrCostLimit = errors.New("the turn reached its cost limit")
	ErrTimeLimit = errors.New("the turn reached its time limit")
)

Limits a turn can stop at. They wrap the limit, e.g. "the turn reached its cost limit ($0.50)"; ErrMaxTurns is the third.

View Source
var ErrBadModelRef = errors.New("not a model name")

ErrBadModelRef reports a model reference with no model name.

View Source
var ErrBadRule = errors.New("invalid permission rule")

ErrBadRule reports a rule that can't be parsed.

View Source
var ErrBypassNeedsSandbox = errors.New("bypass mode needs the OS sandbox (sandbox.shell), which isn't active")

ErrBypassNeedsSandbox refuses bypass mode without an active OS sandbox.

View Source
var ErrHashMismatch = errors.New("the worker changed since it was reviewed")

ErrHashMismatch reports enabling a worker at a hash other than its current one: the files changed after they were reviewed.

View Source
var ErrImagesDisabled = errors.New("image support is disabled")

ErrImagesDisabled is returned when images enabled = false (or the image store could not be created).

View Source
var ErrInvalidAgency = errors.New("agency must be low, medium, high or extreme")

ErrInvalidAgency reports an agency level other than low, medium, high or extreme.

View Source
var ErrMaxTurns = errors.New("maximum turns reached")

ErrMaxTurns is returned when a run exceeds its model-call budget.

View Source
var ErrNoActiveSession = errors.New("no active session")

ErrNoActiveSession reports an operation on the active session when there is none.

View Source
var ErrNoFetch = errors.New("web fetching is disabled")

ErrNoFetch reports that the agent can't fetch web pages, so a web search would give it nothing to read.

View Source
var ErrNoGoal = errors.New("no goal set")

ErrNoGoal is returned when the session has no goal.

View Source
var ErrNoNote = errors.New("no such note")

ErrNoNote is returned by ForgetNote when no note has the name.

View Source
var ErrNoSearch = errors.New("web search is not set up")

ErrNoSearch is returned by Registry.WebSearch when no search provider is configured (web.search_provider), or it can't be used.

View Source
var ErrNothingToCompact = errors.New("nothing to compact yet")

ErrNothingToCompact is returned when a session is too short to compact.

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

ErrNothingToUndo: there are no changes left to restore.

View Source
var ErrOutputLimit = errors.New("the model's reply hit its output limit (max_tokens) and was cut off: raise max_tokens for this model (Run settings › Generation, or max_tokens in [model_settings]) and ask again")

ErrOutputLimit: the model's reply stopped at its output limit (max_tokens) before it was done, so the turn ended without it: a tool call cut short is dropped, which looks like nothing happened.

View Source
var ErrProjectChanged = errors.New("the project settings changed since they were shown")

ErrProjectChanged: the project settings changed since they were shown; review them again.

View Source
var ErrRunInProgress = errors.New("the worker is already running")

ErrRunInProgress reports a run of a worker that is already running.

View Source
var ErrSandboxUnavailable = errors.New("the OS sandbox is unavailable")

ErrSandboxUnavailable: sandbox.shell is "required" and the OS sandbox can't run here, so the workspace doesn't open.

View Source
var ErrScriptsDisabled = errors.New("skill scripts are disabled")

ErrScriptsDisabled reports that skill scripts (and so their environments) are turned off.

View Source
var ErrSessionNotFound = errors.New("no such session")

ErrSessionNotFound reports a session ID with no saved session.

View Source
var ErrSessionOpen = errors.New("the session is open: switch to another first")

ErrSessionOpen is returned when deleting a session that is open: the active one, or one a background run uses.

View Source
var ErrSnapshotNameTaken = errors.New("a snapshot with this name already exists")

ErrSnapshotNameTaken is returned by Snapshot when another snapshot has the name.

View Source
var ErrSteerTooLate = errors.New("the turn has ended: send it as the next prompt")

ErrSteerTooLate refuses a steer message when no turn in the session takes it (none runs, or it already collected the unread ones): send it as the next prompt. The transcript has it already.

View Source
var ErrUndoConflict = errors.New("files changed since the edit")

ErrUndoConflict is returned when files changed after the checkpointed edit.

View Source
var ErrUnknownCommand = errors.New("unknown command")

ErrUnknownCommand reports a slash command that doesn't exist.

View Source
var ErrUnknownLocale = errors.New("not a language")

ErrUnknownLocale reports input that isn't a language.

View Source
var ErrUnknownMode = errors.New("unknown permission mode")

ErrUnknownMode reports a name that isn't a permission mode.

View Source
var ErrUnknownProcess = errors.New("no such background process")

ErrUnknownProcess: no background process with that ID was started for the sessions asking.

View Source
var ErrUnknownRequest = errors.New("no such request is waiting")

ErrUnknownRequest: no request with that ID is waiting.

View Source
var ErrUnknownRun = errors.New("no such background run")

ErrUnknownRun: the service has no background run with that ID.

View Source
var ErrUnknownTask = errors.New("no such task")

ErrUnknownTask: no task with that ID was started in the sessions asking.

View Source
var ErrUnknownWorker = errors.New("no such worker")

ErrUnknownWorker reports a worker name the workspace doesn't define.

View Source
var ErrUnsupportedMedia = errors.New("the model can't take this file")

ErrUnsupportedMedia refuses an attachment the model can't take (its type, or its size); the error wrapping it names the file and the model.

View Source
var ErrWorkerExists = errors.New("a worker with that name exists")

ErrWorkerExists reports creating a worker with a name the workspace already has.

View Source
var ErrWorkerInvalid = errors.New("the worker's definition isn't valid")

ErrWorkerInvalid reports a WORKER.md that can't be used (the engine's workers.InvalidError, which lists why, matches it with errors.Is).

View Source
var ErrWorkerNotEnabled = errors.New("the worker isn't enabled")

ErrWorkerNotEnabled reports running a worker that isn't enabled at its current hash.

View Source
var ErrWorkersDisabled = errors.New("workers are disabled")

ErrWorkersDisabled reports that workers are turned off ([workers] enabled).

View Source
var ErrWorkspaceBusy = errors.New("the workspace is open elsewhere")

ErrWorkspaceBusy reports a workspace another process (or another Workspace in this one) has open. Only one may own a workspace at a time: they would otherwise write the same sessions and checkpoints. The lock goes with the process, so a crash never leaves a workspace locked.

Modes are the permission modes in Shift+Tab order; bypass is last and is only offered when the session started in it.

RewindModes are the modes, in the order offered.

Functions

func IsLimit

func IsLimit(err error) bool

IsLimit reports whether err is a turn stopping at one of its limits.

func IsMultiSelect

func IsMultiSelect(ctx context.Context) bool

IsMultiSelect reports whether a question asked with ctx takes several options.

func WithMultiSelect

func WithMultiSelect(ctx context.Context) context.Context

WithMultiSelect marks a question asked with ctx as taking several of its options (ask_user_question's multi_select).

Types

type ActionKind

type ActionKind string

ActionKind classifies a sensitive tool action for approval purposes.

const (
	ActionCommand ActionKind = "run_command" // shell commands and forged tool execution
	ActionWrite   ActionKind = "write_file"  // file creation and edits
	ActionDelete  ActionKind = "delete_file" // file deletion
	ActionNetwork ActionKind = "network"     // outbound web requests
	ActionMCP     ActionKind = "mcp_tool"    // tools served by MCP servers
)

type AgentInfo

type AgentInfo struct {
	Name        string
	DisplayName string
	Description string
	Active      bool
	// PinnedModel is the model the agent is pinned to ("" when it runs on
	// the configured model).
	PinnedModel string
}

AgentInfo describes an agent.

type AgentTools

type AgentTools struct {
	Agent string
	Tools []ToolInfo // by name
	MCP   []MCPOffer
}

AgentTools is what an agent can use.

type Approval

type Approval struct {
	// Key identifies the approval, for RevokeApprovals.
	Key string
	// Kind is what it allows: "cmd" (a shell command), "write", "delete",
	// "web" (a host), "mcp" (an MCP tool), "uc-run" (a forged tool), or
	// another kind a newer version added.
	Kind string
	// Subject is the command, path, host or tool.
	Subject string
	// Dir is the workspace a command approval is limited to ("" if any).
	Dir string
	// Always: saved for future sessions (Added says when); otherwise it
	// lasts until this process exits.
	Always bool
	Added  time.Time
}

Approval is a standing permission: actions it covers run without asking.

type ApprovalRequest

type ApprovalRequest struct {
	Tool   string
	Kind   ActionKind
	Detail string
	// Diff is a unified diff of the proposed file changes, if any.
	Diff string
	// Key identifies what "allow for this session" / "always allow" covers,
	// e.g. an exact command or all edits in a workspace. Empty means the
	// approval can only be given once.
	Key string
	// KeyLabel describes Key for the user ("this exact command").
	KeyLabel string
	// Targets are what the action is on, for policies that match them (a
	// worker's permissions): workspace-relative paths for file changes (a
	// patch may touch several), the command, the URL's host, the search
	// provider, or the MCP tool as "server:tool". Empty when nothing can
	// match, which such policies refuse.
	Targets []string
	// MustAsk: an ask rule covers the action, so the user is asked even
	// when a mode, an allow rule or a remembered approval would let it
	// through (and refused where nobody can be asked).
	MustAsk bool
}

ApprovalRequest describes an action awaiting user approval.

type Approver

type Approver func(ctx context.Context, req ApprovalRequest) (Decision, error)

Approver asks the user to decide on a sensitive action.

type Backend

type Backend interface {
	// Dir is the workspace directory.
	Dir() string
	// ModelErr is why the configured model couldn't be built (nil if it
	// could); the workspace then runs on a placeholder.
	ModelErr() error
	// SetUI routes the agent's approval requests and questions to the
	// front end.
	SetUI(approve Approver, ask UserPromptFunc)
	// Processes are the background processes to account for when the front
	// end exits; nil when they don't belong to it (a remote workspace).
	Processes() Processes
	// AuditShell records a command the user ran directly (!cmd), with why
	// it didn't start if it didn't.
	AuditShell(command string, exitCode int, startErr error)
	// ImagesEnabled reports whether images can be attached.
	ImagesEnabled() bool
	Close() error

	// Background tasks (invoke_agent with background: true) of the
	// sessions this front end ran turns in, oldest first; Task adds its
	// latest events, in words.
	ListTasks() []TaskInfo
	Task(id string) (TaskInfo, []string, error)
	StopTask(id string) (TaskInfo, error)
	// PendingTaskRequests are their approval requests and questions
	// waiting for an answer; AnswerTaskRequest answers one (a decision
	// for an approval, text for a question).
	PendingTaskRequests() []TaskRequest
	AnswerTaskRequest(id string, decision Decision, answer string) error

	// The active session's goal: SetGoal sets it (the next turns work
	// toward it), Goal returns it (ErrNoGoal), ClearGoal removes it.
	SetGoal(condition string) (Goal, error)
	Goal() (Goal, error)
	ClearGoal() error

	// TakeProcessNotices removes and returns what watched background
	// processes reported while session was idle (the REPL starts a turn).
	TakeProcessNotices(session string) []string

	// The output styles, with the one in use (Set "style" changes it).
	ListStyles() []StyleInfo

	// The configured hooks, by event, with recent failures (/hooks).
	ListHooks() []HookInfo

	// Notes the agent saved across sessions (remember), newest first;
	// ForgetNote deletes one.
	ListNotes() ([]Note, error)
	ForgetNote(name string) error

	// Project settings.
	ProjectSettings() ProjectSettings
	// TrustProject records trusting (or declining) the project settings
	// whose hash is given (ErrProjectChanged if they have changed since).
	// They load when the workspace next opens.
	TrustProject(hash string, trusted bool) error

	// Turns.
	Run(ctx context.Context, sessionID string, t Turn, on func(Event)) (TurnResult, error)
	Steer(ctx context.Context, sessionID, text string) error

	// Sessions.
	OpenSession(resume string, cont bool) (SessionInfo, bool, error)
	ActiveSession() (SessionInfo, bool)
	ListSessions(all bool) ([]SessionInfo, error)
	NewSession() (SessionInfo, error)
	LoadSession(ref string) (SessionInfo, bool, error)
	SaveSnapshot(name string, force bool) (SessionInfo, error)
	RenameSession(title string) (SessionInfo, error)
	// ForkSession starts a copy of the active session up to and including
	// prompt turn (1 the first; 0 all of it) and makes it active (/fork).
	ForkSession(ctx context.Context, turn int) (SessionInfo, error)
	// ExportSession is a session (the active one when "") as Markdown,
	// secrets masked (/export).
	ExportSession(id string) (string, error)
	// MoveSession carries session id into this workspace from the one it
	// was in, and makes it active (/cd).
	MoveSession(id string) (SessionInfo, error)

	// Agents, models and settings.
	ListAgents() []AgentInfo
	ActiveAgent() AgentInfo
	SetAgent(ctx context.Context, name string) (AgentInfo, error)
	Model() ModelInfo
	SetModel(ctx context.Context, ref string) (string, error)
	PinModel(ctx context.Context, agent, ref string) (PinResult, error)
	Unpin(ctx context.Context, agent string) (PinResult, error)
	AllModelSettings() map[string]config.ModelSettings
	ModelSettings(ref string) (ModelSettingsInfo, error)
	UpdateModelSettings(ref string, reset bool, changes []Setting) (ModelSettingsChange, error)
	Settings() Settings
	Set(ctx context.Context, key, value string) (string, error)
	SetPermissionMode(mode string) (string, error)
	ListPermissionRules() []PermissionRule
	AddPermissionRule(effect, rule string, save Scope) (PermissionChange, error)
	RemovePermissionRule(rule string, save Scope) (PermissionChange, error)

	// Skills, environments, MCP and tools.
	ListSkills() []SkillInfo
	SearchSkills(query string) []SkillInfo
	Skill(name string) (SkillInfo, bool)
	ListEnvs() ([]Env, error)
	RemoveEnv(key string) error
	PruneEnvs() (PruneResult, error)
	ListMCPServers() []MCPServer
	ListCommands() []CommandInfo
	ActiveAgentTools() AgentTools

	// Context, memory and language.
	SessionUsage() (Usage, error)
	// Context is how full the context is, with its breakdown by category
	// when parts is set (which reads the session).
	Context(parts bool) (ContextInfo, error)
	Compact(ctx context.Context, focus string) (CompactResult, error)
	MemoryFiles() []string
	ReloadMemory(ctx context.Context) ([]string, error)
	AddMemory(ctx context.Context, text string) (string, error)
	AvailableLocales() ([]LocaleInfo, string)
	SetLocale(ctx context.Context, input string) (LocaleChange, error)
	SandboxSummary() []string

	// Checkpoints and approvals.
	ListCheckpoints() []Checkpoint
	Undo(force bool) (UndoResult, error)
	RewindPoints() ([]RewindPoint, error)
	Rewind(ctx context.Context, index int, mode RewindMode, force bool) (RewindResult, error)
	SessionDiff() string
	GitDiff(ctx context.Context, color bool) (string, error)
	ListApprovals() []Approval
	RevokeApprovals(keys ...string) int
	ClearApprovals() int

	// Images and search.
	LoadImage(path string) (*images.Image, error)
	AddImage(name string, data []byte) (*images.Image, error)
	LoadAttachments(paths []string, prompt string, warn func(string)) ([]*images.Image, error)
	SearchProvider() (string, error)
	SearchWeb(ctx context.Context, terms string) (WebSearch, error)
	SearchSession(terms string) (int, string)
}

Backend is what a front end drives: a *Workspace in this process, or a workspace held by the Blitz service (through the client). Front ends use nothing else, so they work the same either way.

type BackgroundRun

type BackgroundRun struct {
	ID        string // bg-1, bg-2, …
	Workspace string
	SessionID string
	Prompt    string // its first line
	// State is running, waiting (for an answer), done, failed or stopped.
	State   string
	Started time.Time
	Ended   time.Time // zero while it runs
	CostUSD float64
	Waiting int // requests waiting for an answer
	Error   string
}

BackgroundRun is a turn the service runs with no client attached (blitz --bg).

func (BackgroundRun) Active

func (r BackgroundRun) Active() bool

Active reports whether the run hasn't ended.

type BlockedError

type BlockedError struct{ Reason string }

BlockedError reports a prompt refused by a prompt_submit hook. Nothing was recorded or sent.

func (*BlockedError) Error

func (e *BlockedError) Error() string

Error says a prompt_submit hook blocked the prompt, and why.

type Checkpoint

type Checkpoint struct {
	ID    int
	Label string // the prompt that started the turn, shortened
	Time  time.Time
	Files []string
}

Checkpoint is the files one turn changed, which Undo restores.

type CommandInfo

type CommandInfo struct {
	Name         string
	Description  string
	ArgumentHint string
	Source       string // project, user, bundled, skill, or "plugin <name>"
}

CommandInfo describes a custom slash command: a command file, a bundled command, or a skill run by name.

type CompactResult

type CompactResult struct {
	EventsCompacted int
	SummaryChars    int
	Before, After   Usage
}

CompactResult is what Compact did.

type ContextInfo

type ContextInfo struct {
	Tokens int64 // the latest prompt's size
	// AutoCompact: the context is compacted when it passes Threshold
	// tokens, keeping the last Keep events.
	AutoCompact bool
	Threshold   int
	Keep        int
	// Parts estimate what the context is made of, by category, scaled to
	// Tokens (/context).
	Parts []ContextPart
}

ContextInfo is the size of the model's context and when it is compacted.

type ContextPart

type ContextPart struct {
	Name   string
	Tokens int64
}

ContextPart is one category of what a prompt carries. Name is a key: system_prompt, instructions, tool_declarations, user_messages, replies, tool_calls, tool_results, images or summary.

type Decision

type Decision int

Decision is the user's answer to an approval request.

const (
	DecisionDeny    Decision = iota
	DecisionOnce             // allow this one action
	DecisionSession          // allow actions with the same Key until exit
	DecisionAlways           // allow actions with the same Key, persisted
)

The answers to an approval request.

func (Decision) String

func (d Decision) String() string

String is the decision's name: deny, once, session or always.

type Env

type Env struct {
	Key      string
	Deps     []string
	Skills   []string // the skills that used it
	Size     int64    // bytes on disk
	LastUsed time.Time
	Ready    bool // built completely
}

Env is an isolated Python environment built for skill scripts.

type EnvError

type EnvError struct {
	Key string
	Err error
}

EnvError is an environment that couldn't be removed.

type Event

type Event struct {
	// Author is the agent that produced the event (a sub-agent's name
	// when one is working).
	Author     string
	Text       *Text
	ToolCall   *ToolCall
	ToolResult *ToolResult
	// Tasks is the agent's task list, whole, each time it changes (the todo
	// tool).
	Tasks []Task
	// Notice is something the user should know about the turn that isn't
	// the agent's output, such as a message that couldn't be saved.
	Notice *Notice
}

Event is something that happened during a turn. Exactly one of Text, ToolCall and ToolResult is set. Events arrive in order.

type GitStatus

type GitStatus struct {
	Git     bool
	Repo    bool
	Branch  string
	Changed int
}

GitStatus is the workspace's git state for the status bar: its branch (or short commit, detached) and how many files differ from HEAD, untracked ones included. Git is false when git isn't on the service's PATH, Repo outside a repository (a repository with no commit yet is one). Git runs read-only, with no filters or fsmonitor.

type Goal

type Goal struct {
	Condition string
	// Continues is how often the agent was sent on; Max the limit.
	Continues, Max int
	// Last is the judge's latest reason.
	Last string
}

Goal is what a session works toward until a judge says it holds (/goal).

type HookFailure

type HookFailure struct {
	Time  time.Time
	Error string
}

HookFailure is one failed run of a hook.

type HookInfo

type HookInfo struct {
	Event string
	// Type is command, http or prompt.
	Type  string
	Match string
	If    string
	// Runs is what it runs: the command, POST <url> or prompt: <text>.
	Runs string
	// Source is the project file it came from ("": the user's settings).
	Source     string
	FailClosed bool
	// Failures are its latest failed runs since the workspace opened.
	Failures []HookFailure
}

HookInfo is a configured hook, for /hooks.

type InvalidSettingError

type InvalidSettingError struct{ Err error }

InvalidSettingError reports a setting that can't be applied: an unknown key or a value out of range.

func (*InvalidSettingError) Error

func (e *InvalidSettingError) Error() string

Error is the reason the value was refused.

func (*InvalidSettingError) Unwrap

func (e *InvalidSettingError) Unwrap() error

Unwrap returns the reason, for errors.Is and errors.As.

type Limits

type Limits struct {
	MaxTurns   int           `yaml:"max_turns"`
	MaxCostUSD float64       `yaml:"max_cost_usd"`
	Timeout    time.Duration `yaml:"-"`
	TimeoutRaw string        `yaml:"timeout"`
}

Limits bound one run. Every run has them: the host policy fills in what a worker leaves out.

type Link struct{ Title, URL string }

Link is a web search result the agent is asked to read.

type LocaleChange

type LocaleChange struct {
	Tag          string
	NativeName   string // e.g. "Español"
	LanguageName string // in the new language's terms, e.g. "español"
	// HasCatalog: the interface is translated; otherwise only the model's
	// replies are in the language.
	HasCatalog bool
	Saved      Saved
}

LocaleChange describes the interface language after SetLocale.

type LocaleInfo

type LocaleInfo struct{ Tag, Name string }

LocaleInfo names an interface language with a catalog.

type MCPOffer

type MCPOffer struct {
	Server string
	Tools  []string // the tools offered; empty means all of them
	Prefix string   // prepended to tool names ("" for none)
}

MCPOffer is an MCP server offered to an agent.

type MCPServer

type MCPServer struct {
	Name string
	// Target is its URL, or the command that starts it.
	Target      string
	AutoApprove bool
}

MCPServer is a configured MCP server.

type Message

type Message struct {
	Role string // "user" or "model"
	Text string
	Time time.Time
	// Kind tells user messages apart: "" for a prompt (a rewind point),
	// "steer", "hook" (a stop hook's request) or "plan" (an approved
	// plan's go-ahead); and "task" for a background task that ended.
	Kind string
}

Message is one message in a session's transcript.

type ModelInfo

type ModelInfo struct {
	Name     string
	Provider string // the configured provider
}

ModelInfo names the model the active agent runs on.

type ModelSettingsChange

type ModelSettingsChange struct {
	ModelSettingsInfo
	// Unsupported are keys set that the provider or model ignores.
	Unsupported []string
	Saved       Saved
}

ModelSettingsChange describes the result of UpdateModelSettings.

type ModelSettingsInfo

type ModelSettingsInfo struct {
	Model    string // the name settings are kept under, without a provider
	Provider string
	Settings config.ModelSettings
	// GlobalTemperature and GlobalMaxTokens apply when Settings leaves them
	// unset (0: the provider's default).
	GlobalTemperature float64
	GlobalMaxTokens   int
}

ModelSettingsInfo is one model's generation settings and what applies where it has none.

type Note

type Note struct {
	Name string // to show or forget it
	Kind string
	Text string
	Time time.Time
	// Path is its file, to edit (on the machine that keeps it).
	Path string
}

Note is something the agent remembered across sessions of a workspace with its remember tool: a fact, a preference or a correction.

type Notice

type Notice struct {
	Text string
	// Error: something went wrong (shown as an error), else information.
	Error bool
}

Notice is a message from Blitz itself about a turn.

type PermissionChange

type PermissionChange struct {
	Rule    string // canonical form
	Removed int    // RemovePermissionRule: how many rules went
	// NextStart: the rule is saved but only applies from the next start
	// (read rules become blocked paths, which are fixed at start).
	NextStart bool
	Saved     Saved // empty unless saving was asked for
}

PermissionChange is what AddPermissionRule or RemovePermissionRule did.

type PermissionMode

type PermissionMode string

PermissionMode decides which actions run without asking.

const (
	// ModeDefault asks for every sensitive action not covered by a rule.
	ModeDefault PermissionMode = "default"
	// ModeAcceptEdits runs file creates, edits and deletes inside the
	// writable roots without asking; commands and the rest ask as usual.
	ModeAcceptEdits PermissionMode = "accept-edits"
	// ModePlan refuses every tool that could change something, for every
	// prompt, until the mode changes (applied by the workspace).
	ModePlan PermissionMode = "plan"
	// ModeDontAsk denies whatever would ask: only rules and saved
	// approvals let actions through (for CI and scripts).
	ModeDontAsk PermissionMode = "dont-ask"
	// ModeAuto sends what would ask to a reviewer model instead, which
	// allows or denies it with a reason; ask rules still ask the user
	// (spec_parity_027 PAR-PERM-20).
	ModeAuto PermissionMode = "auto"
	// ModeBypass asks for nothing. Deny rules, blocked paths and the
	// sandboxes still apply, and the registry allows it only while the
	// OS sandbox is active.
	ModeBypass PermissionMode = "bypass"
)

func ParsePermissionMode

func ParsePermissionMode(s string) (PermissionMode, error)

ParsePermissionMode reads a mode name, accepting Claude Code's spellings (acceptEdits, dontAsk, bypassPermissions) too.

type PermissionRule

type PermissionRule struct {
	Effect string // allow, ask or deny
	Rule   string // kind(pattern), or a tool name
	// Source: "global" or "workspace" (the settings file it's in),
	// "built-in" (read_only_defaults), "flag" or "session".
	Source string
}

PermissionRule is an allow, ask or deny rule in force.

type PinResult

type PinResult struct {
	Agent string
	Model string // the model the agent now runs on
	Saved Saved
}

PinResult describes an agent's model after PinModel or Unpin.

type ProcessInfo

type ProcessInfo struct {
	ID        int    `json:"id"`
	Command   string `json:"command"`
	Running   bool   `json:"running"`
	ExitCode  int    `json:"exit_code"`
	RuntimeMs int64  `json:"runtime_ms"`
}

ProcessInfo is a snapshot of a background process's status.

type Processes

type Processes interface {
	Running() []ProcessInfo
	WaitAll(ctx context.Context) error
	Shutdown()
}

Processes are a workspace's background processes, as a front end sees them when it exits: which still run, waiting for them, or stopping them.

type ProjectItem

type ProjectItem struct {
	File  string
	Kind  string
	Key   string // the hook's event, the server's, agent's or skill's name, or the setting
	Value string // the rule, command, path, model or number
	// Reason, for an ignored item: never, unknown, not_stricter, outside,
	// provider or user_set.
	Reason string
}

ProjectItem is one project setting. Kind is deny, ask, blocked_path, limit, skill_policy, worker_limit (applied); hook, mcp, allow, writable, model, agent_model, worker_allow, skill_scripts (needing trust); or setting (another key).

type ProjectSettings

type ProjectSettings struct {
	// Files are the project files found, relative to the workspace.
	Files []string
	// State is the trust decision for the content as it is now: none
	// (nothing needs trust), new, changed, trusted or declined.
	State string
	// Hash identifies the content that needs trust; TrustProject takes it
	// back.
	Hash string
	// Loaded: the settings that need trust are in force (trusted when the
	// workspace opened, or for this run only).
	Loaded bool
	// Applied are the settings in force without trust: they only tighten.
	Applied []ProjectItem
	// Pending need trust: they run code or loosen a policy.
	Pending []ProjectItem
	// Ignored may not come from a project, or change nothing.
	Ignored []ProjectItem
	// Problems are files that couldn't be read.
	Problems []string
}

ProjectSettings are what a workspace's project files (.blitz/settings.toml, .blitz/settings.local.toml) say, and whether the person trusts the part that needs it (spec_project_config_031).

type PruneResult

type PruneResult struct {
	Removed int
	Freed   int64 // bytes
	Failed  []EnvError
}

PruneResult is what PruneEnvs removed.

type Refusal

type Refusal struct {
	Tool   string     `json:"tool"`
	Kind   ActionKind `json:"kind"`
	Detail string     `json:"detail"`
	Time   time.Time  `json:"time"`
}

Refusal is an action a run wasn't permitted.

type ResumeError

type ResumeError struct{ Err error }

ResumeError reports a session that can't be resumed: none is saved for this workspace, or no session has the given ID or snapshot name.

func (*ResumeError) Error

func (e *ResumeError) Error() string

Error is why the session couldn't be resumed.

func (*ResumeError) Unwrap

func (e *ResumeError) Unwrap() error

Unwrap returns that reason, for errors.Is and errors.As.

type RewindMode

type RewindMode string

RewindMode is what a rewind restores.

const (
	RewindBoth          RewindMode = "both"            // files and conversation
	RewindConversation  RewindMode = "conversation"    // conversation only; files stay
	RewindCode          RewindMode = "code"            // files only; conversation stays
	RewindSummarizeFrom RewindMode = "summarize_from"  // summarize the prompt and everything after
	RewindSummarizeUpTo RewindMode = "summarize_up_to" // summarize everything before the prompt
)

type RewindPoint

type RewindPoint struct {
	// Index is the prompt's position in the transcript.
	Index int
	Text  string
	Time  time.Time
	// Files are what the agent changed from this prompt until the next
	// (what rewinding the code to it restores, with later prompts' files).
	Files []string
	// Conversation reports whether the conversation can be rewound to it
	// (prompts recorded by older versions can't be).
	Conversation bool
}

RewindPoint is a prompt the session can be rewound to.

type RewindResult

type RewindResult struct {
	Mode RewindMode
	// Restored are the files put back (code).
	Restored []string
	// Prompt is the rewound prompt's text, to edit and send again
	// (conversation).
	Prompt string
	// Compacted is the summary's result (summarize modes).
	Compacted CompactResult
}

RewindResult is what a rewind did.

type Run

type Run struct {
	ID        string    `json:"id"`
	Workspace string    `json:"workspace"`
	Worker    string    `json:"worker"`
	Hash      string    `json:"hash"`
	Status    RunStatus `json:"status"`
	// Manual: started on request, not by the schedule.
	Manual    bool          `json:"manual,omitempty"`
	Started   time.Time     `json:"started"`
	Duration  time.Duration `json:"duration"`
	CostUSD   float64       `json:"cost_usd"`
	Calls     int           `json:"calls"`
	SessionID string        `json:"session_id,omitempty"`
	Refusals  []Refusal     `json:"refusals,omitempty"`
	// Files are the files the run changed, which blitz workers undo
	// restores.
	Files []string `json:"files,omitempty"`
	// Error is why the run failed or stopped.
	Error string `json:"error,omitempty"`
}

Run is one run of a worker.

type RunStatus

type RunStatus string

RunStatus is where a run stands.

const (
	RunRunning   RunStatus = "running"
	RunSucceeded RunStatus = "succeeded"
	RunFailed    RunStatus = "failed"
	// RunLimited: stopped at a limit (turns, cost or time).
	RunLimited RunStatus = "limited"
	// RunSkipped: not started, because the previous run was still going.
	RunSkipped RunStatus = "skipped"
)

Where a run stands. Running is while it runs; the others are how it ended.

type Saved

type Saved struct {
	Path string
	Err  error
}

Saved reports where a change was written in the config file. The change applies either way; Err is why it wasn't saved.

type Scope

type Scope string

Scope is where a permission rule is saved: ScopeSession (nowhere: this session only), ScopeGlobal (~/.blitz/.env.toml) or ScopeWorkspace (the workspace's own settings, which add to the global ones).

const (
	ScopeSession   Scope = ""
	ScopeGlobal    Scope = "global"
	ScopeWorkspace Scope = "workspace"
)

The scopes a permission rule can be saved in.

type SessionEvent

type SessionEvent struct {
	Task     *TaskInfo
	Request  *TaskRequest
	Resolved string
}

SessionEvent is something that happened to a session's background tasks outside its turns: one of Task (started, waiting, running again, ended), Request (waiting for an answer), or Resolved (the ID of a request that no longer waits: answered, or its task ended).

type SessionInfo

type SessionInfo struct {
	ID    string
	Title string // "" until the first prompt names it
	Agent string
	// Workspace is the directory the session belongs to ("" for sessions
	// saved before sessions were scoped to one).
	Workspace string
	// Snapshot is the name of a snapshot saved with SaveSnapshot ("" for an
	// ordinary session).
	Snapshot string
	// From is the session this one was copied from: the saved session for a
	// snapshot, the snapshot for a session started from one.
	From string
	// MovedFrom is the workspace /cd moved the session from, and MovedAt
	// the number of messages it had then ("" and 0 if it never moved).
	MovedFrom    string
	MovedAt      int
	MessageCount int
	Created      time.Time
	Updated      time.Time
	// Messages are filled in for the active session and for sessions
	// opened by OpenSession or LoadSession; lists leave them out.
	Messages []Message
}

SessionInfo describes a saved session.

type Setting

type Setting struct{ Key, Value string }

Setting is one key=value change; an empty Value clears the key.

type Settings

type Settings struct {
	Agency string
	Model  ModelInfo
	Agent  string
	Locale string // the language the model replies in
	// PermissionMode decides which actions run without asking (a
	// PermissionMode).
	PermissionMode string
	// Effort is the session's reasoning effort ("" when each model uses its
	// own reasoning_effort or its default).
	Effort string
	// Style is the output style in use ("default": none).
	Style string
	// SpeechModel is generate_audio's speech model ([audio] model; "" for
	// none), and SpeechError why it can't be used.
	SpeechModel, SpeechError string
}

Settings are the values /set changes, plus the model, agent and locale.

type SkillInfo

type SkillInfo struct {
	Name          string
	Description   string
	Version       string
	License       string
	Category      string
	Compatibility string
	Tags          []string
	// Hash identifies the skill's content, for pinning it in the policy
	// ("" if it couldn't be computed).
	Hash string
	// Tools are the tools the skill says it needs, and why.
	Tools []SkillTool
	// Scripts are the skill's scripts and whether each may run.
	Scripts []SkillScript
	// Tier is the approval tier the scripts run at ("" without scripts);
	// Bypass means the skill may skip approvals (tier 0) and the policy
	// allows it.
	Tier   string
	Bypass bool
	// Network: the scripts may use the network. NeedsNetwork: the skill
	// asks for it (granted or not).
	Network      bool
	NeedsNetwork bool
	// Env are the host environment variables passed to the scripts;
	// Withheld are the ones the skill asked for that the policy keeps back.
	Env, Withheld []string
	// Blocked are reasons none of the scripts may run.
	Blocked []string
}

SkillInfo describes a skill and what the skills policy lets it do.

func (SkillInfo) Runnable

func (s SkillInfo) Runnable() bool

Runnable reports whether any of the skill's scripts may run.

type SkillScript

type SkillScript struct {
	Name     string
	Language string
	Source   string // its path in the skill, or "inline"
	Timeout  time.Duration
	Deps     []string
	Allowed  bool
	Reasons  []string // why it may not run
}

SkillScript is one of a skill's scripts and the policy's verdict on it.

type SkillTool

type SkillTool struct {
	Name   string
	Scopes []string
	Why    string
}

SkillTool is a tool a skill needs.

type State

type State string

State is whether a worker may run.

const (
	// StateNew: found but never enabled.
	StateNew State = "new"
	// StateEnabled: enabled at its current hash; it runs on schedule.
	StateEnabled State = "enabled"
	// StateDisabled: turned off.
	StateDisabled State = "disabled"
	// StateChanged: enabled at an older hash; the files changed since, so
	// it doesn't run until re-enabled.
	StateChanged State = "changed"
	// StateInvalid: WORKER.md can't be used.
	StateInvalid State = "invalid"
)

type StyleInfo

type StyleInfo struct {
	Name, Description string
	// Source is "built-in" or the style's file.
	Source string
	Active bool
}

StyleInfo is an output style (/style).

type Suggestion

type Suggestion struct {
	Kind      SuggestionKind
	Title     string
	Prompt    string
	SessionID string
	Worker    string
	Count     int
	Detail    string
}

Suggestion is one welcome tile. State kinds carry data for a front end to word; an idea carries its text.

type SuggestionKind

type SuggestionKind string

SuggestionKind is what a welcome tile does.

const (
	// SuggestSetup: the workspace has no agent instructions; run /setup.
	SuggestSetup SuggestionKind = "setup"
	// SuggestContinue: pick up the latest conversation (SessionID, Title).
	SuggestContinue SuggestionKind = "continue"
	// SuggestChanges: review the Count uncommitted changes.
	SuggestChanges SuggestionKind = "changes"
	// SuggestWorkerFailed: the Worker's latest run failed (Detail: why).
	SuggestWorkerFailed SuggestionKind = "worker_failed"
	// SuggestIdea: a model's idea from the recent conversations (Title on
	// the tile, Prompt sent).
	SuggestIdea SuggestionKind = "idea"
)

type Suggestions

type Suggestions struct {
	// Tiles: state tiles first, then ideas.
	Tiles []Suggestion
	// HarnessMissing: no .agents/AGENT.md or root instruction file.
	HarnessMissing bool
	// Pending: ideas are being written from newer conversations.
	Pending bool
}

Suggestions are a workspace's welcome tiles.

type Task

type Task struct {
	Content string
	Status  string // pending, in_progress or done
}

Task is an item of the agent's task list.

type TaskInfo

type TaskInfo struct {
	ID    string `json:"id"` // task-1, task-2, … in the workspace
	Agent string `json:"agent"`
	// Prompt is the first line of what it was asked.
	Prompt string `json:"prompt"`
	// Session is the session whose turn started it.
	Session string `json:"session"`
	// State is running, done, failed or stopped.
	State   string    `json:"state"`
	Started time.Time `json:"started"`
	Ended   time.Time `json:"ended,omitzero"` // zero while it runs
	// Result is what it answered, when done.
	Result string `json:"result,omitempty"`
	// Error is why it failed or stopped.
	Error string `json:"error,omitempty"`
	// Usage is its own tokens and cost (also counted in its session's).
	Usage Usage `json:"usage"`
	// Worktree and Branch: it ran in its own git worktree, on this branch,
	// for its changes to be reviewed and merged.
	Worktree string `json:"worktree,omitempty"`
	Branch   string `json:"branch,omitempty"`
}

TaskInfo is a background task: a sub-agent that invoke_agent started with background: true, running beside the turn that started it (spec_background_agents_032).

func (TaskInfo) Active

func (t TaskInfo) Active() bool

Active reports whether it hasn't ended: running, or waiting for an answer.

func (TaskInfo) Runtime

func (t TaskInfo) Runtime() time.Duration

Runtime is how long it has run, or ran.

type TaskRequest

type TaskRequest struct {
	ID      string // answered with AnswerTaskRequest
	TaskID  string
	Agent   string
	Session string
	// Approval, or else Question and its suggested Options.
	Approval *ApprovalRequest
	Question string
	Options  []string
	// MultiSelect: several options may be chosen (one per line).
	MultiSelect bool
}

TaskRequest is a background task's approval request or question, waiting for one of its session's people to answer (spec_background_agents_032 BGA-41).

func (TaskRequest) Label

func (r TaskRequest) Label() string

Label names who asks: "qa · task-3".

type Text

type Text struct {
	Text    string
	Partial bool
	// Repeat marks final text whose partial chunks were already delivered.
	Repeat bool
	// Thought is the model's reasoning rather than its answer; front ends
	// may show it or not, and the transcript leaves it out.
	Thought bool
}

Text is model output. With streaming, partial chunks arrive first and a final event then repeats their text in full (Repeat); without streaming only final events arrive. To show text once, show partial chunks and final text that isn't a Repeat. The transcript keeps final text only.

type ToolCall

type ToolCall struct {
	ID   string // matches the ToolResult
	Name string
	Args map[string]any
	// Partial: the call arrived in a streamed chunk, and the final event
	// repeats it.
	Partial bool
}

ToolCall is the agent calling a tool.

type ToolInfo

type ToolInfo struct {
	Name        string
	Description string
	// PlanAllowed: the tool stays available in plan mode, which refuses
	// tools that change anything.
	PlanAllowed bool
}

ToolInfo is a tool an agent can call.

type ToolResult

type ToolResult struct {
	ID     string
	Name   string
	Result map[string]any
}

ToolResult is what a tool returned.

type Turn

type Turn struct {
	// Text is what the user typed. prompt_submit hooks see it and the
	// transcript records it.
	Text string
	// Prompt, if set, is sent to the agent instead of Text (e.g. /search
	// sends the fetched results, and the transcript records the command).
	Prompt string
	// Plan: Text is a goal to plan for. Tools that change anything are
	// refused for the whole turn, and the transcript
	// records "/plan <Text>".
	Plan bool
	// ReadOnly names a mode that refuses the same tools as plan mode.
	ReadOnly string
	// Aside: a /btw question, answered in a throwaway copy of the session
	// and recorded nowhere. It takes no images, starts no checkpoint and
	// leaves queued steer messages alone.
	Aside bool
	// Accepted: Text already passed prompt_submit hooks and was recorded (a
	// steer message that arrived too late to be read mid-turn).
	Accepted bool
	// Command: Text is a custom slash command ("/name args"), expanded into
	// its prompt with its agent, model, tools and plan mode; the
	// transcript records Text.
	Command bool
	// Images are sent with the prompt.
	Images []*images.Image
	// MaxTurns limits the model calls in the turn (0: unlimited).
	MaxTurns int
	// MaxCostUSD stops the turn once it has cost more than this (0:
	// unlimited); it can only be enforced when the model has a price.
	MaxCostUSD float64
	// Timeout stops the turn after this long (0: unlimited).
	Timeout time.Duration
	// FetchGrants are URLs the agent may fetch in this turn without asking
	// (the pages a web search handed it).
	FetchGrants []string
	// OnAccepted, if set, runs once the prompt has passed prompt_submit
	// hooks and been recorded, just before it is sent.
	OnAccepted func()
	// OnFinished, if set, runs when the agent has stopped, before unread
	// steer messages are collected: a front end still taking a steer message
	// finishes here, so the message ends up in TurnResult.Leftover.
	OnFinished func()
}

Turn is one prompt for the agent.

type TurnResult

type TurnResult struct {
	// Output is the model's final text (partial and thought text excluded).
	Output string
	// Before and After are the session's usage around the turn.
	Before, After Usage
	// Leftover are steer messages sent after the model's last tool call, so
	// never read. Front ends send them as the next turn (with Accepted set)
	// or, if the turn was interrupted, drop them.
	Leftover []string
}

TurnResult describes a finished turn.

type UndoResult

type UndoResult struct {
	Label    string // the undone turn's checkpoint label
	Restored []string
}

UndoResult is what Undo restored.

type UnknownAgentError

type UnknownAgentError struct{ Name string }

UnknownAgentError reports an agent name that isn't registered.

func (*UnknownAgentError) Error

func (e *UnknownAgentError) Error() string

Error names the agent that doesn't exist.

type UnknownSettingError

type UnknownSettingError struct{ Key string }

UnknownSettingError reports a key /set doesn't know.

func (*UnknownSettingError) Error

func (e *UnknownSettingError) Error() string

Error names the setting that doesn't exist.

type Usage

type Usage struct {
	Calls      int     `json:"calls"`
	Input      int64   `json:"input"` // prompt tokens, including cached
	Cached     int64   `json:"cached"`
	CacheWrite int64   `json:"cache_write"` // prompt tokens written to the cache (part of Input)
	Output     int64   `json:"output"`      // candidates + thinking tokens
	LastPrompt int64   `json:"last_prompt"` // prompt size of the latest call: the current context size
	CostUSD    float64 `json:"cost_usd"`
	Priced     bool    `json:"priced"` // false if any call's model had no price
	// SearchQueries are the web searches a search provider billed (Google
	// grounding's queries), priced apart from the tokens: SearchCostUSD
	// isn't part of CostUSD.
	SearchQueries int     `json:"search_queries,omitempty"`
	SearchCostUSD float64 `json:"search_cost_usd,omitempty"`
}

Usage accumulates token counts and estimated cost.

func (*Usage) Add

func (u *Usage) Add(o Usage)

Add adds o's calls, tokens and cost to u; u stays priced only if both are.

type UserPromptFunc

type UserPromptFunc func(ctx context.Context, question string, options []string) (string, error)

UserPromptFunc asks the user a question and returns the answer. With WithMultiSelect, the user may choose several options: the answer is them, one per line.

type WebSearch

type WebSearch struct {
	Links  []Link // none: nothing worth handing over
	Prompt string
}

WebSearch is a search whose results are handed to the agent: run Prompt as a turn with FetchGrants set to the links' URLs, so the agent may read exactly those pages without asking.

func (WebSearch) URLs

func (s WebSearch) URLs() []string

URLs returns the links' URLs, for Turn.FetchGrants.

type WorkerInfo

type WorkerInfo struct {
	Workspace   string
	Name        string
	Description string
	Path        string // WORKER.md
	Hash        string
	State       State
	// Schedule as written, as understood, and when it next runs (zero
	// unless it's enabled and valid).
	Schedule string
	Cron     string
	Timezone string
	Next     time.Time
	Agent    string
	Model    string
	// CatchUp is "once" when a run missed while nothing was running should
	// happen as soon as possible, otherwise "none".
	CatchUp string
	// Permissions and Limits are what the worker gets after the host
	// policy.
	Permissions []string
	Limits      Limits
	// Problems say why the worker is invalid, or what the policy changed.
	Problems []string
	// LastRun is its latest recorded run (nil: none yet).
	LastRun *Run
}

WorkerInfo describes a worker and whether it may run.

type WorkerSpec

type WorkerSpec struct {
	Name, Description  string
	Schedule, Timezone string
	Agent, Model       string
	Permissions        []string // "kind:pattern"
	Limits             Limits   // TimeoutRaw, not Timeout
	CatchUp            string   // "", "none" or "once"
	Prompt             string
}

WorkerSpec is a new worker as a form describes it: WORKER.md's frontmatter fields and its workflow (Prompt). Empty fields are left out of the file.

Jump to

Keyboard shortcuts

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