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
- Variables
- func BlitzCommandRunsInPlan(name string) bool
- func BlitzGroups() [][]BlitzCommand
- func IsLimit(err error) bool
- func IsMultiSelect(ctx context.Context) bool
- func Looser(a, b PermissionMode) bool
- func SecretAnswer(ctx context.Context) bool
- func ShownVersion(v string) string
- func WithChoices(ctx context.Context, choices []Choice, order string) context.Context
- func WithMultiSelect(ctx context.Context) context.Context
- func WithSecretAnswer(ctx context.Context) context.Context
- type ActionKind
- type AgentBrowserCommand
- type AgentInfo
- type AgentModelBackend
- type AgentTools
- type Approval
- type ApprovalRequest
- type Approver
- type AssetFinding
- type Backend
- type BackgroundRun
- type BlitzCommand
- type BlitzRun
- type BlockedError
- type Call
- type ChangeBackend
- type Checkpoint
- type Choice
- type Citation
- type CommandArg
- type CommandEffect
- type CommandInfo
- type CompactResult
- type ContextBlock
- type ContextInfo
- type ContextMemoryBackend
- type ContextPart
- type DataBackend
- type DataColumn
- type DataConnection
- type DataQuery
- type DataQueryInfo
- type DataTable
- type Decision
- type Env
- type EnvError
- type EvalOptions
- type EvalResult
- type EvalRun
- type Event
- type ExtensionBackend
- type File
- type FlowStep
- type GitOperation
- type GitStatus
- type Goal
- type GoalBackend
- type Group
- type HookFailure
- type HookInfo
- type HookResult
- type ImageBackend
- type InvalidSettingError
- type Lifecycle
- type Limits
- type Link
- type ListedModel
- type LocaleChange
- type LocaleInfo
- type MCPOffer
- type MCPServer
- type Message
- type ModelInfo
- type ModelList
- type ModelPreview
- type ModelSettingsChange
- type ModelSettingsInfo
- type Note
- type Notice
- type PermissionChange
- type PermissionMode
- type PermissionRule
- type Personality
- type PinResult
- type Price
- type ProcessInfo
- type Processes
- type ProjectItem
- type ProjectSettings
- type ProviderModels
- type PruneResult
- type Reasoning
- type ReasoningNode
- type ReasoningTurn
- type ReflectDue
- type Reflection
- type Refusal
- type ReloadResult
- type ResumeError
- type RewindMode
- type RewindPoint
- type RewindResult
- type Run
- type RunStatus
- type Saved
- type SchedulePreview
- type Scope
- type ScriptRun
- type SearchBackend
- type SearchHit
- type SearchQuery
- type SearchResult
- type SearchSettings
- type SearchStatus
- type SessionBackend
- type SessionEvent
- type SessionInfo
- type SessionTool
- type Setting
- type Settings
- type SkillFile
- type SkillInfo
- type SkillScript
- type SkillSpec
- type SkillTool
- type SkillTry
- type SpecApproved
- type SpecBackend
- type SpecChange
- type SpecConflict
- type SpecDrift
- type SpecEvidence
- type SpecFinding
- type SpecImpact
- type SpecPlace
- type SpecPlan
- type SpecRecorded
- type SpecRequirement
- type SpecReview
- type SpecStep
- type SpecSummary
- type SpecSymbol
- type SpecVerification
- type State
- type StyleBackend
- type StyleInfo
- type Suggestion
- type SuggestionKind
- type Suggestions
- type Task
- type TaskBackend
- type TaskInfo
- type TaskRequest
- type Text
- type ToolCall
- type ToolInfo
- type ToolResult
- type Totals
- type Turn
- type TurnBackend
- type TurnResult
- type UndoResult
- type UnknownAgentError
- type UnknownSettingError
- type Usage
- type UserPromptFunc
- type WebSearch
- type WorkerInfo
- type WorkerSpec
- type WorkspaceProcess
Constants ¶
const ( TrustNone = "none" TrustNew = "new" TrustChanged = "changed" TrustTrusted = "trusted" TrustDeclined = "declined" // TrustUnknown: the service couldn't be asked, so it isn't known // what the project settings hold or whether they're trusted. TrustUnknown = "unknown" )
The trust states of ProjectSettings.State.
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_052_processes).
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.
const ( EvalRunning = "running" EvalPassed = "passed" EvalFailed = "failed" EvalStopped = "stopped" )
An eval run's status.
const ( PurposeTurn = "turn" // the conversation's own turns PurposeCompaction = "compaction" // summarising it to fit PurposeReview = "review" // the review model checking a plan or a change PurposeTask = "task" // a background task it started PurposeSpeech = "speech" // generate_audio's speech model PurposeImage = "image" // generate_image's image model PurposeSearch = "search" // a search provider's billed queries PurposeBefore = "before" // what was spent before the ledger was kept (CA-126) )
What a call in a conversation's ledger was for (spec_056 CA-120).
const ( // NodeTurn is the turn: its prompt, and its totals. NodeTurn = "turn" // NodeCall is one model call: who answered, its tokens and cost. NodeCall = "call" // NodeThought is a step of the model's reasoning, as it shared it. NodeThought = "thought" // NodeTool is a tool the model called, with its result. NodeTool = "tool" // NodeAgent is a sub-agent the model asked (invoke_agent): its own // calls are its children. NodeAgent = "agent" // NodeText is the model's words: its answer, or what it said between // tools. NodeText = "text" )
The kinds of node in a turn's reasoning graph (spec_066_reasoning).
const ( NodeOK = "ok" NodeFailed = "failed" NodeRunning = "running" )
A reasoning node's status.
const ( MaxReasoningText = 16 << 10 MaxReasoningNodes = 1500 )
MaxReasoningText bounds each node's text, and MaxReasoningNodes a turn's graph.
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.
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.
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.
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.
const HarnessUpdateSpec = "spec"
HarnessUpdateSpec is SuggestHarnessUpdate's Detail when the specification changed.
const SkillEvalPrefix = "skill:"
SkillEvalPrefix names a skill's scenarios as an eval: RunEval, EvalRuns and blitz eval take "skill:<name>" (spec_013_skills SK-111).
Variables ¶
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") )
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.
var BlitzCommands = []BlitzCommand{ {Name: "help", Summary: "The commands, or one command's arguments", Effect: EffectReads, Phase: 1, Args: []CommandArg{{Name: "command", Type: "string", Description: "A command or group (\"connector save\", \"connector\"); empty: every group"}}}, {Name: "connector list", Summary: "The connection kinds with their fields, and the connections with whether each is on, trusted, read-only and working", Effect: EffectReads, Phase: 1}, {Name: "connector save", Summary: "Add or change a connection of this workspace (a database), asked first with the file it writes; a secret goes as ${NAME}, and its value is asked of the person, never given here", Effect: EffectChanges, Phase: 1, Args: []CommandArg{ {Name: "kind", Type: "string", Description: "The connection's kind, from connector list (sqlite, postgres, bigquery, …)", Required: true}, argName, argDesc, {Name: "settings", Type: "object", Description: "The kind's fields, by name (a SQLite database: {\"database\": \"recipes.db\"}, relative to the workspace); a secret as \"${NAME}\""}, {Name: "read_only", Type: "boolean", Description: "Allow reading only"}, {Name: "queries", Type: "list", Description: "Saved queries, each a JSON object with name, description, statement and parameters"}, }}, {Name: "connector enable", Summary: "Turn a connection on in this workspace", Effect: EffectChanges, Phase: 1, Args: []CommandArg{argName}}, {Name: "connector disable", Summary: "Turn a connection off in this workspace", Effect: EffectChanges, Phase: 1, Args: []CommandArg{argName}}, {Name: "settings show", Summary: "The model (the conversation's and the workspace's), image and speech models, effort, permission mode and agent", Effect: EffectReads, Phase: 1}, {Name: "settings set", Summary: "Change one setting: the model, image or speech model, effort, or the permission mode (only to a stricter one)", Effect: EffectChanges, Phase: 1, Args: []CommandArg{ {Name: "key", Type: "string", Description: "What to change", Required: true, Values: []string{"model", "image_model", "speech_model", "effort", "mode"}}, {Name: "value", Type: "string", Description: "The new value (a model as provider/name)", Required: true}, }}, {Name: "doctor", Summary: "Check Blitz here: the model and its provider, Ollama, the mode, the sandbox, MCP servers, connections, language servers", Effect: EffectReads, Phase: 1}, {Name: "org policy", Summary: "What your organization's policy allows and locks", Effect: EffectReads, Phase: 1}, {Name: "org status", Summary: "Your organization: signed in or not, its catalog's version, problems", Effect: EffectReads, Phase: 1}, {Name: "open url", Summary: "Open a web page for the person in Blitz's browser", Effect: EffectOpens, Phase: 2, Args: []CommandArg{{Name: "url", Type: "string", Description: "The address", Required: true}}}, {Name: "open file", Summary: "Open a workspace file in Blitz's editor", Effect: EffectOpens, Phase: 2, Args: []CommandArg{argPath, {Name: "line", Type: "integer", Description: "The line to show"}}}, {Name: "open studio", Summary: "Open a section of Studio", Effect: EffectOpens, Phase: 2, Args: []CommandArg{{Name: "section", Type: "string", Description: "Which section", Required: true, Values: []string{"overview", "settings", "specs", "resources", "agents", "skills", "evals", "jobs", "connectors", "secrets", "workflows", "rules", "guardrails"}}}}, {Name: "open settings", Summary: "Open a section of Settings", Effect: EffectOpens, Phase: 2, Args: []CommandArg{{Name: "section", Type: "string", Description: "Which section", Required: true, Values: []string{"providers", "organization", "personality", "voice", "appearance", "agents", "skills", "evals", "connectors", "secrets", "browser", "workspaces", "permissions", "updates"}}}}, {Name: "open view", Summary: "Open one of Blitz's views", Effect: EffectOpens, Phase: 2, Args: []CommandArg{{Name: "view", Type: "string", Description: "Which view", Required: true, Values: []string{"changes", "processes", "pictures"}}}}, {Name: "picture", Summary: "Open Pictures with a prompt for the person to make it there (its cost shown first); without a Blitz window, use generate_image instead", Effect: EffectOpens, Phase: 2, Args: []CommandArg{ {Name: "prompt", Type: "string", Description: "What to draw", Required: true}, {Name: "model", Type: "string", Description: "An image model; empty: the workspace's"}, {Name: "references", Type: "list", Description: "Workspace pictures to start from or match"}, }}, {Name: "eval list", Summary: "The evals of this workspace's agents and skills", Effect: EffectReads, Phase: 2}, {Name: "eval run", Summary: "Run an agent's or a skill's evals (they call models: asked first)", Effect: EffectCosts, Phase: 2, Args: []CommandArg{{Name: "name", Type: "string", Description: "The eval set (an agent's or skill's name)", Required: true}}}, {Name: "eval results", Summary: "An eval set's last runs", Effect: EffectReads, Phase: 2, Args: []CommandArg{{Name: "name", Type: "string", Description: "The eval set", Required: true}}}, {Name: "spec list", Summary: "The project's specs, in order, with their state", Effect: EffectReads, Phase: 2}, {Name: "spec review", Summary: "Check a spec as written (free); with judge, a model reviews it (costs)", Effect: EffectReads, Phase: 2, Args: []CommandArg{{Name: "path", Type: "string", Description: "The spec's file", Required: true}, {Name: "judge", Type: "boolean", Description: "Have a model review it too (asked first: it costs)"}}}, {Name: "spec verify", Summary: "Trace an approved spec's requirements through the code (free); with judge, a model checks them (costs)", Effect: EffectReads, Phase: 2, Args: []CommandArg{{Name: "path", Type: "string", Description: "The spec's file", Required: true}, {Name: "judge", Type: "boolean", Description: "Have a model check each requirement (asked first: it costs)"}}}, {Name: "spec implement", Summary: "What's left of a spec, as the prompt to carry it out", Effect: EffectReads, Phase: 2, Args: []CommandArg{{Name: "path", Type: "string", Description: "The spec's file", Required: true}}}, {Name: "job list", Summary: "This workspace's scheduled jobs", Effect: EffectReads, Phase: 2}, {Name: "job create", Summary: "Create a job that runs a prompt on a schedule (as create_job: the person approves it, and it starts paused)", Effect: EffectChanges, Phase: 2, Args: []CommandArg{argName, argDesc, {Name: "schedule", Type: "string", Description: "When it runs, in plain English", Required: true}, {Name: "prompt", Type: "string", Description: "What each run does, everything it needs", Required: true}, {Name: "permissions", Type: "list", Description: "What each run may do without asking, kind:pattern"}}}, {Name: "memory list", Summary: "What Blitz remembers here (its notes)", Effect: EffectReads, Phase: 2}, {Name: "memory forget", Summary: "Forget one note", Effect: EffectChanges, Phase: 2, Args: []CommandArg{argName}}, {Name: "chat new", Summary: "Start a new conversation (from the next message)", Effect: EffectChanges, Phase: 2}, {Name: "chat export", Summary: "This conversation as Markdown, written to a workspace file (asked first)", Effect: EffectChanges, Phase: 2, Args: []CommandArg{{Name: "path", Type: "string", Description: "Where to write it, relative to the workspace", Required: true}}}, {Name: "chat search", Summary: "Search past conversations", Effect: EffectReads, Phase: 2, Args: []CommandArg{{Name: "terms", Type: "string", Description: "What to look for", Required: true}}}, {Name: "process list", Summary: "The background processes running here", Effect: EffectReads, Phase: 2}, {Name: "process stop", Summary: "Stop a background process (asked first)", Effect: EffectChanges, Phase: 2, Args: []CommandArg{{Name: "id", Type: "integer", Description: "The process's number, from process list", Required: true}}}, {Name: "approval list", Summary: "The actions always allowed (saved approvals)", Effect: EffectReads, Phase: 2}, {Name: "approval forget", Summary: "Stop always allowing one (Blitz asks again)", Effect: EffectChanges, Phase: 2, Args: []CommandArg{{Name: "key", Type: "string", Description: "The approval, from approval list", Required: true}}}, {Name: "secret list", Summary: "The secrets' names (never their values)", Effect: EffectReads, Phase: 2}, {Name: "secret set", Summary: "Set a secret of this workspace: its value is asked of the person, never given here", Effect: EffectChanges, Phase: 2, Args: []CommandArg{argName}}, {Name: "workflow list", Summary: "This workspace's workflows and their steps", Effect: EffectReads, Phase: 3}, {Name: "workflow save", Summary: "Add or change a workflow (its file, as Studio writes it), asked first", Effect: EffectChanges, Phase: 3, Args: []CommandArg{{Name: "workflow", Type: "object", Description: "The workflow as JSON, as workflow list shows one", Required: true}, {Name: "previous", Type: "string", Description: "Its name before, when renaming"}}}, {Name: "agent list", Summary: "The agents, with their tools and models", Effect: EffectReads, Phase: 3}, {Name: "agent save", Summary: "Add or change an agent of this workspace (its file), asked first", Effect: EffectChanges, Phase: 3, Args: []CommandArg{argName, argDesc, {Name: "instructions", Type: "string", Description: "What it does and how", Required: true}, {Name: "tools", Type: "list", Description: "The tools it may use"}, {Name: "model", Type: "string", Description: "provider/model; empty: the workspace's"}}}, {Name: "skill list", Summary: "The skills", Effect: EffectReads, Phase: 3}, {Name: "skill save", Summary: "Add or change a skill of this workspace (its SKILL.md), asked first", Effect: EffectChanges, Phase: 3, Args: []CommandArg{argName, {Name: "description", Type: "string", Description: "When to use it: what makes an agent load it", Required: true}, {Name: "instructions", Type: "string", Description: "Its body", Required: true}}}, {Name: "mcp list", Summary: "The MCP servers, on or off, and their state", Effect: EffectReads, Phase: 4}, {Name: "mcp add", Summary: "Add an MCP server to this workspace: it runs code, so it's asked with the exact command or address", Effect: EffectChanges, BringsCode: true, Phase: 4, Args: []CommandArg{argName, {Name: "command", Type: "string", Description: "The program that serves it (stdio)"}, {Name: "args", Type: "list", Description: "Its arguments"}, {Name: "url", Type: "string", Description: "Or its address (HTTP)"}}}, {Name: "mcp enable", Summary: "Turn an MCP server on here: it runs code, so it's asked", Effect: EffectChanges, BringsCode: true, Phase: 4, Args: []CommandArg{argName}}, {Name: "mcp disable", Summary: "Turn an MCP server off here", Effect: EffectChanges, Phase: 4, Args: []CommandArg{argName}}, {Name: "rule list", Summary: "The workspace's rules", Effect: EffectReads, Phase: 4}, {Name: "rule save", Summary: "Add or change a rule, asked first", Effect: EffectChanges, Phase: 4, Args: []CommandArg{argName, argDesc, {Name: "text", Type: "string", Description: "The rule", Required: true}}}, {Name: "guardrail list", Summary: "The workspace's guardrails", Effect: EffectReads, Phase: 4}, {Name: "guardrail save", Summary: "Add or change a guardrail, asked first", Effect: EffectChanges, Phase: 4, Args: []CommandArg{argName, argDesc, {Name: "stage", Type: "string", Description: "What it checks: the person's message, a tool's result, the answer, or an action", Required: true, Values: []string{"input", "tool_result", "output", "action"}}, {Name: "action", Type: "string", Description: "What it does when it catches something (block: the default)", Values: []string{"block", "warn"}}, {Name: "check", Type: "string", Description: "What to catch, in words", Required: true}}}, {Name: "command list", Summary: "The slash commands", Effect: EffectReads, Phase: 4}, {Name: "command save", Summary: "Add or change a slash command of this workspace (its file), asked first", Effect: EffectChanges, Phase: 4, Args: []CommandArg{argName, argDesc, {Name: "prompt", Type: "string", Description: "The prompt it runs ($ARGUMENTS for what's typed after it)", Required: true}}}, {Name: "hook list", Summary: "The hooks", Effect: EffectReads, Phase: 4}, {Name: "plugin list", Summary: "The plugins loaded here", Effect: EffectReads, Phase: 4}, }
BlitzCommands is the catalog, in the order help lists it.
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.
var ErrBadModelRef = errors.New("not a model name")
ErrBadModelRef reports a model reference with no model name.
var ErrBadRule = errors.New("invalid permission rule")
ErrBadRule reports a rule that can't be parsed.
var ErrBlocked = errors.New("the provider's safety filters stopped the model's reply")
ErrBlocked means the provider's safety filters stopped the model's reply.
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.
var ErrConfirmWhileAgentWorks = errors.New("not changed: the agent is working in this workspace, so a change confirmed from the command line waits until it finishes (or approve it in the window)")
ErrConfirmWhileAgentWorks refuses a change confirmed from outside the window (blitz do) while the agent is at work in the workspace: the confirmation may be the agent's own command (spec_060 DRV-04a).
var ErrContextLength = errors.New("the conversation is longer than the model can read, even summarised: start a new conversation, or switch to a model with a larger context window")
ErrContextLength means the conversation is longer than the model takes, even summarised (CA-111).
var ErrEmptySearch = errors.New("nothing to search for")
ErrEmptySearch reports a query with nothing to search for.
var ErrEvalNotRunnable = errors.New("the eval can't run")
ErrEvalNotRunnable means the eval has a problem, or no case to run.
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.
var ErrImagesDisabled = errors.New("image support is disabled")
ErrImagesDisabled is returned when images enabled = false (or the image store could not be created).
var ErrInvalidAgency = errors.New("agency must be low, medium, high or extreme")
ErrInvalidAgency reports an agency level other than low, medium, high or extreme.
var ErrMalformedToolCall = errors.New("the model wrote a tool call that couldn't be read, twice: ask again, or try another model")
ErrMalformedToolCall means the model wrote a tool call that couldn't be read, again after being told so.
var ErrMaxTurns = errors.New("maximum turns reached")
ErrMaxTurns is returned when a run exceeds its model-call budget.
var ErrNoActiveSession = errors.New("no active session")
ErrNoActiveSession reports an operation on the active session when there is none.
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.
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.
var ErrNoGoal = errors.New("no goal set")
ErrNoGoal is returned when the session has no goal.
var ErrNoNote = errors.New("no such note")
ErrNoNote is returned by ForgetNote when no note has the name.
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.
var ErrNothingToCompact = errors.New("nothing to compact yet")
ErrNothingToCompact is returned when a session is too short to compact.
var ErrNothingToUndo = errors.New("nothing to undo")
ErrNothingToUndo means there are no changes left to restore.
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.
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.
var ErrRecitation = errors.New("the provider stopped the model's reply because it repeated protected material: ask for it in other words")
ErrRecitation means the provider stopped the model's reply because it repeated material it may not reproduce (Gemini's RECITATION).
var ErrRefused = errors.New("the model declined this request")
ErrRefused means the model declined the request: its words are the turn's last reply (spec_056_conversation_adapters CA-31).
var ErrRunInProgress = errors.New("the worker is already running")
ErrRunInProgress reports a run of a worker that is already running.
var ErrRunStopped = errors.New("stopped by the user")
ErrRunStopped is why a run the user stopped ended: the cause its context is cancelled with.
ErrSandboxUnavailable means sandbox.shell is "required" and the OS sandbox can't run here, so the workspace doesn't open.
var ErrScriptsDisabled = errors.New("skill scripts are disabled")
ErrScriptsDisabled reports that skill scripts (and so their environments) are turned off.
var ErrSearchDisabled = errors.New("workspace search is off (search.enabled = false)")
ErrSearchDisabled reports workspace search turned off.
var ErrSessionNotFound = errors.New("no such session")
ErrSessionNotFound reports a session ID with no saved session.
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.
var ErrSnapshotNameTaken = errors.New("a snapshot with this name already exists")
ErrSnapshotNameTaken is returned by Snapshot when another snapshot has the name.
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.
var ErrUndoConflict = errors.New("files changed since the edit")
ErrUndoConflict is returned when files changed after the checkpointed edit.
var ErrUnknownCommand = errors.New("unknown command")
ErrUnknownCommand reports a slash command that doesn't exist.
var ErrUnknownEval = errors.New("no such eval")
ErrUnknownEval means the workspace has no eval of that name.
var ErrUnknownHook = errors.New("no workflow runs on that git hook: pre-commit or pre-push")
ErrUnknownHook is a git hook no workflow can run on (spec_043 WF-32).
var ErrUnknownLocale = errors.New("not a language")
ErrUnknownLocale reports input that isn't a language.
var ErrUnknownMode = errors.New("unknown permission mode")
ErrUnknownMode reports a name that isn't a permission mode.
var ErrUnknownProcess = errors.New("no such background process")
ErrUnknownProcess means no background process with that ID was started for the sessions asking.
var ErrUnknownRequest = errors.New("no such request is waiting")
ErrUnknownRequest means no request with that ID is waiting.
var ErrUnknownRun = errors.New("no such background run")
ErrUnknownRun means the service has no background run with that ID.
var ErrUnknownSearchMode = errors.New("unknown search mode (keyword, semantic or hybrid)")
ErrUnknownSearchMode reports a mode that isn't keyword, semantic or hybrid.
var ErrUnknownSearchSource = errors.New("unknown search source (files, documents, chats or notes)")
ErrUnknownSearchSource reports a source search doesn't have.
var ErrUnknownTask = errors.New("no such task")
ErrUnknownTask means no task with that ID was started in the sessions asking.
var ErrUnknownWorker = errors.New("no such worker")
ErrUnknownWorker reports a worker name the workspace doesn't define.
var ErrUnsafeChosenEachTime = errors.New("unsafe mode isn't kept in settings: choose it each time, with /mode unsafe or the window's mode menu")
ErrUnsafeChosenEachTime is a setting asking to start in unsafe mode: it's never kept, so the workspace opens in default.
var ErrUnsafeNotHere = errors.New("unsafe mode runs commands outside the sandbox: only you can switch to it (with /mode unsafe, or in the window), and not while you're connected to an organization")
ErrUnsafeNotHere refuses unsafe mode where only the person may choose it and hasn't (a project's settings, an agent, the agent itself), or while connected to an organization.
var ErrUnsafeWhileAgentWorks = errors.New("unsafe mode can't be chosen while the agent is working here (a turn, a background task or a background process): wait for it to finish, or stop it, then choose unsafe")
ErrUnsafeWhileAgentWorks refuses unsafe mode while the agent is at work in the workspace (a turn, a background task, a background process it started): only the person switches to it, when the agent isn't acting.
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.
var ErrWorkerExists = errors.New("a worker with that name exists")
ErrWorkerExists reports creating a worker with a name the workspace already has.
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).
var ErrWorkerNotEnabled = errors.New("the worker isn't enabled")
ErrWorkerNotEnabled reports running a worker that isn't enabled at its current hash.
var ErrWorkersDisabled = errors.New("workers are disabled")
ErrWorkersDisabled reports that workers are turned off ([workers] enabled).
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.
var Modes = []PermissionMode{ModeDefault, ModeAcceptEdits, ModeAuto, ModePlan, ModeDontAsk, ModeBypass, ModeUnsafe}
Modes are the permission modes in Shift+Tab order; bypass is only offered when the session started in it, and unsafe never (it's chosen by name).
var RewindModes = []RewindMode{RewindBoth, RewindConversation, RewindCode, RewindSummarizeFrom, RewindSummarizeUpTo}
RewindModes are the modes, in the order offered.
var SearchSources = []string{SearchFiles, SearchDocuments, SearchChats, SearchNotes}
SearchSources are every source, in order.
Functions ¶
func BlitzCommandRunsInPlan ¶ added in v0.9.6
BlitzCommandRunsInPlan reports whether the command (as the blitz tool was called with it) may run in plan mode: one that reads or opens (DRV-70). An unknown command may: the tool refuses it with help.
func BlitzGroups ¶ added in v0.9.6
func BlitzGroups() [][]BlitzCommand
BlitzGroups are the catalog's groups, in order, each with its commands.
func IsMultiSelect ¶
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 SecretAnswer ¶ added in v0.9.6
SecretAnswer reports whether a question asked with ctx asks for a secret.
func ShownVersion ¶ added in v0.6.4
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 WithChoices ¶ added in v0.9.4
WithChoices marks a question asked with ctx as offering choices (its options, in recommended order, explained), and says what the order rests on.
func WithMultiSelect ¶
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 )
const ActionBlitz ActionKind = "blitz"
ActionBlitz is the approval kind of a blitz command (DRV-04), and a job's permission kind for one ("blitz:connector save").
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; or "file", a workspace file to
// open in the editor, with Path and Line (spec_060_blitz_tools DRV-31).
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
// PrivateSites are the profile's own sites, for "open": a name among
// them may resolve to a private address (an intranet) without
// AllowLocal; loopback still needs AllowLocal (BP-04a).
PrivateSites []string
// URL is the page to show, for "page" and "external".
URL string
// Path is the workspace file to open (relative to the workspace), and
// Line the line to put the cursor on (0: the top), for "file".
Path string
Line int
}
AgentBrowserCommand is what a desktop window is asked to do with a view of the agent's browser (spec_050_agent_browser): 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
// OrgLock is how the organization's catalog applies it: "locked",
// "default", or "" for an agent of the person's, the workspace's or
// Blitz's own (spec_053_enterprise EN-34).
OrgLock string
}
AgentInfo describes an agent.
type AgentModelBackend ¶ added in v1.2.0
type AgentModelBackend interface {
// 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)
// SetSessionModel moves conversation id to ref from its next turn (""
// back to the workspace's model), and PreviewSessionModel says what
// that would mean without moving it (spec_056 CA-100, CA-101).
SetSessionModel(ctx context.Context, id, ref string) (ModelPreview, error)
PreviewSessionModel(ctx context.Context, id, ref string) (ModelPreview, error)
// ListModels is every chat model of every provider set up, from the
// last listing unless refresh (spec_061_models MOD-01, MOD-04).
ListModels(ctx context.Context, refresh bool) (ModelList, 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)
}
AgentModelBackend manages agent definitions, models, model settings, and permission rules.
type AgentTools ¶
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
// Deletes are the Targets a write deletes (a patch's deleted files and
// moved-away sources, a script's removed files): delete(...) permission
// rules govern them as well as write(...) rules.
Deletes []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
// ReviewerDenied is why auto mode's reviewer denied the action, when it
// did and someone is there to answer: they may allow it anyway
// (spec_005_approvals APR-14d).
ReviewerDenied string
}
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 AssetFinding ¶ added in v1.1.0
type AssetFinding struct {
Key string `json:"asset"`
Problems []string `json:"problems,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
AssetFinding is what checking one of the workspace's assets found (spec_065 PK-14): problems keep Blitz from reading it; warnings are worth fixing.
type Backend ¶
type Backend interface {
Lifecycle
TaskBackend
GoalBackend
StyleBackend
SpecBackend
TurnBackend
SessionBackend
AgentModelBackend
ExtensionBackend
ContextMemoryBackend
ChangeBackend
SearchBackend
DataBackend
ImageBackend
}
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. Composed of domain sub-interfaces (ISP).
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 BlitzCommand ¶ added in v0.9.6
type BlitzCommand struct {
// Name is the command as typed: its group, then its verb
// ("connector save"), or the group alone ("doctor").
Name string
Summary string
Effect CommandEffect
Args []CommandArg
// BringsCode marks a command that adds something that runs code (an
// MCP server, a hook, a plugin): always asked, with the code in view
// (DRV-75).
BringsCode bool
// Phase is the spec's phase it came in.
Phase int
}
BlitzCommand is one command of the catalog.
func FindBlitzCommand ¶ added in v0.9.6
func FindBlitzCommand(name string) (BlitzCommand, bool)
FindBlitzCommand is the catalog's command named name (its words, any case and spacing).
func (BlitzCommand) Group ¶ added in v0.9.6
func (c BlitzCommand) Group() string
Group is the command's group: its first word.
func (BlitzCommand) Usage ¶ added in v0.9.6
func (c BlitzCommand) Usage() string
Usage is the command and its arguments as help shows them.
type BlitzRun ¶ added in v0.9.6
BlitzRun is a command's run for the CLI (blitz do, DRV-02): its result, or what the person confirms before it runs (Confirm, with the file it writes as Diff, and the secrets it needs, Asks), or help.
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 Call ¶ added in v0.9.2
type Call struct {
Time time.Time `json:"time"`
// API, Provider and Model are who answered: the wire API, the
// provider as configured, and the model.
API string `json:"api,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Purpose string `json:"purpose"`
// Task is the background task a task's call ran for.
Task string `json:"task,omitempty"`
// Usage is the call's tokens and cost (Calls is 1, or 0 for a search).
Usage Usage `json:"usage"`
// Price is what it was charged at; nil when its model had no price.
Price *Price `json:"price,omitempty"`
}
Call is one entry of a conversation's ledger: a model call, a speech call or a search's billed queries, with what it was for, who answered and what it cost at the time (spec_056 CA-120).
type ChangeBackend ¶ added in v1.2.0
type ChangeBackend interface {
// Checkpoints and approvals.
ListCheckpoints() []Checkpoint
// Undo restores the files session's latest turn changed ("": the
// active session's); other sessions' turns are left alone.
Undo(session string, 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, error)
ClearApprovals() (int, error)
}
ChangeBackend manages checkpoints, undo, rewind, diffs, and approvals.
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 Choice ¶ added in v0.9.4
type Choice struct {
Label, Summary, Details, Why string
}
Choice is a question's option explained for someone who doesn't know the tools it names (spec_005_approvals APR-40b): its Label (plain, short: what the button says), a one-line Summary (its tooltip), Details (what it is and what it means for them) and Why it's ranked where it is.
type Citation ¶ added in v0.9.2
type Citation struct {
Title, URL, Text string
}
Citation is one source an answer cites: its title, its address, and the text of the answer it supports.
type CommandArg ¶ added in v0.9.6
type CommandArg struct {
Name string
// Type is string, integer, boolean, object (a JSON object) or list (a
// list of strings).
Type string
Description string
Required bool
// Values are the values it may take, when they're few.
Values []string
}
CommandArg is one of a command's arguments.
type CommandEffect ¶ added in v0.9.6
type CommandEffect string
CommandEffect is what a command does, which decides where it may run (DRV-70): reads and opens run in plan mode; changes and costs don't.
const ( EffectReads CommandEffect = "reads" EffectOpens CommandEffect = "opens" EffectChanges CommandEffect = "changes" EffectCosts CommandEffect = "costs" )
The effects.
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 ¶
CompactResult is what Compact did.
type ContextBlock ¶ added in v0.7.0
type ContextBlock struct {
// Kind is what it is: "web_page", "web_selection", "console",
// "database" (a connection: its schema is read for the turn) or
// "data_query" (a query's result, Text the table as JSON:
// spec_059_data DAT-41, DAT-42).
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
// Connection is a database or data_query block's connection (one of
// the workspace's databases); Statement the query's SQL.
Connection, Statement string
}
ContextBlock is content the user added to a turn from elsewhere: the desktop app's web preview, or one of the workspace's databases.
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 ContextMemoryBackend ¶ added in v1.2.0
type ContextMemoryBackend interface {
// Context, memory and language.
SessionUsage() (Usage, error)
// SessionLedger is the active session's calls, oldest first, and their
// totals by model and purpose (spec_056 CA-120, CA-121).
SessionLedger() ([]Call, Totals, 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
}
ContextMemoryBackend manages usage, ledger, compaction, memory files, locales, and sandbox status.
type ContextPart ¶
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 DataBackend ¶ added in v1.2.0
type DataBackend interface {
// Data (spec_059_data DAT-45): the workspace's database connections
// and their saved queries, and a query run read-only on one of them
// by name (on, trusted and readable, as a chat's @db: finds it).
DataConnections(ctx context.Context) ([]DataConnection, error)
RunDataQuery(ctx context.Context, q DataQuery) (DataTable, error)
}
DataBackend manages database connections and read-only data queries.
type DataColumn ¶ added in v0.9.7
type DataColumn struct {
Name string `json:"name"`
Description string `json:"description"`
// Type is portable: string, integer, number, boolean, date, time,
// timestamp, json, bytes or other.
Type string `json:"type"`
Length *int64 `json:"length"`
// DBType is the database's own type.
DBType string `json:"db_type,omitempty"`
Nullable *bool `json:"nullable,omitempty"`
}
DataColumn is a column of a DataTable (DAT-02).
type DataConnection ¶ added in v0.9.7
type DataConnection struct {
Name string
// Kind is its kind's ID (sqlite, postgres, bigquery…).
Kind string
ReadOnly bool
// On says it's on in this workspace (CON-17).
On bool
// Trusted says the person trusted it; a chat or the CLI uses only
// trusted ones (DAT-44).
Trusted bool
// Problem is why it can't be read ("" when it can).
Problem string
Queries []DataQueryInfo
// Org says it's one of the organization's shared connectors, which its
// service runs (spec_053 EN-72).
Org bool
}
DataConnection is one of the workspace's database connections, as the CLI's /data and blitz data list show it (spec_059_data DAT-45).
func (DataConnection) Usable ¶ added in v0.9.7
func (c DataConnection) Usable() bool
Usable reports whether a chat or the CLI may query c: on, trusted and readable.
type DataQuery ¶ added in v0.9.7
type DataQuery struct {
Connection string
Query string
Named map[string]any
Statement string
Params []any
// MaxRows is the most rows the table holds (1,000 when 0).
MaxRows int
}
DataQuery is a query to run on one of the workspace's connections, by name: a saved one (Query, its parameters in Named) or a statement (its parameters in Params, in order). It runs read-only.
type DataQueryInfo ¶ added in v0.9.7
type DataQueryInfo struct {
Name string
Description string
// Params are its parameters' names, in order.
Params []string
}
DataQueryInfo is one of a connection's saved queries.
type DataTable ¶ added in v0.9.7
type DataTable struct {
Columns []DataColumn `json:"columns"`
Rows [][]any `json:"rows"`
Total int `json:"total"`
Truncated bool `json:"truncated"`
// Markdown is the table as Markdown, its first 50 rows (DAT-05).
Markdown string `json:"-"`
}
DataTable is a query's result (spec_059_data DAT-01): its columns described, its rows as arrays in the columns' order.
func DataTableFrom ¶ added in v0.9.7
func DataTableFrom(columns []DataColumn, rowsJSON string, total int, truncated bool, markdown string) (DataTable, error)
DataTableFrom is a table read from its JSON (DAT-01): the engine's table, or rows_json beside its columns.
type Decision ¶
type Decision int
Decision is the user's answer to an approval request.
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 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_013_skills 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.
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_043_workflows).
Step *FlowStep
// File is a file the model made: an image it drew, audio
// (spec_056_conversation_adapters CA-71).
File *File
// Reflect, at a chat turn's end, says the runs since the last
// reflection hit enough problems to /reflect on
// (spec_048_harness_learning HE-63).
Reflect *ReflectDue
// Citations are the sources the answer before it cites, from the
// provider's own search or fetch (spec_056 CA-84).
Citations []Citation
}
Event is something that happened during a turn. Exactly one of Text, ToolCall and ToolResult is set. Events arrive in order.
type ExtensionBackend ¶ added in v1.2.0
type ExtensionBackend interface {
// 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_042_evals) and records
// the run.
RunEval(ctx context.Context, name string, o EvalOptions) (EvalRun, error)
// RunGitHook runs the workflows that run on the git hook event
// (pre-commit, pre-push) on input, the changes (spec_043 WF-32).
RunGitHook(ctx context.Context, event, input string) ([]HookResult, error)
// ValidateAssets checks the workspace's assets (.agents) as Blitz reads
// them, and what's worth fixing (spec_065 PK-14).
ValidateAssets(ctx context.Context) ([]AssetFinding, error)
}
ExtensionBackend manages skills, environments, MCP servers, commands, evals, and git hooks.
type File ¶ added in v0.9.2
type File struct {
// URI is its reference there (blitz-image:<sha256>).
URI string
Name string
MIME string
// Path is where it's kept on this machine, and Size its size ("" and 0
// when that isn't known).
Path string
Size int64
}
File is a file a model made, kept in the attachment store.
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 GoalBackend ¶ added in v1.2.0
type GoalBackend interface {
// 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
}
GoalBackend manages turn goals for a session.
type HookFailure ¶
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 HookResult ¶ added in v1.1.0
type HookResult struct {
Workflow string `json:"workflow"`
Version string `json:"version,omitempty"`
Passed bool `json:"passed"`
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
}
HookResult is what a workflow a git hook ran found (spec_043 WF-32): whether it passed, its last message, why it failed; Version is the organization's version of it ("" for the workspace's own).
type ImageBackend ¶ added in v1.2.0
type ImageBackend interface {
// 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)
}
ImageBackend manages loading and preparing image attachments.
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 Lifecycle ¶ added in v1.2.0
type Lifecycle 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
}
Lifecycle covers workspace opening, UI routing, background processes and teardown.
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 ¶
type Link struct{ Title, URL string }
Link is a web search result the agent is asked to read.
type ListedModel ¶ added in v0.9.6
type ListedModel struct {
ID, DisplayName string
// Default is the organization's default model.
Default bool
// HasPrice says the price per million tokens is known.
HasPrice bool
InputPerMTok, OutputPerMTok float64
// Tools, Images and Thinking say what it can do, and Context its
// window in tokens (0: unknown).
Tools, Images, Thinking bool
Context int
}
ListedModel is one model, with what Blitz knows of it.
func (ListedModel) Ref ¶ added in v0.9.6
func (m ListedModel) Ref(provider string) string
Ref is the model as a reference that names its provider.
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 ModelList ¶ added in v0.9.6
type ModelList struct {
Providers []ProviderModels
// DefaultProvider is the provider a name without "provider/" is of.
DefaultProvider string
// NotSetUp are the providers the person could set up (MOD-06).
NotSetUp []string
}
ModelList is every chat model of every provider set up, grouped by provider (spec_061_models MOD-01), and the providers that aren't set up.
type ModelPreview ¶ added in v0.9.2
type ModelPreview struct {
// Model is the model reference ("" for the workspace's model).
Model string
// Tokens is about how much the next turn reads again: the
// conversation's context, on a model with none of it cached.
Tokens int64
// CostUSD is what reading Tokens costs, when Priced.
CostUSD float64
Priced bool
// Compacts is set when the conversation is compacted first, to fit.
Compacts bool
// Unseen names the attachments the model can't see, which are
// described to it instead.
Unseen []string
// NoTools is set for a model that can't call tools: the agent only
// answers on it.
NoTools bool
// ActivePin is the active agent's pinned model, which it keeps.
ActivePin string
}
ModelPreview is what moving a conversation to a model means before it moves (spec_056_conversation_adapters CA-101).
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_027_parity 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" // ModeUnsafe is bypass with the shell's commands run outside the OS // sandbox (spec_005 APR-14e): nothing is asked, and a command can read // and write what the person can. Deny rules, guardrails and the file // tools' blocked paths still apply. Only the person chooses it (never a // project's settings, an agent or the agent itself), and not while // connected to an organization. ModeUnsafe PermissionMode = "unsafe" )
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),
// "project" (a trusted project file's), "built-in"
// (read_only_defaults), "flag" or "session".
Source string
}
PermissionRule is an allow, ask or deny rule in force.
type Personality ¶ added in v1.0.0
type Personality struct {
Name, Description string
// Voice is the Gemini voice it speaks with in spec_063's voice
// conversations ("": the [voice] setting's).
Voice string
// Source is "built-in", "organization" or "own" (the person's file).
Source string
// Text is how it should sound; empty in lists.
Text string
// Active is whether the workspace uses it (in ListPersonalities).
Active bool
}
Personality is how the root agent sounds (spec_064_personality).
type Price ¶ added in v0.9.2
type Price struct {
Input float64 `json:"input"`
CachedInput float64 `json:"cached_input,omitempty"`
CacheWrite float64 `json:"cache_write,omitempty"`
Output float64 `json:"output"`
}
Price is what a model charged per million tokens when a call was made.
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, plugin_off (applied); hook, mcp, allow, writable, model, agent_model, worker_allow, plugin, 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_031_project_config).
type ProviderModels ¶ added in v0.9.6
type ProviderModels struct {
Provider string
Models []ListedModel
Error string
// Note says what the list is when it isn't the provider's own.
Note string
}
ProviderModels are one provider's models, or why they couldn't be listed.
type PruneResult ¶
PruneResult is what PruneEnvs removed.
type Reasoning ¶ added in v1.2.0
type Reasoning struct {
Turns []ReasoningTurn
// Turn is the index of the turn Nodes draw.
Turn int
Nodes []ReasoningNode
// Cut says the turn had more nodes than MaxReasoningNodes: the rest
// aren't drawn.
Cut bool
}
Reasoning is a session's turns and the graph of one of them.
type ReasoningNode ¶ added in v1.2.0
type ReasoningNode struct {
ID, Parent string
Kind string
// Title is its short label; Text its whole text (a step of the
// reasoning, an answer, the prompt), cut at MaxReasoningText.
Title, Text string
// Author is the agent whose call it is (a sub-agent's name inside one).
Author string
// Provider and Model answered a call.
Provider, Model string
// Tool, Args and Result are a tool's call and what it returned.
Tool string
Args, Result map[string]any
Status string
Start time.Time
Duration time.Duration
// Usage is a call's tokens and estimated cost, or a turn's or a
// sub-agent's total.
Usage *Usage
// Hidden marks a call that reasoned (Usage.Reasoning) without sharing
// its reasoning: the provider keeps it to itself.
Hidden bool
}
ReasoningNode is one node of a turn's reasoning graph. Parent is the ID of the node it hangs from ("" for the turn).
type ReasoningTurn ¶ added in v1.2.0
type ReasoningTurn struct {
Index int
Prompt string
Start time.Time
Calls int
// Thoughts counts the steps of reasoning the model shared.
Thoughts int
Usage Usage
}
ReasoningTurn sums up one turn of a session, for the turn picker.
type ReflectDue ¶ added in v0.8.4
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_048_harness_learning 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
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 ¶
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
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).
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 SearchBackend ¶ added in v1.2.0
type SearchBackend interface {
// Workspace search (spec_035_search).
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
SearchProvider() (string, error)
SearchWeb(ctx context.Context, terms string) (WebSearch, error)
SearchSession(terms string) (int, string)
}
SearchBackend handles workspace and web search.
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
// Folder keeps the files and documents under one folder (relative to
// the workspace; "" for the whole workspace), as Find in folder asks
// (SRCH-18). Chats and notes aren't in a folder: a scoped search
// leaves them out.
Folder string
}
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
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 SessionBackend ¶ added in v1.2.0
type SessionBackend interface {
// 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)
}
SessionBackend manages conversation sessions and snapshots.
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
// Model is the conversation's own model, "" when it runs on the
// workspace's (spec_056 CA-100).
Model 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
// ModeNote says why auto mode isn't used, when it isn't for a reason
// the person should know: a local model would review its own actions
// (spec_005_approvals APR-14c). "" otherwise.
ModeNote 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
// ImageModel is generate_image's image model ([images] model; "" for
// none), and ImageError why it can't be used.
ImageModel, ImageError string
// ReadOnly is why the workspace's files can only be read (a Viewer's
// clone, spec_053 EN-60); "" when they can be changed.
ReadOnly string
}
Settings are the values /set changes, plus the model, agent and locale.
type SkillFile ¶ added in v0.7.1
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_013_skills 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_013_skills 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.
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 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 SpecApproved ¶ added in v0.9.4
SpecApproved is an approved spec: its text as written (Status: approved) and the diff kept of what changed since its last approval ("" when there was none).
type SpecBackend ¶ added in v1.2.0
type SpecBackend interface {
// The project's specification (spec_057_spec_driven): its files in
// order, and a review of one (path, its text as edited; judge asks
// the model too, which costs).
ListSpecs() ([]SpecSummary, error)
ReviewSpec(ctx context.Context, path, text string, judge bool) (SpecReview, error)
// TraceSpecs is the requirements of the spec at path ("" for every
// spec) as the ledger traces them; ApproveSpec approves it (force:
// with errors or open questions); VerifySpec finds each requirement in
// the work (judge: and has the model judge it; estimate: only says
// what that would cost).
TraceSpecs(path string) ([]SpecRequirement, error)
ApproveSpec(ctx context.Context, path string, force bool) (SpecApproved, error)
VerifySpec(ctx context.Context, path string, judge, estimate bool) (SpecVerification, error)
// RecordSpecChange records a saved change to an approved spec (its
// diff, Status: changed); ImpactSpec scans what the change reaches in
// the work (judge: and has the model write the fix; estimate: only
// says what that would cost).
RecordSpecChange(ctx context.Context, path string) (SpecRecorded, error)
ImpactSpec(ctx context.Context, path string, judge, estimate bool) (SpecImpact, error)
// PlanSpec is how the spec at path would be implemented: what's left,
// what it waits for, and the prompt for an agent.
PlanSpec(path string) (SpecPlan, error)
}
SpecBackend handles specification review, tracing, verification, and planning.
type SpecChange ¶ added in v0.9.4
SpecChange is a requirement that differs from its spec's approval: its kind (added, changed, removed) and its text then and now.
type SpecConflict ¶ added in v0.9.4
SpecConflict is another spec's requirement a change contradicts.
type SpecDrift ¶ added in v0.9.4
SpecDrift is an approved requirement that no longer holds (SDD-31): Why is "changed" (since approval), "lost" (no longer found in the work) or "judged" (the model said missing or contradicted).
type SpecEvidence ¶ added in v0.9.4
SpecEvidence is where a requirement was found: a file's line (code, test or doc) or a commit (Path is its hash).
type SpecFinding ¶ added in v0.9.4
type SpecFinding struct {
// Line is where (1-based; 0 for the whole spec).
Line int
// ID is the requirement it's about, if one.
ID string
// Severity is "error", "warning" or "info".
Severity string
// Code names the check (no-title, vague, …; "judged" for the model's).
Code string
Message string
// Judged marks the model's findings (SDD-03), not the checks'.
Judged bool
}
SpecFinding is something a review found in a spec.
type SpecImpact ¶ added in v0.9.4
type SpecImpact struct {
Changes []SpecChange
Symbols []SpecSymbol
Places []SpecPlace
Summary string
Steps []SpecStep
Conflicts []SpecConflict
Report string
CostUSD float64
EstimatedUSD float64
Priced bool
Problem string
}
SpecImpact is a change's impact on the work (SDD-20, SDD-21): the changes, the symbols and places they reach (found without a model), and with the model its summary, the steps to fix it and the conflicts, the report written, and what it cost (or, estimated, would cost).
type SpecPlace ¶ added in v0.9.4
SpecPlace is a place a change reaches: where a requirement was found, a use of a symbol it sits in, or a passage search found; Why says which.
type SpecPlan ¶ added in v0.9.4
type SpecPlan struct {
Pending []SpecRequirement
BlockedBy []int
Prompt string
}
SpecPlan is how a spec is implemented (SDD-30): its requirements not implemented yet, in order, the dependencies not done that it waits for, and the prompt that has an agent do it.
type SpecRecorded ¶ added in v0.9.4
type SpecRecorded struct {
Changes []SpecChange
Diff string
Text string
}
SpecRecorded is a saved change to an approved spec (SDD-20): what changed, the diff kept in the ledger, and the spec's text now that it says Status: changed ("" when nothing changed, or it said so already).
type SpecRequirement ¶ added in v0.9.4
type SpecRequirement struct {
// Spec is its spec's file; Line its line there (0 when removed).
Spec string
ID string
Text string
Line int
// Change is "added" or "changed" since the spec was approved, or
// "removed" (still in the approval, gone from the spec); "" otherwise.
Change string
// State is its last verification's: traced or untraced (the check
// without a model), implemented, partial, missing or contradicted (the
// model's, Judged); "" when never verified.
State string
Judged bool
Reason string
// Stale reports that its text changed since it was verified.
Stale bool
VerifiedAt time.Time
Evidence []SpecEvidence
}
SpecRequirement is one requirement as traced (SDD-10, SDD-12): where it is in its spec, how it differs from what was approved, and its last verification.
type SpecReview ¶ added in v0.9.4
type SpecReview struct {
Findings []SpecFinding
CostUSD float64
Problem string
}
SpecReview is a spec's review: the checks' findings, and the model's when asked, with what it cost. Problem says why the model's review didn't come (the checks' findings are there all the same).
type SpecStep ¶ added in v0.9.4
SpecStep is one step of an impact report's fix, with the files it touches.
type SpecSummary ¶ added in v0.9.4
type SpecSummary struct {
// File is its name (001-overview.md); Path is it in the workspace.
File string
Path string
// Number is its place in the order (0 for the index or an unnumbered file).
Number int
Title string
// Status is its Status: line ("" when there's none).
Status string
DependsOn []int
// Items counts its requirements with IDs.
Items int
// Errors and Warnings count what the checks without a model found.
Errors int
Warnings int
// OpenQuestions counts its open questions.
OpenQuestions int
// Approved reports that the ledger has its approval (SDD-11).
Approved bool
// Traced counts its requirements the work names (or the model found
// implemented); Implemented those the model judged so; Changed those
// added or changed since it was approved (SDD-10, SDD-12).
Traced int
Implemented int
Changed int
// Done: approved, unchanged, every requirement found in the work.
// Next: the first in order not done whose dependencies are; BlockedBy:
// the dependencies not done it waits for (SDD-32).
Done bool
Next bool
BlockedBy []int
}
SpecSummary is one file of the project's specification (.agents/specs), as read: what spec_057_spec_driven's list shows (SDD-01).
type SpecSymbol ¶ added in v0.9.4
SpecSymbol is a declaration a changed requirement's work sits in, and how many uses of it were found.
type SpecVerification ¶ added in v0.9.4
type SpecVerification struct {
Requirements []SpecRequirement
Drift []SpecDrift
CostUSD float64
EstimatedUSD float64
Priced bool
Problem string
}
SpecVerification is a spec's verification: its requirements as found, and (an approved spec's) those that drifted; with the model, what it cost, or (estimate) what it would cost and whether the model has a price.
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 StyleBackend ¶ added in v1.2.0
type StyleBackend interface {
// 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 personalities (spec_064_personality), with the one in use (Set
// "personality" changes it).
ListPersonalities() []Personality
// 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
}
StyleBackend handles workspace styles, personalities, hooks, notes, and project settings.
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 TaskBackend ¶ added in v1.2.0
type TaskBackend interface {
// 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
}
TaskBackend covers background task tracking and approval/question handling.
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_032_background_agents).
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
// Choices explain the options, in recommended order, and Order says
// what that order rests on (spec_005_approvals APR-40b).
Choices []Choice
Order string
// Secret: the answer is a secret's value, typed hidden (DRV-05).
Secret bool
}
TaskRequest is a background task's approval request or question, waiting for one of its session's people to answer (spec_032_background_agents BGA-41).
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 ¶
ToolResult is what a tool returned.
type Totals ¶ added in v0.9.2
Totals is a ledger summed: the whole, by model and by purpose, each sorted by cost, highest first (spec_056 CA-121).
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 TurnBackend ¶ added in v1.2.0
type TurnBackend interface {
// Turns.
Run(ctx context.Context, sessionID string, t Turn, on func(Event)) (TurnResult, error)
Steer(ctx context.Context, sessionID, text string) error
}
TurnBackend handles executing turns and steering active turns.
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 ¶
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
// Reasoning is the thinking tokens among Output, where the provider
// reports them apart.
Reasoning int64 `json:"reasoning,omitempty"`
// Unpriced counts the calls whose model had no price: CostUSD is the
// others', and only these calls' cost is unknown (spec_056 CA-121).
Unpriced int `json:"unpriced,omitempty"`
// 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.
type UserPromptFunc ¶
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 ¶
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.
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
// RunsOn is "here", or "service" when the organization's service runs
// it and this computer doesn't (spec_053_enterprise EN-40).
RunsOn string
// OnRequest is what a run does when it needs more than it may do:
// "refuse", or "pause" for its owner's answer; "" for where it runs's
// default (refuse here, pause on the service; EN-43).
OnRequest string
// Merge is where a run on the service leaves its changes: "main" (on
// main too when they merge cleanly) or "never" (on its branch only).
Merge 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"
RunsOn string // "", "here" or "service" (spec_053_enterprise EN-40)
OnRequest string // "", "refuse" or "pause" (EN-43)
Merge string // "", "main" or "never" (blitz-enterprise JB-10)
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.