harness

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 61 Imported by: 2 modules, 3 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.

README

harness

harness

ci Go Reference

An open, embeddable agent harness written in Go: a ReAct loop whose tools run in a sandbox (a local directory or a remote OpenSandbox container), streaming AG-UI events. The Go loop drives the model (OpenAI-compatible or Anthropic) and the sandbox only executes; nothing spawns another agent CLI. It ships tools (files, shell, search, document rendering), skills, memory, goals and plans, tool approvals and permissions, context compaction and verification of produced documents.

It is meant to sit behind any front end: a web server, a TUI, a worker, a desktop app. The repository contains a terminal client, a net/http + SSE server package and a benchmark runner; product-specific HTTP APIs (authentication, multi-tenant routing) are left to the embedding application.

        web UI ──► product ► hosts/httpapi (net/http, SSE) ──┐
        TUI    ──► app/cmd/harness (reference)  ───┤
        your app ──────────────────────────────┤
                                               ▼
                                    harness.Harness  (Send / Events / Cancel / Steer)
                                               │
        ┌───────────── runtime (claim, heartbeat, hooks) ─────────────┐
        │  agent loop ── llm (OpenAI chat / Responses, Anthropic)│
        │      │         compaction · steering · approvals · goals    │
        │      ▼                                                      │
        │  tools ── sandboxtools (exec, read, edit, search, view…)    │
        │           skilltools · memorytools · harnesstools · mcptools│
        └──────────────┬───────────────────────────┬──────────────────┘
                       ▼                           ▼
              sandbox.Manager ──► Backend    store.Store · eventlog.Log · queue
              (OpenSandbox | your own)       (memory | Postgres+Redis)

See it work

Watch the agent work, stream its tool calls and diffs, and steer it mid-run. The panel on the right shows the files, plan, memory and activity of the thread.

An approval card asking to run go test
Approvals. Risky commands pause the run until you approve or deny them; permissions decide what asks. A line chart the agent produced
Documents and charts. The sandbox renders charts, decks, memos and spreadsheets, and the harness verifies what it produced. A board-update slide the agent produced
Decks. PowerPoint, Word, Excel and PDF through built-in skills. The memory panel
Memory. The agent keeps notes across threads, with review and scopes.

Quick start

Terminal. Run harness in a repository. With no API key configured it opens a home screen that walks you through connecting a provider (pick one, paste the key, choose a model; no restart). Or configure everything up front:

AGENT_PROFILE=coding SANDBOX_BACKEND=local LLM_PROVIDER=anthropic LLM_API_KEY=… \
LLM_MODELS=claude-sonnet-5-5 LLM_DEFAULT_MODEL=claude-sonnet-5-5 harness

Web. harness-web -local serves the same agent with a browser UI at http://127.0.0.1:8080/.

Embedded in Go.

cfg, _ := config.Load()                       // ~/.har/config.yml + <repo>/.har/config.yml + env: LLM_*, SANDBOX_*, …
h, _ := harness.New(harness.Options{Config: cfg})
go h.Run(ctx)                                 // consumes queued runs

th, _ := h.NewThread(ctx, "alice", "")
run, _ := h.Send(ctx, "alice", th.ID, "Make a chart of …", harness.RunOptions{Model: "gpt-5"})
for ev := range h.Events(ctx, run.ID, 0) {    // AG-UI events, ev.Seq is the resume point
    fmt.Println(ev.Type, string(ev.Data))
}
h.Steer(ctx, "alice", run.ID, "use blue instead")   // message to a running run
h.Cancel(ctx, "alice", run.ID)

By default everything lives in memory: the only thing to run is the sandbox. For several replicas, pass a Postgres store and Redis infrastructure (see Infrastructure). Requires Go 1.26.

More ways to use it:

  • Credentials: harness auth login <provider> stores an API key in ~/.har/auth.json (mode 0600), never in a repository (configuration).
  • No container: SANDBOX_BACKEND=local runs the tools on this machine, confined to the workspace (permissions).
  • Your own front end: write it against hosts/client, which has in-process and HTTP implementations.
  • Your own sandbox: implement sandbox.Backend (docs/sandbox-adapters.md).
  • A website: docs/embedding.md and examples/website.
  • Your own tools or features: Options.Tools, Options.Features (docs/features.md).

Packages

The repository is a root Go module plus seven standalone modules (listed in go.work), in strict layers: a lower layer never imports a higher one. Each standalone module can be used on its own.

Package What it is Docs
ai Messages, tools, the model contract, OpenAI / Anthropic / Responses clients, the tool-calling loop, context compaction. A library on its own ai/README.md
ai/agent The tool-calling loop README
ai/llm Provider factory, retry, and the anthropic, responses and llmtest packages; ai/openai is the Chat Completions client README
ai/compaction Keeps a conversation inside the context window README
core AG-UI events, domain types and the ports (store, sandbox, blobs) core/README.md
modelinfo Model context windows, capabilities and prices modelinfo/README.md
hosts/client The Client contract every front end is written against hosts/client/README.md, front ends
hosts/tui The terminal UI (Bubble Tea) hosts/tui/README.md
hosts/httpapi HTTP + SSE server with an embedded browser UI hosts/httpapi/README.md
hosts/worker Headless queue consumer for multi-process deployments hosts/worker/README.md
adapters/sandbox Local and OpenSandbox backends, the SANDBOX_BACKEND registry adapters/sandbox/README.md
sandbox-image The sandbox container image and OpenSandbox server config sandbox-image/README.md
app/cmd The binaries: harness, harness-web, harness-worker, bench app/cmd/README.md
bench Coding benchmark run through the real harness bench/README.md
root The engine, features, facade, stores: what you embed this page, docs/

The full directory tree is in docs/layout.md; the layering rules in docs/architecture.md.

Documentation

Topic Page
Configuration: config.yml, providers and API keys, precedence, trust, instruction files, MCP servers, environment variables docs/configuration.md
Permissions and git safety for the local backend docs/permissions.md
Features, profiles (work, coding, minimal), skills, writing your own feature, sandbox per run docs/features.md
Infrastructure (Redis, Postgres), local sessions, the sandbox definition docs/infrastructure.md
Writing a front end against the client contract docs/front-ends.md
Embedding in a website docs/embedding.md, examples/website
Writing a sandbox backend docs/sandbox-adapters.md
Agent factory (webhooks, unattended PRs) docs/factory.md
MCP marketplace docs/marketplace.md
Team product docs/team.md
Architecture and layering docs/architecture.md
Building, CI, known gaps docs/development.md
Releasing docs/releasing.md

Contributing

Contributions are welcome: see CONTRIBUTING.md. Report a vulnerability privately, as SECURITY.md describes.

License

MIT, see LICENSE. The standalone modules (ai, core, modelinfo, hosts/client, hosts/tui, adapters/sandbox) carry the same license.

Documentation

Overview

Package harness is an embeddable agent harness: a ReAct loop (eino) whose tools run in a remote sandbox (OpenSandbox), with compaction, steering, skills, artifacts, memory and approvals, streaming AG-UI events.

It is a library for hosts that own the user interface: a web server (see package httpserver), a TUI or a desktop app. A host builds a Harness, starts it and then talks to it with a handful of calls:

h, _ := harness.New(harness.Options{Config: cfg})
go h.Run(ctx)
th, _ := h.NewThread(ctx, "alice", "My thread")
run, _ := h.Send(ctx, "alice", th.ID, "Make a chart of …", harness.RunOptions{Model: "gpt-5"})
for ev := range h.Events(ctx, run.ID, 0) { … }   // AG-UI events

Without Redis and Postgres everything lives in the process (memory store, event log and queue); pass Options.Store (store/pgstore) and Options.Infra (redisinfra) to share state between processes.

Index

Constants

View Source
const (
	FeatureSandbox     = "sandbox"
	FeatureCodecheck   = "codecheck"
	FeatureExplore     = "explore"
	FeatureSkills      = "skills"
	FeatureMCP         = "mcp"
	FeaturePlan        = "plan"
	FeatureProjectDocs = "projectdocs"
	FeatureArtifacts   = "artifacts"
	FeatureWorkspace   = "workspace"
	FeatureTitles      = "titles"
	FeatureVerify      = "verify"
	FeatureGoals       = "goals"
	FeatureMemory      = "memory"
	FeatureToolProfile = "toolprofile"
	FeaturePermissions = "permissions"
)

Names of the built-in features (Feature.Name, Builder.Has, Builder.Require).

View Source
const (
	// MaxAttachments is the most attachments one message carries (the number of
	// images one model request carries).
	MaxAttachments = agent.MaxRequestImages
	// MaxAttachmentBytes is the largest attachment (the largest image a vision
	// model is sent).
	MaxAttachmentBytes = 5 << 20
)

Limits of RunOptions.Attachments.

View Source
const FeatureFactory = "factory"

FeatureFactory is the name of the Factory feature.

Variables

View Source
var (
	// ErrNothingToUndo means the thread has no user message left to remove.
	ErrNothingToUndo = errors.New("nothing to undo")
	// ErrNothingToRedo means no undone step is available: none was undone, or a message was sent since.
	ErrNothingToRedo = errors.New("nothing to redo")
	// ErrHistoryUnsupported means the Store cannot edit a thread's history (store.HistoryStore).
	ErrHistoryUnsupported = errors.New("the store cannot edit a thread's history")
)

Errors of the history operations (Compact, Undo, Redo, Fork).

View Source
var ErrInvalidRequest = errors.New("invalid request")

ErrInvalidRequest wraps the errors caused by the caller's input.

View Source
var ErrNoSandbox = errors.New("this run requires a sandbox but the harness has none: set Options.Backend or SANDBOX_BACKEND")

ErrNoSandbox is returned (wrapped in ErrInvalidRequest) by Send when the run asks for SandboxOn and the harness has no sandbox.

Functions

func DefaultLocalStoreDir

func DefaultLocalStoreDir() string

DefaultLocalStoreDir is the state directory OpenLocalStore uses when none is given: $LOCAL_STATE_DIR, else <user dir>/sessions ($HAR_HOME or ~/.har), else (user directory disabled or unknown) $XDG_STATE_HOME/harness, else ~/.local/state/harness.

func Lookup

func Lookup[T any](b *Builder) (T, bool)

Lookup returns the service of type T published by an earlier feature.

func NewSandboxBackend

func NewSandboxBackend(cfg *config.Config) (sandbox.Backend, error)

NewSandboxBackend builds the backend the configuration selects (Config.SandboxBackendName): the registered factory of SANDBOX_BACKEND, or of "opensandbox" when only OPENSANDBOX_URL is set, or none (a nil sandbox.Backend). Every process that can create a sandbox goes through it, so every one of them applies the production refusal of unrestricted egress (config.EgressMode) before a backend is built.

func OpenLocalStore

func OpenLocalStore(dir string) (*filestore.Store, error)

OpenLocalStore opens the durable single-process store for local hosts (CLI, TUI, desktop): threads, messages, runs, plans, summaries, approvals and event logs survive restarts, with no Postgres or Redis. Pass it as Options.Store and Close it on exit.

dir is the state directory; "" uses DefaultLocalStoreDir. Runs that were in progress when the previous process died are marked interrupted. Use Store.Sessions() to list, fork and delete threads. See store/filestore.

func Provide

func Provide[T any](b *Builder, v T) error

Provide publishes a service for the features installed after this one (looked up by its type with Lookup). One service per type.

func RegisterMCP added in v0.3.0

func RegisterMCP(install func(*Builder) error)

RegisterMCP sets the implementation of the MCP feature; package mcpfeature calls it from an init function.

func SandboxSettings

func SandboxSettings(cfg *config.Config) backends.Settings

SandboxSettings maps the configuration (SANDBOX_BACKEND, OPENSANDBOX_*, SANDBOX_*, LOCAL_*) to the settings the registered sandbox backends are built from.

func SpendOf added in v0.4.0

func SpendOf(usage []agui.Usage, fallbackModel string, price func(string) (modelinfo.Info, bool)) factory.Spend

SpendOf converts per-model usage to a factory.Spend. A model without a price adds its tokens and counts as unpriced rather than free.

func StoreAs

func StoreAs[T any](b *Builder) (T, error)

StoreAs returns the Builder's store as T, or an error naming the feature when the store does not provide that capability (a feature that needs a store extension declares it this way).

Types

type Attachment

type Attachment struct {
	// Name is the file name (its extension is corrected to MIME's).
	Name string
	// MIME is image/png, image/jpeg, image/gif or image/webp.
	MIME string
	Data []byte
}

Attachment is an image sent with a message. It is stored in the thread's workspace like an uploaded file and shown to vision models; a model without vision sees the file's path only.

type Author

type Author struct {
	Login      string
	Kind       string
	OnBehalfOf string
}

Author identifies who sends a message or a steer.

type Broker

type Broker interface {
	queue.Queue
	queue.Bus
	runtime.RunQueue
}

Broker is the run queue and the per-run control bus (cancel, steers). The in-process one is queue.NewMemory; the Redis one (redisinfra) shares it between processes. Any other transport (NATS, SQS...) implements the same three interfaces.

type Builder

type Builder struct {
	// Config is the environment-driven configuration.
	Config *config.Config
	// Store is the persistence (Options.Store, default: in memory).
	Store Store
	// Models builds the chat models.
	Models llm.Factory
	// Sandboxes manages the sandboxes; Sandboxes.Enabled() reports whether a
	// backend is configured.
	Sandboxes sandbox.Manager
	// Blobs stores artifact contents.
	Blobs artifacts.Blobs
	// Infra is the infrastructure shared between processes (queue, event log...).
	Infra Infra
	// Options are the options the host passed to New (read only).
	Options Options

	// Services of the built-in features, set by the feature that provides them
	// and nil until it is installed (so install it earlier in the list).
	Artifacts *artifacts.Service
	Workspace *workspace.Service
	Skills    *skills.Registry
	Installer *skills.Installer
	Memory    *memory.Service
	Verifier  *verify.Verifier
	// contains filtered or unexported fields
}

Builder is what a Feature sees while the harness is built: the environment to read, and the contributions it may make. A feature that builds on another finds that feature's services in the exported fields (nil when its feature is not installed) or through Lookup.

func (*Builder) AddTools

func (b *Builder) AddTools(ps ...tools.Provider)

AddTools offers tool providers to the agent (nil ones are ignored), in the order features are installed, before Options.Tools.

func (*Builder) After

func (b *Builder) After(f func() error)

After registers f to run once every feature is installed (to build what depends on the other features' contributions).

func (*Builder) Background

func (b *Builder) Background(f func(ctx context.Context))

Background starts f in a goroutine once the harness is built (New returned without error); ctx is never cancelled by the harness, f ends on its own.

func (*Builder) BeforeTool

func (b *Builder) BeforeTool(h agent.BeforeToolHook)

BeforeTool adds a hook that gates tool calls before they run.

func (*Builder) Configure

func (b *Builder) Configure(f func(*agent.Harness))

Configure changes the agent's configuration after every feature contributed (an escape hatch for what the other methods do not cover). Mutators run in installation order.

func (*Builder) ContextSection

func (b *Builder) ContextSection(s agent.PromptSection)

ContextSection adds a dynamic section, rendered in the prompt's final context block (recalled memories, the current goal...).

func (*Builder) EndOfRun

func (b *Builder) EndOfRun(h runtime.Hook)

EndOfRun adds a hook run at the end of every run, before Options.Hooks.

func (*Builder) Factory added in v0.4.0

func (b *Builder) Factory() *Factory

Factory returns the Factory service published by the feature (nil when it is not installed).

func (*Builder) Has

func (b *Builder) Has(name string) bool

Has reports whether the named feature is installed (so far).

func (*Builder) Job

func (b *Builder) Job(j runtime.Job)

Job adds a periodic maintenance job (run by one runtime at a time when the Infra has a Coordinator).

func (*Builder) OnReady added in v0.4.0

func (b *Builder) OnReady(f func(*Harness))

OnReady calls f with the finished Harness, after every feature is installed and before the Background functions start: a feature that must act through the Harness (start runs, read stores) binds to it here.

func (*Builder) OnSandboxCreate

func (b *Builder) OnSandboxCreate(f func(ctx context.Context, threadID string, sb sandbox.Sandbox, recreated bool) string)

OnSandboxCreate registers a function run when a sandbox is created; a non-empty result is added to the notice the model sees.

func (*Builder) PrepareSandbox

func (b *Builder) PrepareSandbox(f func(ctx context.Context, threadID string, sb sandbox.Sandbox, recreated bool) string)

PrepareSandbox registers a function run when a sandbox is created, before the OnSandboxCreate ones (restoring history before restoring files).

func (*Builder) Require

func (b *Builder) Require(names ...string) error

Require fails unless the named features are installed (earlier in the list).

func (*Builder) RequireSandbox

func (b *Builder) RequireSandbox() error

RequireSandbox fails unless a sandbox backend is configured (Options.Backend, SANDBOX_BACKEND or OPENSANDBOX_URL).

func (*Builder) RunStart

func (b *Builder) RunStart(h agent.RunStartHook)

RunStart adds a hook run before the first step of every run.

func (*Builder) SandboxTools

func (b *Builder) SandboxTools(f func(*sandboxtools.Options))

SandboxTools changes the options of the sandbox tools (execute_command, read_file...): hook into the lifecycle of a sandbox or of a command. Each feature chains onto what the previous ones set; it applies only when the "sandbox" feature is installed and a backend is configured.

func (*Builder) Section

func (b *Builder) Section(s agent.PromptSection)

Section adds a static system-prompt section (rendered in order).

func (*Builder) SetAnswers

func (b *Builder) SetAnswers(a agent.AnswerChecker) error

SetAnswers sets the reviewer of final answers; only one feature may.

func (*Builder) SetChecker

func (b *Builder) SetChecker(c agent.Checker, d agent.DeliverableSource) error

SetChecker sets the deliverable checker and the source of the deliverables restored after a compaction; only one feature may.

func (*Builder) SetImages

func (b *Builder) SetImages(i agent.ImageAttacher) error

SetImages sets how attached images reach vision models; only one feature may.

func (*Builder) SetPurger

func (b *Builder) SetPurger(p runtime.Purger) error

SetPurger sets the retention job; only one feature may.

func (*Builder) StepNote

func (b *Builder) StepNote(n agent.StepNote)

StepNote adds a note source asked before every model call of a run (news that appears mid-run, such as the project skills of a sandbox the run started).

func (*Builder) TailSection

func (b *Builder) TailSection(s agent.PromptSection)

TailSection adds a section rendered once per run into the reminder at the end of every request (keeps the system prompt a cacheable prefix).

func (*Builder) ToolHook

func (b *Builder) ToolHook(h agent.ToolHook)

ToolHook adds an observer of tool results.

func (*Builder) WrapTools

func (b *Builder) WrapTools(w func(tools.Provider) tools.Provider)

WrapTools wraps the whole tool registry (filters, auditing...). Wrappers apply in installation order, the first one innermost.

type CompactResult

type CompactResult struct {
	// Compacted is false when there was nothing to summarise.
	Compacted    bool
	TokensBefore int
	TokensAfter  int
}

CompactResult is the outcome of Compact.

type Coordinator

type Coordinator interface {
	sandbox.Coordinator
	runtime.Locks
}

Coordinator is the small shared key/value state the processes of one deployment use to cooperate: sandbox creation locks and health streaks (sandbox.Coordinator), the sweeper and job locks and the run liveness marks (runtime.Locks). redisx.NewCoordinator is the Redis one; sandbox.LocalCoordinator keeps it in the process.

type Factory added in v0.4.0

type Factory struct {
	Store    factory.Store
	Tasks    *tasks.Service
	Webhook  *triggers.Webhook
	Triggers *triggers.Scheduler
	Loop     *forge.Loop // nil without a Forge
	Budget   *budget.Guard
	Spawner  *FactorySpawner
	Roles    map[string]delegate.Role
}

Factory is the running agent factory, published by the Factory feature (harness.Lookup / Builder.Factory). Hosts mount Webhook, call Tasks to create and inspect tasks, and Triggers to schedule work.

func (*Factory) Report added in v0.4.0

func (f *Factory) Report(ctx context.Context, projectID string, since time.Time) (budget.Report, error)

Report is the project's factory spend since a time, for dashboards.

func (*Factory) WebhookHandler added in v0.4.0

func (f *Factory) WebhookHandler() http.Handler

WebhookHandler is the GitHub webhook endpoint.

type FactoryOptions added in v0.4.0

type FactoryOptions struct {
	// Store holds tasks, triggers and thread links (factorystore.NewMem or NewPG). Required.
	Store factory.Store

	// Forge is the code host. Without one the factory runs tasks that need no
	// pull request (an answer is the result); with one it also opens, watches
	// and merges pull requests.
	Forge factory.Forge
	// Auth mints repository tokens for cloning and pushing and for the forge client (required with Forge).
	Auth factory.RepoAuth
	// ReviewModel is the model of the reviewer that gates every merge. Set, it
	// must differ from the model that wrote the change (the gate refuses to approve
	// its own author's work). Empty, the default model reviews: weaker, because a
	// model grades its own work, and every approval says so (review.SelfReviewNote).
	ReviewModel string
	// NoReview merges on green CI alone. It is a deliberate opt-out.
	NoReview bool
	// Protected are path globs no automated change may touch (review.DefaultProtected when nil).
	Protected []string
	// RequireTests flags diffs that change source without a test.
	RequireTests bool
	// ReviewRubric is appended to the reviewer's default rubric.
	ReviewRubric string
	// MergeMethod is how pull requests merge (default squash).
	MergeMethod factory.MergeMethod
	// AllowNoChecks lets a repository without CI merge.
	AllowNoChecks bool
	// LoopEvery is how often the pull request loop polls (default 30s); Settle is how long checks must stay
	// green before the PR is judged (default 60s).
	LoopEvery, Settle time.Duration

	// Price returns model prices for the budgets (nil: tokens are counted, dollars are not).
	Price func(model string) (modelinfo.Info, bool)
	// DailyBudget caps all factory spend per Window (zero: no cap); PerProject applies it to each project.
	DailyBudget factory.Budget
	PerProject  bool
	// DefaultBudget is the budget of tasks that name none.
	DefaultBudget factory.Budget

	// DefaultPolicy is the autonomy policy of tasks that name none (default factory.PolicySandboxed).
	DefaultPolicy string
	// MaxConcurrent bounds the tasks running at once (default 4).
	MaxConcurrent int
	// MaxAttempts is the default attempts per task (default 3).
	MaxAttempts int
	// Backoff is the delay before a failed attempt is retried (default 30s doubling, capped at 15m);
	// PollEvery is how often the dispatcher looks for ready tasks (default 5s).
	Backoff   func(attempt int) time.Duration
	PollEvery time.Duration

	// Lessons distils what finished tasks taught into the project's memory, so
	// later runs recall it. LessonsModel (default: the default model) writes them.
	// Needs the Memory feature, installed earlier in the list.
	Lessons      bool
	LessonsModel string

	// OnSpawn is told of every thread the factory creates for a task (the task's run and its delegated
	// sub-agents), before its first run is queued. A team host links the thread to the task's project here
	// so the project's members can watch the agent work. An error is logged, never fatal.
	OnSpawn func(ctx context.Context, threadID string, t factory.Task, req factory.SpawnRequest)

	// Escalator hears of tasks that need a human (nil: the log only).
	Escalator factory.Escalator
	// Observers hear of finished tasks (the lessons distiller is one).
	Observers []factory.Observer
	// WebhookSecret signs GitHub deliveries; empty rejects every delivery.
	WebhookSecret []byte
	// Roles overrides the role catalogue (nil: delegate.DefaultRoles).
	Roles map[string]delegate.Role

	// Run says whether this process runs the dispatcher, the scheduler and the
	// pull request loop. They are safe to run in several processes over a
	// shared Store; a web-only process may leave them off.
	Run bool

	// Policy adds the autonomy policy engine: every tool call of a task's thread is classified and allowed,
	// asked about (supervised) or denied (force-push, secrets, protected paths, merges...) by the task's
	// policy. Ordinary chat threads are untouched. PolicyConfig adds project rules; PolicyProtectedBranches
	// supplies the repository's protected branches.
	Policy                  bool
	PolicyConfig            factorypolicy.Config
	PolicyProtectedBranches func(ctx context.Context, repo string) []string

	// ExtraBeforeTool are policy hooks installed ahead of the budget guard.
	ExtraBeforeTool []agent.BeforeToolHook
}

FactoryOptions configures the Factory feature.

type FactorySpawner added in v0.4.0

type FactorySpawner struct {
	H *Harness
	// Store records the ThreadInfo (nil: none is recorded).
	Store factory.Store
	// DefaultModel is used when a request names none (default: the config's).
	DefaultModel string
	// OnSpawn is called with each new thread of a task, after its ThreadInfo is recorded and before the run
	// is queued (nil: nothing).
	OnSpawn func(ctx context.Context, threadID string, t factory.Task, req factory.SpawnRequest)
	// Price converts a run's token usage to dollars (nil: tokens only).
	Price func(model string) (modelinfo.Info, bool)
}

FactorySpawner is the factory.Spawner over a Harness: every spawn is a new thread of the login, linked to its task and role through factory.ThreadInfo before the first run is queued, so the hooks and prompt sections of the factory features see it from the first step.

func (*FactorySpawner) Spawn added in v0.4.0

Spawn implements factory.Spawner.

type Feature

type Feature interface {
	// Name identifies the feature: unique in a harness, used in errors and by
	// Builder.Has / Builder.Require.
	Name() string
	Install(*Builder) error
}

A Feature is an optional capability of the harness: a set of tools, prompt sections, hooks and background jobs that belong together (permissions, memory, skills, goals...). A host picks the features it wants with Options.Features (or a named profile: ProfileCoding, ProfileWork, ProfileMinimal) and may add its own.

Install is called once, in the order of Options.Features, while the harness is being built. It reads the environment from the Builder (configuration, store, models, sandboxes, infrastructure), contributes through the Builder's methods, and returns an error to abort harness.New: an invalid configuration, or a missing capability (see Builder.RequireSandbox, Builder.Require and StoreAs).

func Artifacts

func Artifacts() Feature

Artifacts tracks the files the agent produces (snapshots on tool results, previews, links in answers, image attachments) and purges deleted threads' data after HARNESS_PURGE_AFTER_DAYS. Contents go to Options.Blobs (default: the Store). It publishes Builder.Artifacts.

func Codecheck

func Codecheck(coding bool) Feature

Codecheck adds a syntax check to the notice of write_file and edit_file (the coding agent's immediate feedback; AGENT_CODE_CHECKS adds commands). With coding false it only installs when AGENT_CODE_CHECKS is set. It requires the Sandbox feature.

func Explore

func Explore() Feature

Explore offers the explore tool, a read-only sub-agent that searches and reads the workspace and reports back (LLM_EXPLORE_MODEL, default the default model). Without a sandbox it contributes nothing. It requires the Sandbox feature.

func FactoryFeature added in v0.4.0

func FactoryFeature(o FactoryOptions) Feature

FactoryFeature installs the agent factory: tasks that agents work on unattended, fed by cron and GitHub webhooks, delegated to role agents, delivered as pull requests that CI and an independent reviewer gate, under per-task budgets, loop guards and autonomy policies.

func FeatureFunc

func FeatureFunc(name string, install func(*Builder) error) Feature

FeatureFunc adapts a function to a Feature.

func Goals

func Goals() Feature

Goals lets a thread carry a goal that is judged after every run and, while unmet, continues with another run. It uses Artifacts and Verify, when installed, to show the judge what was produced.

func MCP

func MCP() Feature

MCP offers the tools of the MCP servers of the configuration (MCP_SERVERS). It needs the implementation in package mcpfeature, imported for its side effect (a blank import). Without it, a configuration that names MCP servers is an error, not silently ignored; one that names none installs nothing.

func Memory

func Memory() Feature

Memory gives the agent a long-term memory: the memory tools, the memory prompt and the recall of relevant entries, and a periodic consolidation job. It publishes Builder.Memory.

func Permissions

func Permissions(coding bool) Feature

Permissions puts the permission layer (allow/ask/deny rules, modes; AGENT_PERMISSIONS*) in front of the tools and snapshots the git working tree at the start of runs on the local backend. It applies to the local backend and, with coding true, to the coding agent on a remote sandbox; with neither it contributes nothing (the work profile on a remote sandbox).

The mode is AGENT_PERMISSIONS; without it the local backend asks and the coding agent on a remote sandbox, which is isolated, does not (yolo: deny rules still apply). The interactive approvals gate stays behind it for the tools the policy has no rule for.

func Plan

func Plan() Feature

Plan offers update_plan and ask_user.

func ProfileCoding

func ProfileCoding() []Feature

ProfileCoding is the lean coding agent (AGENT_PROFILE=coding): ProfileWork plus the explore sub-agent, the syntax checks of written files and the permission layer, with the tool allow-list that leaves out the document viewer, the skills (unless the user has some) and the memory.

func ProfileMinimal

func ProfileMinimal() []Feature

ProfileMinimal is the smallest useful agent: the sandbox tools and the plan tools, with no artifacts, memory, skills, goals or titles.

func ProfileNamed

func ProfileNamed(name string) []Feature

ProfileNamed returns the feature set of a profile name (AGENT_PROFILE): "coding", "minimal", anything else the work profile.

func ProfileWork

func ProfileWork() []Feature

ProfileWork is the full feature set: the sandbox tools, skills, MCP, plan tools, project documents, artifacts, workspace checkpoints, titles, verification, goals and memory. It is what AGENT_PROFILE=work (or unset) runs. Code checks (AGENT_CODE_CHECKS) and permissions (local backend) apply when configured.

func ProjectDocs

func ProjectDocs() Feature

ProjectDocs adds the instructions of the project and of the user (AGENTS.md, CLAUDE.md, GEMINI.md, Cursor and Copilot files, .har/instructions.md; see package projectdocs) to the prompt, and the notes of subdirectories to the results of read_file, write_file and edit_file. The user's own ~/.har/AGENTS.md is read with the local backend, or when HARNESS_USER_INSTRUCTIONS is set.

func Sandbox

func Sandbox() Feature

Sandbox offers the sandbox tools: execute_command, job_output, job_kill, read_file, view_file, search_files, write_file, edit_file, list_files. Other features hook into them through Builder.SandboxTools. Without a configured sandbox backend it contributes nothing.

func Skills

func Skills() Feature

Skills offers the skills (<name>/SKILL.md folders): the load_skill tool, the skills index in the prompt, and their installation into sandboxes. The built-in skills, Options.ExtraSkills and the user directory (SKILLS_DIR) are read; the project skills come from the host with the local backend and from each thread's own /workspace with a remote one (skills.LoadSandbox). It publishes Builder.Skills and Builder.Installer.

func Titles

func Titles() Feature

Titles names new threads from their first exchange.

func ToolProfile

func ToolProfile(coding bool) Feature

ToolProfile applies the tool profile: with coding true the lean coding allow-list (no document viewer, skills only when the user has some, no memory unless AGENT_MEMORY_IN_CODING), and in both cases the AGENT_TOOLS overrides. It also drops the prompt sections of the skills and memory features whose tools it hides. It takes effect on the Skills and Memory features whatever the order.

func Verify

func Verify() Feature

Verify runs the checkers of the deliverables the agent writes and keeps the agent from finishing on an unverified one. It requires the Artifacts feature (and uses Skills, when installed, to install a checker's skill) and publishes Builder.Verifier.

func Workspace

func Workspace() Feature

Workspace checkpoints /workspace in a local Git history before every turn (per-file history, diff, restore), archives it after the run, and tells the model about it. It requires the Artifacts feature and publishes Builder.Workspace.

type Harness

type Harness struct {
	Store     Store
	Log       eventlog.Log
	Queue     queue.Queue
	Bus       queue.Bus
	Sandboxes sandbox.Manager
	Artifacts *artifacts.Service
	Skills    *skills.Registry
	Workspace *workspace.Service
	Runtime   *runtime.Runtime
	Agent     *agent.Agent
	// Memory is the memory service (nil without the Memory feature).
	Memory *memory.Service
	// contains filtered or unexported fields
}

Harness runs agent runs for any number of users and threads.

func New

func New(o Options) (*Harness, error)

New wires the harness: the core (store, models, sandboxes, infrastructure, agent loop, runtime) and the features of Options.Features (default: the profile of AGENT_PROFILE, see ProfileWork, ProfileCoding, ProfileMinimal).

func (*Harness) Cancel

func (h *Harness) Cancel(ctx context.Context, user, runID string) error

Cancel stops a run: a queued one is cancelled at once, a running one gets a cancel signal and ends with a "cancelled" RUN_FINISHED.

func (*Harness) Compact

func (h *Harness) Compact(ctx context.Context, user, threadID, model string) (*CompactResult, error)

Compact summarises the thread's history now with a run of kind compact on model, and waits for it. store.ErrRunActive (wrapped) when the thread has a run in progress.

func (*Harness) Events

func (h *Harness) Events(ctx context.Context, runID string, after int64) <-chan store.Event

Events streams the run's AG-UI events with seq > after, then follows it live until RUN_FINISHED or RUN_ERROR. Each event carries its seq (resume point).

Events takes no user: it trusts the caller to have established that the run belongs to the requesting user (Store.GetUserRun), as hosts/client and hosts/web do. A host that exposes run ids to end users without going through them must make that check itself.

func (*Harness) FactoryOf added in v0.4.0

func (h *Harness) FactoryOf() *Factory

FactoryOf returns the Factory service of a built harness (nil without the feature).

func (*Harness) Fork

func (h *Harness) Fork(ctx context.Context, user, threadID, messageID string) (*store.Thread, error)

Fork copies the thread's messages up to and including messageID ("" is the whole thread, a tool call is kept with its results) into a new thread titled "<old> (fork)".

func (*Harness) HasSandbox

func (h *Harness) HasSandbox() bool

HasSandbox reports whether runs can use a sandbox: a backend is configured and the Sandbox feature is installed.

func (*Harness) NewThread

func (h *Harness) NewThread(ctx context.Context, user, title string) (*store.Thread, error)

NewThread creates a conversation owned by user.

func (*Harness) Redo

func (h *Harness) Redo(ctx context.Context, user, threadID string) (*HistoryStep, error)

Redo reapplies the step Undo removed last: its messages and, in a git workspace, its files. It is valid until a message is sent. The thread must be idle (store.ErrRunActive).

func (*Harness) ReleaseSandbox added in v0.4.0

func (h *Harness) ReleaseSandbox(ctx context.Context, threadID string)

ReleaseSandbox destroys the sandbox of a thread that is finished for good and forgets it, so it stops counting against its owner's MAX_SANDBOXES_PER_USER at once instead of when the provider expires it. A thread without a sandbox is a no-op; a thread that is used again later simply gets a new one.

func (*Harness) Resume

func (h *Harness) Resume(ctx context.Context, user, threadID string, r ResumeRequest) (*store.Run, error)

Resume answers a run's interrupt (a tool approval or an ask_user question) and queues the run that continues the conversation. Follow it with Events.

func (*Harness) Run

func (h *Harness) Run(ctx context.Context) error

Run consumes queued runs until ctx is done, then lets in-flight runs finish (or interrupts them after the shutdown grace).

func (*Harness) Send

func (h *Harness) Send(ctx context.Context, user, threadID, text string, o RunOptions) (*store.Run, error)

Send adds a user message to the thread and queues a run answering it. The run is executed by Run; follow it with Events.

func (*Harness) Steer

func (h *Harness) Steer(ctx context.Context, user, runID, text string) error

Steer adds a message to a running run: the model sees it at its next step.

func (*Harness) SteerAs

func (h *Harness) SteerAs(ctx context.Context, user, runID, text string, a Author) error

SteerAs is Steer recording who sent the steer.

func (*Harness) Undo

func (h *Harness) Undo(ctx context.Context, user, threadID string) (*HistoryStep, error)

Undo removes the thread's last user message with everything after it and, in a git workspace, restores the files to the snapshot taken before that message's run. The replaced workspace state is kept so Redo can bring it back. The thread must be idle (store.ErrRunActive).

type HistoryStep

type HistoryStep struct {
	// Prompt is the user message removed (Undo) or restored (Redo).
	Prompt string
	// Files are the workspace paths whose content changed; empty without a git workspace.
	Files []string
	// CanUndo and CanRedo tell whether another step is available.
	CanUndo, CanRedo bool
}

HistoryStep is the outcome of Undo and Redo.

type Infra

type Infra struct {
	// Log is the per-run event log (default eventlog.NewMemory over the Store).
	Log eventlog.Log
	// Broker is the run queue and control bus (default queue.NewMemory).
	Broker Broker
	// Coordinator shares sandbox and sweeper locks (default: none, in-process).
	Coordinator Coordinator
	// Jobs persists the running background jobs so that a restarted process
	// resumes their keep-alives (default: in memory only).
	Jobs sandboxtools.JobList
	// Installs shares which skill revisions each sandbox holds, and the install
	// locks (default: in-process).
	Installs skills.InstallState
}

Infra is everything the harness shares between processes. Every field is optional: a missing one falls back to its in-process implementation, so a zero Infra is a self-contained single-process harness. A host that runs several processes injects implementations built on the infrastructure it has (package redisinfra for Redis).

type MCPServersFunc added in v0.5.0

type MCPServersFunc func(ctx context.Context, threadID, login string) ([]config.MCPServer, error)

MCPServersFunc returns the MCP servers a run may use besides the configured ones. An error is logged and the run continues without them.

type Options

type Options struct {
	// Config is the environment-driven configuration (config.Load).
	Config *config.Config
	// Store persists threads, runs, messages, artifacts, memory… (default: in memory;
	// store/pgstore for Postgres).
	Store Store
	// Models builds the chat models (default: llm.New over llmOptions(Config), the OpenAI-compatible
	// provider, or Anthropic with LLM_PROVIDER=anthropic).
	Models llm.Factory
	// Backend provides the sandboxes. Default: the backend named by
	// SANDBOX_BACKEND (local, opensandbox, none, or one registered with
	// backends.Register), else OpenSandbox when OPENSANDBOX_URL is set, else
	// none: the agent then has no sandbox tools and a prompt that says so.
	Backend sandbox.Backend
	// Blobs stores artifact contents (default: in the Store).
	Blobs artifacts.Blobs
	// Infra holds the implementations of what several processes share: run
	// queue and control bus, event log, locks, job list, skill installs. Every
	// part is optional and falls back to its in-process version. A host on
	// another transport (NATS, SQS...) injects its own; package redisinfra
	// builds the Redis one. Without it the harness is single-process.
	Infra *Infra
	// Features are the capabilities to install, in order (default: the profile
	// of AGENT_PROFILE: ProfileWork, ProfileCoding or ProfileMinimal). Compose
	// your own list from the constructors (Sandbox(), Memory()...) and your
	// own Features; see README "Features and profiles".
	Features []Feature
	// BuiltinSkills holds <name>/SKILL.md folders (default: skills/skillsfs).
	BuiltinSkills fs.FS
	// ExtraSkills holds more <name>/SKILL.md folders, added after the built-ins
	// and before the user directory (config SKILLS_DIR): the host's own skills.
	ExtraSkills fs.FS
	// Tools are extra tool providers (host-defined tools).
	Tools []tools.Provider
	// Hooks run at the end of every run, after the harness' own.
	Hooks []runtime.Hook
	// Version identifies the host to MCP servers.
	Version string
	// RuntimeID names this process in run ownership (default: hostname-random).
	RuntimeID string
	// MemoryKey, when set, names the memory (the key its entries are stored
	// under) a run of login on threadID reads and writes; "" means login's own.
	// A team host returns "project:<id>" for project threads.
	MemoryKey func(ctx context.Context, login, threadID string) string
	// MemoryUserKey names the user's private layer inside a shared memory ("" for none), MemoryShared
	// says whether a key is a memory shared between people (a project's).
	MemoryUserKey func(ctx context.Context, login, threadID string) string
	MemoryShared  func(key string) bool
	// MCPServers, when set, supplies more MCP servers for each run of login on threadID (a marketplace kept in
	// a database: the servers of the thread's project or of the user). They are merged after the configured
	// ones, are treated as untrusted (config.MCPServer.Untrusted) and need package mcpfeature to be imported.
	MCPServers MCPServersFunc
}

Options configures a Harness. Only Config is required.

type ResumeRequest

type ResumeRequest struct {
	// InterruptID is the interrupt's id (the approval id for a tool approval).
	InterruptID string
	// Reason is the interrupt reason: store.ReasonToolApproval or the ask_user reason.
	Reason string
	// Decision applies to tool approvals: store.DecisionApprove, DecisionDeny or DecisionRespond.
	Decision string
	// Always approves the tool for the rest of the run chain (scope "run").
	Always bool
	// Text is the answer to an ask_user question, or the free text of a respond.
	Text string
	// Model, Interactive and ReasoningEffort are the RunOptions of the resumed run.
	Model           string
	Interactive     bool
	ReasoningEffort string
	// Mode is ModeBuild or ModePlan; empty keeps the mode of the thread's previous run.
	Mode RunMode
}

ResumeRequest answers the interrupt a run ended with.

type RunMode

type RunMode string

RunMode is RunOptions.Mode.

const (
	// ModeBuild (the default): the run has all the tools its profile allows.
	ModeBuild RunMode = "build"
	// ModePlan: the run is read-only. The engine offers it only tools without
	// side effects (reads, searches, read-only MCP tools) and no command
	// execution, and its prompt asks for an investigation and a plan. A resumed
	// run keeps the mode of the thread's previous run.
	ModePlan RunMode = "plan"
)

type RunOptions

type RunOptions struct {
	// Model is required: an id the Config allows.
	Model string
	// ReasoningEffort is low|medium|high|… ("" for the model's default).
	ReasoningEffort string
	// Skills are skill names requested explicitly for this run.
	Skills []string
	// Interactive makes risky tool calls wait for Approve/Reject.
	Interactive bool
	// MessageID makes Send idempotent for that user message (optional).
	MessageID string
	// Sandbox says whether the run may use a sandbox (default SandboxAuto).
	// It is kept in the run record: a resumed run, a goal turn and a
	// compaction keep the mode of the thread's latest run.
	Sandbox SandboxMode
	// Mode is ModeBuild (default) or ModePlan (read-only: no tool may change
	// anything). It is kept in the run record, so a worker process honours it.
	Mode RunMode
	// Attachments are images sent with the message (at most MaxAttachments of
	// MaxAttachmentBytes each); they are stored in the thread's workspace.
	Attachments []Attachment
	// Author is the user who typed the message when it is not the thread's
	// owner (a project member), with AuthorKind and OnBehalfOf for a
	// supervisor; they are recorded on the message and shown to the model in
	// threads with several speakers. Empty means the owner.
	Author     string
	AuthorKind string
	OnBehalfOf string
}

RunOptions are the per-run settings of Send.

type SandboxMode

type SandboxMode string

SandboxMode is RunOptions.Sandbox.

const (
	// SandboxAuto (the default): the run has the sandbox tools when a backend
	// is configured and the Sandbox feature is installed; the sandbox is only
	// created when a tool first needs it. Without a backend the run simply has
	// no sandbox tools.
	SandboxAuto SandboxMode = "auto"
	// SandboxOff: the run has no sandbox tools, gets the no-sandbox prompt and
	// never creates (or uses) a sandbox, whatever the harness is configured with.
	SandboxOff SandboxMode = "off"
	// SandboxOn: like SandboxAuto, but Send fails with ErrInvalidRequest when
	// the harness cannot provide a sandbox (no backend, or no Sandbox feature).
	SandboxOn SandboxMode = "on"
)

type Store

type Store interface {
	store.Full
	sandbox.Store
	store.WorkspaceGitStore
}

Store is the persistence the harness needs: the core store plus the sandbox, workspace and catalog extensions. store/memstore and store/pgstore implement it.

Directories

Path Synopsis
adapters
blobs/s3blobs
Package s3blobs is the S3-compatible artifacts.Blobs backend (Dell ECS, RustFS, AWS).
Package s3blobs is the S3-compatible artifacts.Blobs backend (Dell ECS, RustFS, AWS).
errtrack
Package errtrack sends the errors the harness logs to an error tracker that speaks the Sentry protocol (Sentry, Rustrak, GlitchTip…).
Package errtrack sends the errors the harness logs to an error tracker that speaks the Sentry protocol (Sentry, Rustrak, GlitchTip…).
redisx
Package redisx builds the Redis client (Sentinel or standalone).
Package redisx builds the Redis client (Sentinel or standalone).
store/capstore
Package capstore persists the MCP marketplace (core/capabilities): the catalog and the installs of projects and users.
Package capstore persists the MCP marketplace (core/capabilities): the catalog and the installs of projects and users.
store/conformance
Package conformance is the behavioural test suite every store backend (memstore, filestore, pgstore) must pass: the same cases run against each one, so a backend cannot drift from the port's contract (core/store, core/sandbox.Store).
Package conformance is the behavioural test suite every store backend (memstore, filestore, pgstore) must pass: the same cases run against each one, so a backend cannot drift from the port's contract (core/store, core/sandbox.Store).
store/factorystore
Package factorystore implements factory.Store: Mem (in memory, for tests and single-process hosts) and PG (Postgres, shared by several processes).
Package factorystore implements factory.Store: Mem (in memory, for tests and single-process hosts) and PG (Postgres, shared by several processes).
store/filestore
Package filestore is a durable single-process store.Full for local hosts (CLI, TUI, desktop): it wraps store/memstore and persists the conversation state to an append-only JSON-lines journal in a state directory, so a closed terminal (or kill -9) never loses a session.
Package filestore is a durable single-process store.Full for local hosts (CLI, TUI, desktop): it wraps store/memstore and persists the conversation state to an append-only JSON-lines journal in a state directory, so a closed terminal (or kill -9) never loses a session.
store/memstore
Package memstore is an in-memory store.Full used by tests (and nothing else).
Package memstore is an in-memory store.Full used by tests (and nothing else).
store/pgstore/migrate
Package migrate applies the embedded SQL migrations (mirrors authn/internal/migrate).
Package migrate applies the embedded SQL migrations (mirrors authn/internal/migrate).
store/teamstore
Package teamstore implements store.TeamStore: Mem (in memory, optionally persisted to a JSON file, for local and single-process hosts) and PG.
Package teamstore implements store.TeamStore: Mem (in memory, optionally persisted to a JSON file, for local and single-process hosts) and PG.
sandbox module
ai module
app module
Package bench runs coding tasks through the real harness (local sandbox, coding profile) against a model and reports pass/fail with the cost: steps, tool calls, tokens, prompt-cache hits, wall time and memory.
Package bench runs coding tasks through the real harness (local sandbox, coding profile) against a model and reports pass/fail with the cost: steps, tool calls, tokens, prompt-cache hits, wall time and memory.
swebench
Package swebench turns SWE-bench instances (https://www.swebench.com) into bench tasks and scores the resulting repositories the way SWE-bench does.
Package swebench turns SWE-bench instances (https://www.swebench.com) into bench tasks and scores the resulting repositories the way SWE-bench does.
coding
codecheck
Package codecheck gives the agent immediate syntax feedback on the files it writes: after write_file or edit_file, a cheap per-extension command checks the file and its complaint is appended to the tool result, so a broken edit is fixed in the next step instead of surfacing at the end of a test run.
Package codecheck gives the agent immediate syntax feedback on the files it writes: after write_file or edit_file, a cheap per-extension command checks the file and its complaint is appended to the tool result, so a broken edit is fixed in the next step instead of surfacing at the end of a test run.
gitsafe
Package gitsafe takes restorable snapshots of a git working tree without touching what belongs to the user: no commit on a branch, no change to the index or the stash list.
Package gitsafe takes restorable snapshots of a git working tree without touching what belongs to the user: no commit on a branch, no change to the index or the stash list.
sandboxtools
Package sandboxtools exposes the thread sandbox to the model: execute_command (with background jobs: job_output, job_kill), read_file (text, documents, images), view_file (rendered pages), search_files, write_file, edit_file and list_files.
Package sandboxtools exposes the thread sandbox to the model: execute_command (with background jobs: job_output, job_kill), read_file (text, documents, images), view_file (rendered pages), search_files, write_file, edit_file and list_files.
sandboxtools/conformance
Package conformance checks that a sandbox adapter runs the harness' sandbox tools (execute_command with background jobs, read/write/edit/list files, search_files) end to end: the scripts those tools send through sandbox.Sandbox.Exec need bash, GNU coreutils, python3 and ripgrep in the sandbox image (docs/sandbox-adapters.md).
Package conformance checks that a sandbox adapter runs the harness' sandbox tools (execute_command with background jobs, read/write/edit/list files, search_files) end to end: the scripts those tools send through sandbox.Sandbox.Exec need bash, GNU coreutils, python3 and ripgrep in the sandbox image (docs/sandbox-adapters.md).
Package config loads the service configuration from environment variables.
Package config loads the service configuration from environment variables.
core module
engine
agent
Package agent is the agent loop: an own ReAct loop on eino ToolCallingChatModel that streams AG-UI events and checkpoints messages.
Package agent is the agent loop: an own ReAct loop on eino ToolCallingChatModel that streams AG-UI events and checkpoints messages.
approvals
Package approvals implements Work's interactive mode: risky tool calls of an interactive run pause before they execute until the user approves, denies or answers them (agent BeforeToolHook; decisions are applied by the store when the resume run is created and by the agent when it starts).
Package approvals implements Work's interactive mode: risky tool calls of an interactive run pause before they execute until the user approves, denies or answers them (agent BeforeToolHook; decisions are applied by the store when the resume run is created and by the agent when it starts).
eventlog
Package eventlog is the per-run AG-UI event log contract and its in-process implementation (MemoryLog).
Package eventlog is the per-run AG-UI event log contract and its in-process implementation (MemoryLog).
queue
Package queue holds the Redis-backed run queue, the per-run control channel (cancel) and the per-run steer list.
Package queue holds the Redis-backed run queue, the per-run control channel (cancel) and the per-run steer list.
runtime
Package runtime claims queued runs, drives the agent and finishes runs.
Package runtime claims queued runs, drives the agent and finishes runs.
syncx
Package syncx holds small concurrency helpers: a keyed mutex whose entries are freed on release and a bounded LRU cache.
Package syncx holds small concurrency helpers: a keyed mutex whose entries are freed on release and a bounded LRU cache.
tools
Package tools defines tool providers assembled per run.
Package tools defines tool providers assembled per run.
examples
sandbox-adapter
Package example is a worked sandbox adapter for a generic REST service that can create sandboxes and run commands in them.
Package example is a worked sandbox adapter for a generic REST service that can create sandboxes and run commands in them.
website command
Command website shows how a website embeds the harness as a Go library: one process serving its own pages and endpoints next to the agent.
Command website shows how a website embeds the harness as a Go library: one process serving its own pages and endpoints next to the agent.
features
artifacts
Package artifacts makes the files the agent produces under /workspace durable: snapshots after file-changing tools (and at run end), versioned and sha256-deduplicated content in a blob store (Postgres or a host-provided Blobs (see artifacts/s3blobs)), workspace restore on sandbox (re)creation, classified downloads, Office → PDF previews and user uploads.
Package artifacts makes the files the agent produces under /workspace durable: snapshots after file-changing tools (and at run end), versioned and sha256-deduplicated content in a blob store (Postgres or a host-provided Blobs (see artifacts/s3blobs)), workspace restore on sandbox (re)creation, classified downloads, Office → PDF previews and user uploads.
artifacts/workspace
Package workspace keeps a thread's /workspace history: a local Git repository with an automatic checkpoint before every AI turn, per-file history, diffs and restores, persisted across sandbox expiry (the .git directory is archived into the blob store after each run and restored into every new sandbox of the thread), plus the workspace status / explicit restore of the files panel.
Package workspace keeps a thread's /workspace history: a local Git repository with an automatic checkpoint before every AI turn, per-file history, diffs and restores, persisted across sandbox expiry (the .git directory is archived into the blob store after each run and restored into every new sandbox of the thread), plus the workspace status / explicit restore of the files panel.
commands
Package commands loads custom commands: markdown prompt templates a user invokes by name ("/review src/main.go").
Package commands loads custom commands: markdown prompt templates a user invokes by name ("/review src/main.go").
explore
Package exploretools provides the explore tool: a read-only sub-agent that investigates the repository with search_files, list_files and read_file in its own short conversation and returns a short report.
Package exploretools provides the explore tool: a read-only sub-agent that investigates the repository with search_files, list_files and read_file in its own short conversation and returns a short report.
factory/budget
Package budget meters and enforces what factory tasks spend.
Package budget meters and enforces what factory tasks spend.
factory/delegate
Package delegate lets an agent hand work to other agents: the delegate tool runs a full sub-agent (its own thread and sandbox, a role-specific prompt) and returns its report, and the prompt sections tell a thread which role and task it was started for.
Package delegate lets an agent hand work to other agents: the delegate tool runs a full sub-agent (its own thread and sandbox, a role-specific prompt) and returns its report, and the prompt sections tell a thread which role and task it was started for.
factory/forge
Package forge connects the agent factory to GitHub: the factory.Forge over the REST API, the tools an agent uses to open and follow its pull request, the repository checkout of a task's sandbox, and the loop that drives a pull request through CI, review and merge.
Package forge connects the agent factory to GitHub: the factory.Forge over the REST API, the tools an agent uses to open and follow its pull request, the repository checkout of a task's sandbox, and the loop that drives a pull request through CI, review and merge.
factory/lessons
Package lessons distils what a finished factory task taught into durable, repo-level memory entries.
Package lessons distils what a finished factory task taught into durable, repo-level memory entries.
factory/policy
Package policy governs what the agents of a factory task may do.
Package policy governs what the agents of a factory task may do.
factory/review
Package review is the merge-blocking gate of the agent factory: an independent reviewer that reads a pull request's diff against the task it was meant to solve and decides whether it may merge.
Package review is the merge-blocking gate of the agent factory: an independent reviewer that reads a pull request's diff against the task it was meant to solve and decides whether it may merge.
factory/tasks
Package tasks is the factory's task service: it creates tasks, dispatches the ready ones to agent runs, and moves a task through its states as runs end, pull requests open, CI and the reviewer speak.
Package tasks is the factory's task service: it creates tasks, dispatches the ready ones to agent runs, and moves a task through its states as runs end, pull requests open, CI and the reviewer speak.
factory/triggers
Package triggers creates factory tasks from the outside: a cron scheduler that fires stored cron triggers, and an HTTP handler for GitHub webhooks that normalizes each delivery into a factory.Event and creates the tasks of the webhook triggers it matches.
Package triggers creates factory tasks from the outside: a cron scheduler that fires stored cron triggers, and an HTTP handler for GitHub webhooks that normalizes each delivery into a factory.Event and creates the tasks of the webhook triggers it matches.
goals
Package goals keeps a thread working toward its goal (harness v2 §6): the goal is part of every run's system prompt, each completed run is judged by a short model call, and an unmet goal gets a new run until its turns run out.
Package goals keeps a thread working toward its goal (harness v2 §6): the goal is part of every run's system prompt, each completed run is judged by a short model call, and an unmet goal gets a new run until its turns run out.
mcp
Package mcptools exposes tools of configured MCP servers (MCP_SERVERS).
Package mcptools exposes tools of configured MCP servers (MCP_SERVERS).
memory
Package memory is the harness's memory service: per-user entries with a path, title, content, tags, importance and metadata, searched with Work's hybrid ranking, written under Work's policy (triggers, warn/strict write mode, secret redaction, soft/hard delete), recalled in the system prompt and consolidated periodically (deduplication, cleanup of deleted entries).
Package memory is the harness's memory service: per-user entries with a path, title, content, tags, importance and metadata, searched with Work's hybrid ranking, written under Work's policy (triggers, warn/strict write mode, secret redaction, soft/hard delete), recalled in the system prompt and consolidated periodically (deduplication, cleanup of deleted entries).
memory/memorytools
Package memorytools exposes Work's memory MCP tools (memory_search, memory_get, memory_create, memory_update, memory_delete, memory_create_batch, memory_delete_batch, memory_capabilities) with the same names, input schemas and result shapes, backed by memory.Service.
Package memorytools exposes Work's memory MCP tools (memory_search, memory_get, memory_create, memory_update, memory_delete, memory_create_batch, memory_delete_batch, memory_capabilities) with the same names, input schemas and result shapes, backed by memory.Service.
permissions
Package permissions is the safety layer of the local/coding profile: rules (allow / ask / deny) and modes decide, before a tool call runs, whether it is executed, needs the user's approval or is refused.
Package permissions is the safety layer of the local/coding profile: rules (allow / ask / deny) and modes decide, before a tool call runs, whether it is executed, needs the user's approval or is refused.
plan
Package harnesstools provides the harness v2 agent tools update_plan and ask_user (the memory tools are in memorytools).
Package harnesstools provides the harness v2 agent tools update_plan and ask_user (the memory tools are in memorytools).
projectdocs
Package projectdocs puts the instructions of the project and of the user (AGENTS.md and the files other agent tools read) in front of the agent of the coding profile, so it knows the build and test commands and the conventions without spending a tool call to find them.
Package projectdocs puts the instructions of the project and of the user (AGENTS.md and the files other agent tools read) in front of the agent of the coding profile, so it knows the build and test commands and the conventions without spending a tool call to find them.
skills
Package skills is the skill registry: a skill is a folder with a SKILL.md (frontmatter name and description) and optional scripts and references.
Package skills is the skill registry: a skill is a folder with a SKILL.md (frontmatter name and description) and optional scripts and references.
skills/skillsfs
Package skillsfs embeds the built-in skills (builtin/<name>/).
Package skillsfs embeds the built-in skills (builtin/<name>/).
skills/skilltools
Package skilltools exposes load_skill: it returns a skill's SKILL.md (without frontmatter) and file list, and records the skill as loaded by the run.
Package skilltools exposes load_skill: it returns a skill's SKILL.md (without frontmatter) and file list, and records the skill as loaded by the run.
titles
Package titles gives threads a short model-written title after their first completed run (harness v2 §5), unless the user set one.
Package titles gives threads a short model-written title after their first completed run (harness v2 §5), unless the user set one.
verify
Package verify runs the deliverable checkers of harness v3 §4: after a tool call changed a file under /workspace/outputs/, the skill checker that matches its extension runs in the thread's sandbox (≤ 60 s) and its result becomes an agent.CheckResult (appended to the tool result, CUSTOM work.verification, the verification StopGuard and the goal judge).
Package verify runs the deliverable checkers of harness v3 §4: after a tool call changed a file under /workspace/outputs/, the skill checker that matches its extension runs in the thread's sandbox (≤ 60 s) and its result becomes an agent.CheckResult (appended to the tool result, CUSTOM work.verification, the verification StopGuard and the goal judge).
hosts
clienttest
Package clienttest is the conformance suite of client.Client: any implementation (in process, over HTTP, a future one) must pass Run, so that a front end behaves the same against all of them.
Package clienttest is the conformance suite of client.Client: any implementation (in process, over HTTP, a future one) must pass Run, so that a front end behaves the same against all of them.
httpapi
Package httpserver exposes a harness.Harness over HTTP for web front ends: a JSON API for threads, runs, approvals, files and models, the run's AG-UI events as Server-Sent Events (the SSE id is the event seq, so reconnects resume with Last-Event-ID or ?after= without loss or duplicates), and a small built-in browser UI (ui/) served at / and /ui/.
Package httpserver exposes a harness.Harness over HTTP for web front ends: a JSON API for threads, runs, approvals, files and models, the run's AG-UI events as Server-Sent Events (the SSE id is the event seq, so reconnects resume with Last-Event-ID or ?after= without loss or duplicates), and a small built-in browser UI (ui/) served at / and /ui/.
worker
Package worker is the headless host that executes agent runs queued by other processes (a web server, an API, a scheduler): it connects to the shared Redis queue and Postgres store, consumes runs, and exposes an admin HTTP server (/healthz, /readyz, /metrics).
Package worker is the headless host that executes agent runs queued by other processes (a web server, an API, a scheduler): it connects to the shared Redis queue and Postgres store, consumes runs, and exposes an admin HTTP server (/healthz, /readyz, /metrics).
client module
tui module
Package longtest drives the real harness (local sandbox, coding profile) through long scripted sessions: a fake model that behaves like an agent doing 50-200 steps of read_file / search_files / edit_file / execute_command in a generated repository, with realistic tool-output sizes (some 20-60 KB, which trigger spill and masking).
Package longtest drives the real harness (local sandbox, coding profile) through long scripted sessions: a fake model that behaves like an agent doing 50-200 steps of read_file / search_files / edit_file / execute_command in a generated repository, with realistic tool-output sizes (some 20-60 KB, which trigger spill and masking).
Package mcpfeature is the implementation of harness.MCP(): the tools of the MCP servers of the configuration (MCP_SERVERS, .mcp.json, mcp.servers in config.yml), connected per run.
Package mcpfeature is the implementation of harness.MCP(): the tools of the MCP servers of the configuration (MCP_SERVERS, .mcp.json, mcp.servers in config.yml), connected per run.
modelinfo module
Package prompts holds the agent's system prompts: a registry of variants selected per model (LLM_PROMPT_VARIANTS), the shared wording of the optional sections, and the assembly order that keeps the request cache-stable — the static instructions first, the dynamic context (date, user, goal, recalled memories, conversation summary) last (harness v3 §5, §6).
Package prompts holds the agent's system prompts: a registry of variants selected per model (LLM_PROMPT_VARIANTS), the shared wording of the optional sections, and the assembly order that keeps the request cache-stable — the static instructions first, the dynamic context (date, user, goal, recalled memories, conversation summary) last (harness v3 §5, §6).
Package redisinfra builds the harness.Infra of a deployment that shares Redis between processes: the run queue and control bus, the event log, locks, the background-job list and the skill installs.
Package redisinfra builds the harness.Infra of a deployment that shares Redis between processes: the run queue and control bus, the event log, locks, the background-job list and the skill installs.

Jump to

Keyboard shortcuts

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