harness

package
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Bridge between the agent framework and a Bubble Tea program, turning callbacks into messages and prompts into answers

Index

Constants

View Source
const (
	ProjectDir  = ".icebath"
	ConfigFile  = "config.json"
	RulesFile   = "rules.json"
	HooksFile   = "hooks.json"
	SessionsDir = "sessions"
	// Directory under the user configuration directory holding the state each project keeps between runs
	ProjectsDir = "projects"
)

Name of the project directory and of the files inside it and the user configuration directory

View Source
const (
	ProfileEnv = "ICEBATH_PROFILE"
	ModelEnv   = "ICEBATH_MODEL"
)

Environment variables that override the chosen profile and model

View Source
const DefaultCompactShare = 0.7

Share of the model context window at which compaction runs when compact_threshold is unset

View Source
const DefaultPruneAfter = 10

Assistant turns a tool result stays in requests when prune_after is unset

View Source
const DefaultScrollback = 10000

Rows a terminal window keeps above its screen unless configured

View Source
const KindsDir = "kinds"

Directory under a configuration directory holding one kind per JSON file

View Source
const NoKind = "none"

Name that stands for no kind wherever a kind is chosen

View Source
const NoteKind = "note"

Record kind of a note a workflow wrote into a session for the person

Variables

View Source
var ErrClosed = errors.New("harness: approver closed")

Error an ask returns once the approver was closed

View Source
var ErrNoProfile = errors.New("harness: no profile is open, pick one in config or pass -profile")

Error of a run or an open while nothing names a profile

View Source
var ErrQuestionsClosed = errors.New("harness: questioner closed")

Error an ask returns once the questioner was closed

Scopes a new entry may be written to, the project first

Functions

func Base

func Base(configured string) string

Conduct followed by any configured instructions, the base every session starts from

func CheckMatcher

func CheckMatcher(m string) error

Checks that a matcher compiles as a regular expression

func Compose

func Compose(blocks ...string) string

System prompt of blocks separated by blank lines, empty ones left out

func Environment

func Environment(f Facts) string

Facts about the machine and session the client adds after the base

func NewestSession

func NewestSession(ctx context.Context, store *session.Store, root string) (string, error)

Id of the newest stored session of the project that no other icebath has open, sub-agent sessions left out

func ParseSetting

func ParseSetting(s string) (string, string, error)

Parses a numeric or bare value for a setting override such as max_tokens=4096

func RegisterHook

func RegisterHook(build func(AgentInfo) agent.Hook) error

Adds a hook every agent built later runs with, built per agent

func RegisterKind

func RegisterKind(k Kind) error

Makes a kind available to every app built later, refusing an invalid or duplicate one

func RegisterPrompt

func RegisterPrompt(fragment func(ctx context.Context, a *App, ep Endpoint) string) error

Adds text to the system prompt of every run, composed per turn and left out when empty

func RegisterSetting

func RegisterSetting(s Setting) error

Makes a setting known to the configuration, refusing a built in key, an invalid default or a duplicate

func RegisterTools

func RegisterTools(build func(a *App) ([]tool.Tool, error)) error

Adds tools every app built later offers, built once the app stands

func RegisterWorkflow

func RegisterWorkflow(w Workflow) error

Makes a workflow available as a command, refusing an invalid or duplicate one

func RunFrom

func RunFrom(ctx context.Context) string

Run id carried by the context, empty when none was set

func Save

func Save(dir string, sources []string, fields ...Field) error

Writes each value into every file setting it, else the user file, and removes unset ones from every file

func ScratchDir

func ScratchDir(sessionID string) string

Directory under the system temp directory a session may fill with working notes and temporary files

func StatePath

func StatePath(root string) (string, error)

Directory a project keeps its state in between runs, named after the root with a digest of the full path so two projects sharing a base name stay apart

func WithRun

func WithRun(ctx context.Context, id string) context.Context

Carries the run id so tools and askers can name the run they serve

Types

type AgentInfo

type AgentInfo struct {
	Name     string
	Session  *session.Session
	Endpoint Endpoint
	Kind     Kind
	App      *App
}

Agent being built, as hook builders see it

type Answer added in v1.0.12

type Answer struct {
	Picked   []string `json:"picked,omitempty"`
	Text     string   `json:"text,omitempty"`
	Declined bool     `json:"declined,omitempty"`
}

Answer the person gave one question, the labels picked or the text typed, declined when they gave neither

func (Answer) Given added in v1.0.12

func (a Answer) Given() bool

Reports whether the answer carries something the asker can read

func (Answer) String added in v1.0.12

func (a Answer) String() string

Answer as one line, the labels picked and the text typed, or the refusal

type App

type App struct {
	Config    Config
	Root      string
	Primary   Endpoint
	Tools     *tool.Registry
	Shell     *shell.Shell
	Files     files.Options
	Rules     *policy.Rules
	Mode      *policy.ModeSwitch
	Memory    *policy.Memory
	Gate      policy.Gate
	Approver  *Approver
	Questions *Questioner
	Pump      *Pump
	Meter     *Meter
	MCP       *MCP
	Facts     *facts.Store
	Missions  *mission.Store
	Subagents *agent.Subagents
	Store     *session.Store
	Session   *session.Session
	Control   *Controller
	Saver     *Saver
	Flows     *Flows
	System    string
	// Profiles the profile files hold, in file order
	Profiles []Instance
	// Working directory the configuration was discovered under
	Dir string
	// contains filtered or unexported fields
}

Everything built from a configuration, shared by the terminal app and the headless runner

func Build

func Build(ctx context.Context, cfg Config, send Sender, opts BuildOptions) (*App, error)

Opens providers, tools, policy, stores and the bridge from the configuration

func (*App) AddHook

func (a *App) AddHook(scope Scope, e HookEntry) error

Adds a hook to the hooks file of the scope

func (*App) AddRule

func (a *App) AddRule(scope Scope, d policy.Decision, rule string) error

Adds a rule to the rules file of the scope

func (*App) Announce added in v1.0.11

func (a *App) Announce(msg any)

Posts a message into the program for an extension that mirrors the live sessions

func (*App) Busy

func (a *App) Busy(l *Live) bool

Reports whether a root run goes on the open session

func (*App) Close

func (a *App) Close(ctx context.Context) error

Stops runs, closes servers and the shell, saves every open session and fires the SessionEnd hooks

func (*App) CloseServer

func (a *App) CloseServer(name string) error

Closes and forgets the server when it is open, waiting for it to exit

func (*App) Create

func (a *App) Create() (*Live, error)

Opens a fresh session on the default endpoint beside the ones already open

func (*App) CreateKind

func (a *App) CreateKind(ctx context.Context, name string) (*Live, error)

Opens a fresh session of the kind beside the ones already open, on the endpoint the kind names or the default

func (*App) CreateOn

func (a *App) CreateOn(ep Endpoint, kind string) (*Live, error)

Opens a fresh session on an opened endpoint beside the ones already open, running as the kind when the app knows it and as none otherwise

func (*App) Current

func (a *App) Current() *Live

Open session the app works on

func (*App) DefaultBase

func (a *App) DefaultBase() string

Base prompt every session starts from, the conduct and the configured instructions

func (*App) EndpointNamed

func (a *App) EndpointNamed(ctx context.Context, profile, model string) (Endpoint, error)

Endpoint of a profile by name with the model, the default for an empty or unknown name and the default with its model swapped for the name of the default profile

func (*App) EnvironmentFor

func (a *App) EnvironmentFor(ctx context.Context, model string) (string, error)

Environment block the client adds for a run on the model as the machine stands now

func (*App) FactsFor

func (a *App) FactsFor(ctx context.Context) *facts.Store

Facts store the calling run records into, the selected one outside a run

func (*App) FindProfile

func (a *App) FindProfile(name string) (profiles.Profile, bool)

Profile by name, a written one before the built in one it may shadow

func (*App) Fork

func (a *App) Fork(l *Live, n int) (*Live, error)

Opens a fork of an open session cut at n entries on the same endpoint and writes it to the store

func (*App) ForkStored

func (a *App) ForkStored(ctx context.Context, id string) (*Live, error)

Opens a full fork of a stored session, the open one when it is open here, without taking the source from another process

func (*App) Ghosted

func (a *App) Ghosted(s *session.Session) bool

Reports whether the session stays off disk, by the ghost of its profile or of the session it serves

func (*App) HookEntries

func (a *App) HookEntries() ([]HookEntry, error)

Every hook the configuration files hold, in read order and event order

func (*App) Instances

func (a *App) Instances() []Instance

Written profiles in file order

func (*App) Kind

func (a *App) Kind(name string) (Kind, bool)

Kind by name

func (*App) KindOf

func (a *App) KindOf(sess *session.Session) (Kind, bool)

Kind the session runs as, false while it runs as none or as one the app no longer knows

func (*App) Kinds

func (a *App) Kinds() []Kind

Kinds the app knows, sorted by name

func (*App) LiveByID

func (a *App) LiveByID(id string) *Live

Open session with the id, nil when it is not open

func (*App) LiveOf

func (a *App) LiveOf(sess *session.Session) *Live

Open session wrapping sess, nil when it is not open

func (*App) LiveOfRun

func (a *App) LiveOfRun(id string) *Live

Open session a run serves, found through the root of a child run

func (*App) Lives

func (a *App) Lives() []*Live

Open sessions in open order

func (*App) MissionsFor

func (a *App) MissionsFor(ctx context.Context) *mission.Store

Mission store the calling run plans into, the selected one outside a run

func (*App) MoveProfile

func (a *App) MoveProfile(name string, delta int) error

Moves a written profile delta places through its file

func (*App) NewAgent

func (a *App) NewAgent(name string, sess *session.Session) (*agent.Agent, error)

Builds an agent on the session with every configured hook, the endpoint of the session and the shared gate

func (*App) Open

func (a *App) Open(ctx context.Context, id string) (*Live, error)

Opens a stored session beside the ones already open, returning the open one when it already is

func (*App) OpenEndpoint

func (a *App) OpenEndpoint(ctx context.Context, name, model string) (Endpoint, error)

Opens a profile as an endpoint without changing the app, usable off the event loop

func (*App) ProfileInUse

func (a *App) ProfileInUse(name string) bool

Reports whether the profile is the default or any open session runs on it

func (*App) ProjectInstructions

func (a *App) ProjectInstructions() string

func (*App) PromptFor

func (a *App) PromptFor(ctx context.Context, ep Endpoint, kind Kind) (string, error)

Prompt of a run on the endpoint as the kind, the kind, profile or built in base, the environment unless left out, then every registered fragment

func (*App) PutKind added in v1.0.11

func (a *App) PutKind(k Kind) error

Replaces the kind of the same name or adds it, so runs started from now on follow it, refusing an invalid one

func (*App) Release

func (a *App) Release(l *Live) error

Writes an open session that holds anything, gives its lease back and forgets it, selecting another when it was the selected one

func (*App) ReloadHooks

func (a *App) ReloadHooks() error

Reads every hook file again and puts its hooks in force for later runs

func (*App) ReloadProfiles

func (a *App) ReloadProfiles() error

Reads every profile file again

func (*App) ReloadRules

func (a *App) ReloadRules() error

Reads every rule file again and puts its rules in force

func (*App) RemoveHook

func (a *App) RemoveHook(e HookEntry) error

Deletes a hook from the file holding it

func (*App) RemoveProfile

func (a *App) RemoveProfile(name string) error

Deletes a written profile, refusing one in use

func (*App) RemoveRule

func (a *App) RemoveRule(e RuleEntry) error

Deletes a rule from the file holding it

func (*App) RemoveServer

func (a *App) RemoveServer(name string) error

Deletes a server from every file configuring it, leaving the close to CloseServer

func (*App) ReplaceHook

func (a *App) ReplaceHook(old, e HookEntry) error

Replaces a hook in the file holding it

func (*App) ReplaceRule

func (a *App) ReplaceRule(old RuleEntry, d policy.Decision, rule string) error

Replaces a rule in the file holding it

func (*App) RestartServer

func (a *App) RestartServer(ctx context.Context, old string, cfg ServerConfig) error

Closes the server named old and opens it under cfg unless turned off, blocking while the old one exits

func (*App) RuleEntries

func (a *App) RuleEntries() ([]RuleEntry, error)

Every rule the configuration files hold, in read order

func (*App) Run

func (a *App) Run(ctx context.Context, missionID string, input []protocol.Part) (*Run, error)

Starts a run of a fresh root agent on the app session

func (*App) RunOn

func (a *App) RunOn(ctx context.Context, l *Live, missionID string, input []protocol.Part) (*Run, error)

Starts a run on an open session

func (*App) SaveProfile

func (a *App) SaveProfile(old string, p profiles.Profile) error

Writes a profile over the one named old, or adds it to the user file when old is empty

func (*App) SaveServer

func (a *App) SaveServer(scope Scope, old string, cfg ServerConfig) error

Writes a server over old in its file or into the config file of the scope, without restarting it

func (*App) ScopeOf

func (a *App) ScopeOf(path string) string

Scope a file belongs to, its path when it is neither scope directory

func (*App) ScratchFor

func (a *App) ScratchFor(ctx context.Context) (string, error)

Scratch directory of the calling run's session, created when missing, empty with no session

func (*App) Select

func (a *App) Select(l *Live)

Makes an open session the one hooks, the meter and the headless runner work on

func (*App) ServerEntries

func (a *App) ServerEntries() ([]ServerEntry, error)

Servers the configuration files hold, a later file replacing an earlier namesake in place

func (*App) SessionFor

func (a *App) SessionFor(ctx context.Context) *session.Session

Session of the calling run, the selected one outside a run

func (*App) SessionStart

func (a *App) SessionStart(ctx context.Context, source string) error

Fires the SessionStart hooks

func (*App) SetDefaultEndpoint

func (a *App) SetDefaultEndpoint(name string, ep Endpoint)

Moves new sessions to an opened endpoint

func (*App) SetDefaultModel

func (a *App) SetDefaultModel(id string)

Changes the model new sessions start on

func (*App) SetEndpointOn

func (a *App) SetEndpointOn(ctx context.Context, l *Live, name string, ep Endpoint) error

Moves an open session to an opened endpoint, now the default, forgetting its stored copy when the profile is ghost

func (*App) SetKindOn

func (a *App) SetKindOn(l *Live, name string) error

Makes an open session run as the kind from its next run, an empty name or none returning it to the plain agent

func (*App) SetModelOn

func (a *App) SetModelOn(l *Live, id string)

Changes the model of an open session, moving the default along when the session is on the default profile

func (*App) SetProfileEnabled

func (a *App) SetProfileEnabled(name string, on bool) error

Turns a written profile on or off, refusing to turn off one in use

func (*App) SetServerEnabled

func (a *App) SetServerEnabled(name string, on bool) (ServerConfig, error)

Turns a server on or off in the file configuring it, returning the settings RestartServer opens it under

func (*App) SetToolEnabled

func (a *App) SetToolEnabled(name string, on bool) error

Turns a tool on or off and saves the names turned off

func (*App) Shadowed

func (a *App) Shadowed(name string) bool

Reports whether a written profile carries the name

func (*App) Stuck added in v1.0.11

func (a *App) Stuck() []Stuck

Profiles stuck right now, in name order

func (*App) StuckOf added in v1.0.11

func (a *App) StuckOf(profile string) (Stuck, bool)

Stuck state of a profile, false while its endpoint answers

type ApprovalDoneMsg

type ApprovalDoneMsg struct {
	ID      int
	Run     string
	Verdict policy.Verdict
	Err     error
}

Approval that was answered, cancelled or timed out

type ApprovalMsg

type ApprovalMsg struct {
	Pending *Pending
}

Approval a person must answer

type Approver

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

Asker that posts each request into the program and waits for the answer the program hands back

func NewApprover

func NewApprover(send Sender) *Approver

func (*Approver) Answer

func (a *Approver) Answer(id int, v policy.Verdict) bool

Delivers the answer to a pending approval and reports whether one was waiting

func (*Approver) Ask

func (a *Approver) Ask(ctx context.Context, req policy.Request) (policy.Verdict, error)

Posts the request and blocks until it is answered or the context ends

func (*Approver) Close

func (a *Approver) Close()

Refuses every later ask and denies the ones waiting

func (*Approver) DenyAll

func (a *Approver) DenyAll() int

Answers every pending approval with no

func (*Approver) Len

func (a *Approver) Len() int

func (*Approver) Pending

func (a *Approver) Pending() []*Pending

Approvals waiting, oldest first

type Asking added in v1.0.12

type Asking struct {
	ID        int
	Run       string
	Session   string
	Questions []Question
	Asked     time.Time
	// contains filtered or unexported fields
}

Questions of one tool call waiting on the person

type AttemptMsg

type AttemptMsg struct {
	Attempt   provider.Attempt
	Telemetry Telemetry
}

One provider attempt with the telemetry as it stood afterwards

type BuildOptions

type BuildOptions struct {
	// Session to resume, a new one when empty
	Resume string
	// Working directory of the shell and base of relative paths, the process directory when empty
	Dir string
}

Options a caller passes beside the configuration

type Choice added in v1.0.12

type Choice struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

One answer a question offers

type Compaction

type Compaction struct {
	// Context tokens at which old turns are summarized, unset for the default share of the window and zero to never compact
	Threshold *int `json:"threshold,omitempty"`
	// Messages kept verbatim after the summary
	Keep int `json:"keep,omitempty"`
	// Profile and model writing summaries, the main model when empty
	Model *Target `json:"model,omitempty"`
	// Extra guidance appended to the summary instructions
	Instructions string `json:"instructions,omitempty"`
}

Compaction settings

type Config

type Config struct {
	Profile string `json:"profile,omitempty"`
	Model   string `json:"model,omitempty"`
	// System prompt text, or the file it is read from
	System     string `json:"system,omitempty"`
	SystemFile string `json:"system_file,omitempty"`
	// Permission mode such as default, acceptEdits, plan or bypassPermissions
	Mode        string                     `json:"mode,omitempty"`
	MaxTokens   int                        `json:"max_tokens,omitempty"`
	MaxRounds   int                        `json:"max_rounds,omitempty"`
	Temperature *float64                   `json:"temperature,omitempty"`
	Extra       map[string]json.RawMessage `json:"extra,omitempty"`
	Compaction  Compaction                 `json:"compaction,omitempty"`
	Pruning     Pruning                    `json:"pruning,omitempty"`
	Permissions policy.RuleSet             `json:"permissions,omitempty"`
	Hooks       agent.HookConfig           `json:"hooks,omitempty"`
	MCP         []ServerConfig             `json:"mcp,omitempty"`
	Subagents   Subagents                  `json:"subagents,omitempty"`
	Shell       ShellConfig                `json:"shell,omitempty"`
	Web         WebConfig                  `json:"web,omitempty"`
	Tools       ToolsConfig                `json:"tools,omitempty"`
	UI          UIConfig                   `json:"ui,omitempty"`
	Terminal    TerminalConfig             `json:"terminal,omitempty"`
	// Values of the settings extensions register, by key
	Settings map[string]string `json:"settings,omitempty"`
	// Project root for hooks, rules and servers, the working directory when empty
	Root string `json:"root,omitempty"`
	// Directory sessions are written to, sessions under the configuration directory when empty
	SessionsDir string `json:"sessions_dir,omitempty"`
	// Extra profile lists loaded before the user list
	ProfileFiles []string `json:"profile_files,omitempty"`
	// Catalog files loaded over the built in one
	CatalogFiles []string `json:"catalog_files,omitempty"`
	// Files the configuration was read from, in load order
	Sources []string `json:"-"`
}

Everything the shell app and the headless runner need, read from files, environment and flags

func Discover

func Discover(dir string) (Config, error)

Reads the user configuration, then the project configuration under dir, then the environment, later layers winning

func Merge

func Merge(base, over Config) Config

Lays over onto base, scalars replacing when set and lists joining

func ReadConfig

func ReadConfig(r io.Reader) (Config, error)

Reads one configuration file, ignoring keys it does not know

func ReadConfigFile

func ReadConfigFile(path string) (Config, error)

func (Config) CompactThreshold

func (c Config) CompactThreshold(window int) int

Context tokens at which compaction runs for a model with that window, the default share when unset

func (Config) OptionAsAlt added in v1.0.13

func (c Config) OptionAsAlt() bool

Reports whether characters a Mac Option key types are read as alt chords, on under macOS unless set

func (Config) PruneAfter

func (c Config) PruneAfter() int

Assistant turns a tool result stays in requests, the default when unset

func (*Config) SaveSetting

func (c *Config) SaveSetting(dir, key, value string) error

Applies a setting and saves it so the next start under dir reads the same value

func (Config) SessionsPath

func (c Config) SessionsPath() (string, error)

Directory sessions are stored in, created on demand

func (*Config) Set

func (c *Config) Set(key, value string) error

Applies a KEY=VALUE override to the configuration, an empty value unsetting the setting

func (Config) Setting

func (c Config) Setting(key string) string

Value of an extension setting, empty while unset

func (Config) SystemPrompt

func (c Config) SystemPrompt() (string, error)

System prompt from the inline text or the named file

func (Config) WithEnv

func (c Config) WithEnv() Config

Applies the environment overrides

type Controller

type Controller struct {
	Pump     *Pump
	Saver    *Saver
	Meter    *Meter
	Missions *mission.Store
	// Subagent tool whose children the controller can cancel and steer
	Subagents *agent.Subagents
	// Mission store of a session, the shared one when nil or when it answers nil
	MissionsOf func(*session.Session) *mission.Store
	// Reports whether a session shows thinking, runs on one that does not losing every thinking event before the pump
	Thinking func(*session.Session) bool
	// Hears every root run as it ends, before the program does
	OnEnd func(*Run)
	// contains filtered or unexported fields
}

Starts, steers, interrupts and cancels runs and keeps a registry of them and their children

func NewController

func NewController(send Sender, pump *Pump) *Controller

func (*Controller) Active

func (c *Controller) Active() []*Run

Runs still going, root runs first then children by start time

func (*Controller) Busy

func (c *Controller) Busy() bool

Reports whether any root run is going

func (*Controller) Cancel

func (c *Controller) Cancel(id string) error

Stops the agent at once

func (*Controller) Children

func (c *Controller) Children(id string) []*Run

Children of a run in start order

func (*Controller) Done

func (c *Controller) Done(id string) (<-chan struct{}, bool)

Channel closed when the run ends

func (*Controller) Get

func (c *Controller) Get(id string) (*Run, bool)

func (*Controller) Interrupt

func (c *Controller) Interrupt(id string) error

Asks the agent to stop after the current turn or tool round

func (*Controller) Runs

func (c *Controller) Runs() []*Run

Every run in start order

func (*Controller) Shutdown

func (c *Controller) Shutdown()

Stops every run and waits for them to end

func (*Controller) Start

func (c *Controller) Start(ctx context.Context, a *agent.Agent, missionID string, input []protocol.Part) (*Run, error)

Starts a run of the agent with the input, assigning it to a mission when one is named

func (*Controller) Steer

func (c *Controller) Steer(id string, parts ...protocol.Part) error

Queues input the agent sees at its next turn

type Endpoint

type Endpoint struct {
	Profile  profiles.Profile
	Provider *provider.Provider
	Model    string
	Catalog  profiles.Model
	// Base prompt the profile names, read as the endpoint opened, empty while it names none or the built in one
	System string
}

One endpoint the app opened, with the model it serves

type EventMsg

type EventMsg struct {
	Run   string
	Event agent.Event
}

Agent event of one run, text deltas merged per frame

type FactMsg

type FactMsg struct {
	Session string
	Change  facts.Change
}

Fact store change of one session

type Facts

type Facts struct {
	Dir      string
	Git      bool
	Platform string
	Shell    string
	Date     time.Time
	Model    string
	Mission  bool
	// Directory created for the session to hold working notes and temporary files
	Scratch string
	// Working plan the session keeps while no mission is attached, as the plan tool reports it
	Plan string
}

What the agent is told about the machine and session it runs in

func GatherFacts

func GatherFacts(dir, model string, missionAttached bool, scratch string) Facts

Facts about the machine as it stands, the working directory given by the caller

type Field

type Field struct {
	Path  []string
	Value any
	// Removes the value from every file holding it instead of writing one
	Unset bool
}

One value at a path inside a configuration file

type Flow

type Flow struct {
	ID   string
	Name string
	Arg  string
	App  *App
	// Session the workflow was started from, nil when it started without one
	Live    *Live
	Started time.Time
	// contains filtered or unexported fields
}

One running or finished workflow with what it may do

func (*Flow) Done

func (f *Flow) Done() <-chan struct{}

Channel closed when the workflow ends

func (*Flow) Elapsed

func (f *Flow) Elapsed() time.Duration

Time the workflow has taken so far or took

func (*Flow) Err

func (f *Flow) Err() error

Error the workflow ended with

func (*Flow) Finished

func (f *Flow) Finished() time.Time

Time the workflow ended, zero while it goes

func (*Flow) Interrupt added in v1.0.11

func (f *Flow) Interrupt(r *Run) error

Asks the run to stop after the turn or tool round it is in

func (*Flow) Note added in v1.0.11

func (f *Flow) Note(l *Live, level Level, text string)

Writes a note for the person into the transcript of the session, stored with it and shown at once

func (*Flow) Notify

func (f *Flow) Notify(level Level, text string)

Shows the person a notice, a toast in the terminal and a line when headless

func (*Flow) Open

func (f *Flow) Open(ctx context.Context, kind string) (*Live, error)

Opens a fresh session of the kind, the default kind when empty, and announces it so a card shows it

func (*Flow) Panel added in v1.0.11

func (f *Flow) Panel(key string)

Asks the terminal to open the panel beside the sessions of the workflow

func (*Flow) Running

func (f *Flow) Running() bool

Reports whether the workflow still goes

func (*Flow) SetStatus

func (f *Flow) SetStatus(text string)

Sets the words shown beside the workflow

func (*Flow) Start

func (f *Flow) Start(ctx context.Context, l *Live, missionID string, input []protocol.Part) (*Run, error)

Starts a run on the session with the input, assigning it to a mission when one is named, refusing a session with a run going

func (*Flow) Status

func (f *Flow) Status() string

Words shown beside the workflow, what it is doing now

func (*Flow) Steer

func (f *Flow) Steer(r *Run, parts ...protocol.Part) error

Queues input the run sees at its next turn

func (*Flow) Wait

func (f *Flow) Wait(ctx context.Context, r *Run) (protocol.Response, error)

Waits for a run to end and hands back its final response or error

type FlowDoneMsg

type FlowDoneMsg struct {
	ID       string
	Name     string
	Err      error
	Duration time.Duration
}

Workflow that reached its end

type Flows

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

Starts, lists and stops workflows and keeps a registry of them

func NewFlows

func NewFlows(app *App, send Sender) *Flows

func (*Flows) Active

func (fs *Flows) Active() []*Flow

Workflows still going, in start order

func (*Flows) Cancel

func (fs *Flows) Cancel(id string) error

Stops a workflow and the runs it started

func (*Flows) Get

func (fs *Flows) Get(id string) (*Flow, bool)

func (*Flows) List

func (fs *Flows) List() []*Flow

Every workflow started, in start order

func (*Flows) Restart added in v1.0.12

func (fs *Flows) Restart(ctx context.Context, id string, w Workflow, live *Live, arg string) (*Flow, error)

Starts the workflow again under the id of an ended flow, so it carries on in the workspaces of the first run

func (*Flows) Shutdown

func (fs *Flows) Shutdown()

Stops every workflow and waits for them to end

func (*Flows) Start

func (fs *Flows) Start(ctx context.Context, w Workflow, live *Live, arg string) (*Flow, error)

Starts the workflow in the background from the session, which may be nil, reporting its end as a message

type HookEntry

type HookEntry struct {
	Event   agent.HookEvent
	Matcher string
	Command string
	Timeout int
	Path    string
}

One hook command with the event and matcher it runs for and the file holding it

type HookOutputMsg

type HookOutputMsg struct {
	Run  string
	Text string
}

Hook output that is not part of a verdict, such as plain text a hook printed

type Instance

type Instance struct {
	Profile profiles.Profile
	Written profiles.Profile
	Path    string
}

One profile a profile file holds, with its template applied and as written

type JobMsg

type JobMsg struct {
	Event shell.JobEvent
}

Background shell job change

type Kind

type Kind struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Base prompt sent in place of the built in one
	System string `json:"system,omitempty"`
	// Text appended to the base prompt
	Append string `json:"append,omitempty"`
	// Tool names offered, every tool when empty
	Tools []string `json:"tools,omitempty"`
	// Tool names withheld
	Deny []string `json:"deny,omitempty"`
	// Profile and model sessions created with the kind start on, the default endpoint when nil
	Model *Target `json:"model,omitempty"`
	// Tool rounds one run may take, the configured limit when zero
	MaxRounds int `json:"max_rounds,omitempty"`
	// Output tokens one model turn may produce, the configured limit when zero
	MaxTokens int `json:"max_tokens,omitempty"`
	// Hooks every agent of the kind runs with
	Hooks []agent.Hook `json:"-"`
	// Extension or file the kind came from
	Source string `json:"-"`
}

Named recipe an agent is built from, a session type

func RegisteredKinds

func RegisteredKinds() []Kind

Kinds registered so far, sorted by name

func (Kind) Offers

func (k Kind) Offers(name string) bool

Reports whether the kind offers the tool

func (Kind) Validate

func (k Kind) Validate() error

Checks that the kind has a usable name and lists no tool as both offered and withheld

type Level

type Level int

Weight of a notice

const (
	Info Level = iota
	Success
	Warn
	Error
)

type Live

type Live struct {
	Session  *session.Session
	Facts    *facts.Store
	Missions *mission.Store
	Endpoint Endpoint
	// contains filtered or unexported fields
}

Session open in the shell with the stores that log into it and the endpoint its runs go to

func (*Live) Kind

func (l *Live) Kind() string

Name of the kind the session runs as, empty while it runs as none

func (*Live) SetThinking

func (l *Live) SetThinking(on bool)

Hands the thinking of its runs to the transcript or keeps every thinking event out of it

func (*Live) ShowsThinking

func (l *Live) ShowsThinking() bool

Reports whether the thinking of its runs reaches the transcript

type MCP

type MCP struct {
	Options mcp.Options
	// contains filtered or unexported fields
}

Keeps MCP servers connected and their tools registered, swapping tools off the callback goroutine

func NewMCP

func NewMCP(send Sender, registry *tool.Registry) *MCP

func (*MCP) Add

func (m *MCP) Add(ctx context.Context, cfg ServerConfig) error

Adds a server and connects it in the background unless it starts disabled

func (*MCP) Close

func (m *MCP) Close()

Closes every server and waits for background work to finish

func (*MCP) Connect

func (m *MCP) Connect(ctx context.Context, name string) error

Opens the server in the background, reporting state changes as messages

func (*MCP) Disconnect

func (m *MCP) Disconnect(name string) error

Closes the server, dropping its tools from the registry

func (*MCP) Reconnect

func (m *MCP) Reconnect(ctx context.Context, name string) error

Closes the server and opens it again

func (*MCP) Remove

func (m *MCP) Remove(name string) error

Forgets a server after closing it

func (*MCP) Status

func (m *MCP) Status() []ServerStatus

State of every server in configuration order

type MCPMsg

type MCPMsg struct {
	Server string
	State  mcp.State
	Err    error
	Tools  []string
}

MCP server connection change

type Meter

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

Provider observer and agent event consumer that keeps the telemetry current

func NewMeter

func NewMeter(send Sender) *Meter

func (*Meter) Apply

func (m *Meter) Apply(run string, ev agent.Event)

Updates usage, cost, context fill and throughput from an agent event

func (*Meter) Attempts

func (m *Meter) Attempts() []provider.Attempt

Recent attempts, oldest first

func (*Meter) Begin

func (m *Meter) Begin(a provider.Attempt)

Records when a request leaves, the origin the first token is timed from

func (*Meter) Observe

func (m *Meter) Observe(a provider.Attempt)

Records one provider attempt

func (*Meter) Reset

func (m *Meter) Reset()

Forgets usage, cost, attempts and counters for a new session, keeping the model, pricing and threshold

func (*Meter) SetCatalog

func (m *Meter) SetCatalog(model profiles.Model, providerName string)

Uses an explicit catalog entry, for endpoints that report their own pricing

func (*Meter) SetThreshold

func (m *Meter) SetThreshold(n int)

Records the compaction threshold shown against the context fill

func (*Meter) Snapshot

func (m *Meter) Snapshot() Telemetry

Current telemetry

type MissionMsg

type MissionMsg struct {
	Session string
	Mission mission.Mission
	Op      mission.Op
}

Mission store change of one session

type NoteData added in v1.0.11

type NoteData struct {
	Text  string `json:"text"`
	Level Level  `json:"level"`
}

Note as the session record stores it

type NoteMsg added in v1.0.11

type NoteMsg struct {
	Session string
	Text    string
	Level   Level
	Flow    string
}

Text a workflow wrote into the transcript of a session for the person, kept with the session

type NoticeMsg

type NoticeMsg struct {
	Text  string
	Level Level
	// Workflow that raised it, empty for none
	Flow string
}

Text a workflow or extension wants the person to see

type OpenedMsg

type OpenedMsg struct {
	Live *Live
	Flow string
}

Session a workflow opened, so a card may show it

type PanelMsg added in v1.0.11

type PanelMsg struct {
	Key  string
	Flow string
}

Panel a workflow asks the terminal to open beside its sessions

type Pending

type Pending struct {
	ID      int
	Run     string
	Agent   string
	Request policy.Request
	Asked   time.Time
	// contains filtered or unexported fields
}

One approval waiting for a person

type ProgressMsg

type ProgressMsg struct {
	Run      string
	Progress tool.Progress
}

Output or progress a running tool reported

type Pruning

type Pruning struct {
	// Assistant turns a tool result stays in requests before a stub replaces it, unset for the default and zero to never prune
	After *int `json:"after,omitempty"`
}

Tool result pruning settings

type Pump

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

Observer that forwards events as messages, merging streamed deltas so a fast model never floods the program

func NewPump

func NewPump(send Sender) *Pump

func (*Pump) Flush

func (p *Pump) Flush()

Delivers every held delta now

func (*Pump) Observer

func (p *Pump) Observer(run string) func(agent.Event)

Observer for one run, safe to call from any goroutine

func (*Pump) Push

func (p *Pump) Push(run string, ev agent.Event)

Delivers an event, holding deltas until the frame ends and flushing them ahead of anything else

type Question added in v1.0.12

type Question struct {
	Text    string   `json:"question"`
	Header  string   `json:"header,omitempty"`
	Choices []Choice `json:"options"`
	Multi   bool     `json:"multi_select,omitempty"`
}

Question put to the person, answered by picking choices or typing an answer of their own

type QuestionDoneMsg added in v1.0.12

type QuestionDoneMsg struct {
	ID      int
	Run     string
	Session string
	Answers []Answer
	Err     error
}

Questions that were answered, declined or abandoned

type QuestionMsg added in v1.0.12

type QuestionMsg struct {
	Asking *Asking
}

Question a person must answer

type Questioner added in v1.0.12

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

Asker that posts each set of questions into the program and waits for the answers the program hands back

func NewQuestioner added in v1.0.12

func NewQuestioner(send Sender) *Questioner

func (*Questioner) Answer added in v1.0.12

func (q *Questioner) Answer(id int, answers []Answer) bool

Delivers one answer per question to a pending ask and reports whether one was waiting for that many

func (*Questioner) Ask added in v1.0.12

func (q *Questioner) Ask(ctx context.Context, run, sessionID string, questions []Question) ([]Answer, error)

Posts the questions for the session and blocks until every one is answered or the context ends

func (*Questioner) Close added in v1.0.12

func (q *Questioner) Close()

Refuses every later ask and declines the ones waiting

func (*Questioner) Decline added in v1.0.12

func (q *Questioner) Decline(id int) bool

Answers every question of a pending ask as declined and reports whether one was waiting

func (*Questioner) ForSession added in v1.0.12

func (q *Questioner) ForSession(id string) *Asking

Oldest ask waiting on the session, nil while none is

func (*Questioner) Len added in v1.0.12

func (q *Questioner) Len() int

func (*Questioner) Pending added in v1.0.12

func (q *Questioner) Pending() []*Asking

Asks waiting, oldest first

type RuleEntry

type RuleEntry struct {
	Decision policy.Decision
	Rule     string
	Path     string
}

One permission rule with its decision and the file holding it

type Run

type Run struct {
	ID      string
	Name    string
	Mission string
	Agent   *agent.Agent
	Session *session.Session
	// Run id of the parent, empty at the root
	Parent string
	Depth  int
	// Tool call that spawned a child run
	CallID      string
	Description string
	Started     time.Time
	// contains filtered or unexported fields
}

One agent run the controller started or discovered as a child of one it started

func (*Run) Elapsed

func (r *Run) Elapsed(now time.Time) time.Duration

Seconds the run has taken so far or took

func (*Run) Err

func (r *Run) Err() error

Error the run ended with

func (*Run) Finished

func (r *Run) Finished() time.Time

Time the run ended, zero while it goes

func (*Run) LastTool

func (r *Run) LastTool() (string, int)

Name of the last tool called and how many calls the run made

func (*Run) Response

func (r *Run) Response() protocol.Response

Final response of a finished run

func (*Run) Running

func (r *Run) Running() bool

Reports whether the run is still going

type RunDoneMsg

type RunDoneMsg struct {
	Run      string
	Response protocol.Response
	Err      error
	Duration time.Duration
}

Run that reached its end

type SavedMsg

type SavedMsg struct {
	Session string
	Path    string
	// Listing entry of the session as saved, so a card need not read the store again
	Info session.Info
	Err  error
}

Session written to the store

type Saver

type Saver struct {
	Store *session.Store
	// Reports whether a session stays off disk, nothing of it written while it does
	Off func(*session.Session) bool
	// contains filtered or unexported fields
}

Writes sessions to a store after a short quiet period so a burst costs one write, skipping empty sessions

func NewSaver

func NewSaver(store *session.Store, send Sender) *Saver

func (*Saver) Flush

func (s *Saver) Flush(sess *session.Session)

Saves the session now, cancelling any pending save

func (*Saver) Touch

func (s *Saver) Touch(sess *session.Session)

Schedules a save of the session once changes go quiet

func (*Saver) Wait

func (s *Saver) Wait()

Waits for every scheduled save to finish

type Scope

type Scope string

Where a new entry is written, the project directory or the user configuration directory

const (
	ScopeProject Scope = "project"
	ScopeUser    Scope = "user"
)

type Sender

type Sender func(msg any)

Delivers a message into the program from any goroutine

type ServerConfig

type ServerConfig struct {
	Name    string            `json:"name"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
	Dir     string            `json:"dir,omitempty"`
	URL     string            `json:"url,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	// Seconds each handshake and listing may take
	Timeout int `json:"timeout,omitempty"`
	// Starts disabled, connected only on request
	Disabled bool `json:"disabled,omitempty"`
}

One MCP server as configuration names it, over stdio when a command is given and streamable HTTP when a URL is

func (ServerConfig) Dialer

func (c ServerConfig) Dialer() (mcp.Dialer, error)

Dialer for the transport the configuration names

type ServerEntry

type ServerEntry struct {
	Config ServerConfig
	Path   string
}

One MCP server with the file configuring it

type ServerStatus

type ServerStatus struct {
	Name     string
	Config   ServerConfig
	State    mcp.State
	Err      error
	Tools    []string
	Attempts int
	Info     mcp.ServerInfo
	Since    time.Time
}

Connection and tool state of one managed server

type Setting

type Setting struct {
	Key  string
	Help string
	// Values the setting may take, a choice when set
	Choices []string
	// Floor, ceiling and step of a number, no ceiling when it sits at or under the floor
	Lo, Hi, Step float64
	Integer      bool
	// Further check of a value after the choice or range one
	Check func(value string) error
	// Shown masked wherever it is edited, for a key or token
	Secret bool
	// Extension the setting came from
	Source string
}

Setting an extension adds to the configuration, saved under settings in the configuration file

func LookupSetting

func LookupSetting(key string) (Setting, bool)

Setting registered under the key

func Settings

func Settings() []Setting

Settings registered so far, in registration order

func (Setting) Number

func (s Setting) Number() bool

Reports whether the setting takes a number

func (Setting) Validate

func (s Setting) Validate(value string) error

Checks a value against the choices, the range and the extra check

type ShellConfig

type ShellConfig struct {
	// Seconds a command may run when the model names no timeout
	Timeout int `json:"timeout,omitempty"`
	// Seconds the model may ask for at most
	MaxTimeout int `json:"max_timeout,omitempty"`
	// KEY=VALUE pairs every command sees
	Env []string `json:"env,omitempty"`
}

Shell settings

type Stuck added in v1.0.11

type Stuck struct {
	Profile string
	Err     *protocol.Error
	Since   time.Time
}

Profile whose endpoint refuses every call until the person acts, with the refusal and when it was first heard

func (Stuck) Text added in v1.0.11

func (s Stuck) Text() string

Why the profile is stuck and since when, for the person

type Subagents

type Subagents struct {
	MaxDepth int  `json:"max_depth,omitempty"`
	Parallel bool `json:"parallel,omitempty"`
	// Seconds one child may run
	Timeout int `json:"timeout,omitempty"`
	// Profile and model children use, the main one when empty
	Model *Target `json:"model,omitempty"`
}

Subagent settings

type Target

type Target struct {
	Profile string `json:"profile"`
	Model   string `json:"model,omitempty"`
}

Profile and model pair naming where compaction and child agents run

type Telemetry

type Telemetry struct {
	Model    string
	Provider string
	// Tokens the next request will carry
	Context int
	// Context window of the model, zero when unknown
	ContextLimit int
	// Context at which compaction runs, zero when none is configured
	Threshold int
	Usage     protocol.Usage
	// Dollars spent over the session, zero when no pricing is known
	Cost float64
	// Whether the model has pricing, so the cost means something
	Priced bool
	// Share of the last request served from cache
	CacheRatio float64
	// Output tokens per second of the current or last turn
	TokensPerSecond float64
	Streaming       bool
	Requests        int
	Retries         int
	Failures        int
	LastRequestID   string
	LastLatency     time.Duration
	AvgLatency      time.Duration
	// Time from the request start to the first token of the current or last turn
	FirstToken time.Duration
	RateLimit  provider.RateLimit
	// Dollars per run id
	Costs map[string]float64
	// Calls and estimated result tokens per tool name
	Tools map[string]ToolStat
	// Estimated result tokens over every tool call
	ToolTokens int
}

What the model layer has done so far, as a card can show it

type TerminalConfig added in v1.0.10

type TerminalConfig struct {
	// Command line the shell of a terminal window runs, the login shell of the user when empty
	Shell string `json:"shell,omitempty"`
	// Rows a terminal window keeps above its screen, nil for the default
	Scrollback *int `json:"scrollback,omitempty"`
}

Terminal window settings

type ToolStat

type ToolStat struct {
	Calls  int
	Tokens int
}

Calls a tool took and the estimated tokens its results put into context

type ToolsConfig

type ToolsConfig struct {
	// Tool names withheld from the model and refused when called
	Disabled []string `json:"disabled,omitempty"`
}

Tool settings

type UIConfig

type UIConfig struct {
	// Theme name such as blackwall, light, contrast or plain
	Theme string `json:"theme,omitempty"`
	// Motion scale from zero for snapping to one for full springs
	Motion *float64 `json:"motion,omitempty"`
	// Main slot share of the width
	Ratio float64 `json:"ratio,omitempty"`
	// Cascade lights the focused card's border with a flowing energy comet
	Cascade *bool `json:"cascade,omitempty"`
	// Characters a Mac Option key types read as alt chords, nil for on under macOS only
	OptionAsAlt *bool `json:"option_as_alt,omitempty"`
}

Appearance settings

type WebConfig

type WebConfig struct {
	// Disables the fetch tool
	Disabled bool `json:"disabled,omitempty"`
}

Web fetch settings

type Workflow

type Workflow struct {
	Name        string
	Title       string
	Description string
	// Placeholder of the argument, asked for when the command comes without one, none when empty
	Arg string
	Run func(ctx context.Context, f *Flow, arg string) error
	// Extension the workflow came from
	Source string
}

Named procedure that drives sessions and runs, offered as a command

func LookupWorkflow

func LookupWorkflow(name string) (Workflow, bool)

Workflow registered under the name

func Workflows

func Workflows() []Workflow

Workflows registered so far, in registration order

func (Workflow) Validate

func (w Workflow) Validate() error

Checks that the workflow has a usable name and something to run

Jump to

Keyboard shortcuts

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