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 ¶
- Variables
- func InitPrompt() string
- func IsLimit(err error) bool
- type ActionKind
- type AgentInfo
- type AgentTools
- type Approval
- type ApprovalRequest
- type Approver
- type Backend
- type BlockedError
- type Checkpoint
- type CommandInfo
- type CompactResult
- type ContextInfo
- type Decision
- type Env
- type EnvError
- type Event
- type InvalidSettingError
- type Limits
- type Link
- type LocaleChange
- type LocaleInfo
- type MCPOffer
- type MCPServer
- type Message
- type ModelInfo
- type ModelSettingsChange
- type ModelSettingsInfo
- type PermissionChange
- type PermissionMode
- type PermissionRule
- type PinResult
- type ProcessInfo
- type Processes
- type PruneResult
- type Refusal
- type ResumeError
- type RewindMode
- type RewindPoint
- type RewindResult
- type Run
- type RunStatus
- type Saved
- type SessionInfo
- type Setting
- type Settings
- type SkillInfo
- type SkillScript
- type SkillTool
- type State
- type Task
- type Text
- type ToolCall
- type ToolInfo
- type ToolResult
- type Turn
- type TurnResult
- type UndoResult
- type UnknownAgentError
- type UnknownSettingError
- type Usage
- type UserPromptFunc
- type WebSearch
- type WorkerInfo
Constants ¶
This section is empty.
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 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 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 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 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 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 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 ErrRunInProgress = errors.New("the worker is already running")
ErrRunInProgress reports a run of a worker that is already running.
var ErrScriptsDisabled = errors.New("skill scripts are disabled")
ErrScriptsDisabled reports that skill scripts (and so their environments) are turned off.
var ErrSnapshotNameTaken = errors.New("a snapshot with this name already exists")
ErrSnapshotNameTaken is returned by Snapshot when another snapshot has the name.
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 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 ErrUnknownWorker = errors.New("no such worker")
ErrUnknownWorker reports a worker name the workspace doesn't define.
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, ModePlan, ModeDontAsk, ModeBypass}
Modes are the permission modes in Shift+Tab order; bypass is last and is only offered when the session started in it.
var RewindModes = []RewindMode{RewindBoth, RewindConversation, RewindCode, RewindSummarizeFrom, RewindSummarizeUpTo}
RewindModes are the modes, in the order offered.
Functions ¶
func InitPrompt ¶
func InitPrompt() string
InitPrompt asks the agent to write or update BLITZ.md, the project's instructions for future sessions (/init, blitz init).
Types ¶
type ActionKind ¶
type ActionKind string
ActionKind classifies a sensitive tool action for approval purposes.
const ( ActionCommand ActionKind = "run_command" // shell commands and forged tool execution ActionWrite ActionKind = "write_file" // file creation and edits ActionDelete ActionKind = "delete_file" // file deletion ActionNetwork ActionKind = "network" // outbound web requests ActionMCP ActionKind = "mcp_tool" // tools served by MCP servers )
type AgentInfo ¶
type AgentInfo struct {
Name string
DisplayName string
Description string
Active bool
// PinnedModel is the model the agent is pinned to ("" when it runs on
// the configured model).
PinnedModel string
}
AgentInfo describes an agent.
type AgentTools ¶
AgentTools is what an agent can use.
type Approval ¶
type Approval struct {
// Key identifies the approval, for RevokeApprovals.
Key string
// Kind is what it allows: "cmd" (a shell command), "write", "delete",
// "web" (a host), "mcp" (an MCP tool), "uc-run" (a forged tool), or
// another kind a newer version added.
Kind string
// Subject is the command, path, host or tool.
Subject string
// Dir is the workspace a command approval is limited to ("" if any).
Dir string
// Always: saved for future sessions (Added says when); otherwise it
// lasts until this process exits.
Always bool
Added time.Time
}
Approval is a standing permission: actions it covers run without asking.
type ApprovalRequest ¶
type ApprovalRequest struct {
Tool string
Kind ActionKind
Detail string
// Diff is a unified diff of the proposed file changes, if any.
Diff string
// Key identifies what "allow for this session" / "always allow" covers,
// e.g. an exact command or all edits in a workspace. Empty means the
// approval can only be given once.
Key string
// KeyLabel describes Key for the user ("this exact command").
KeyLabel string
// Targets are what the action is on, for policies that match them (a
// worker's permissions): workspace-relative paths for file changes (a
// patch may touch several), the command, the URL's host, the search
// provider, or the MCP tool as "server:tool". Empty when nothing can
// match, which such policies refuse.
Targets []string
// MustAsk: an ask rule covers the action, so the user is asked even
// when a mode, an allow rule or a remembered approval would let it
// through (and refused where nobody can be asked).
MustAsk bool
}
ApprovalRequest describes an action awaiting user approval.
type Approver ¶
type Approver func(ctx context.Context, req ApprovalRequest) (Decision, error)
Approver asks the user to decide on a sensitive action.
type Backend ¶
type Backend interface {
// Dir is the workspace directory.
Dir() string
// ModelErr is why the configured model couldn't be built (nil if it
// could); the workspace then runs on a placeholder.
ModelErr() error
// SetUI routes the agent's approval requests and questions to the
// front end.
SetUI(approve Approver, ask UserPromptFunc)
// Processes are the background processes to account for when the front
// end exits; nil when they don't belong to it (a remote workspace).
Processes() Processes
// AuditShell records a command the user ran directly (!cmd), with why
// it didn't start if it didn't.
AuditShell(command string, exitCode int, startErr error)
// ImagesEnabled reports whether images can be attached.
ImagesEnabled() bool
Close() error
// Turns.
Run(ctx context.Context, sessionID string, t Turn, on func(Event)) (TurnResult, error)
Steer(ctx context.Context, sessionID, text string) error
// Sessions.
OpenSession(resume string, cont bool) (SessionInfo, bool, error)
ActiveSession() (SessionInfo, bool)
ListSessions(all bool) ([]SessionInfo, error)
NewSession() (SessionInfo, error)
LoadSession(ref string) (SessionInfo, bool, error)
SaveSnapshot(name string, force bool) (SessionInfo, error)
RenameSession(title string) (SessionInfo, error)
// Agents, models and settings.
ListAgents() []AgentInfo
ActiveAgent() AgentInfo
SetAgent(ctx context.Context, name string) (AgentInfo, error)
Model() ModelInfo
SetModel(ctx context.Context, ref string) (string, error)
PinModel(ctx context.Context, agent, ref string) (PinResult, error)
Unpin(ctx context.Context, agent string) (PinResult, error)
AllModelSettings() map[string]config.ModelSettings
ModelSettings(ref string) (ModelSettingsInfo, error)
UpdateModelSettings(ref string, reset bool, changes []Setting) (ModelSettingsChange, error)
Settings() Settings
Set(ctx context.Context, key, value string) (string, error)
SetPermissionMode(mode string) (string, error)
ListPermissionRules() []PermissionRule
AddPermissionRule(effect, rule string, save bool) (PermissionChange, error)
RemovePermissionRule(rule string, save bool) (PermissionChange, error)
// Skills, environments, MCP and tools.
ListSkills() []SkillInfo
SearchSkills(query string) []SkillInfo
Skill(name string) (SkillInfo, bool)
ListEnvs() ([]Env, error)
RemoveEnv(key string) error
PruneEnvs() (PruneResult, error)
ListMCPServers() []MCPServer
ListCommands() []CommandInfo
ActiveAgentTools() AgentTools
// Context, memory and language.
SessionUsage() (Usage, error)
Context() (ContextInfo, error)
Compact(ctx context.Context, focus string) (CompactResult, error)
MemoryFiles() []string
ReloadMemory(ctx context.Context) ([]string, error)
AddMemory(ctx context.Context, text string) (string, error)
AvailableLocales() ([]LocaleInfo, string)
SetLocale(ctx context.Context, input string) (LocaleChange, error)
SandboxSummary() []string
// Checkpoints and approvals.
ListCheckpoints() []Checkpoint
Undo(force bool) (UndoResult, error)
RewindPoints() ([]RewindPoint, error)
Rewind(ctx context.Context, index int, mode RewindMode, force bool) (RewindResult, error)
SessionDiff() string
GitDiff(ctx context.Context, color bool) (string, error)
ListApprovals() []Approval
RevokeApprovals(keys ...string) int
ClearApprovals() int
// Images and search.
LoadImage(path string) (*images.Image, error)
AddImage(name string, data []byte) (*images.Image, error)
LoadAttachments(paths []string, prompt string, warn func(string)) ([]*images.Image, error)
SearchProvider() (string, error)
SearchWeb(ctx context.Context, terms string) (WebSearch, error)
SearchSession(terms string) (int, string)
}
Backend is what a front end drives: a *Workspace in this process, or a workspace held by the Blitz service (through the client). Front ends use nothing else, so they work the same either way.
type BlockedError ¶
type BlockedError struct{ Reason string }
BlockedError reports a prompt refused by a prompt_submit hook. Nothing was recorded or sent.
func (*BlockedError) Error ¶
func (e *BlockedError) Error() string
Error says a prompt_submit hook blocked the prompt, and why.
type Checkpoint ¶
type Checkpoint struct {
ID int
Label string // the prompt that started the turn, shortened
Time time.Time
Files []string
}
Checkpoint is the files one turn changed, which Undo restores.
type CommandInfo ¶
type CommandInfo struct {
Name string
Description string
ArgumentHint string
Source string // project, user, bundled, skill
}
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 ContextInfo ¶
type ContextInfo struct {
Tokens int64 // the latest prompt's size
// AutoCompact: the context is compacted when it passes Threshold
// tokens, keeping the last Keep events.
AutoCompact bool
Threshold int
Keep int
}
ContextInfo is the size of the model's context and when it is compacted.
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 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
}
Event is something that happened during a turn. Exactly one of Text, ToolCall and ToolResult is set. Events arrive in order.
type InvalidSettingError ¶
type InvalidSettingError struct{ Err error }
InvalidSettingError reports a setting that can't be applied: an unknown key or a value out of range.
func (*InvalidSettingError) Error ¶
func (e *InvalidSettingError) Error() string
Error is the reason the value was refused.
func (*InvalidSettingError) Unwrap ¶
func (e *InvalidSettingError) Unwrap() error
Unwrap returns the reason, for errors.Is and errors.As.
type Limits ¶
type Limits struct {
MaxTurns int `yaml:"max_turns"`
MaxCostUSD float64 `yaml:"max_cost_usd"`
Timeout time.Duration `yaml:"-"`
TimeoutRaw string `yaml:"timeout"`
}
Limits bound one run. Every run has them: the host policy fills in what a worker leaves out.
type Link ¶
type Link struct{ Title, URL string }
Link is a web search result the agent is asked to read.
type LocaleChange ¶
type LocaleChange struct {
Tag string
NativeName string // e.g. "Español"
LanguageName string // in the new language's terms, e.g. "español"
// HasCatalog: the interface is translated; otherwise only the model's
// replies are in the language.
HasCatalog bool
Saved Saved
}
LocaleChange describes the interface language after SetLocale.
type LocaleInfo ¶
type LocaleInfo struct{ Tag, Name string }
LocaleInfo names an interface language with a catalog.
type MCPOffer ¶
type MCPOffer struct {
Server string
Tools []string // the tools offered; empty means all of them
Prefix string // prepended to tool names ("" for none)
}
MCPOffer is an MCP server offered to an agent.
type MCPServer ¶
type MCPServer struct {
Name string
// Target is its URL, or the command that starts it.
Target string
AutoApprove bool
}
MCPServer is a configured MCP server.
type Message ¶
type Message struct {
Role string // "user" or "model"
Text string
Time time.Time
// Kind tells user messages apart: "" for a prompt (a rewind point),
// "steer", "hook" (a stop hook's request) or "plan" (an approved
// plan's go-ahead).
Kind string
}
Message is one message in a session's transcript.
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 PermissionChange ¶
type PermissionChange struct {
Rule string // canonical form
Removed int // RemovePermissionRule: how many rules went
// NextStart: the rule is saved but only applies from the next start
// (read rules become blocked paths, which are fixed at start).
NextStart bool
Saved Saved // empty unless saving was asked for
}
PermissionChange is what AddPermissionRule or RemovePermissionRule did.
type PermissionMode ¶
type PermissionMode string
PermissionMode decides which actions run without asking.
const ( // ModeDefault asks for every sensitive action not covered by a rule. ModeDefault PermissionMode = "default" // ModeAcceptEdits runs file creates, edits and deletes inside the // writable roots without asking; commands and the rest ask as usual. ModeAcceptEdits PermissionMode = "accept-edits" // ModePlan refuses every tool that could change something, for every // prompt, until the mode changes (applied by the workspace). ModePlan PermissionMode = "plan" // ModeDontAsk denies whatever would ask: only rules and saved // approvals let actions through (for CI and scripts). ModeDontAsk PermissionMode = "dont-ask" // ModeBypass asks for nothing. Deny rules, blocked paths and the // sandboxes still apply, and the registry allows it only while the // OS sandbox is active. ModeBypass PermissionMode = "bypass" )
func ParsePermissionMode ¶
func ParsePermissionMode(s string) (PermissionMode, error)
ParsePermissionMode reads a mode name, accepting Claude Code's spellings (acceptEdits, dontAsk, bypassPermissions) too.
type PermissionRule ¶
type PermissionRule struct {
Effect string // allow, ask or deny
Rule string // kind(pattern), or a tool name
Source string // config, session
}
PermissionRule is an allow, ask or deny rule in force.
type ProcessInfo ¶
type ProcessInfo struct {
ID int `json:"id"`
Command string `json:"command"`
Running bool `json:"running"`
ExitCode int `json:"exit_code"`
RuntimeMs int64 `json:"runtime_ms"`
}
ProcessInfo is a snapshot of a background process's status.
type Processes ¶
type Processes interface {
Running() []ProcessInfo
WaitAll(ctx context.Context) error
Shutdown()
}
Processes are a workspace's background processes, as a front end sees them when it exits: which still run, waiting for them, or stopping them.
type PruneResult ¶
PruneResult is what PruneEnvs removed.
type Refusal ¶
type Refusal struct {
Tool string `json:"tool"`
Kind ActionKind `json:"kind"`
Detail string `json:"detail"`
Time time.Time `json:"time"`
}
Refusal is an action a run wasn't permitted.
type ResumeError ¶
type ResumeError struct{ Err error }
ResumeError reports a session that can't be resumed: none is saved for this workspace, or no session has the given ID or snapshot name.
func (*ResumeError) Error ¶
func (e *ResumeError) Error() string
Error is why the session couldn't be resumed.
func (*ResumeError) Unwrap ¶
func (e *ResumeError) Unwrap() error
Unwrap returns that reason, for errors.Is and errors.As.
type RewindMode ¶
type RewindMode string
RewindMode is what a rewind restores.
const ( RewindBoth RewindMode = "both" // files and conversation RewindConversation RewindMode = "conversation" // conversation only; files stay RewindCode RewindMode = "code" // files only; conversation stays RewindSummarizeFrom RewindMode = "summarize_from" // summarize the prompt and everything after RewindSummarizeUpTo RewindMode = "summarize_up_to" // summarize everything before the prompt )
type RewindPoint ¶
type RewindPoint struct {
// Index is the prompt's position in the transcript.
Index int
Text string
Time time.Time
// Files are what the agent changed from this prompt until the next
// (what rewinding the code to it restores, with later prompts' files).
Files []string
// Conversation reports whether the conversation can be rewound to it
// (prompts recorded by older versions can't be).
Conversation bool
}
RewindPoint is a prompt the session can be rewound to.
type RewindResult ¶
type RewindResult struct {
Mode RewindMode
// Restored are the files put back (code).
Restored []string
// Prompt is the rewound prompt's text, to edit and send again
// (conversation).
Prompt string
// Compacted is the summary's result (summarize modes).
Compacted CompactResult
}
RewindResult is what a rewind did.
type Run ¶
type Run struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Worker string `json:"worker"`
Hash string `json:"hash"`
Status RunStatus `json:"status"`
// Manual: started on request, not by the schedule.
Manual bool `json:"manual,omitempty"`
Started time.Time `json:"started"`
Duration time.Duration `json:"duration"`
CostUSD float64 `json:"cost_usd"`
Calls int `json:"calls"`
SessionID string `json:"session_id,omitempty"`
Refusals []Refusal `json:"refusals,omitempty"`
// Error is why the run failed or stopped.
Error string `json:"error,omitempty"`
}
Run is one run of a worker.
type RunStatus ¶
type RunStatus string
RunStatus is where a run stands.
const ( RunRunning RunStatus = "running" RunSucceeded RunStatus = "succeeded" RunFailed RunStatus = "failed" // RunLimited: stopped at a limit (turns, cost or time). RunLimited RunStatus = "limited" // RunSkipped: not started, because the previous run was still going. RunSkipped RunStatus = "skipped" )
Where a run stands. Running is while it runs; the others are how it ended.
type Saved ¶
Saved reports where a change was written in the config file. The change applies either way; Err is why it wasn't saved.
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
MessageCount int
Created time.Time
Updated time.Time
// Messages are filled in for the active session and for sessions
// opened by OpenSession or LoadSession; lists leave them out.
Messages []Message
}
SessionInfo describes a saved session.
type Setting ¶
type Setting struct{ Key, Value string }
Setting is one key=value change; an empty Value clears the key.
type Settings ¶
type Settings struct {
Agency string
Model ModelInfo
Agent string
Locale string // the language the model replies in
// PermissionMode decides which actions run without asking (a
// PermissionMode).
PermissionMode string
// Effort is the session's reasoning effort ("" when each model uses its
// own reasoning_effort or its default).
Effort string
}
Settings are the values /set changes, plus the model, agent and locale.
type SkillInfo ¶
type SkillInfo struct {
Name string
Description string
Version string
License string
Category string
Compatibility string
Tags []string
// Hash identifies the skill's content, for pinning it in the policy
// ("" if it couldn't be computed).
Hash string
// Tools are the tools the skill says it needs, and why.
Tools []SkillTool
// Scripts are the skill's scripts and whether each may run.
Scripts []SkillScript
// Tier is the approval tier the scripts run at ("" without scripts);
// Bypass means the skill may skip approvals (tier 0) and the policy
// allows it.
Tier string
Bypass bool
// Network: the scripts may use the network. NeedsNetwork: the skill
// asks for it (granted or not).
Network bool
NeedsNetwork bool
// Env are the host environment variables passed to the scripts;
// Withheld are the ones the skill asked for that the policy keeps back.
Env, Withheld []string
// Blocked are reasons none of the scripts may run.
Blocked []string
}
SkillInfo describes a skill and what the skills policy lets it do.
type SkillScript ¶
type SkillScript struct {
Name string
Language string
Source string // its path in the skill, or "inline"
Timeout time.Duration
Deps []string
Allowed bool
Reasons []string // why it may not run
}
SkillScript is one of a skill's scripts and the policy's verdict on it.
type State ¶
type State string
State is whether a worker may run.
const ( // StateNew: found but never enabled. StateNew State = "new" // StateEnabled: enabled at its current hash; it runs on schedule. StateEnabled State = "enabled" // StateDisabled: turned off. StateDisabled State = "disabled" // StateChanged: enabled at an older hash; the files changed since, so // it doesn't run until re-enabled. StateChanged State = "changed" // StateInvalid: WORKER.md can't be used. StateInvalid State = "invalid" )
type Text ¶
type Text struct {
Text string
Partial bool
// Repeat marks final text whose partial chunks were already delivered.
Repeat bool
// Thought is the model's reasoning rather than its answer; front ends
// may show it or not, and the transcript leaves it out.
Thought bool
}
Text is model output. With streaming, partial chunks arrive first and a final event then repeats their text in full (Repeat); without streaming only final events arrive. To show text once, show partial chunks and final text that isn't a Repeat. The transcript keeps final text only.
type ToolCall ¶
type ToolCall struct {
ID string // matches the ToolResult
Name string
Args map[string]any
// Partial: the call arrived in a streamed chunk, and the final event
// repeats it.
Partial bool
}
ToolCall is the agent calling a tool.
type ToolInfo ¶
type ToolInfo struct {
Name string
Description string
// PlanAllowed: the tool stays available in plan mode, which refuses
// tools that change anything.
PlanAllowed bool
}
ToolInfo is a tool an agent can call.
type ToolResult ¶
ToolResult is what a tool returned.
type Turn ¶
type Turn struct {
// Text is what the user typed. prompt_submit hooks see it and the
// transcript records it.
Text string
// Prompt, if set, is sent to the agent instead of Text (e.g. /search
// sends the fetched results, and the transcript records the command).
Prompt string
// Plan: Text is a goal to plan for. Tools that change anything are
// refused for the whole turn, and the transcript
// records "/plan <Text>".
Plan bool
// ReadOnly names a mode that refuses the same tools as plan mode.
ReadOnly string
// Aside: a /btw question, answered in a throwaway copy of the session
// and recorded nowhere. It takes no images, starts no checkpoint and
// leaves queued steer messages alone.
Aside bool
// Accepted: Text already passed prompt_submit hooks and was recorded (a
// steer message that arrived too late to be read mid-turn).
Accepted bool
// Command: Text is a custom slash command ("/name args"), expanded into
// its prompt with its agent, model, tools and plan mode; the
// transcript records Text.
Command bool
// Images are sent with the prompt.
Images []*images.Image
// MaxTurns limits the model calls in the turn (0: unlimited).
MaxTurns int
// MaxCostUSD stops the turn once it has cost more than this (0:
// unlimited); it can only be enforced when the model has a price.
MaxCostUSD float64
// Timeout stops the turn after this long (0: unlimited).
Timeout time.Duration
// FetchGrants are URLs the agent may fetch in this turn without asking
// (the pages a web search handed it).
FetchGrants []string
// OnAccepted, if set, runs once the prompt has passed prompt_submit
// hooks and been recorded, just before it is sent.
OnAccepted func()
// OnFinished, if set, runs when the agent has stopped, before unread
// steer messages are collected: a front end still taking a steer message
// finishes here, so the message ends up in TurnResult.Leftover.
OnFinished func()
}
Turn is one prompt for the agent.
type TurnResult ¶
type TurnResult struct {
// Output is the model's final text (partial and thought text excluded).
Output string
// Before and After are the session's usage around the turn.
Before, After Usage
// Leftover are steer messages sent after the model's last tool call, so
// never read. Front ends send them as the next turn (with Accepted set)
// or, if the turn was interrupted, drop them.
Leftover []string
}
TurnResult describes a finished turn.
type UndoResult ¶
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
Input int64 // prompt tokens, including cached
Cached int64
CacheWrite int64 // prompt tokens written to the cache (part of Input)
Output int64 // candidates + thinking tokens
LastPrompt int64 // prompt size of the latest call: the current context size
CostUSD float64
Priced bool // false if any call's model had no price
}
Usage accumulates token counts and estimated cost.
type UserPromptFunc ¶
UserPromptFunc asks the user a question and returns the answer.
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
// CatchUp is "once" when a run missed while nothing was running should
// happen as soon as possible, otherwise "none".
CatchUp string
// Permissions and Limits are what the worker gets after the host
// policy.
Permissions []string
Limits Limits
// Problems say why the worker is invalid, or what the policy changed.
Problems []string
}
WorkerInfo describes a worker and whether it may run.