api

package
v0.8.10 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 8 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 (
	// ProcessFlagCPU: it has kept a core busy for a while.
	ProcessFlagCPU = "cpu"
	// ProcessFlagMemory: its memory is over the limit, or keeps growing.
	ProcessFlagMemory = "memory"
	// ProcessFlagLeft: it was left running: its session ended, or has had
	// no turn for a long time.
	ProcessFlagLeft = "left"
)

Why a background process looks bad (spec_processes_052).

View Source
const (
	EvalPass  = "pass"
	EvalFail  = "fail"
	EvalWarn  = "warn"
	EvalInfo  = "info"
	EvalError = "error"
)

An eval result's status: it passed, or what its failure means by the case's scope; error is a case that couldn't be run or scored.

View Source
const (
	EvalRunning = "running"
	EvalPassed  = "passed"
	EvalFailed  = "failed"
	EvalStopped = "stopped"
)

An eval run's status.

View Source
const (
	// SearchFiles are the workspace's text files (.gitignore and blocked
	// paths left out).
	SearchFiles = "files"
	// SearchDocuments are the text of its PDFs and notebooks.
	SearchDocuments = "documents"
	// SearchChats are its chats.
	SearchChats = "chats"
	// SearchNotes are its notes (remember) and plans (.blitz/plans).
	SearchNotes = "notes"
)

The sources workspace search looks in.

View Source
const (
	// SearchKeyword ranks by the words (BM25), the default without an
	// embedding model.
	SearchKeyword = "keyword"
	// SearchSemantic ranks by meaning (embeddings).
	SearchSemantic = "semantic"
	// SearchHybrid fuses both, the default with an embedding model.
	SearchHybrid = "hybrid"
)

The ways to search.

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.

View Source
const (
	StepRunning = "running"
	StepDone    = "done"
	StepFailed  = "failed"
	// StepSkipped is a step on a path not taken (a gateway's other
	// branch): it doesn't run.
	StepSkipped = "skipped"
	// StepWaiting is a human task waiting for its answer, or a timer for
	// its time: the run is paused until then.
	StepWaiting = "waiting"
)

A workflow step's status.

View Source
const HarnessUpdateSpec = "spec"

HarnessUpdateSpec is SuggestHarnessUpdate's Detail when the specification changed.

View Source
const SkillEvalPrefix = "skill:"

SkillEvalPrefix names a skill's scenarios as an eval: RunEval, EvalRuns and blitz eval take "skill:<name>" (spec_skills_013 SK-111).

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 ErrApprovalsStillSaved = errors.New("still saved, so they come back at the next start")

ErrApprovalsStillSaved means approvals were revoked for this session but couldn't be removed from the saved file, so they come back at the next start. The error wrapping it names them.

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 ErrEmptySearch = errors.New("nothing to search for")

ErrEmptySearch reports a query with nothing to search for.

View Source
var ErrEvalNotRunnable = errors.New("the eval can't run")

ErrEvalNotRunnable means the eval has a problem, or no case to run.

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 ErrNoEmbeddings = errors.New("semantic search needs an embedding model (search.embedding_model)")

ErrNoEmbeddings reports a semantic or hybrid search with no embedding model set.

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 means 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 means 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 means 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 ErrRunStopped = errors.New("stopped by the user")

ErrRunStopped is why a run the user stopped ended: the cause its context is cancelled with.

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

ErrSandboxUnavailable means 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 ErrSearchDisabled = errors.New("workspace search is off (search.enabled = false)")

ErrSearchDisabled reports workspace search 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 ErrUnknownEval = errors.New("no such eval")

ErrUnknownEval means the workspace has no eval of that name.

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 means no background process with that ID was started for the sessions asking.

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

ErrUnknownRequest means no request with that ID is waiting.

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

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

View Source
var ErrUnknownSearchMode = errors.New("unknown search mode (keyword, semantic or hybrid)")

ErrUnknownSearchMode reports a mode that isn't keyword, semantic or hybrid.

View Source
var ErrUnknownSearchSource = errors.New("unknown search source (files, documents, chats or notes)")

ErrUnknownSearchSource reports a source search doesn't have.

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

ErrUnknownTask means 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.

SearchSources are every source, in order.

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 Looser added in v0.7.1

func Looser(a, b PermissionMode) bool

Looser reports whether mode a lets more through without asking than b (accept-edits and auto are level: each lets through what the other asks about).

func ShownVersion added in v0.6.4

func ShownVersion(v string) string

ShownVersion is a Blitz version as people see it: a release's with its "v" (v0.6.2), as the tags, the releases and the docs write it; anything else ("dev", a commit) as it is. The stamped version has no "v", since packages need it to start with a digit, and it's what the desktop app compares with the service's.

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 AgentBrowserCommand added in v0.8.4

type AgentBrowserCommand struct {
	// BrowserID names the view, the same in every command and reply.
	BrowserID string
	// Kind is "open", "message" or "close"; or, for a page the user asked
	// to see (AB-10), "page" (a web tab) or "external" (the system's
	// browser), with URL and no BrowserID.
	Kind string
	// Message is a DevTools Protocol command as JSON (Kind "message").
	Message string
	// Show is "watch" (a tab the user sees) or "silent" (off screen), and
	// Profile the browser profile whose sign-ins it uses ("": none, a
	// throwaway session), for "open".
	Show    string
	Profile string
	// AllowLocal lets it reach loopback and private addresses, and
	// DenyDomains are never reached (web.deny_domains), for "open".
	AllowLocal  bool
	DenyDomains []string
	// URL is the page to show, for "page" and "external".
	URL string
}

AgentBrowserCommand is what a desktop window is asked to do with a view of the agent's browser (spec_agent_browser_050): open one, pass it a DevTools message, or close it.

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 means the approval is 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 means 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

	// Reflection is what the harness has to learn from the workspace's
	// runs, for the welcome (/reflect).
	Reflection() (Reflection, 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
	// RunEval runs the workspace's eval name (spec_evals_042) and records
	// the run.
	RunEval(ctx context.Context, name string, o EvalOptions) (EvalRun, error)

	// 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)
	// Reload reads the agents, skills, instruction files and rules again
	// whether or not they look changed (each turn reloads what changed).
	Reload(ctx context.Context) (ReloadResult, 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

	// Workspace search (spec_search_035).
	Search(ctx context.Context, q SearchQuery) (SearchResult, error)
	SearchStatus() SearchStatus
	// Reindex starts a scan of the workspace for search and returns at once.
	Reindex() error
	RevokeApprovals(keys ...string) (int, error)
	ClearApprovals() (int, error)

	// 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 ContextBlock added in v0.7.0

type ContextBlock struct {
	// Kind is what it is: "web_page", "web_selection" or "console".
	Kind string
	// URL is where it came from, and Title the page's title.
	URL, Title string
	// HTML is the content as HTML, made into text for the agent; Text is
	// used when it's empty.
	HTML, Text string
}

ContextBlock is content the user added to a turn from elsewhere: the desktop app's web preview.

type ContextInfo

type ContextInfo struct {
	Tokens int64 // the latest prompt's size
	// AutoCompact means 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 EvalOptions added in v0.7.1

type EvalOptions struct {
	// Cases are the case IDs to run (none: every case).
	Cases []string
	// OnStart receives the run as it starts; OnResult each result as it's
	// scored.
	OnStart  func(EvalRun)
	OnResult func(EvalResult)
}

EvalOptions are how an eval runs.

type EvalResult added in v0.7.1

type EvalResult struct {
	Case  string `json:"case"`
	Name  string `json:"name,omitempty"`
	Agent string `json:"agent"`
	// Type is exact or near; Scope is fail, warn or info.
	Type  string `json:"type"`
	Scope string `json:"scope"`
	// Status is EvalPass, or EvalFail, EvalWarn or EvalInfo (the case's
	// scope) when it didn't pass, or EvalError.
	Status    string  `json:"status"`
	Score     float64 `json:"score"`
	Threshold float64 `json:"threshold,omitempty"`
	Prompt    string  `json:"prompt"`
	Expected  string  `json:"expected"`
	Output    string  `json:"output"`
	// Reason is the judge's, or why the case couldn't be run or scored.
	Reason string `json:"reason,omitempty"`
	// Refusals are the actions the eval didn't allow, as "tool: detail".
	Refusals []string      `json:"refusals,omitempty"`
	CostUSD  float64       `json:"cost_usd,omitempty"`
	Duration time.Duration `json:"duration"`
	// SkillsUsed are the skills the agent used (a skill's scenario,
	// spec_skills_013 SK-111).
	SkillsUsed []string `json:"skills_used,omitempty"`
}

EvalResult is one case run by one agent, and its score.

type EvalRun added in v0.7.1

type EvalRun struct {
	ID        string        `json:"id"`
	Workspace string        `json:"workspace"`
	Eval      string        `json:"eval"`
	Started   time.Time     `json:"started"`
	Duration  time.Duration `json:"duration"`
	// Status is EvalPassed (no fail-scope case failed or errored),
	// EvalFailed, EvalStopped or, while it runs, EvalRunning.
	Status  string       `json:"status"`
	Results []EvalResult `json:"results"`
	CostUSD float64      `json:"cost_usd,omitempty"`
	// Error is why the run couldn't start or finish.
	Error string `json:"error,omitempty"`
}

EvalRun is a run of an eval: every case (or those asked for) by every agent it names.

func (EvalRun) Counts added in v0.7.1

func (r EvalRun) Counts() map[string]int

Counts are the run's results by status.

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
	// Step is a workflow's step starting or ending (spec_workflows_043).
	Step *FlowStep
	// Reflect, at a chat turn's end, says the runs since the last
	// reflection hit enough problems to /reflect on
	// (spec_harness_learning_048 HE-63).
	Reflect *ReflectDue
}

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

type FlowStep added in v0.7.1

type FlowStep struct {
	Workflow string
	ID       string
	Title    string
	Type     string
	// Index and Count place it: step Index of Count, from 1.
	Index, Count int
	// Status is StepRunning, StepDone or StepFailed.
	Status string
	// Output is what it produced, ended (the start of it, up to 4 KiB).
	Output string
	Error  string
	// Run is the run's ID (its receipt's).
	Run string
}

FlowStep is a workflow's step starting, or how it ended.

type GitOperation added in v0.6.4

type GitOperation string

GitOperation is what a repository is in the middle of.

const (
	// GitMerging is a merge waiting to be completed or aborted.
	GitMerging GitOperation = "merge"
	// GitRebasing is a rebase waiting to be continued or aborted.
	GitRebasing GitOperation = "rebase"
)

type GitStatus

type GitStatus struct {
	Git     bool
	Repo    bool
	Branch  string
	Changed int
	// Remote is whether the repository has a remote; Upstream is the
	// branch's (such as "origin/main"), empty when it has none. Ahead and
	// Behind count the commits each side has that the other hasn't, as of
	// the last fetch.
	Remote        bool
	Upstream      string
	Ahead, Behind int
	// Operation is a merge or rebase in progress (a pull that stopped on
	// conflicts), and Conflicts the files still in conflict.
	Operation GitOperation
	Conflicts []string
	// Merging is the branch a merge in progress brings in, such as
	// "feature" or "origin/main" ("" when none, or when git can't name it).
	Merging string
}

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 means 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
	// Disabled means it's configured but never started (disabled = true).
	Disabled bool
	// State is "disabled", "idle" (its tools not listed yet), "connected"
	// or "failed" (Error says why); Tools is how many tools it offered.
	State string
	Error string
	Tools int
}

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 marks something that went wrong (shown as an error); otherwise
	// it's information.
	Error bool
	// Transient marks a passing status (the model's connection dropped and
	// is being retried): a front end shows it briefly, not in the chat.
	Transient 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 means 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 is "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"`
	// Session is the session whose turn started it ("" outside one).
	Session string `json:"session,omitempty"`
	// CPUPercent is what it and its children used of one core over the
	// last sample, and MemoryBytes their resident memory; both 0 until
	// sampled, and on a system that isn't sampled (Measured false).
	CPUPercent  float64 `json:"cpu_percent,omitempty"`
	MemoryBytes int64   `json:"memory_bytes,omitempty"`
	Measured    bool    `json:"measured,omitempty"`
	// Flags say why it looks bad (ProcessFlagCPU, ProcessFlagMemory,
	// ProcessFlagLeft); none while it looks fine.
	Flags []string `json:"flags,omitempty"`
	// IdleMs is how long its session has gone without a turn (0 while
	// one runs).
	IdleMs int64 `json:"idle_ms,omitempty"`
}

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 means 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 ReflectDue added in v0.8.4

type ReflectDue struct {
	Patterns int
	Score    int
}

ReflectDue is the evidence that suggests /reflect: its patterns, and its score (the costly patterns twice).

type Reflection added in v0.8.3

type Reflection struct {
	// Patterns is how many items of the evidence since the last
	// reflection are patterns.
	Patterns int
	// Score weighs them, the costly ones twice; /reflect is suggested once
	// it reaches Threshold ([harness] reflect_threshold; 0: never)
	// (spec_harness_learning_048 HE-62).
	Score     int
	Threshold int
	// Proposals is how many changes a scheduled reflection proposed,
	// waiting for /reflect.
	Proposals int
}

Reflection is what a workspace's harness has to learn, as the welcome screens say it.

func (Reflection) Suggested added in v0.8.3

func (r Reflection) Suggested() (Suggestion, bool)

Suggested is the welcome tile it makes, if any: the proposals to review, else /reflect once the score reaches the threshold.

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 ReloadResult added in v0.6.5

type ReloadResult struct {
	Agents   int
	Skills   int
	Files    []string
	Problems []string
}

ReloadResult is what Reload loaded: how many agents and skills from files (built-in ones aside), the instruction files and rules, and the files that didn't load.

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 means the run 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 means the run stopped at a limit (turns, cost or time).
	RunLimited RunStatus = "limited"
	// RunSkipped means the run wasn't started, because the previous one was
	// still going.
	RunSkipped RunStatus = "skipped"
	// RunStopped means the user stopped the run while it went.
	RunStopped RunStatus = "stopped"
)

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 SchedulePreview added in v0.8.4

type SchedulePreview struct {
	Cron     string
	Timezone string
	Next     []time.Time
}

SchedulePreview is how a schedule is understood: its cron form, the time zone it runs in, and its next runs.

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 ScriptRun added in v0.7.1

type ScriptRun struct {
	ExitCode       int
	Stdout, Stderr string
	TimedOut       bool
	Sandbox        string
	Files          []string
	Error          string
}

ScriptRun is how a skill's script ran from Studio's Test run.

type SearchHit added in v0.3.0

type SearchHit struct {
	Source  string
	Ref     string
	Title   string
	Line    int
	Section string
	Snippet string
	Score   float64
	// Summary and Tags are what a model wrote of the item
	// (search.enrich), if it has.
	Summary string
	Tags    []string
}

SearchHit is one item found. Ref is a path relative to the workspace (files, documents, plans), a session's ID (chats) or a note's name; Line is the passage's line in the item's text (1-based) and Section labels it (a PDF's page, a notebook's cell).

type SearchQuery added in v0.3.0

type SearchQuery struct {
	Text    string
	Sources []string
	Limit   int
	Mode    string
	// Hidden includes hidden items: dotfiles and dot folders, and files git
	// ignores (search.include_ignored). The desktop app asks for them when
	// it shows hidden files.
	Hidden bool
}

SearchQuery is a workspace search: words and "quoted phrases", in the sources named (none: search.sources), up to Limit hits (0: 20), by Mode ("": hybrid with an embedding model, else keyword).

type SearchResult added in v0.3.0

type SearchResult struct {
	Hits    []SearchHit
	Sources []string
}

SearchResult is a search's hits, best first, and the sources searched.

type SearchSettings added in v0.3.0

type SearchSettings struct {
	Enabled          bool
	Sources          []string
	EmbeddingModel   string
	Enrich           bool
	EnrichModel      string
	EnrichDailyLimit int
	IncludeIgnored   bool
}

SearchSettings are the [search] settings a workspace follows.

type SearchStatus added in v0.3.0

type SearchStatus struct {
	Enabled    bool
	Items      map[string]int
	Scanning   bool
	LastScan   time.Time
	Unreadable int
	Error      string
	// EmbeddingModel is semantic search's model ("": off); Embedded counts
	// the chunks with vectors, and EmbedError is why embedding stopped.
	EmbeddingModel string
	Embedded       int
	EmbedError     string
	// Enriched counts the items with a summary (search.enrich), and
	// EnrichError is why describing stopped.
	Enriched    int
	EnrichError string
	// Settings are the [search] settings followed (even with search off);
	// Problem is what kept them from applying in full (an embedding model
	// or describer that couldn't be built, an index that couldn't open).
	Settings SearchSettings
	Problem  string
}

SearchStatus is how a workspace's search index is: items per source, whether a scan runs, when the last one finished, how many items it couldn't read, and its error.

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
	// Origin is what started the session: "worker" (a worker's run),
	// "background" (blitz --bg), or "" for a chat.
	Origin       string
	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 SessionTool added in v0.7.1

type SessionTool struct {
	// Turn is the prompt it ran under: the Turn-th prompt of the session
	// (0 first); Prompt is that prompt's start, to check it by.
	Turn   int
	Prompt string
	ID     string
	Name   string
	Args   map[string]any
	Result map[string]any
}

SessionTool is one tool call a saved session made, with its result, so a reopened chat shows its tools as they ran.

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 SkillFile added in v0.7.1

type SkillFile struct {
	Info     SkillInfo
	Path     string
	Hash     string
	Spec     SkillSpec
	Editable bool
}

SkillFile is a skill as Studio edits it: what ListSkills says of it, its SKILL.md (path, content hash), the form's fields as written, and whether it's the workspace's own, which may be edited.

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 means the scripts may use the network. NeedsNetwork means 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
	// Dir is the skill's folder on disk ("" for a built-in skill).
	Dir string
	// Kind is simple, references, scripts or meta, from its folder
	// (spec_skills_013 SK-97).
	Kind string
	// Agents are the agents it's offered to (none: every one); Members the
	// skills a meta skill combines; References its files under
	// references/.
	Agents, Members, References []string
	// PackageFiles are its package files (requirements.txt,
	// pyproject.toml, package.json), as paths in its folder.
	PackageFiles []string
	// Project means the workspace's own: its folder is in the workspace,
	// so Studio edits it.
	Project bool
	// NeedsReview means its scripts, on disk, weren't reviewed and trusted
	// with this content (new, changed, a registry's): each run asks first.
	NeedsReview bool
	// Triggers are its trigger phrases (spec_skills_013 SK-110);
	// Scenarios how many scenarios/*.md it carries (SK-111).
	Triggers  []string
	Scenarios int
}

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
	// Found means it isn't declared but was found in scripts/ (SK-98).
	Found bool
}

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

type SkillSpec added in v0.7.1

type SkillSpec struct {
	Name, Description, Tools string
	Agents, Members          []string
	Instructions             string
	Triggers                 []string
}

SkillSpec is what Studio's skill form edits (SK-100): the skill's name (its folder's), what it's for, the tools it may use (allowed-tools, space-separated), the agents it's offered to, the skills it combines and its instructions.

type SkillTool

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

SkillTool is a tool a skill needs.

type SkillTry added in v0.8.0

type SkillTry struct {
	Skill, Agent, Prompt string
	Output               string
	SkillsUsed           []string
	// Triggered: the agent used the skill; Forced: it was given it.
	Triggered, Forced bool
	Refusals          []string
	CostUSD           float64
	Duration          time.Duration
}

SkillTry is a prompt tried once with a skill (SK-112): what the agent answered, the skills it used, and whether this one was among them.

type State

type State string

State is whether a worker may run.

const (
	// StateNew is a worker found but never enabled.
	StateNew State = "new"
	// StateEnabled is a worker enabled at its current hash; it runs on
	// schedule.
	StateEnabled State = "enabled"
	// StateDisabled is a worker turned off.
	StateDisabled State = "disabled"
	// StateChanged is a worker enabled at an older hash; the files changed
	// since, so it doesn't run until re-enabled.
	StateChanged State = "changed"
	// StateInvalid is a worker whose 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 suggests /setup: the workspace has no agent instructions.
	SuggestSetup SuggestionKind = "setup"
	// SuggestHarnessUpdate suggests updating the skills and agents; Detail
	// says why: HarnessUpdateSpec, the specification (.agents/specs/)
	// changed after them (/skills update, then /agents update); "skills"
	// or "agents", the runs since they changed hold patterns about them
	// (/skills update or /agents update).
	SuggestHarnessUpdate SuggestionKind = "harness_update"
	// SuggestReflect suggests /reflect: the evidence since the last
	// reflection holds Count patterns, and its score reached the threshold.
	SuggestReflect SuggestionKind = "reflect"
	// SuggestReflectReview suggests /reflect to review the Count changes a
	// scheduled reflection proposed.
	SuggestReflectReview SuggestionKind = "reflect_review"
	// SuggestContinue suggests picking up the latest conversation (SessionID,
	// Title).
	SuggestContinue SuggestionKind = "continue"
	// SuggestChanges suggests reviewing the Count uncommitted changes.
	SuggestChanges SuggestionKind = "changes"
	// SuggestWorkerFailed says the Worker's latest run failed (Detail: why).
	SuggestWorkerFailed SuggestionKind = "worker_failed"
	// SuggestIdea is a model's idea from the recent conversations (Title on
	// the tile, Prompt sent).
	SuggestIdea SuggestionKind = "idea"
)

type Suggestions

type Suggestions struct {
	// Tiles are the state tiles first, then ideas.
	Tiles []Suggestion
	// HarnessMissing means there's no .agents/AGENTS.md or root instruction
	// file.
	HarnessMissing bool
	// Pending means 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 means 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 means 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 means 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 means 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 means Text is 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 means Text already passed prompt_submit hooks and was recorded
	// (a steer message that arrived too late to be read mid-turn).
	Accepted bool
	// Command means 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
	// Context is what the user added from outside the workspace (a web
	// page, a selection, a console's errors), given to the agent as content
	// to read, not instructions.
	Context []ContextBlock
	// 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
	// Workflow is the workflow it runs ("": its prompt, as a turn).
	Workflow 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
	Workflow           string   // run with the prompt as input ("": a turn)
	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.

type WorkspaceProcess added in v0.8.5

type WorkspaceProcess struct {
	Workspace string
	Process   ProcessInfo
}

WorkspaceProcess is a background process and the workspace it runs in.

Jump to

Keyboard shortcuts

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