bonnie

package module
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 46 Imported by: 1 module, 0 packages

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

README

BONNIE

BONNIE

Durable agent runs for Go.
Survive a crash. Wait days for a human. Answer over HTTP, Slack, Discord, Telegram, or GitHub.

Go Reference MIT

[!WARNING] Early and experimental. Use at your own risk. BONNIE is pre-1.0 software under active development. The API can change without notice. The durability and the sandbox claims have tests, but no release is proven in production. Do not use a release for work whose loss would hurt. Read Limits before you deploy.


An agent turn usually lives and dies with the process. Stop the process during a tool call and the work is gone. Ask the user a question and you must hold the process open until the user answers.

BONNIE corrects that. It wraps the Kit agent SDK, and a run becomes durable:

run, _ := runner.Start(ctx, "deploy-42", runtime.Input{Text: "Deploy the app."})

if run.State == runtime.RunWaiting {
    fmt.Println(run.Suspend.Prompt) // "Which region?"
    os.Exit(0)                      // ← the process can stop here
}

Come back tomorrow, in a different process, and complete the run:

run, _ := runner.Resume(ctx, "deploy-42",
    []runtime.InputResponse{{Text: "eu-west-1"}})

fmt.Println(run.Response) // "Deployed to eu-west-1."

The journal keeps the full conversation, including saved tool calls and results. Replay does not repeat completed steps. An external effect can occur before its result is saved, however; recovery cannot prove its outcome. Use external idempotency keys for actions that must not repeat. See Durable work.

Contents

Install

As a library:

go get github.com/mark3labs/bonnie

As a CLI, download the Linux amd64 or arm64 archive and checksum file from Releases. Verify SHA-256 before extracting or executing the binary. Follow the full manual installation procedure. A checksum confirms agreement with the published manifest, not an independent publisher signature or proof of safety.

Alternatively, download and review the installer source. It downloads the release binary and refuses one whose checksum it cannot verify. It selects the first existing writable directory from ~/.local/bin, ~/bin, and /usr/local/bin, or creates ~/.local/bin if none qualifies.

Download the script:

curl -fsSLO https://raw.githubusercontent.com/mark3labs/bonnie/master/install.sh

Inspect it with less or an editor:

less install.sh

Execute only after review:

bash install.sh

The URL tracks master; --version selects the binary release, not the script revision. To pin a release and choose a directory after review:

bash install.sh --version v0.35.0 --bin-dir "$HOME/.local/bin"

Ensure the install directory is in PATH, then run bonnie version. The script does not configure Go, provider credentials, or sandbox prerequisites.

As a CLI, from source:

go install github.com/mark3labs/bonnie/cmd/bonnie@latest

With Nix. This gives you the CLI, and the microsandbox CLI (msb) on its PATH:

nix profile add github:mark3labs/bonnie   # or: nix run github:mark3labs/bonnie

Set a provider key, or use provider login for OpenAI ChatGPT/Codex. BONNIE uses the provider that Kit is configured for:

export ANTHROPIC_API_KEY=sk-ant-...   # or OPENAI_API_KEY, or GEMINI_API_KEY

BONNIE also reads a .env in the working directory when one is there, so you can write the key (and any channel credential) into a file instead of exporting it each time. An exported variable still wins over the file, and a missing .env is not an error.

BONNIE needs Linux. To author an agent also needs Go 1.27+; the release binary does not. The kernel must be 5.13 or newer with Landlock enabled, which is the default on each current distribution. A sandbox is not optional, and the default sandbox needs no installation. Docker or msb give stronger isolation. macOS and Windows are not supported — see Limits.

Development shell

devenv gives you a shell with Go 1.27, golangci-lint, goreleaser, and the microsandbox CLI. devenv.nix defines it:

devenv shell
go test -race ./...

The repository has an .envrc, thus direnv allow opens the same shell when you cd into it.

Flake output What it is
packages.default, packages.bonnie the BONNIE CLI
packages.microsandbox the msb CLI and its libkrunfw
apps.msb nix run github:mark3labs/bonnie#msb
overlays.default both packages, for your own nixpkgs

Scaffold an agent

Scaffold an agent, edit one file, then run it.

bonnie init my-agent --model anthropic/claude-sonnet-4-5
cd my-agent
go mod tidy
# edit instructions.md — that file is the agent's system prompt
bonnie dev

bonnie init writes instructions.md (the system prompt), main.go (the one call you own, in newAgent), bonnie_gen.go (the generated wiring), go.mod, and the seed directories skills/ and context/. It copies authored context files into each run; it does not add them to the prompt. With --tools it also writes a sample tool at tools/echo/tool.go. It never replaces a file: if one file exists, it refuses, names each file it found, and changes nothing.

// main.go — the full default agent
package main

import "github.com/mark3labs/bonnie"

func main() {
	newAgent().Serve()
}

// newAgent builds the agent. Evals build the same agent with it.
func newAgent() *bonnie.Agent {
	return bonnie.New(
		bonnie.WithModel("anthropic/claude-sonnet-4-5"),
	)
}
# speak to it over HTTP
curl -s localhost:8080/bonnie/v1/runs -d '{"text":"What are you?"}'

# or speak to it in the terminal — one durable conversation, streamed live
bonnie chat --addr 127.0.0.1:8080

Chat uses the full terminal width and an alternate-screen transcript. Use Page Up/Down or the mouse wheel to scroll. New output follows the bottom only when you are already there. Ctrl+Home goes to the first output; Ctrl+End goes to the latest output. Enter sends a message; Shift+Enter adds a new line. The input grows to show up to 8 lines; longer text scrolls inside it. Drag over the transcript to select text; release the button to copy it. A wrapped paragraph is copied as one line. The copy uses OSC 52, so the terminal must support it (kitty, WezTerm, iTerm2, Ghostty, Alacritty, Windows Terminal, and zellij do; GNOME Terminal does not). Inside tmux, the copy also goes through tmux load-buffer -w, so it works whatever set-clipboard is. In other terminals, Shift+drag uses the terminal's own selection.

Local commands: /help, /new, /retry, /cancel, and /exit (or /quit). /new starts a separate conversation and keeps the old run on the server. /retry sends the last user message again as a new turn. It does not undo history or tool effects, so an external action can repeat. Cancel an active turn, or wait for it to finish, before you use /new or /retry.

Files under context/ are context files. BONNIE copies them into each run's isolated sandbox by default. It does not add them to the prompt or replace files the model has written.

For a deliberate single-user development workflow, a host can use one shared working-files directory across all runs:

bonnie.New(
    bonnie.WithSharedDirectory("./working-files"),
)

This uses the directory directly instead of copying seed files. It keeps the default Landlock filesystem confinement: runs share this directory, but do not get unrestricted host access. Explicit Landlock and Local providers are also supported; Local provides no isolation. Other backends are rejected.

Do not combine this option with WithContextFiles. Overlapping opens through the same provider are rejected, not queued. The guard does not coordinate separate processes or provider instances: use one server for this development directory. Run pruning does not remove the shared directory. Without this option, each run has separate working files.

For one-off tasks, enable automatic sandbox cleanup:

bonnie.New(
    bonnie.WithRunSandboxCleanup(bonnie.SandboxCleanupPolicy{
        CompletedAfter: time.Hour,
        RetiredAfter:   time.Hour,
    }),
).Serve()

Import time for these durations. This works in the compiled agent; it does not need the BONNIE CLI. Sandbox cleanup runs at startup and once per minute. Zero keeps the sandbox for that state. FailedAfter and CancelledAfter can also be set. Pending, running, and waiting runs are never cleaned up. The journal and channel addresses remain. A later turn on a cleaned-up run starts without its earlier files, so publish task output before the run completes.

Sandbox cleanup cannot be combined with WithSharedDirectory, shared provider modes, or WithAgentFactory. Negative durations and providers without deletion support are rejected at startup. Use one server for the journal and working files; cleanup locks do not coordinate separate processes. Each deletion has a 30-second timeout. Failures are logged and retried on the next sweep.

Files under skills/ are the agent's skills: one *.md per skill, or one subdirectory per skill with a SKILL.md in it, each with YAML frontmatter that gives a name and a description. Those two fields go in the system prompt; the body arrives only when the model calls activate_skill, so a large skill set costs few tokens until it is used. The tree's skills/ is the authored set. The managed agent-tree path selects that directory explicitly and does not automatically discover model-written skills in run working files unless workspace discovery is explicitly enabled. Skills beside the host process are not inherited.

Enable repository skills in each run's workspace with:

bonnie.New(
    bonnie.WithWorkspaceSkills(bonnie.WorkspaceSkills{}),
).Serve()

Discovery scans only .agents/skills/<bundle>/SKILL.md and .kit/skills/<bundle>/SKILL.md, recursively inside the sandbox, before the next model request. Plain skills/ directories do not qualify. WithSkills("") disables tree skills, not this opt-in. Repository skills cannot replace authored names. Names have the form workspace/repo-a/review--<64-hex-path-hash>; metadata includes the source location and repository scope. Bodies remain on-demand through activate_skill; assets use the sandbox-relative bundle base directory. Neither metadata nor activation authorizes execution.

Defaults are depth 12, 100 skills, 128 KiB per file, and 32 KiB of escaped metadata. Scans honor nested .gitignore files and prune .git, dependency, and cache directories. They never use host ignore configuration or follow symlinks. Discovery opens sandbox compute at startup. Saved content versions are journalled before requests; the first resumed request uses its saved catalogue even if source files changed. Assets are live files, not snapshots. See Tools and Skills for exact limits, exclusions, diagnostics, remote helper requirements and the untrusted-input boundary.

There is no configuration file. A setting is a file at a known path (instructions.md, context/, skills/, tools/) or an option in main.go. Thus a setting that does not exist is a compile error, and not a key that nothing reads. The built binary accepts operator flags such as --addr, --model, --web, --sandbox, and --schedule-clock. Explicit flags override the related options, so an operator can change settings without a new build.

Use WithCommand to add Cobra commands and flags to the built binary. Use Agent.Configure to apply parsed options before serving, and Agent.WithJournal or Agent.WithRuntime for scoped operations without starting an HTTP server. See Agent commands and flags for a complete example and resource ownership rules.

When the agent is ready, bonnie build compiles the tree into one static binary. The binary contains the tools, the instructions, the skills, and the seed files. It serves on a host that has no Go and no BONNIE installation.

The agent binary also includes its operator commands:

./my-agent update models             # refresh the shared model database
./my-agent auth login openai          # log in with ChatGPT/Codex
./my-agent auth login anthropic       # store an API key (hidden prompt)
./my-agent auth status
./my-agent auth logout openai
./my-agent serve                      # same action as ./my-agent
./my-agent chat --run <run-id>        # continue a run on the HTTP server
./my-agent runs                       # the run console: inspect, trace, act
./my-agent runs list                  # read the configured local journal
./my-agent runs show <run-id> --json
./my-agent runs trace <run-id>        # a turn's trace as a waterfall
./my-agent runs answer <run-id> --approve
./my-agent schedules list             # use the running server's HTTP API
./my-agent version                    # agent and BONNIE build information

chat and schedules default to the agent's configured address and accept --token for bearer authentication. runs defaults to WithJournal and accepts --journal to select another local journal. Inspection works when the server is stopped. No command starts a server except the default action and serve.

Use WithUpdateCommand(false), WithAuthCommand(false), WithChatCommand(false), WithRunsCommand(false), WithSchedulesCommand(false), or WithVersionCommand(false) in main.go to disable individual commands. These options control command availability, not access to stored credentials, HTTP routes, or journal files, and do not promise smaller binaries. The same commands are included when you compile the agent with go build. Agent.Run remains terminal-free. Development and sandbox provisioning commands remain in the BONNIE CLI.

Use the library

A durable run in 25 lines. The journal on disk is what makes the run durable.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/mark3labs/bonnie/runtime"
	"github.com/mark3labs/bonnie/sandbox"
	kit "github.com/mark3labs/kit/pkg/kit"
)

func main() {
	// Each message is journalled here before it is kept.
	journal, err := runtime.OpenSQLiteJournal(".bonnie")
	if err != nil {
		log.Fatal(err)
	}
	defer journal.Close()

	// sandbox.Agent gives the model a shell and a filesystem that are not
	// the host's. It also registers the human-in-the-loop tools.
	runner := runtime.NewRunner(journal, sandbox.Agent(
		sandbox.Landlock(),
		kit.WithModel("anthropic/claude-sonnet-4-5"),
	))

	run, err := runner.Start(context.Background(), "run-1",
		runtime.Input{Text: "In one sentence, what is a durable agent run?"})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(run.Response)
}

runtime.KitAgent is the unsandboxed seam. It builds a Kit agent whose core tools — shell, read, write, edit — run in your process, with your files and your credentials. bonnie.New() never uses it directly: it wraps it in sandbox.Agent. Call runtime.KitAgent only when your process is already inside isolation that you control. A working directory is not isolation: an absolute path leaves it.

Start the program again with a different message and the same run ID. BONNIE replays the conversation first, thus the agent remembers:

run, _ := runner.Start(ctx, "run-1", runtime.Input{Text: "What did I just ask?"})
// `You asked me "In one sentence, what is a durable agent run?"`

Runs continue after a crash or a restart

A served agent (Agent.Serve, Agent.Run) continues each run that has no stop reason when it starts: a run that is running (written by a process that is gone) or interrupted. No new message is necessary. The result goes to the channel the conversation is on; HTTP clients read it from the run. On SIGTERM, the agent interrupts each turn in flight instead of waiting for it, so the next start continues it.

Runner.Continue does the least work that ends the turn. A final answer or a human-input wait that is already in the journal closes the turn without a model call. A durable human answer that the model has not seen is sent to it. Other runs continue the saved conversation through ContinuationAgent. A tool call that the crash left without a result gets an "effect unknown" result and is not run again, unless both the saved run's replay-safe policy and the current WithReplaySafeTools policy permit the tool. Adding a tool only to the current policy is not enough. A run whose input never became durable fails with runtime.ErrRecoveryInputLost; send it again.

A host that owns the runner calls Runner.Recover at startup and Runner.Drain before it closes the journal. Runs in the submission inbox belong to RunScheduler, scheduled dispatches to the schedule engine, and NATS JetStream tasks to broker redelivery (channel.RecoveryOwner).

New input and interrupted work

Nonempty Start input always means a new command, even when it equals a saved message. If unfinished work owns the conversation, Start returns a nil Run and runtime.ErrInputDeferred. BONNIE does not queue the command. Retain it as undelivered and recover the admitted work with StartRetry:

run, err := runner.Start(ctx, runID, newInput)
if errors.Is(err, runtime.ErrInputDeferred) {
    // Keep newInput undelivered. originalInput is the admitted recovery data.
    recovered, retryErr := runner.StartRetry(ctx, runID, originalInput)
    if retryErr != nil {
        return retryErr
    }
    if recovered.State != runtime.RunCompleted {
        // If waiting, use Resume for the human answer before new input.
        return nil
    }
    run, err = runner.Start(ctx, runID, newInput)
}
// Handle err and run through the host's normal outcome path.

Import errors for errors.Is. Files, context, title, origin, trigger, and whitespace text also count as explicit input. Empty slices and zero-value metadata do not. Ordinary refusal leaves saved work unchanged, before session restore or repair. Recovery of a previously durable cancellation command can write cancellation bookkeeping first.

StartRetry uses saved work and the original input if it was not yet saved. It returns a cancelled snapshot rather than starting a new turn. It does not promise idempotency after completion. Start(..., runtime.Input{}) retains legacy recovery behavior, not explicit admission. Do not cancel old work unless cancellation is intended. The caller must retain deferred commands durably; successful Start calls and external effects are not exactly once. One Runner or process must own each run.

runtime.Input carries more than text:

Field Function
Text the user's message — the one part that becomes conversation history
Files file parts for the turn (kit.LLMFilePart)
Context what the model must know for this turn only; shown before Text, never history
Title names the run in operator listings; recorded on the first turn
Origin where the conversation lives (Channel, Kind); recorded on the first turn

Examine what occurred, with no server:

bonnie runs --journal .bonnie                 # the interactive console
bonnie runs inspect --journal .bonnie run-1   # the console, on one run
bonnie runs list --journal .bonnie
bonnie runs show --journal .bonnie run-1
bonnie runs trace --journal .bonnie run-1 --turn 2

bonnie runs opens the run console on a terminal (without one, it prints the list). The left side lists runs and the turns of the selected run; the main panel has four tabs:

  • Overview: state, origin, caller, sandbox, trace ID, counts, the open question of a waiting run, tool usage, and turn durations.
  • Conversation: the transcript, with each tool call and its result, reasoning, suspensions, and answers. / searches it.
  • Trace: a waterfall of the selected turn — invoke_agent, a chat span per step, an execute_tool span per call — rebuilt from journal times, so it needs no tracing backend. A call with no journalled outcome reads as unknown, not done.
  • Journal: every record; Enter opens its payload.

The console reads the journal, refreshes every second, and works with a stopped server. When the HTTP channel at --addr answers, it can also act on the selected run: a answers a waiting run, n sends a message, c cancels the turn, x retires the run, C clears and m compacts the context. The same actions are commands — runs answer, send, cancel, retire, clear, compact — for scripts. ? lists every key; the mouse works too. A drag in the main panel selects text and copies it, as in chat. On the overview and conversation tabs the selection stays on its text when you scroll, and a wrapped message copies as one line. On the trace and journal tabs it marks the cells on the screen, so a scroll or a key drops it.

RUN    TITLE              STATE      STEPS  LAST
run-1  What is a durab…   completed  2      You asked me "In one sentence, …"

Park and resume

This is the primary function. An agent asks a question, your process stops, and a new process completes the work.

BONNIE has two tools for this. The model can call them:

Tool Parks the run to...
ask_human ask the operator a question
request_approval get approval before a dangerous action

runtime.KitAgent registers both, thus sandbox.Agent and bonnie.New() register them too by default. To omit both built-in human-input tools:

bonnie.New(bonnie.WithoutHumanInput()).Serve()

The model decides when to call these tools; there is no automatic approval policy for external actions. WithoutHumanInput does not change sandbox permissions, remove caller-supplied tools, or prevent a custom tool from parking a run. The model can still ask questions in response text. This option cannot be combined with WithAgentFactory, which owns the agent's tools. Low-level hosts can use sandbox.AgentWithoutHumanInput or runtime.KitAgentWithoutHumanInput.

runner := runtime.NewRunner(journal, sandbox.Agent(
	sandbox.Landlock(),
	kit.WithModel("anthropic/claude-sonnet-4-5"),
	kit.WithSystemPrompt("Before you deploy anything, use ask_human to ask "+
		"which region to deploy to."),
))

run, err := runner.Start(ctx, "deploy-42", runtime.Input{Text: "Deploy the app."})
if err != nil {
	log.Fatal(err)
}

if run.State == runtime.RunWaiting {
	fmt.Println("agent asks:", run.Suspend.Prompt)
	return // no compute is held — the process can stop
}

Later, in any process that can read the same journal:

run, err := runner.Resume(ctx, "deploy-42",
	[]runtime.InputResponse{{Text: "eu-west-1"}})

A parked run holds no compute. To wait one week costs nothing. The examples/github-bot agent does this for real: it asks a question in a comment, the process can stop, and a later delivery resumes the run from the journal.

Your own tools

A BONNIE tool is a Kit tool. Give it to the agent and it joins the sandboxed set and the human-in-the-loop set:

type chargeInput struct {
	Amount int    `json:"amount" description:"Amount in cents."`
	UserID string `json:"user_id" description:"Who to charge."`
}

chargeCard := kit.NewTool("charge_card", "Charge a customer's card.",
	func(ctx context.Context, in chargeInput) (kit.ToolOutput, error) {
		// This runs in YOUR process, with your secrets. The model sees
		// only the result you return.
		if err := stripe.Charge(in.UserID, in.Amount); err != nil {
			return kit.ErrorResult(err.Error()), nil
		}
		return kit.TextResult("Charged."), nil
	})

// In an agent tree:
bonnie.New(bonnie.WithTools(chargeCard)).Serve()

// Or one layer down:
runner := runtime.NewRunner(journal, sandbox.Agent(
	sandbox.Landlock(),
	kit.WithModel("anthropic/claude-sonnet-4-5"),
	kit.WithExtraTools(chargeCard),
))

You can also write a tool that parks the run. ask_human is exactly this:

return kit.ToolOutput{
	Content: "Waiting for the finance team.",
	Halt:    true,
	FinalValue: runtime.SuspendRequest{
		Kind:   "approval",
		Prompt: "Approve a $4,000 refund?",
	},
}, nil

The run stops, Start returns with State == RunWaiting, and run.Suspend.Prompt holds your question.

The turn ends at the halting tool: the model is not asked again until the run resumes. A tool that the model calls in the same step as the halting tool still runs, because Kit runs the calls of one step together.

In an agent tree, bonnie init --tools writes one sample tool. A tool there is tools/<name>/tool.go with func Tool() kit.Tool, and the directory name is the tool's name. bonnie dev and bonnie build generate the wiring again, thus main.go never names a tool.

A tool that needs the current agent can instead export func Tool(scope bonnie.ToolScope) kit.Tool. BONNIE constructs it for each Start or Resume, before the first prompt. Existing zero-argument tools need no change. The scoped form avoids a global agent pointer and permits child model calls through scope.Kit.Subagent.

For tools registered in application code, use bonnie.WithToolFactory(func(context.Context, bonnie.ToolScope) ([]kit.Tool, error)). The scope also provides RunID, Session, and Exec for sandbox commands. scope.Session.Caller() is who sent the current turn; check Verified. Factories run before WithKitSetup callbacks. Do not retain a scope after its execution ends or call Kit.Prompt from an active tool on the same Kit instance. Child calls are not durable BONNIE runs and can repeat after interruption. Custom Go tool code runs on the host; use scope.Exec for sandbox commands. See Tools and Skills for a complete tree tool and application factory example.

Self-modification

Under bonnie dev, ask the agent to change itself — "add a tool that converts temperatures" — and its modify_agent tool does it. A subagent edits a staged copy of the tree's authored files, the changed tree must build, and only then is the change written to the tree. The dev loop rebuilds, and the next message on the run is answered by the new build. A binary from bonnie build never has the tool. bonnie dev --no-self-modify leaves it out.

A deployed agent can propose a change instead, with selfmod.Remote: it opens a draft pull request and never changes the running deployment. It needs an Authorize function and GitHub credentials. See Self-Modification.

Sandboxes

Built-in file and command tools run in a sandbox. Custom Go tool code runs on the host. Explicit sandbox.Local() provides no isolation, and the low-level runtime.KitAgent factory is unsandboxed. WithSandbox selects a backend. If you do not call it, you get sandbox.Landlock(), and not your process.

The default confines tool calls to the run's own working files with the Linux Landlock LSM, and needs no installation. That is why it is the floor: a default that needs Docker is a default that people switch off.

bonnie.New().Serve() // already sandboxed

Select a stronger backend when the work is not trusted. bonnie init writes both lines as comments, thus the choice is visible:

bonnie.New(
	bonnie.WithSandbox(sandbox.Docker(sandbox.WithDockerImage("python:3.12-slim"))),
	bonnie.WithNetwork(sandbox.NetworkPolicy{Mode: sandbox.NetworkDenyAll}),
).Serve()

To let an operator select a backend without rebuilding the agent, declare its permitted providers with WithSandboxes:

bonnie.New(
	bonnie.WithSandboxes(
		sandbox.Microsandbox(
			sandbox.WithMicrosandboxImage("python:3.12-slim"),
			sandbox.WithMicrosandboxMemory(2048),
			sandbox.WithMicrosandboxCPUs(2),
		),
		sandbox.Local(), // No isolation; select explicitly for development only.
	),
).Serve()
./my-agent                        # First provider: microsandbox.
./my-agent --sandbox microsandbox # Keeps the configured image, memory, and CPUs.
./my-agent --sandbox local        # Explicit host execution for development.

Compiled agents use Cobra and Fang for styled help and startup errors. Run ./my-agent --help to see the permitted sandbox names and the default. This adds no separate executable; Microsandbox still requires msb. Host-registered Go flags remain supported, as do single-dash long flags such as -addr. Agent.Run(ctx) does not parse flags or render command help.

The first provider is the default. Only the selected provider must be available; a failure never selects another backend. An unknown name returns an error with the permitted names. The list must be non-empty, with non-nil providers and unique, non-empty names. Do not combine WithSandboxes with WithSandbox or WithAgentFactory, or call WithSandboxes more than once.

WithSandbox permits just its one provider. With neither option, a compiled agent permits only Landlock. Agent.Run does not read flags and uses the first provider. Network and environment options apply to the selected backend; a backend that cannot enforce the network policy returns an error.

If you wire the runner yourself, it is the same provider one layer down:

provider := sandbox.Docker(sandbox.WithDockerImage("python:3.12-slim"))

runner := runtime.NewRunner(journal, sandbox.Agent(provider,
	kit.WithModel("anthropic/claude-sonnet-4-5"),
))

The model gets ten sandbox-backed tools (see the table below). Their default file root is sandbox.WorkDir, /workspace. Landlock file operations reject paths outside this directory, including symlink escapes, with sandbox.ErrOutsideWorkDir. Local provides no isolation and permits other host paths. Docker and microsandbox permit absolute paths inside their guest filesystem; their boundary is the container or microVM, not only the work directory.

Local, Landlock, Docker, and microsandbox support asynchronous shell jobs. shell waits up to 30 seconds by default, then returns status: "running" with a job_id and output paths. wait_seconds can set a shorter wait (1–30); zero selects the default. Reaching this wait limit does not stop the command or sandbox. Use shell_status, shell_wait, and shell_cancel to observe, wait for, or cancel that job. Output returned to the model is bounded to 32 KiB per stream; the output files do not have a disk-use limit.

Jobs continue after a sandbox handle closes. Local and Landlock share active job ownership between handles from the same provider. A fresh provider can recover saved completed results, but reports an unfinished host job as unknown. Docker and microsandbox use guest job files and process identity to reconnect. Stopping a sandbox need not preserve running processes. Process-group cancellation cannot contain children that deliberately detach. Local and Landlock accept Command.Timeout for an execution deadline; asynchronous CLI jobs reject that setting rather than silently ignore it.

Job support is optional for custom backends. A backend without JobSandbox keeps synchronous shell execution. EnvInjected and Seeded preserve job support, and EnvInjected adds environment values to launched jobs.

The shell tool checks for Bash inside the sandbox on each call. It uses Bash when available and falls back to sh otherwise. Each result names the selected shell. A failed command is never retried under another shell. Detection does not open the sandbox before the first tool call.

Backend Isolation You install Network policy
sandbox.Landlock() — default filesystem containment, shared kernel — none: a policy is refused
sandbox.Local() none — development only — none: a policy is refused
sandbox.Docker() container namespaces Docker allow-all, deny-all
sandbox.Microsandbox() microVM, guest kernel msb allow-all, deny-all, allow-list

The Docker and microsandbox backends drive a CLI, and Landlock is pure Go. When microsandbox is selected, startup first uses msb from PATH, then <journal>/msb or <journal>/microsandbox/bin/msb (<journal> is .bonnie by default). Existing binaries are not upgraded. If none exists, BONNIE downloads its tracked release (sandbox.MicrosandboxVersion, currently v0.7.7), checks its pinned SHA-256, and installs msb and libkrunfw in <journal>/microsandbox. The first install needs network access and a writable journal directory. The host still needs microsandbox's system requirements, including KVM on Linux. Automatic installation supports Linux amd64/arm64 and macOS arm64. Use bonnie.WithSandboxDownload(false) to disable downloads. A custom sandbox.WithMicrosandboxBinary path is never downloaded or replaced. Thus BONNIE stays one static binary.

The default is containment, not isolation. Landlock confines the filesystem and does not inherit host environment credentials by default. Keep journals and secrets outside permitted paths. Injected environment values can be printed into model-visible tool results; injection is not secret protection. Landlock does not confine the network, and it does not give the command its own kernel. For hostile code, use Docker or microsandbox, and stop egress.

Each Landlock command runs in a child process that re-executes BONNIE's binary, restricts itself, and then becomes the command. The restriction stays after execve and is inherited, thus a subshell cannot escape it.

The microsandbox adapter is verified on Linux with KVM (msb 0.6.18, all 18 conformance cases, network policies enforced with real egress). Its network policy is fixed when the sandbox is made. To attach again with a different policy fails with ErrPolicyMismatch, and does not use the old rules in silence.

Constrain the network. A backend that cannot enforce a policy refuses it with ErrPolicyUnsupported. It never permits everything in silence:

provider := sandbox.Docker()
provider.SetNetworkPolicy(sandbox.NetworkPolicy{Mode: sandbox.NetworkDenyAll})

Select the best backend that is available, with no silent fall-back to no isolation:

provider, err := sandbox.Select(ctx, sandbox.Microsandbox(), sandbox.Docker(), sandbox.Landlock())

sandbox.Seeded(provider, dir) copies a local directory into each sandbox, and never replaces a file that the run already has. An agent tree wraps its context/ directory this way.

The sandbox opens at the first tool call that needs it, thus a parked run holds no container. Read the godoc of each provider in package sandbox before you deploy. Each provider states what it contains and what it does not.

Web UI

Open an agent tree in your browser with hot reload:

bonnie dev my-agent --web

This replaces the default terminal interface and opens /web/ after the server is ready. If the browser cannot open, the CLI prints the URL.

For a deployed agent, enable the UI with bonnie.WithWebUI(true) in main.go, or pass --web to the compiled agent. It is disabled by default. bonnie serve --web also enables it.

The UI includes conversations, approval and input responses, a run list, and cancel, compact, clear, and reset controls. Assistant messages use safe Markdown. The journal trace groups records by turn, with text and tool summaries, sequence numbers, timestamps, and expandable formatted payloads. Use the filter to find text, tool names, errors, roles, and record kinds. Clear changes model context; reset retires a run. Neither deletes its journal.

The UI uses templ, shadcn-templ, and Datastar. All browser assets are embedded in the binary. Event-driven live updates show committed journal state and escaped transient assistant text. Reconnects restore durable state, not old transient text. Reasoning deltas are not shown. Navigation does not reload the document, and the browser saves the System, Light, or Dark theme choice.

Web access uses the HTTP channel's authenticator. For browser deployments, use a session cookie or an authenticated reverse proxy; there is no built-in bearer-token login. This is an operator UI: an authenticated operator can read all conversation runs and their full payloads. Do not expose it to untrusted users. Web actions also have same-origin and CSRF checks.

The default /web/ page is chat. Send a first message to create a run; send followups from the same bottom composer. New chat starts an empty chat. Use Runs (?view=runs) for run controls, or Trace (?view=trace&run=ID) for journal records and filtering. These views do not share the chat transcript or composer.

See web/README.md for asset and template maintenance.

HTTP API

bonnie serve --journal .bonnie --model anthropic/claude-sonnet-4-5 --sandbox docker

Or run an agent tree. Its configuration is Go in its own main.go, thus you serve the tree when you run it:

bonnie dev my-agent          # hot reload while you work
bonnie build my-agent        # one static binary, then run it anywhere

Or mount the channel in your own server. A channel gives you its routes, and it is also the inbound surface that a handler resolves an address through:

runner := runtime.NewRunner(journal, sandbox.Agent(provider, opts...))
ch := bonniehttp.New(runner)

mux := http.NewServeMux()
for _, rt := range ch.Routes() {
	handler := rt.Handler
	mux.HandleFunc(rt.Method+" "+rt.Path, func(w http.ResponseWriter, r *http.Request) {
		handler(w, r, ch, nil) // nil: no other channel to hand off to
	})
}
http.ListenAndServe(":8080", mux)

Each route is under /bonnie/v1. The version segment is the wire contract.

Route Function
GET /bonnie/v1/health liveness: {"ok":true,"status":"ready"}, no journal read
GET /bonnie/v1/info agent name, BONNIE version, mounted channels
POST /bonnie/v1/runs start a run, or route to the run that serves an address
GET /bonnie/v1/addresses/{address} report the run that an address resolves to
POST /bonnie/v1/addresses/{address} send to the run that an address resolves to
GET /bonnie/v1/runs/{id} report a run's durable state
POST /bonnie/v1/runs/{id} send a message to one exact run
POST /bonnie/v1/runs/{id}/respond answer a parked run
POST /bonnie/v1/runs/{id}/cancel stop the turn in progress
POST /bonnie/v1/runs/{id}/reset retire the run and free its address
POST /bonnie/v1/runs/{id}/clear drop the conversation, keep the run
POST /bonnie/v1/runs/{id}/compact summarise the older messages now
GET /bonnie/v1/runs/{id}/stream NDJSON event stream, resumable with ?cursor=
# Start a run. It parks on a question.
curl -s localhost:8080/bonnie/v1/runs -d '{"text":"Deploy the app. Ask me the region first."}'
# {"run_id":"run-e8b3fa...","cursor":4,"state":"waiting",
#  "suspend":{"kind":"question","prompt":"Which region?"}}

# Answer it.
curl -s localhost:8080/bonnie/v1/runs/run-e8b3fa.../respond \
  -d '{"responses":[{"text":"eu-west-1"}]}'
# {"run_id":"run-e8b3fa...","state":"completed","response":"Deployed to eu-west-1."}

Each error reply has a message and a stable code: {"error":"...","code":"run_not_found"}. The codes include run_not_found, invalid_run_id, run_not_waiting, run_active, run_retired, unknown_turn_policy, bad_request, too_large, and internal. A client can branch on the code, and not on the text.

POST /bonnie/v1/runs accepts operation_id as an idempotency key, and turn_policy to select what occurs when a turn is already running: steer (the default) injects the message into the turn, queue lets the turn finish first.

Search and targeted edits

The built-in tool names are shell, shell_status, shell_wait, shell_cancel, read_file, write_file, list_files, grep, find, and edit. Do not reuse these names for extra tools; Kit's existing collision behavior applies. Host core tools stay disabled. All file operations use the selected sandbox.

Tool Arguments and defaults
shell Required command; optional dir; wait_seconds defaults to 30 (0–30).
shell_status Required job_id.
shell_wait Required job_id; wait_seconds defaults to 30 (0–30).
shell_cancel Required job_id.
read_file Required path.
write_file Required path and full content; can create files.
list_files path defaults to /workspace.
find Required pattern; directory path defaults to /workspace; limit defaults to 100 (1–1000, zero uses default).
grep Required nonempty pattern; file or directory path defaults to /workspace; optional glob; literal defaults to false; context defaults to 0 (0–10); limit defaults to 100 matching lines (1–1000, zero uses default).
edit Required existing-file path; either old_text and new_text, or replacements (1–100 objects with both fields). Do not mix forms.

Relative paths start at /workspace. Absolute paths use the backend's namespace and restrictions. Local maps /workspace to the run directory, but does not provide isolation and permits other host paths. Landlock rejects paths outside its work directory, including symlink escapes. Guest backends use guest paths.

Search returns JSON text with results, truncated, and a reason when partial. Paths are relative to the selected directory, with slash separators. Single-file grep uses the basename. Structured records preserve filenames with newlines. Traversal is lexical, excludes .git directories, includes other dotfiles, ignores non-regular files, and does not follow descendant symlinks. The selected root follows the backend's normal path policy. These tools do not honor .gitignore. Narrow the path or glob for large trees.

Globs use slash-separated segments: *, ?, and character classes match within one segment. A segment exactly ** matches zero or more directories. Thus *.go matches only root files; **/*.go also matches nested files. Absolute, malformed, blank, and . or .. segment patterns are rejected. grep uses Go regular expressions by default, or an exact case-sensitive substring with literal: true. It searches each line, not across lines. Each matching line is one result, with path, one-based line, text, and before/after arrays of line/text records. CR is removed only as part of CRLF; a final line needs no LF. No matches is a successful empty result.

Search stops at 10,000 visited entries, 30 seconds (or the caller's earlier deadline), the requested result limit, or the 32 KiB response limit, including JSON framing. Count and byte limits stop after evidence of an omitted result. NUL-containing binary files are skipped. Files above 1 MiB are skipped and make results partial. A very long result line can exhaust the response limit without being included. Visit/size limits state the partial reason; filesystem errors, cancellation, and deadlines are tool errors, not complete search results. Existing ReadFile operations read whole files: these ceilings bound accepted input, work, and model output, not backend allocation or process memory.

For a single exact edit:

{"path":"main.go","old_text":"return false","new_text":"return true"}

For several regions validated against the original file:

{"path":"main.go","replacements":[{"old_text":"oldName","new_text":"newName"},{"old_text":"obsolete comment","new_text":""}]}

edit accepts UTF-8 files without NUL, at most 1 MiB. Empty new_text deletes; omitted new_text is an error. Empty old_text is an error. Each old text must occur exactly once, including overlapping occurrences. Regions must not overlap; adjacent regions are valid. Inserted text is never searched by later replacements in the request. All regions are validated before one write. Validation errors do not write, and a missing file is not created. Success reports the requested path, replacement count, and resulting byte count.

A context-cancellable gate serializes edit and write_file within one tool set. It does not coordinate shell commands, custom tools, separate handles or processes, or external writers. Reads and enumeration are not a snapshot. Writes are not compare-and-swap transactions. A write failure does not promise rollback; read and check current content before retrying an uncertain edit. There is no automatic edit approval policy, and no exactly-once guarantee across a crash between a write and journal persistence. Custom providers can keep the required Sandbox interface unchanged; enumeration uses optional DirectoryReader, or a POSIX sh fallback through sandbox Exec.

Addresses

Chat platforms have threads, not run IDs. Send an address, and BONNIE keeps the mapping in the journal. Thus a restart does not orphan a conversation:

curl -s localhost:8080/bonnie/v1/runs -d '{"address":"session-42","text":"hi"}'

The same address always resolves to the same run. POST /bonnie/v1/runs/{id} is the opposite: it targets one exact run, and returns 404 instead of making a run.

Host agent presence

A host can advertise an agent in a presence.Registry after all channel lifecycles have started. Registration and refresh failures fail Agent.Run; shutdown publishes draining and unregisters using a bounded context.

bonnie.New(
    bonnie.WithPresence(bonnie.PresenceConfig{
        Registry: registry, AgentID: "support-agent",
        Labels: map[string]string{"region": "eu-west"},
        // Set externally advertised URLs explicitly; bind addresses are not URLs.
        Endpoints: []presence.Endpoint{{Channel: "http", Address: "https://agent.example.com/bonnie/v1/runs", Input: true, Delivery: true}},
    }),
).Serve()

AgentID and Registry are required. InstanceID is generated randomly when omitted, and RefreshInterval defaults to 10 seconds. Negative intervals are refused. If the registry implements presence.TTLStore, the interval must be less than its TTL. When Endpoints is omitted, mounted channels implementing channel.PresenceProvider provide endpoint data, including HTTP. Presence does not schedule or assign work. Without WithPresence, host behavior is unchanged.

NATS presence registry

Use a caller-owned NATS connection with JetStream enabled:

// Import presencenats "github.com/mark3labs/bonnie/presence/nats".
registry, err := presencenats.New(ctx, nc, presencenats.Config{
    Bucket: "agents", Create: true, // Explicit permission to create resources.
})
if err != nil { return err }
// Pass registry to WithPresence. Use the same AgentID in WithNATS.
agents, err := registry.Discover(ctx, presence.Filter{
    Labels: map[string]string{"region": "eu-west"},
})
if err != nil { return err }
_ = agents
snapshot, changes, err := registry.Watch(ctx, presence.Filter{})
if err != nil { return err }
_ = snapshot
for event := range changes {
    if event.Err != nil { return event.Err } // Start a new watch to resynchronise.
    // event.Deleted removes event.Record.Identity from the local view.
}

The bucket is the discovery scope. Its default TTL is 30 seconds. Existing buckets must match the requested TTL. Watches poll at min(TTL/3, one second); they include an initial snapshot and report expired records as deletions. This is current-state discovery, not a durable history of every join and leave. Protect registration and discovery with NATS permissions. Labels are not authorization claims. A different live instance cannot replace an agent record.

All built-in channels report input and delivery capabilities separately. NATS also reports connection readiness; the webhook channels report local configured capabilities, not remote platform health. HTTP addresses are relative unless explicit endpoint overrides provide a public URL. Overrides replace the full endpoint list and are the application's responsibility. No credentials are published. Presence expiry is not proof that task execution stopped and must not trigger automatic reassignment. Scheduling, claims, and failover remain outside this feature.

See the deployment guide for registry ownership, watch error handling, and memory-store limits, and the option reference for all PresenceConfig fields.

Chat channels

Slack, Discord, Telegram, and GitHub put the same durable runs into a conversation. Mount a channel in main.go, put its credentials in the environment, and run:

bonnie.New(
	bonnie.WithSlack(slack.Config{}),
	bonnie.WithDiscord(discord.Config{}),
	bonnie.WithTelegram(telegram.Config{Username: "mybot"}),
	bonnie.WithGitHub(github.Config{BotName: "my-agent"}),
).Serve()
export SLACK_BOT_TOKEN=xoxb-... SLACK_SIGNING_SECRET=...
export DISCORD_BOT_TOKEN=... DISCORD_PUBLIC_KEY=...
export TELEGRAM_BOT_TOKEN=... TELEGRAM_WEBHOOK_SECRET=...
export GITHUB_APP_ID=... GITHUB_APP_PRIVATE_KEY=... GITHUB_WEBHOOK_SECRET=...
bonnie dev

Credentials come from the environment and never from code. A missing credential is a startup error that names the variable. The GitHub bot name is a setting and not a secret, thus it stays in the config.

Channel Webhook route Verification Address
slack POST /slack/events v0 HMAC signature <channel>/<thread_ts>, or <channel> for a DM
discord POST /discord/interactions Ed25519 signature the channel or thread ID
telegram POST /telegram shared secret header <chat_id>, or <chat_id>/<topic>
github POST /github/events HMAC signature <owner>/<repo>/issues/<n>, or <owner>/<repo>/pulls/<n>/reviews/<id>

An address is channel-local. The framework puts the channel's name in front of it, thus the durable form is slack/C123/1700000000.000900.

Each channel answers in the platform's ACK period while the turn continues. The reply goes back to the thread. A parked run posts its question, and the next message on the thread is the answer. /new in a thread retires the run and starts a new conversation in the same place.

The GitHub channel is a GitHub App. A comment that names @<BotName> on an issue, a pull request, or a review thread starts or continues a run. The channel mints an installation token for each event, uses it only to post back and to read the pull request's changed files, and never lets the token enter the run. A review thread is its own conversation, separate from the pull request's timeline. The hooks OnIssue, OnPullRequest, and OnCheckSuite let the host start a turn from an event with no comment.

While a turn runs, the Slack channel shows what the agent is doing. The mode is slack.Config.Activity: ActivityMessage (the default) edits one placeholder message, ActivityStatus uses Slack's assistant status and needs the assistant:write scope, and ActivityOff shows nothing until the reply.

A mounted channel can also start a conversation on another channel. A route handler gets channel.Outbound beside channel.Inbound:

to, ok := out.To("slack")
if ok {
	err := to.Receive(ctx, "C0123456789", "the nightly digest, please",
		channel.SendOptions{Auth: principal})
}

This is an agent hand-off and not a notification: the text becomes turn input, and the model runs on the destination channel. The destination binds the address before the turn runs, thus a platform event that arrives during the turn continues this run.

The per-platform setup, the dispatch rules, and what is deliberately not implemented are in the godoc of package channel and each adapter below it.

Model database refresh

Both bonnie update models [source] and ./my-agent update models [source] refresh Kit's shared model database. They need no server, provider key, or Kit executable. Rebuild an existing agent once with this Bonnie version to add the command; later catalog updates do not need a new binary.

bonnie update models
bonnie update models https://example.com/models.json
bonnie update models ./models.json
bonnie update models embedded

With no source, Kit uses KIT_MODELS_URL, then https://models.dev/api.json?type=all. Explicit HTTP(S) URLs download a catalog; other sources load a local JSON file. HTTP work has a 30-second limit and honors earlier cancellation. embedded removes the cache, also when it is already absent. It restores the embedded catalog on the next registry load.

On Linux, the shared cache is $XDG_DATA_HOME/kit/providers.json, defaulting to ~/.local/share/kit/providers.json. Imports and resets affect subsequent loads by Kit and other compatible agents for that user. Restart running agents to use the model database: existing registries do not reload. Counts describe the imported catalog, including model types that are not chat models, not the merged registry. This command does not update binaries or restart servers.

Use only trusted catalog sources. This explicit host operation is outside an agent run's sandbox. Cancellation or a reporting error cannot undo an update already committed by Kit; an output error can occur after the cache changed.

update alone displays help without changing storage. Compiled agents enable the group by default. Use WithUpdateCommand(false) to remove it before adding a custom update group with WithCommand. Later options win. Disabling the command does not restrict filesystem access or prevent Kit from reading the shared cache. Agent.Run does not register commands.

CLI

bonnie update models [source]  Refresh the shared model database
bonnie auth     Manage provider login credentials
bonnie init     Scaffold an agent tree
bonnie dev      Run an agent tree with hot reload and the built-in TUI
bonnie build    Compile an agent tree into one static binary
bonnie eval     Run the evals of an agent tree and report the scores
bonnie serve    Mount the HTTP channel and serve durable runs, with no tree
bonnie chat     Interact with an agent over the HTTP channel in a terminal
bonnie runs     Inspect and manage durable runs
bonnie sandbox  Reclaim the sandboxes of finished runs
bonnie version  Print the BONNIE version
bonnie init my-agent --model anthropic/claude-sonnet-4-5
bonnie init .                      adopt this directory; never replaces a file
bonnie init my-agent --tools       add a sample Go tool

bonnie dev my-agent                hot reload and the terminal interface
bonnie dev my-agent --tui=false    the serve loop alone, for CI
bonnie dev my-agent --dry-run      print the discovery plan, build nothing

bonnie build my-agent              one static binary at ./my-agent
bonnie build my-agent --output bin/agent

bonnie eval my-agent --judge openrouter/typesafe/jev-1.14
bonnie eval my-agent --strict      a missed soft threshold fails, for CI
bonnie eval show my-agent          open the newest saved run again

bonnie chat --addr 127.0.0.1:8080
bonnie chat --addr 127.0.0.1:8080 --run <run-id>

bonnie serve --addr :8080 --journal .bonnie \
             --model anthropic/claude-sonnet-4-5 \
             --sandbox docker --sandbox-deny-network \
             --slack --discord --telegram

bonnie runs --journal .bonnie --addr 127.0.0.1:8080
bonnie runs list --journal .bonnie --state waiting
bonnie runs show --journal .bonnie run-1
bonnie runs show --journal .bonnie run-1 --json | jq '.[] | select(.kind=="message")'
bonnie runs trace --journal .bonnie run-1 --json
bonnie runs answer run-1 --reject "not on a Friday" --addr 127.0.0.1:8080

bonnie sandbox prune --journal .bonnie --sandbox docker --dry-run

--sandbox accepts landlock (the default), docker, microsandbox, local, or auto. none is refused by name, because it was the old default and still lives in scripts.

bonnie serve has no --github flag: the GitHub channel needs a bot name, which is a setting in code and not an environment variable. Mount it from an agent tree with bonnie.WithGitHub.

runs reads the journal directly, thus it works while the server is stopped — which is when you need it.

Provider login

Use the shared auth command to manage Kit's provider credentials:

bonnie auth login openai                                   # ChatGPT/Codex OAuth
bonnie auth login anthropic                                # API key, hidden prompt
printenv GROQ_API_KEY | bonnie auth login groq --api-key-stdin
bonnie auth login amazon-bedrock --region eu-central-1
bonnie auth status
bonnie auth logout openai

Compiled agents include the same commands: replace bonnie with ./my-agent. These commands do not start the agent's HTTP server. WithAuthCommand(false) removes them from the compiled agent, but does not stop Kit from loading stored credentials.

auth login openai is BONNIE's OAuth flow for OpenAI ChatGPT/Codex access, not the general OpenAI API. It is the only OAuth login in BONNIE, because Kit's SDK login (kit.LoginProvider) supports openai only.

For other providers in Kit's model database that accept API keys, auth login <provider> stores an API key. The key comes from a hidden prompt, or from standard input with --api-key-stdin. It is never a command-line argument, so it does not reach shell history or the process list. A stored key takes precedence over the provider's environment variable. --region stores the AWS region with an amazon-bedrock key; without it, a rotated key keeps the stored region. auth login openai --api-key-stdin stores an OpenAI API key instead of OAuth. GitHub Copilot uses OAuth only; log in with kit auth login copilot. Keys stored with kit auth login are in the same store, and agents use them.

Stored credentials can take precedence over environment keys; remove stored OpenAI OAuth credentials if you want to switch to an API key. Login does not select a model. Select an accessible OpenAI model in main.go:

bonnie.New(bonnie.WithModel("openai/gpt-5.4")).Serve()

auth status lists stored providers and credential types. It does not show secrets, refresh tokens, test account access, or report environment keys. auth logout removes stored credentials from the shared Kit store. It does not revoke the account grant, remove environment keys, or change providers already loaded by running agents.

Kit stores credentials at $XDG_CONFIG_HOME/.kit/credentials.json. When XDG_CONFIG_HOME is not set, the default is ~/.config/.kit/credentials.json. Use the same user and configuration directory for login and the agent. Keep the store writable so Kit can save refreshed tokens. In a container or remote deployment, use persistent storage. Protect the file and its directory from other users, and do not put credentials in source control or sandbox working files.

Login uses a loopback callback on port 1455. For a remote host, forward this port to the host where the login command runs. For example, run this on your local machine before you start login on the remote host:

ssh -L 1455:127.0.0.1:1455 user@remote-host

Login prints the URL; it does not open a browser. There is no manual code-entry fallback. Login ends after at most five minutes and can be cancelled with Ctrl+C. Open the login URL in your local browser. Do not expose the callback port on a public interface. After login, restart running agents to load the new credentials.

Journal

The journal is the durability seam. Two implementations are in the box:

runtime.NewMemoryJournal()            // tests and ephemeral runs
runtime.OpenSQLiteJournal(".bonnie")  // SQLite, one database for the journal root

SQLiteJournal writes <root>/journal.db through a pure-Go driver (modernc.org/sqlite). Thus BONNIE still builds and cross-compiles with CGO_ENABLED=0, and bonnie build still makes one static binary. The database uses WAL mode and fsyncs each commit. runtime.WithFsync(runtime.FsyncRelaxed) trades a bounded loss window for throughput.

One record for each row, thus any SQLite client can read a run:

sqlite3 .bonnie/journal.db \
  "SELECT seq, role, text FROM records WHERE run_id = 'run-1' ORDER BY seq"

What the database gives, against the JSONL files that it replaced:

  • A step is atomic. A tool-calling step is one transaction. Thus the torn single write that a file append permitted is closed, and not only smaller.
  • Concurrent writers are safe, and not refused. SQLite serialises write transactions across processes, and the (run_id, seq) primary key makes a reused sequence number a constraint violation. The per-run lock file, and the ErrRunOwnedElsewhere that it caused, are gone.

Upgrade. A .bonnie directory that still has runs/*.jsonl from an earlier BONNIE is imported at the first open. Records keep their sequence numbers, and each source file is renamed to <run>.jsonl.imported and not deleted. The import is idempotent, thus a crash in the middle costs one more read.

Supply your own journal with seven methods:

type Journal interface {
	Append(ctx context.Context, rec Record) (seq int, err error)
	Replay(ctx context.Context, runID string) ([]Record, error)
	Checkpoint(ctx context.Context, runID string, state RunState) error
	State(ctx context.Context, runID string) (RunState, error)
	Runs(ctx context.Context, state RunState) ([]string, error)
	Persisted() bool
	Close() error
}

The table-driven conformance suite in runtime/journal_conformance_test.go runs against each implementation. Add yours, and it gets the full suite.

Events

Subscribe to a run's events in the process:

events, unsubscribe := runner.Events().Subscribe("run-1", 0)
defer unsubscribe()

for ev := range events {
	fmt.Println(ev.Seq, ev.Type, ev.Text)
}

The types are run_state, run_suspend, run_resume, and run_response, and the live deltas that Kit forwards during a turn.

Or over HTTP, one JSON object for each line:

curl -sN localhost:8080/bonnie/v1/runs/run-1/stream

Each event has a monotonic seq. If a client disconnects, connect again with the last seq it saw, and lose nothing:

curl -sN "localhost:8080/bonnie/v1/runs/run-1/stream?cursor=12"

Durable events are anchored to the journal record that caused them. Thus a cursor keeps its meaning after a restart. Live-only deltas are never replayed.

Session controls

runner.Steer("run-1", "actually, use eu-west-1")   // joins the turn in progress
runner.Cancel("run-1")                             // stops the turn
runner.Clear(ctx, "run-1")                         // forgets the conversation
runner.Compact(ctx, "run-1")                       // summarises the older messages
runner.Retire(ctx, "run-1", "user asked for a new conversation")

To cancel keeps each completed step, thus the run restores to a valid conversation and continues with Start. To retire is permanent: Start and Resume then refuse the run with ErrRunRetired, and the run stays readable.

runner.Snapshot(ctx, runID) reports a run without a turn. runner.IsActive(runID) reports whether a turn runs now.

Run states

pending → running → completed
                  → waiting    (parked for a human; continue with Resume)
                  → cancelled  (stopped by an operator; continue with Start)
                  → interrupted (host stopped; continue with Continue or Recover)
                  → failed     (the agent could not finish the turn)
                  → retired    (closed for good; Start and Resume refuse it)

A persisted running state can remain after a crash; it does not prove a live executor. Use Runner.IsActive for this process. Served agents recover unfinished running and interrupted work at startup.

How it works

BONNIE uses four public Kit extension points. There is no fork and no patched SDK:

Need Kit API
Journal each message Options.SessionManager
Checkpoint each step Kit.OnStepFinish
Inject replayed context Kit.OnContextPrepare
Park for a human kit.ToolOutput{Halt, FinalValue}

Three properties are the difference between a demonstration and something you can deploy:

  • Replay is lossless. A journalled message keeps its typed parts, thus a resumed run knows which tools it called and what they returned. This is not exactly-once execution of external effects.
  • A step commits atomically. SQLite saves a tool-calling step in one transaction through kit.StepAppender, not one file write and fsync. An effect can occur before the result is saved. Recovery supplies an "effect unknown" result rather than repeating an uncertain call, unless both saved and current policy permit it through WithReplaySafeTools. Replay-safe tools must enforce authorization and external idempotency themselves. Restore can also repair incomplete trailing steps from legacy or custom journals.
  • To cancel keeps finished work. A step is written before the context is examined, thus a cancelled turn loses only the step in progress.

The full detail, with the Kit citations, is in the godoc of runtime/. The code is the specification.

Limits

Stated plainly, because the failure modes are not obvious:

  • Linux only. BONNIE's floor is the Landlock LSM, thus a release builds for linux/amd64 and linux/arm64 and nothing else. macOS and Windows are not supported and are not on the roadmap: to restore macOS needs a seatbelt (sandbox-exec) backend of equal strength first, and not one more build target. A kernel older than 5.13, or a kernel booted with Landlock disabled, has no default sandbox. BONNIE refuses to start instead of a run with no confinement — use --sandbox docker there.
  • The default sandbox is containment, not isolation. Landlock confines the filesystem and keeps host credentials away from a command. It does not confine the network, and it shares the host kernel.
  • Do not run BONNIE as a user in the docker group. Landlock mediates the open of a file, and not the connection to a socket. Thus a tool call reaches /var/run/docker.sock when the process can, and that is a full host escape. No path setting closes it. Use an unprivileged user, or microsandbox.
  • Docker is namespaces, not a kernel. Use microsandbox for hostile code.
  • microsandbox is verified on Linux with KVM. Each network policy mode is enforced, but the policy is fixed when the sandbox is made. To attach again with a different policy fails with ErrPolicyMismatch.
  • Sandbox egress is open until you set a policy, and the default backend cannot set one — it refuses the policy instead of ignoring it.
  • A halt stops the turn, not the step. Kit runs the tool calls of one step together, thus a tool that the model calls in the same step as request_approval (or another halting tool) still runs before the run parks. Approval gates the next step, not a sibling call.
  • A skill's bundled files stay on the host. Kit names a skill's scripts/, references/, and assets/ files in the text of the activation, with a host path. The tools run in a sandbox that does not have that path, thus the model is told about a file that it cannot open. Put what the model must read in the skill body, and put a file that it must open in context/, which is copied into the sandbox.
  • The HTTP channel verifies a caller only when you configure one. http.WithAuthenticator (or bonnie.WithHTTPAuthenticator) checks every route but GET /bonnie/v1/health and mints the run's identity from what it proved. Without one the channel carries a Principal it does not examine, so authenticate in front of it, and operation_id is refused because an idempotency key with no proven owner reads another caller's run. The chat channels are different: each one verifies its platform's signature, and a channel with no credentials refuses to serve. That verifies the platform and not the person: a user ID in a verified Slack event is Slack's word.
  • Run ownership is per host, and the journal does not refuse a second writer. SQLite serialises write transactions and rejects a reused sequence number, thus two processes that write one run cannot corrupt it. That is journal integrity and not turn coordination: two servers that both execute the same run still interleave the conversation. SQLite locking also needs POSIX locks that work, thus a journal on a network filesystem is still unsafe.
  • Events are journal-anchored. The stream replays the journal after the in-memory backlog, thus a reconnect — also after a restart — has no gap. Live-only deltas are the exception, and they are marked.
  • Sandbox lifecycle is journalled; cleanup is opt-in. bonnie sandbox prune deletes the sandboxes of finished runs. Compiled agents can use WithRunSandboxCleanup for retention-based sandbox cleanup; the CLI serve command does not sweep them. Cleanup keeps waiting runs and history, but deletes earlier files of eligible finished runs. Publish output before completion. Cleanup locks do not coordinate separate processes or Runner instances.
  • A decision is a probability, not an authorization. Enforce access rules in host code. A keyed decision is not exactly once: if the process stops after the model answers and before the record is written, the next call asks again. Agent.Decide has no run and writes no record. The startup check proves that Kit can call the model, not that its credentials work.
  • The model database refresh changes a shared cache. update models writes Kit's per-user cache outside every sandbox, and other agents of that user read it on their next load. Use only trusted catalog sources. A cancellation or an output error does not undo an update that Kit committed. Running agents must restart to use it.
  • Mouse copy needs OSC 52. A terminal without OSC 52 (GNOME Terminal) does not get the selection, except inside tmux. Use Shift+drag there.
  • Evals call live models and run real tools. bonnie eval sends real requests to the agent's model and to the judge, which can cost money. Judge calls are not journalled. There are no tool stubs: an eval runs the agent's own tools in its sandbox. .bonnie/evals keeps each eval's full journal; protect it.
  • The mark3labs modules are publicly fetchable. A scaffolded module runs go mod tidy and resolves bonnie and kit from the proxy; no GOPRIVATE. To author an agent needs Go on your machine. The binary that bonnie build makes needs nothing on the host.

NATS tasks

A deployed agent can subscribe to Core NATS and publish outcomes asynchronously:

// Import natschannel "github.com/mark3labs/bonnie/channel/nats".
bonnie.New(
    bonnie.WithModel("opencode/kimi-k3"),
    bonnie.WithNATS(natschannel.Config{
        Subject:       "agents.review.tasks",
        AnswerSubject: "agents.review.answers",
        ResultSubject: "agents.review.results",
    }),
).Serve()

Set NATS_URL to the broker URL and configure the model's provider key. Each subject must be a distinct literal subject.

Activity logging

Add this option to bonnie.New(...) to log agent activity to stdout:

bonnie.WithActivityLogger(bonnie.NewActivityLogger(nil)),

Activity logging works with every channel, including NATS. It is off by default. The default logger uses charmbracelet/log with timestamps. Info output includes run states, suspensions, resumes, tool names and call IDs, and final response text. Failures use Error level. Warnings and retries use Warn level. Other lifecycle events and raw payloads use Debug level.

To select JSON output or Debug level, supply a Charm logger:

// Import "os" and "github.com/charmbracelet/log".
logger := log.NewWithOptions(os.Stdout, log.Options{
    Formatter:       log.JSONFormatter,
    Level:           log.DebugLevel,
    ReportTimestamp: true,
})
// Add this option to bonnie.New(...):
bonnie.WithActivityLogger(bonnie.NewActivityLogger(logger)),

Logs can contain sensitive data. Info output includes final responses; Debug output also includes prompts, tool arguments, results, and reasoning. Only live events are logged; journal replay does not log them again. Logging is synchronous, so a slow output writer delays the run. A host can also supply its own runtime.ActivityLogger through the same option.

NATS authentication

For NKey authentication, set NATS_NKEY_SEED to the user seed value, not its file path. BONNIE reads it when it builds the channel; the WithNATS setup above does not need to change. Load the value from your secret store. Do not put it in source code, logs, or the agent sandbox environment. The server must authorize the corresponding public user NKey.

You can also set NKeySeed in natschannel.Config explicitly. An explicit value takes precedence over NATS_NKEY_SEED. Malformed seeds and non-user seeds fail validation without including the seed in the error. This works with both Core NATS and JetStream.

For bearer token authentication, set NATS_TOKEN or Config.Token. For user/password authentication, set NATS_USERNAME and NATS_PASSWORD, or Config.Username and Config.Password. A username is required when a password is set; an empty password is permitted. Each explicit nonempty field takes precedence over its environment fallback. Use TLS to protect credentials in transit.

Configure only one method: NKey seed, token, or user/password. This includes environment fallbacks; unset variables for methods you do not use. Do not combine URL credentials with authentication fields. Conflicts fail validation without including credential values in the error.

For JWT credentials or other connection options, supply an authenticated Config.Conn instead. Do not combine Conn with URL or authentication fields. When Conn is supplied, BONNIE ignores all connection environment variables and does not close the connection; the caller owns its lifetime.

Start a result subscriber before publishing a task:

nats sub agents.review.results
# In another terminal:
nats pub agents.review.tasks '{"task_id":"review-42","text":"Review the supplied code."}'

Each task ID starts an independent durable run. The result contains task_id, run_id, state, and response, or an error. A waiting result contains suspend, including its tool_call_id. Publish an explicit answer to resume it:

nats pub agents.review.answers '{"task_id":"review-42","tool_call_id":"CALL_ID_FROM_RESULT","responses":[{"text":"Use staging."}]}'

A repeated task is rejected, not interpreted as an answer. Answers must match the current suspension. Active task executions and buffers are bounded; Concurrency defaults to 4 and Buffer to 64. Shutdown interrupts active turns and waits for their execution to stop. Connection loss also interrupts active turns. The saved interrupted state is not an operator cancellation. Over Core NATS the host continues it at its next start; the result stays in the journal, because the request's reply inbox is gone.

This adapter follows the asynchronous GitHub pattern, not a durable broker queue. It uses Core NATS, not JetStream. Offline subscribers, buffer overflow, and process failure can lose tasks or result delivery. The journal preserves run state, and the host continues an interrupted run at its next start, but the adapter does not retry result publication. Use broker permissions to restrict publishers and subscribers; message payloads do not verify identity. Run one owner for each task namespace; multiple ordinary subscribers each receive a copy and can repeat the work.

Root subjects and task statuses

Use a root subject to enable JetStream and derive all protocol subjects:

bonnie.WithNATS(natschannel.Config{
    RootSubject: "agents.review",
    AgentID: "review-1",
    CreateStream: true,
})

The defaults are <root>.tasks, .results, .events, .answers, .commands, and .queries. Answers, commands, and queries append .<agent_id>. Explicit subject fields override individual defaults. Any literal root is valid, including tasks or company.team.agents.review; no wildcard or empty token is permitted. Root configuration creates stable input, result, and event stream names. CreateStream permits creation of all three. JetStream must be enabled on the server, and the connection needs stream administration permissions. Existing resources are validated, never changed. Without CreateStream, provision them first. Stream names can be overridden.

The client uses the same root:

c, err := natsclient.New(nc, natsclient.Config{
    RootSubject: "agents.review",
    CreateStream: true,
})

ConsumeEvents(ctx, handler) delivers durable task_accepted and run_state events. State values include pending, running, waiting, completed, failed, and cancelled. Acceptance confirms a saved task/attempt/run mapping, not execution. Events contain IDs, timestamps, and journal cursors, not agent text or tool activity. The agent recovers unpublished states from its journal after restart. Delivery is at least once: discard duplicate event_id values and order each run by seq. Results remain on .results and retain responses and input requests. Events and results are independent streams; do not assume cross-stream ordering. Separate applications need separate EventConsumer and ResultConsumer names when each needs all messages. Stream retention limits can remove old events.

Use c.Status(ctx, event.Target) to query an exact attempt and c.Cancel(ctx, event.Target) to request cancellation. These are agent-routed NATS request/reply calls, not durable queued commands. A reply's Error reports rejection; a Go error reports transport or decoding failure. CancelRequested confirms the request only. The final state arrives separately. Cancellation stops an active turn; waiting and finished runs return not-active. External effects are not undone. A timeout does not prove task failure. Keep each agent's identity and journal stable, and run only one live owner of that identity.

Status queries include Active: a saved running state with Active: false indicates interruption, not current execution. Querying an unknown attempt returns an error. There is no global task lookup across separate agent journals. Protect agent routes and reply inboxes with NATS permissions. Replies use _INBOX.* subjects; custom inbox prefixes are not supported.

Targeted task delivery

Enable TargetedTasks: true on both the NATS channel and typed client. This requires JetStream. An agent reads shared tasks and tasks for its own AgentID.

bonnie.WithNATS(natschannel.Config{
    RootSubject: "agents.review",
    AgentID: "review-1",
    TargetedTasks: true,
    CreateStream: true,
})

// nc is a caller-owned NATS connection.
c, err := natsclient.New(nc, natsclient.Config{
    RootSubject: "agents.review",
    TargetedTasks: true,
    CreateStream: true,
})
if err != nil { return err }
_, err = c.SubmitTo(ctx, "review-1", natsclient.Task{
    TaskID: "review-42", Text: "Review the code.",
})

Submit still sends shared work. SubmitTo stores work on <task-subject>.agent.<agent-id>. Each agent has a separate durable targeted consumer. An offline target's task stays in JetStream within retention limits; it never falls back to another agent. Keep one live owner per agent identity. Answers and results use their existing routes. Delivery remains at least once.

New input streams include <task-subject>.agent.*. For an existing stream, add that subject explicitly before enabling targeted delivery. BONNIE does not change existing streams. Update NATS permissions to permit these routes. Task IDs are deduplicated per route: sending the same ID to shared work or another agent is a separate submission and can execute again.

JetStream and the typed client

Set Stream to enable JetStream. Leave Consumer empty to share tasks through a stable consumer derived from the task subject. Each agent must have a unique, stable AgentID and its own journal and sandbox data. Agents do not exchange run state. Set Consumer explicitly for separate processing groups or to bind an existing consumer. Changing its name can replay retained tasks. natschannel.DefaultConsumerName(subject) gives the derived name for operators.

bonnie.WithNATS(natschannel.Config{
    Subject: "agents.review.tasks", AnswerSubject: "agents.review.answers",
    ResultSubject: "agents.review.results",
    Stream: "REVIEW-TASKS", AgentID: "review-1",
    CreateStream: true,
})

CreateStream explicitly permits input stream creation. Provision a result stream before agents start, or use the typed client's CreateStream option. Existing streams and consumers are validated, not changed. Input streams must retain the task subject and agents.review.answers.* with limits retention. The agent creates or binds durable pull consumers. Answers use a separate consumer for each agent.

The main service can use client/nats instead of raw JSON:

// nc is a caller-owned *nats.Conn.
c, err := natsclient.New(nc, natsclient.Config{
    TaskSubject: "agents.review.tasks", AnswerSubject: "agents.review.answers",
    ResultSubject: "agents.review.results",
    CreateStream: true,
})
if err != nil { return err }
_, err = c.Submit(ctx, natsclient.Task{TaskID: "review-42", Text: "Review the code."})
if err != nil { return err }
return c.Consume(ctx, func(ctx context.Context, outcome natsclient.Outcome) error {
    // Store the result or input request. Return an error if storage fails.
    return storeOutcome(ctx, outcome)
})

The client derives stable result stream and consumer names from ResultSubject. Override ResultStream for an existing stream or ResultConsumer for independent readers. The default consumer shares processing across main-service instances. Stream creation still requires CreateStream: true.

Import natsclient "github.com/mark3labs/bonnie/client/nats". Submit confirms broker storage, not execution. Consume acknowledges only after handler success. Call c.Answer(ctx, outcome, responses) for a waiting outcome; the client checks and selects its agent route. The service does not construct subjects or JSON. Raw publishers use protocol version 1; the typed client supplies it for tasks.

Agents send acknowledgement progress while executing and publish a confirmed result before acknowledging each input. A waiting result also releases the input. Outcomes are saved locally so redelivery to the same agent can retry publication without repeating completed execution. An admitted answer can recover a completed or new-waiting outcome after restart. An interrupted answer that cannot be safely continued returns an explicit failure instead of guessing. Oversized outcomes return a bounded error; full run data stays in the journal.

Delivery is at least once, not exactly once. Redelivery to another agent can execute the task again. Redelivery to the same agent reuses its saved local attempt and run after interruption. Keep the original journal and sandbox data; recovery does not make external effects exactly once. Track task_id, attempt_id, and run_id, and make external effects and result handlers safe to repeat. Broker deduplication has a bounded window. A waiting run needs its original agent and stored state to answer; lost agent state requires a new task. Use separate task consumers for intentional agent fan-out, and separate result consumers for applications that each need all outcomes.

Examples

Each example is an agent tree made with bonnie init, run with bonnie dev, and shipped with bonnie build — the same shape as your own agent.

Example Shows
examples/github-bot a durable agent on GitHub: issues, pull requests, review threads
examples/slack-bot a durable agent in Slack: threads, controls, a live activity indicator
examples/triage-desk a support triage agent that routes tickets with a decision model; no outside service needed
examples/refund-desk a refund assistant with evals that grade it (bonnie eval); no outside service needed
cd examples/github-bot
bonnie dev --addr 127.0.0.1:8081 --tui=false

See examples/README.md for commands you can copy.

Documentation

The documentation site has installation steps, agent guides, channel setup, and CLI and Go API references. To run or build it locally, see www/README.md.

Document Purpose
godoc The specification. Each exported symbol has its contract and, often, the defect that shaped it
CHANGELOG.md What each release changed, and the limits it recorded
docs/SCHEDULES.md Define cron schedules in code, trigger them over HTTP, and understand their delivery limits
docs/RELEASE.md The release checklist, and what each tag confirmed
CONTRIBUTING.md Boundary rule, work-directory setup, commands
AGENTS.md The same rules, for a coding agent
SECURITY.md Disclosure, and what BONNIE does not protect you from

Contributing

go build ./...
go test -race ./...
golangci-lint run

Or run the same loop with task check, and CI parity with task ci.

The live-model tests need a build tag and a provider key:

go test -race -tags integration ./runtime ./sandbox

They skip, and never fail, when no key is present. One rule is above the rest: BONNIE uses the public Kit SDK only. See CONTRIBUTING.md.

Iroh transport

Serve the HTTP wire API over Iroh with bonnie.WithIroh. Only explicitly paired peers have access. See Iroh setup and programmatic pairing.

License

MIT — see LICENSE.

Run API over NATS

Use bonnie.WithNATSAPI to expose the existing authenticated run API on one journal-owning agent's Core NATS subject, optionally with bonnie.WithHTTPListenerDisabled() for no TCP listener. client/natsapi provides an http.RoundTripper for the existing Go client, including snapshots, same-run messages, explicit suspension answers and cursor-based NDJSON streams. This is separate from NATS task/result delivery, not a shared worker queue. API credentials and restrictive broker ACLs are required; access is operator-wide, not per-run ownership. See NATS API setup, protocol and durability limits.

Documentation

Overview

Package bonnie is the entry point of an authored agent tree.

A BONNIE agent is a directory of files whose meaning comes from their paths, and one Go file that starts it:

package main

import "github.com/mark3labs/bonnie"

func main() { bonnie.New().Serve() }

That is the whole default agent. Every slot in the tree has a framework default, and authoring the slot replaces it: instructions.md is the system prompt, context/ is the default seed copied into each isolated run, tools/ holds one directory per tool, and .bonnie holds the journal. Configuration that is not a file is code — an Option on New:

func main() {
	bonnie.New(
		bonnie.WithModel("anthropic/claude-sonnet-4-5"),
		bonnie.WithSandbox(sandbox.Docker()),
	).Serve()
}

There is no manifest file. Data-shaped settings live at their default paths, and everything else is a Go call, so a setting that does not exist is a compile error rather than a key that is accepted and ignored.

The tree's code — its tools — and the copies of its data files that a `bonnie build` binary carries are wired by codegen into bonnie_gen.go, which calls Register from its init. main.go never has to name them.

Index

Examples

Constants

View Source
const (
	// DefaultInstructions is the system prompt file, relative to the tree.
	DefaultInstructions = "instructions.md"

	// DefaultContextFiles is the seed directory mirrored into each run's isolated
	// sandbox working directory. These files are working data, not prompt text.
	// Use [WithSharedDirectory] for explicit shared
	// local development storage.
	DefaultContextFiles = "context"

	// DefaultSkills is the tree's skills directory.
	DefaultSkills = "skills"

	// DefaultJournal is the directory the run journal is written to.
	DefaultJournal = ".bonnie"

	// DefaultAddr is the address the HTTP channel binds when none is given.
	DefaultAddr = ":8080"

	// DevRootEnv names the environment variable `bonnie dev` sets on the
	// child it serves. Its value is the absolute tree root. A process that
	// `bonnie dev` did not start does not have it, and dev-only behaviour,
	// such as local self-modification, keys on it.
	DevRootEnv = "BONNIE_DEV_ROOT"
)

The default layout of a scaffolded tree. These are the paths `bonnie init` writes, the paths codegen embeds, and the paths Agent.Run reads when no option overrides them. They are constants rather than five copies of a string literal, because the scaffold, the generator, the dev loop, and the runtime must agree on the answer: a rule written more than once is a rule one caller can honour while another misses it.

View Source
const DecideToolName = "decide"

DecideToolName is the name of the tool WithDecisionTool adds.

View Source
const DefaultDotenv = ".env"

DefaultDotenv is the environment file Agent.Run loads when it is present in the process's working directory.

Variables

View Source
var ErrContinuationLimit = runtime.ErrContinuationLimit

ErrContinuationLimit reports an exhausted completion continuation budget.

Functions

func Register

func Register(t Tree)

Register hands the generated wiring to the runtime. The generated bonnie_gen.go calls it from init, before main runs.

It is the seam that keeps main.go short: adding a tool to the tree changes the generated file and nothing the author wrote.

func RegisterDefaults added in v0.32.0

func RegisterDefaults(opts ...Option)

RegisterDefaults adds options that New applies before its own arguments. Generated code calls it from init. `bonnie dev` uses it to install dev-only defaults without a change to main.go. An option in main.go is applied later, so it replaces a default with the same slot. A default tool factory is dropped, not refused, beside WithAgentFactory: the host's agent owns its tools, and a default must not stop a tree that worked without it.

Types

type ActivityLogger added in v0.13.0

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

ActivityLogger writes live run activity with charmbracelet/log. Use NewActivityLogger to build one and WithActivityLogger to enable it. It is safe for concurrent use when its underlying logger is not changed.

func NewActivityLogger added in v0.13.0

func NewActivityLogger(logger *log.Logger) *ActivityLogger

NewActivityLogger uses logger to write activity. Nil selects a new text logger on stdout at Info level. Run states, tool calls, tool results, and final responses use Info level; failures use Error level. Warnings and retries use Warn level. Other lifecycle events and raw payloads use Debug level.

Logs can contain sensitive data. Final response text is included at Info level. Debug output also includes prompts, tool arguments, and results.

func (*ActivityLogger) LogActivity added in v0.13.0

func (l *ActivityLogger) LogActivity(ev runtime.Event)

LogActivity writes one live event. It does not change the event. A nil receiver or a zero ActivityLogger writes nothing.

type Agent

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

Agent is a configured agent: the tree's defaults with the options applied over them. Build one with New, then Agent.Serve it.

Nothing is opened, bound, or read until an operation starts, so building an agent cannot fail and New returns no error. A setting that cannot apply — a network policy with no sandbox to enforce it, a model beside a host-supplied agent factory — is refused when Run or WithRuntime starts. WithJournal needs only the journal configuration.

func New

func New(opts ...Option) *Agent

New builds an agent from the tree's default layout and the options.

func main() { bonnie.New().Serve() }

With no options that is a complete agent: instructions.md is the system prompt, context/ is the agent's root for files, .bonnie is the journal, the tools under tools/ are wired by codegen, and the HTTP channel is served on :8080. Each Option replaces one of those. Options from RegisterDefaults apply first, so an argument here wins over them.

func (*Agent) Configure added in v0.19.0

func (a *Agent) Configure(opts ...Option)

Configure applies options in order to the agent's current configuration. It uses the same option rules as New: replacement options override earlier values, and additive options append or merge. Validation stays in Agent.Run; Configure does not read files, open resources, or start the agent.

Use it before Run, for example in a WithCommand pre-run hook to apply parsed flags. Configure is not safe for concurrent use. Do not call it while Run or Serve is running, except in Serve's command setup or pre-run hooks. It does not support changes to a live agent. Built-in Serve flags still apply before Run and override the matching options when those flags have a value.

func (*Agent) Decide added in v0.34.0

func (a *Agent) Decide(ctx context.Context, req DecisionRequest) (*kit.DecisionResult, error)

Decide asks the agent's decision model outside a run, for example in a schedule's Prepare function or in a channel that decides whether to answer. There is no run, so no journal record is written and Key is ignored. In a run, use RunScope.Decide, which journals each call.

It uses Kit's default settings: API keys from stored credentials or the environment, and no HTTP transport from WithKit.

Example

ExampleAgent_Decide skips a quiet schedule before it starts a turn.

package main

import (
	"context"

	kit "github.com/mark3labs/kit/pkg/kit"

	"github.com/mark3labs/bonnie"
	"github.com/mark3labs/bonnie/runtime"
	"github.com/mark3labs/bonnie/schedule"
)

func main() {
	readInbox := func(context.Context) (string, error) { return "", nil }
	agent := bonnie.New(bonnie.WithDecisionModel("ollama/pplx-decider"))
	agent.Configure(bonnie.WithSchedule(schedule.Definition{
		Name: "inbox", Cron: "*/15 * * * *", Revision: "1",
		Prepare: func(ctx context.Context, fire schedule.Fire) ([]schedule.Dispatch, error) {
			inbox, err := readInbox(ctx)
			if err != nil {
				return nil, err
			}
			res, err := agent.Decide(ctx, bonnie.DecisionRequest{
				State:     kit.DecisionState{Text: inbox},
				Questions: []kit.DecisionQuestion{kit.BooleanQuestion("work", "Does a message need a reply?")},
			})
			if err != nil {
				return nil, err
			}
			if a, err := res.Boolean("work"); err == nil && a.Probability < 0.3 {
				return nil, nil
			}
			return []schedule.Dispatch{{Key: "reply", Input: runtime.Input{Text: "Reply to the inbox."}}}, nil
		},
	}))
}

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) (runErr error)

Run serves the agent until ctx ends, then interrupts in-flight turns and returns. It is Agent.Serve without the process: no flags, no signal handler, no exit — for a host that already owns those.

Optional channel.Lifecycle channels start after the listener is bound. All constructed lifecycle channels shut down before the journal closes, including when startup fails. Each shutdown phase uses WithShutdownTimeout.

At startup, Run continues each run that a previous process left without a stop reason — a crash, a kill, or a restart in the middle of a turn — and sends each result to the channel the conversation is on. At shutdown it interrupts each turn instead of waiting for it, so the next start continues it. A run that parks holds no compute and lives in the journal, so stopping here is never destructive.

func (*Agent) Serve

func (a *Agent) Serve()

Serve runs the agent's command interface and owns the process. With no subcommand, or with serve, it serves until the process is interrupted. It also includes chat, runs, schedules, and version commands by default. Use WithChatCommand, WithRunsCommand, WithSchedulesCommand, and WithVersionCommand to disable them. Operator commands do not start the agent.

It owns the process, which is what makes a one-line main possible: it uses Cobra and Fang for operator flags, help, and startup errors. It installs the signal handler, drains in-flight turns on SIGINT or SIGTERM, and exits non-zero after writing the error to stderr. A host that owns its own process calls Agent.Run instead.

The flags -addr, -model, and -web override the matching options. The -sandbox flag selects a provider declared with WithSandboxes or WithSandbox; without either option, only the default Landlock provider is permitted. An operator can change the port, model, or permitted backend without rebuilding the binary. `bonnie dev` starts a tree's binary with -addr, which is the whole contract between the dev loop and the child.

func (*Agent) WithJournal added in v0.19.0

func (a *Agent) WithJournal(ctx context.Context, fn func(context.Context, runtime.Journal) error) (scopeErr error)

WithJournal opens the configured journal for inspection during fn, then closes it. It does not load dotenv, prompts, skills, or context files, build an agent factory, check a provider, or start a server or background work. Do not close the journal or use it after fn returns. Wait for all journal operations before returning. A nil fn is an error and opens no resources. Callback, cancellation, and close errors are returned together.

func (*Agent) WithRuntime added in v0.19.0

func (a *Agent) WithRuntime(ctx context.Context, fn func(context.Context, *Runtime) error) (scopeErr error)

WithRuntime prepares the same agent factory and runner as Agent.Run, calls fn, then closes the journal. It loads dotenv and resolves and seeds the agent's files, but does not start a server, channels, scheduler, or background cleanup. The caller manages any scheduler explicitly. Wait for all operations before fn returns, and keep no resource references after the callback. A nil fn is an error and opens no resources. Callback, cancellation, and close errors are returned together.

type Channel

type Channel interface {
	channel.Channel
	channel.Inbound
}

Channel is an inbound transport BONNIE can mount: the HTTP routes it needs and the inbound surface a run resolves through. Every adapter in channel/ is both.

type ChannelFunc

type ChannelFunc func(*runtime.Runner) (Channel, error)

ChannelFunc builds a channel for the runner that serves it. It is called once at start; an error stops the process before it listens.

type CompletionCandidate added in v0.13.0

type CompletionCandidate = runtime.CompletionCandidate

CompletionCandidate is a normal response awaiting acceptance.

type CompletionFeedback added in v0.13.0

type CompletionFeedback = runtime.CompletionFeedback

CompletionFeedback permits completion when ContinueWith is empty. Otherwise ContinueWith supplies the input for another model turn.

type CompletionHook added in v0.13.0

type CompletionHook = runtime.CompletionHook

CompletionHook performs work before BONNIE publishes a final outcome. It is skipped on suspension and model failure. Errors fail the run. An interrupted hook can run again; external effects must tolerate retries.

type CompletionHookFactory added in v0.13.0

type CompletionHookFactory func(context.Context, RunScope) (CompletionHook, error)

CompletionHookFactory creates a hook for one managed execution. Closure state is not durable. BONNIE restores continuation state separately.

type CompletionPolicy added in v0.13.0

type CompletionPolicy struct {
	NewHook CompletionHookFactory
	// MaxContinuations bounds additional model turns. Zero permits no extra
	// turns. Suspension and recovery do not reset the budget.
	MaxContinuations int
}

CompletionPolicy configures work before the final outcome.

type Decider added in v0.34.0

type Decider = runtime.Decider

Decider sends one request to a decision model. WithDecider installs one in place of the provider call.

type DecisionRequest added in v0.34.0

type DecisionRequest struct {
	// Model is a decision model in "provider/model" format. Empty uses
	// the model of [WithDecisionModel].
	Model     string
	State     kit.DecisionState
	Questions []kit.DecisionQuestion
	// ProviderOptions are sent as-is on wires that accept them.
	ProviderOptions map[string]any
	// Key makes a call in a run idempotent. When the run already has a
	// successful decision with the same key and input, the stored result is
	// returned and the model is not asked again, also after a restart. Use
	// a key that names the decision, for example the ID of the tool call it
	// gates. A key used again with different input returns
	// [runtime.ErrDecisionKeyReused]. Empty asks the model each time.
	// [Agent.Decide] has no run, so it ignores Key.
	Key string
}

DecisionRequest is one request to the agent's decision model. See kit.DecisionRequest for the model, state and question fields.

type KitSetup added in v0.13.0

type KitSetup func(context.Context, *kit.Kit, RunScope) error

KitSetup registers SDK hooks after BONNIE installs its durable session and hooks, but before the first prompt. It runs again on Start or Resume. Callback code runs on the host; use scope.Exec for sandbox commands.

type Option

type Option func(*config)

Option configures New or Agent.Configure. This is where a setting that is not a file in the tree lives: the model, a sandbox, an extra channel. A setting that does not exist is a compile error, which is the point.

func Quiet

func Quiet() Option

Quiet suppresses the startup banner.

It no longer has to make an exception for a no-sandbox warning, because no default run is unsandboxed: the banner names the backend in force instead. sandbox.Local can still be selected without confinement.

func WithActivityLogger added in v0.13.0

func WithActivityLogger(logger runtime.ActivityLogger) Option

WithActivityLogger enables live activity logging for all channels, including NATS. Nil disables logging. Any runtime.ActivityLogger can be used, including one built with NewActivityLogger. Replayed events are not logged again.

func WithAddr

func WithAddr(addr string) Option

WithAddr binds the HTTP channel to addr instead of DefaultAddr.

func WithAgentFactory

func WithAgentFactory(f runtime.AgentFactory) Option

WithAgentFactory replaces the model-backed agent entirely with one the host builds itself. It is the escape hatch for a program that implements runtime.Agent — a test double, a router, a second framework — and wants BONNIE only for durability and transport.

It cannot be combined with the options that configure the agent BONNIE would have built (WithModel, WithSystemPrompt, WithSandbox, WithSandboxes, WithSandboxEnv, WithNetwork, WithTools, WithToolFactory, WithKit, WithKitSetup, WithCompletionHook, WithDecisionTool, WithoutHumanInput): the factory owns the agent, so those settings would be accepted and ignored. Agent.Run refuses instead, naming both.

What the factory owns, it owns completely: tree instructions, skills, and the tools codegen discovered do not reach it either. They are available through Registered for a host that wants them. The journal, the working files, the channels, and the shutdown behaviour are unaffected — those are BONNIE's side of the boundary.

func WithAuthCommand added in v0.23.0

func WithAuthCommand(enabled bool) Option

WithAuthCommand controls the provider login commands in Agent.Serve. They are enabled by default. Disabling them does not prevent Kit from loading stored credentials or remove their dependencies from the binary.

func WithChannel

func WithChannel(f ChannelFunc) Option

WithChannel mounts another inbound transport beside the HTTP channel.

func WithChatCommand added in v0.20.0

func WithChatCommand(enabled bool) Option

WithChatCommand controls the chat command in Agent.Serve. It is enabled by default and connects to a running HTTP channel; it does not start a server. Disabling the command does not remove its dependencies from the binary.

func WithCommand added in v0.19.0

func WithCommand(fn func(*cobra.Command, *Agent)) Option

WithCommand adds a callback that configures the root command used by Agent.Serve. Callbacks run in registration order, after the built-in flags and host Go flags are added, but before parsing. They may add flags and subcommands or set Cobra hooks. They do not run in Agent.Run.

To apply parsed flags, call Agent.Configure from a pre-run hook. Help runs the registration callbacks, but does not run pre-run hooks or open resources.

func WithCompletionHook added in v0.13.0

func WithCompletionHook(policy CompletionPolicy) Option

WithCompletionHook installs a completion policy. A second policy, a nil factory, or a negative limit is a configuration error. This option cannot be combined with WithAgentFactory.

func WithContextFiles added in v0.17.0

func WithContextFiles(dir string) Option

WithContextFiles selects the context files to copy into each new run, instead of DefaultContextFiles. These files are seed data, not system prompt text. An empty dir disables copying; it does not give tools access to the process directory or disable the sandbox.

func WithDecider added in v0.34.0

func WithDecider(d Decider) Option

WithDecider replaces the provider call with d. A test uses it to script answers, and a host uses it to reach a model Kit cannot call. Each call in a run is still journalled. When it is set, Agent.Run does not check the model of WithDecisionModel against the model database.

func WithDecisionModel added in v0.34.0

func WithDecisionModel(model string) Option

WithDecisionModel sets the decision model the agent uses, in "provider/model" format, for example "openrouter/typesafe/jev-1.14" or "ollama/pplx-decider". See kit.GetDecisionModels.

A decision model answers typed questions with probabilities. It does not chat. The option makes RunScope.Decide available to tool factories, Kit setup callbacks and completion hooks, and makes Agent.Decide available to host code outside a run. WithDecisionTool also gives it to the model. A probability is not an authorization: enforce access rules in host code.

Agent.Run refuses a model that Kit cannot call as a decision model. It does not check credentials.

Example

ExampleWithDecisionModel gates shell commands with a decision model and checks that each response completes the task. The recipes are those of www/pages/guides/decisions.md; this example keeps them compiling. It needs a provider, so it has no Output and does not run.

package main

import (
	"context"

	kit "github.com/mark3labs/kit/pkg/kit"

	"github.com/mark3labs/bonnie"
)

func main() {
	bonnie.New(
		bonnie.WithDecisionModel("openrouter/typesafe/jev-1.14"),
		bonnie.WithKitSetup(func(ctx context.Context, k *kit.Kit, scope bonnie.RunScope) error {
			k.OnBeforeToolCall(kit.HookPriorityNormal, func(h kit.BeforeToolCallHook) *kit.BeforeToolCallResult {
				if h.ToolName != "shell" {
					return nil
				}
				res, err := scope.Decide(ctx, bonnie.DecisionRequest{
					State: kit.DecisionState{Text: h.ToolArgs},
					Questions: []kit.DecisionQuestion{
						kit.BooleanQuestion("destructive", "Does this command delete or overwrite data?"),
					},
					Key: "gate:" + h.ToolCallID,
				})
				if err != nil {
					return &kit.BeforeToolCallResult{Block: true, Reason: "The safety check failed. Ask for approval with request_approval."}
				}
				if a, err := res.Boolean("destructive"); err != nil || a.Probability > 0.2 {
					return &kit.BeforeToolCallResult{Block: true, Reason: "This command can destroy data. Ask for approval with request_approval first."}
				}
				return nil
			})
			return nil
		}),
		bonnie.WithCompletionHook(bonnie.CompletionPolicy{
			MaxContinuations: 2,
			NewHook: func(_ context.Context, scope bonnie.RunScope) (bonnie.CompletionHook, error) {
				return func(ctx context.Context, c bonnie.CompletionCandidate) (bonnie.CompletionFeedback, error) {
					res, err := scope.Decide(ctx, bonnie.DecisionRequest{
						State: kit.DecisionState{Text: c.Response},
						Questions: []kit.DecisionQuestion{
							kit.BooleanQuestion("done", "Does this response complete the task, with no step left for later?"),
						},
					})
					if err != nil {
						return bonnie.CompletionFeedback{}, nil
					}
					if a, err := res.Boolean("done"); err == nil && a.Probability < 0.5 {
						return bonnie.CompletionFeedback{ContinueWith: "The task is not complete. Continue."}, nil
					}
					return bonnie.CompletionFeedback{}, nil
				}, nil
			},
		}),
		bonnie.WithDecisionTool(),
	)
}

func WithDecisionTool added in v0.34.0

func WithDecisionTool() Option

WithDecisionTool gives the model the "decide" tool, which asks the decision model typed questions about a text. It needs WithDecisionModel or WithDecider, and it cannot be combined with WithAgentFactory.

Each call is journalled with the tool call's ID as its key, and the tool is replay-safe: a call interrupted by a crash returns the stored answer when the answer was journalled, and asks again when it was not.

func WithDiscord

func WithDiscord(cfg discord.Config) Option

WithDiscord mounts the Discord channel. DISCORD_BOT_TOKEN and DISCORD_PUBLIC_KEY come from the environment; see WithSlack.

func WithGitHub added in v0.5.0

func WithGitHub(cfg github.Config) Option

WithGitHub mounts the GitHub App channel. GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY, and GITHUB_WEBHOOK_SECRET come from the environment; see WithSlack. GITHUB_INSTALLATION_ID comes from there too, and only a hand-off needs it: a webhook carries its own installation. The bot name is configured, not environmental: it is a setting, not a secret.

func WithHTTPAuthenticator added in v0.7.0

func WithHTTPAuthenticator(fn bonniehttp.Authenticator) Option

WithHTTPAuthenticator verifies who is calling the framework's own HTTP API, and makes the principal it returns the run's identity.

Every chat adapter already does this from a platform signature — Slack's HMAC, Discord's Ed25519, GitHub's HMAC. The HTTP channel carries no such signature, so what counts as proof is the host's to decide: a bearer token, an OIDC assertion, a client certificate, a session cookie.

Without this option the HTTP API authenticates nobody. That is the right default for a loopback `bonnie dev`, and the wrong one for anything reachable by someone else — the routes start runs, read transcripts, and retire conversations. A deployment either passes an authenticator here or puts the process behind something that has already established who is calling.

See github.com/mark3labs/bonnie/channel/http.Authenticator for what a verifier returns, and github.com/mark3labs/bonnie/channel/http.ErrUnauthenticated for how it refuses one.

func WithHTTPListenerDisabled added in v0.27.0

func WithHTTPListenerDisabled() Option

WithHTTPListenerDisabled explicitly disables TCP API and schedule routes. It rejects web UI, injected listeners, and channels with TCP routes.

func WithInstructions

func WithInstructions(path string) Option

WithInstructions reads the system prompt from path instead of DefaultInstructions. An empty path means the agent has no instructions file, which is how a host with no tree runs.

func WithIroh added in v0.25.0

func WithIroh(cfg irohchannel.Config) Option

WithIroh mounts the HTTP-compatible Iroh channel. Only explicitly paired endpoint IDs can access it. Pairing grants operator access to all runs.

func WithJournal

func WithJournal(dir string) Option

WithJournal writes the run journal to dir instead of DefaultJournal.

func WithKit

func WithKit(opts ...kit.Option) Option

WithKit passes Kit options through to the agent, for settings BONNIE does not name itself.

func WithKitSetup added in v0.13.0

func WithKitSetup(setup KitSetup) Option

WithKitSetup adds a managed setup callback. Callbacks run in registration order. Closure state is local to the instance, not durable. This option cannot be combined with WithAgentFactory.

func WithListener

func WithListener(ln net.Listener) Option

WithListener serves on an already-bound listener instead of dialling the configured address. Tests bind :0 with it and learn the port.

func WithModel

func WithModel(model string) Option

WithModel selects the model, as "provider/name". Without it, Kit's default applies.

func WithNATS added in v0.11.0

func WithNATS(cfg natschannel.Config) Option

WithNATS mounts an asynchronous NATS task channel. NATS_URL fills an empty URL. NATS_NKEY_SEED, NATS_TOKEN, NATS_USERNAME, and NATS_PASSWORD fill empty authentication fields. All fallbacks are skipped when Conn is supplied. Set only one authentication method, including in the environment. Subjects can be configured explicitly or derived from RootSubject. Seeds are values, not paths. Config.Stream or RootSubject enables JetStream. Core NATS does not retain tasks or retry results; see channel/nats.

func WithNATSAPI added in v0.27.0

func WithNATSAPI(cfg natsapi.Config) Option

WithNATSAPI mounts the run API on an explicit agent-specific Core NATS subject. Broker authentication alone is not API authentication; cfg requires a verifier.

func WithName added in v0.5.0

func WithName(name string) Option

WithName names the agent. The name is reported by `GET /bonnie/v1/info` and nowhere else today; it is for a client that talks to several agents.

func WithNamedToolFactory added in v0.32.0

func WithNamedToolFactory(name string, factory ToolFactory) Option

WithNamedToolFactory adds a tool factory that a later option with the same name replaces in place. A package that ships a default factory, such as github.com/mark3labs/bonnie/selfmod, uses the name, so an explicit option in main.go replaces a default that `bonnie dev` registered and the model does not see the same tool twice. An empty name is the same as WithToolFactory.

func WithNetwork

func WithNetwork(p sandbox.NetworkPolicy) Option

WithNetwork constrains what the sandbox may reach. It needs a backend that can enforce it: a policy is refused at startup by a backend that cannot, never stored and ignored. The default Landlock backend confines the filesystem and not the network, so a policy with it is refused and names the backends that can.

func WithPresence added in v0.20.0

func WithPresence(cfg PresenceConfig) Option

WithPresence enables agent presence registration after channel startup. AgentID and Registry are required; InstanceID is generated when omitted. It copies labels and endpoints. Endpoint overrides replace provider endpoints. Registration and refresh failures stop Agent.Run. Shutdown attempts to publish draining and unregister with a context bounded by WithShutdownTimeout.

func WithReplaySafeTools added in v0.19.0

func WithReplaySafeTools(names ...string) Option

WithReplaySafeTools permits recovery to repeat the named interrupted tools. The default is none. Each tool must make external actions idempotent and enforce its own authorization: recovery calls its implementation directly, not interactive Kit approval hooks. Both the recorded and current policy must permit replay. Do not declare shell or payment tools safe by default. Each use adds to the set: two options name the union of their tools.

func WithRunSandboxCleanup added in v0.17.0

func WithRunSandboxCleanup(policy SandboxCleanupPolicy) Option

WithRunSandboxCleanup enables automatic cleanup of run-owned working files. It cannot be combined with WithSharedDirectory or WithAgentFactory. The provider must implement sandbox.RunDeleter. Shared-directory modes are rejected. Each deletion has a 30-second timeout; errors are logged and retried. Without this option, sandboxes and working files are kept.

func WithRunsCommand added in v0.20.0

func WithRunsCommand(enabled bool) Option

WithRunsCommand controls the local journal commands in Agent.Serve. They are enabled by default. This option does not restrict journal access.

func WithSandbox

func WithSandbox(p sandbox.Provider) Option

WithSandbox selects the backend for managed command and file tools. Custom Go callbacks still run on the host.

It SELECTS a sandbox, it does not enable one. Leaving it out does not give the model this process's filesystem: a run with no explicit backend gets sandbox.Landlock, which confines tool calls to the run's own working directory using the Linux Landlock LSM and needs nothing installed.

Pass this to choose something stronger — sandbox.Docker for namespaces, sandbox.Microsandbox for a microVM with its own kernel — or to widen the confinement deliberately with sandbox.Local, which provides no isolation at all and is for development only. The operator may select only this provider with --sandbox. Use WithSandboxes to permit more than one backend. These two options cannot be combined.

The godoc on each provider in package sandbox states what that backend does and does not contain.

func WithSandboxDownload added in v0.18.0

func WithSandboxDownload(enabled bool) Option

WithSandboxDownload controls automatic installation of the tracked microsandbox release at startup. Downloads are enabled by default, only for a selected microsandbox backend with no msb in PATH or the journal directory. Disabling downloads does not prevent use of an existing local installation.

func WithSandboxEnv added in v0.7.0

func WithSandboxEnv(env map[string]string) Option

WithSandboxEnv injects environment variables into every command the sandbox runs. It is how a run gets a credential or a setting the model must not choose — a database URL, a registry token, a feature flag — configured out of band so the model never holds the value.

The variables reach every backend, because the injection travels over the same seam a per-command environment does. An injected value wins over a per-command variable of the same name, so a fixed secret cannot be clobbered. Repeated calls merge, and a later key overrides an earlier one. See sandbox.EnvInjected for the full statement.

It does not encrypt the value or hide it from a command the model runs: a command inside the sandbox can print any variable it is given. The isolation is that the model cannot choose what is injected, not that it cannot read it.

func WithSandboxes added in v0.16.0

func WithSandboxes(providers ...sandbox.Provider) Option

WithSandboxes declares the sandbox backends the operator may select with --sandbox in Agent.Serve. The first provider is the default. Selection keeps the provider's configured options; it does not build a new provider. Only the selected provider is checked for availability. An unavailable provider returns an error, never a fallback to another backend.

The list must be non-empty, with non-nil providers and unique, non-empty names from sandbox.Provider.Name. This option may be set only once and cannot be combined with WithSandbox or WithAgentFactory. Invalid configuration is refused when serving starts. Agent.Run uses the first provider without reading process flags.

func WithSchedule added in v0.16.0

func WithSchedule(definitions ...schedule.Definition) Option

WithSchedule adds durable time-based agent dispatch or host callback definitions. Host callbacks must be safe to repeat. See schedule.Definition.

func WithScheduleClock added in v0.16.0

func WithScheduleClock(enabled bool) Option

WithScheduleClock enables or disables cron schedule evaluation. It is enabled by default.

func WithScheduleTriggerAuthorizer added in v0.16.0

func WithScheduleTriggerAuthorizer(fn func(*http.Request) error) Option

WithScheduleTriggerAuthorizer enables external schedule triggers after authorization.

func WithSchedulesCommand added in v0.20.0

func WithSchedulesCommand(enabled bool) Option

WithSchedulesCommand controls the schedule commands in Agent.Serve. They are enabled by default. This option does not disable HTTP schedule routes.

func WithSharedDirectory added in v0.17.0

func WithSharedDirectory(dir string) Option

WithSharedDirectory selects one host directory for every run instead of creating an isolated working directory per run. The default Landlock provider keeps filesystem confinement. Explicit Landlock and Local providers are supported; Local provides no filesystem isolation. Other providers are rejected. Overlapping opens through one provider are rejected. Separate processes and provider instances are not coordinated. The directory is never removed by run pruning. This option cannot be combined with WithContextFiles.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout bounds each shutdown phase of Agent.Run. When a signal arrives, each in-flight turn is interrupted and records "interrupted" at its next context check; the next start continues it. A turn that does not stop within the timeout still keeps its finished steps — the journal is what survives — and the next start continues it from there.

func WithSkills added in v0.7.0

func WithSkills(dir string) Option

WithSkills reads the tree's skills from dir instead of DefaultSkills. An empty dir disables tree skills and Kit automatic discovery, but does not disable an explicit WithWorkspaceSkills option. Explicit skills passed through WithKit remain in use.

A skill is a markdown file with YAML frontmatter: dir holds one *.md or *.txt per skill, or one subdirectory per skill with a SKILL.md in it. Kit scans the directory as given and adds nothing to the path, so BONNIE's skills/ is the whole skill set — the agent never inherits a skill from a .agents/skills it happens to be running beside.

Each skill's name and description reach the system prompt; the body arrives only when the model calls activate_skill. A bundled scripts/, references/, or assets/ file is NAMED in that activation text but lives on the host, outside the sandbox the tools run in, so the model cannot open it. Put what the model must read in the skill body, and put a file it must open in context/.

func WithSlack

func WithSlack(cfg slack.Config) Option

WithSlack mounts the Slack channel. Credentials come from the environment and never from code: SLACK_BOT_TOKEN and SLACK_SIGNING_SECRET fill the config's empty fields, and a missing one is a startup error naming the variable. A webhook that does not verify its caller is a door with no lock.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system prompt directly, instead of reading the tree's instructions file. It wins over WithInstructions.

func WithTelegram

func WithTelegram(cfg telegram.Config) Option

WithTelegram mounts the Telegram channel. TELEGRAM_BOT_TOKEN and TELEGRAM_WEBHOOK_SECRET come from the environment; see WithSlack.

func WithToolFactory added in v0.24.0

func WithToolFactory(factory ToolFactory) Option

WithToolFactory adds tools built with access to the current agent and run. Factories run in registration order, after discovered tool factories and before WithKitSetup callbacks. A nil factory stops agent construction. It cannot be combined with WithAgentFactory.

func WithTools

func WithTools(tools ...kit.Tool) Option

WithTools adds tools to the set the model may call, beside the tools codegen discovered under tools/ and Kit's core set.

func WithTracing added in v0.32.0

func WithTracing(tp trace.TracerProvider, opts ...observe.Option) Option

WithTracing records each turn as OpenTelemetry spans through tp: one invoke_agent span per turn, with a chat span per model step and an execute_tool span per tool call. The agent's name (WithName) names the spans. See package observe for the span tree and for what a span records.

Spans carry metadata only unless an option allows content:

bonnie.WithTracing(tp, observe.WithCapture(observe.CaptureAll))

The caller owns tp and must shut it down after Agent.Serve or Agent.Run returns, or the last spans are lost. A nil tp disables tracing. To send traces to Langfuse, build tp with package observe/langfuse.

func WithUpdateCommand added in v0.35.0

func WithUpdateCommand(enabled bool) Option

WithUpdateCommand controls the update command group in Agent.Serve. It is enabled by default. Disable it before adding a replacement with WithCommand. This does not restrict filesystem access or shared cache reads.

func WithVersionCommand added in v0.20.0

func WithVersionCommand(enabled bool) Option

WithVersionCommand controls the version command in Agent.Serve. It is enabled by default and reports build information without starting the agent.

func WithWebUI added in v0.19.0

func WithWebUI(enabled bool) Option

WithWebUI enables the browser interface at /web on the HTTP listener. It uses the same runner, journal, and HTTP channel as the wire API. The interface is disabled by default. This option does not open a browser.

func WithWorkspaceSkills added in v0.31.0

func WithWorkspaceSkills(policy WorkspaceSkills) Option

WithWorkspaceSkills enables untrusted repository metadata in model context. Only .agents/skills/<bundle>/SKILL.md and .kit/skills/<bundle>/SKILL.md qualify. Tree skills remain separate, including with WithSkills(""). This option opens the sandbox at startup and cannot use WithAgentFactory. Repeated options replace the policy. Bundled assets remain live, not saved. Each built-in sandbox supports it, and so does a custom sandbox that implements SkillDiscovery. Local and Landlock use rooted no-follow opens on the host. Docker and Microsandbox scan through Exec in the guest.

func WithoutHumanInput added in v0.13.0

func WithoutHumanInput() Option

WithoutHumanInput omits BONNIE's built-in ask_human and request_approval tools. Both tools are enabled by default. Sandbox permissions do not change. Caller-supplied tools remain available and can still suspend a run. This option does not prevent the model from asking questions in its response text. It cannot be combined with WithAgentFactory, which owns the agent's tools.

type PresenceConfig added in v0.20.0

type PresenceConfig struct {
	// Registry is required. The host does not close it.
	Registry presence.Registry
	// AgentID is the required stable agent name. It must match each mounted
	// channel's non-empty [channel.AgentIdentity].
	AgentID string
	// InstanceID distinguishes process instances. When empty, the host generates
	// a random ID for each Run. Do not reuse it across simultaneous instances.
	InstanceID string
	// Labels holds discovery metadata, not authorization claims.
	Labels map[string]string
	// RefreshInterval defaults to 10 seconds. Negative values are invalid.
	// It must be less than the registry TTL when it implements [presence.TTLStore].
	RefreshInterval time.Duration
	// Endpoints replaces the full provider endpoint list when entries are supplied.
	// When omitted, the host collects endpoints from [channel.PresenceProvider]
	// implementations, including HTTP. Supply public URLs explicitly; the host
	// does not infer them from bind addresses. Override readiness follows host state.
	Endpoints []presence.Endpoint
}

PresenceConfig configures optional agent registration during Agent.Run. Presence is advisory; it does not assign work or coordinate execution.

type RunScope added in v0.13.0

type RunScope struct {
	RunID string
	// Session provides trusted setup code with durable state and tool recovery controls.
	Session *runtime.Session
	// Exec opens the sandbox lazily and uses the same handle as agent tools.
	Exec func(context.Context, sandbox.Command) (*sandbox.Result, error)
	// Decide asks the decision model of [WithDecisionModel] or
	// [WithDecider] and journals each call that reaches the provider call,
	// also a failed one. It is nil when neither option is set. See
	// [runtime.Session.Decide].
	Decide func(context.Context, DecisionRequest) (*kit.DecisionResult, error)
}

RunScope gives trusted application code access to one managed execution. A new scope is created for each Start or Resume. Do not retain Exec after that execution ends. BONNIE owns sandbox cleanup.

type Runtime added in v0.19.0

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

Runtime gives access to a journal and its configured runner during Agent.WithRuntime. Do not use the Runtime, journal, or runner after the callback returns. Wait for all operations and goroutines before returning. No server, channels, scheduler, or cleanup loop starts automatically. The caller must start, cancel, and wait for Runner.RunScheduler if needed. Only one scheduler may own the journal at a time.

func (*Runtime) Journal added in v0.19.0

func (r *Runtime) Journal() runtime.Journal

Journal returns the journal owned by this callback scope. Do not close it.

func (*Runtime) Runner added in v0.19.0

func (r *Runtime) Runner() *runtime.Runner

Runner returns the configured runner owned by this callback scope.

type SandboxCleanupPolicy added in v0.17.0

type SandboxCleanupPolicy = runtime.SandboxCleanupPolicy

SandboxCleanupPolicy sets retention periods for run-owned working files. Zero keeps files for that state; positive durations permit deletion after the latest terminal checkpoint. Negative durations are rejected at startup. Completed runs can receive later turns; those turns start with an empty working directory if cleanup has removed it. The journal and channel addresses are kept.

Cleanup runs at startup and once per minute. One process must own the journal and sandboxes: separate processes are not coordinated.

type ToolFactory added in v0.24.0

type ToolFactory func(context.Context, ToolScope) ([]kit.Tool, error)

ToolFactory builds tools for one managed execution, before its first prompt. Closure state is not durable. Factories run again on Start or Resume. An error or a nil returned tool stops construction. An empty tool slice is valid.

type ToolScope added in v0.24.0

type ToolScope struct {
	RunScope
	// Kit is the agent bound to this execution's durable session.
	Kit *kit.Kit
}

ToolScope gives a tool factory access to the current agent and run. BONNIE creates a new scope on each Start or Resume. Do not retain it after that execution ends. Tool code runs on the host; use Exec for sandbox commands. Use Kit.Subagent, not Kit.Prompt, for model calls from an active tool. Child calls are not durable BONNIE runs and can repeat after interruption.

type Tree

type Tree struct {
	// Tools are the tools discovered under tools/ that need no run scope.
	Tools []kit.Tool

	// ToolFactory builds discovered scoped tools for each Start or Resume.
	ToolFactory ToolFactory

	// Instructions is the embedded copy of the tree's instructions file.
	Instructions string

	// Skills is the embedded copy of the tree's skills directory.
	// [Agent.Run] materialises it beside the journal when the tree's skills
	// directory is not on disk, which is what a built binary on a bare host
	// has, and hands the directory to Kit as Options.SkillsDir.
	Skills embed.FS

	// ContextFiles is the embedded copy of the tree's context files. [Agent.Run]
	// copies them into each new run; they are not added to the system prompt. It
	// materialises them beside a built binary that has no tree, and
	// never overwrites a file that is already there.
	ContextFiles embed.FS
}

Tree is what codegen discovered in an agent tree: the code it wired and the data files it embedded. The generated bonnie_gen.go builds one and hands it to Register from its init, so main.go never names a tool or an embed.

A tree run from its source directory reads its data files from disk and uses the embedded copies only as a fallback. A binary from `bonnie build` has no tree beside it, so the embedded copies are all it has.

func Registered

func Registered() Tree

Registered returns what the generated file registered. It is the zero Tree when a tree has not been generated yet, which is what a hand-written main.go with no tools sees.

Call it at run time — inside main, or later. The generated file registers from init, and Go initialises every package-level variable before it runs any init function, so a package-level `var x = bonnie.Registered()` reads the empty tree.

type WorkspaceSkills added in v0.31.0

type WorkspaceSkills struct {
	// Exclude adds directory globs to the mandatory exclusions and Git rules.
	Exclude []string
	// MaxDepth bounds directory segments below the root (root depth is zero).
	MaxDepth int
	// MaxSkills bounds the selected workspace catalogue.
	MaxSkills int
	// MaxSkillBytes bounds original bytes, including frontmatter.
	MaxSkillBytes int64
	// MaxMetadataBytes bounds exact escaped catalogue text, not skill bodies.
	MaxMetadataBytes int64
}

WorkspaceSkills controls opt-in recursive workspace discovery. Zero values select depth 12, 100 skills, 128 KiB per file and 32 KiB of metadata. Exclude adds workspace-relative directory globs (*, ?, classes, whole ** segments). Negative limits and invalid patterns are rejected at startup. Discovery never follows symlinks or enables Kit's home discovery.

Directories

Path Synopsis
Package agent implements BONNIE's L2 discovery: the authored agent tree.
Package agent implements BONNIE's L2 discovery: the authored agent tree.
Package channel defines BONNIE's inbound transport abstraction (L3).
Package channel defines BONNIE's inbound transport abstraction (L3).
chat
Package chat holds the plumbing every chat-platform channel shares: the journalled address map, per-run turn locks, the channel.SessionRef implementation, and the dispatch rule that sends a message to the right runner entry point.
Package chat holds the plumbing every chat-platform channel shares: the journalled address map, per-run turn locks, the channel.SessionRef implementation, and the dispatch rule that sends a message to the right runner entry point.
discord
Package discord is BONNIE's Discord inbound transport (L3).
Package discord is BONNIE's Discord inbound transport (L3).
github
Package github is BONNIE's GitHub App channel (L3).
Package github is BONNIE's GitHub App channel (L3).
http
Package http is BONNIE's HTTP inbound transport (L3).
Package http is BONNIE's HTTP inbound transport (L3).
iroh
Package iroh serves the BONNIE HTTP API over authenticated Iroh QUIC streams.
Package iroh serves the BONNIE HTTP API over authenticated Iroh QUIC streams.
nats
Package nats carries asynchronous tasks over Core NATS or JetStream.
Package nats carries asynchronous tasks over Core NATS or JetStream.
natsapi
Package natsapi serves the existing authenticated run API over Core NATS.
Package natsapi serves the existing authenticated run API over Core NATS.
slack
Package slack is BONNIE's Slack inbound transport (L3).
Package slack is BONNIE's Slack inbound transport (L3).
telegram
Package telegram is BONNIE's Telegram inbound transport (L3).
Package telegram is BONNIE's Telegram inbound transport (L3).
Package channeltest is the conformance suite for channel adapters, in the same spirit as the journal and sandbox suites.
Package channeltest is the conformance suite for channel adapters, in the same spirit as the journal and sandbox suites.
Package client is a Go client for BONNIE's HTTP wire API.
Package client is a Go client for BONNIE's HTTP wire API.
iroh
Package iroh connects the BONNIE HTTP client to an Iroh channel.
Package iroh connects the BONNIE HTTP client to an Iroh channel.
nats
Package nats provides a typed JetStream client for channel/nats.
Package nats provides a typed JetStream client for channel/nats.
natsapi
Package natsapi adapts the existing BONNIE HTTP client to Core NATS.
Package natsapi adapts the existing BONNIE HTTP client to Core NATS.
cmd
bonnie command
Command bonnie is the BONNIE developer CLI.
Command bonnie is the BONNIE developer CLI.
Package eval runs evals against a BONNIE agent: scored checks that drive the real agent and grade what it did.
Package eval runs evals against a BONNIE agent: scored checks that drive the real agent and grade what it did.
internal
agentcmd
Package agentcmd provides commands shared by the CLI and agent binaries.
Package agentcmd provides commands shared by the CLI and agent binaries.
evalui
Package evalui is the terminal interface of `bonnie eval`: it reads the output of go test -json, keeps each eval run under .bonnie/evals, and shows the evals, their scores and their conversations.
Package evalui is the terminal interface of `bonnie eval`: it reads the output of go test -json, keeps each eval run under .bonnie/evals, and shows the evals, their scores and their conversations.
fakemodel
Package fakemodel is a scripted language model for tests that drive a real Kit.
Package fakemodel is a scripted language model for tests that drive a real Kit.
flaky
Package flaky disables tests that fail intermittently, without deleting them.
Package flaky disables tests that fail intermittently, without deleting them.
natsapi
Package natsapi implements the private version-one HTTP framing protocol.
Package natsapi implements the private version-one HTTP framing protocol.
natswire
Package natswire holds the NATS wire rules shared by the server and client.
Package natswire holds the NATS wire rules shared by the server and client.
otelspan
Package otelspan rewrites finished OpenTelemetry spans on their way to an exporter.
Package otelspan rewrites finished OpenTelemetry spans on their way to an exporter.
presencesmoke command
Command presencesmoke checks agent discovery, HTTP endpoints, shared and targeted NATS tasks, presence deletion after a crash, and graceful shutdown across separate processes.
Command presencesmoke checks agent discovery, HTTP endpoints, shared and targeted NATS tasks, presence deletion after a crash, and graceful shutdown across separate processes.
runsui
Package runsui is the operator console for durable runs: a terminal interface that lists the runs in a journal, shows each one as an overview, a conversation, a trace, and raw journal records, and sends operator actions to a running server.
Package runsui is the operator console for durable runs: a terminal interface that lists the runs in a journal, shows each one as an overview, a conversation, a trace, and raw journal records, and sends operator actions to a running server.
selection
Package selection is the mouse text selection that BONNIE's terminal interfaces share.
Package selection is the mouse text selection that BONNIE's terminal interfaces share.
shelltest
Package shelltest makes shell fixtures for tests.
Package shelltest makes shell fixtures for tests.
skillfs
Package skillfs provides bounded no-follow discovery operations.
Package skillfs provides bounded no-follow discovery operations.
termtheme
Package termtheme holds the palette and the layout primitives that BONNIE's full-screen terminal interfaces share.
Package termtheme holds the palette and the layout primitives that BONNIE's full-screen terminal interfaces share.
tracectx
Package tracectx reads W3C trace context from inbound requests, so a channel can make a turn a child of the request that started it.
Package tracectx reads W3C trace context from inbound requests, so a channel can make a turn a child of the request that started it.
treetest
Package treetest builds throwaway agent trees that compile against this checkout, for tests that need a real `go build` of a scaffolded module.
Package treetest builds throwaway agent trees that compile against this checkout, for tests that need a real `go build` of a scaffolded module.
tui
Package tui is the BONNIE terminal user interface.
Package tui is the BONNIE terminal user interface.
workspaceskills
Package workspaceskills discovers untrusted, on-demand workspace skills.
Package workspaceskills discovers untrusted, on-demand workspace skills.
Package observe traces BONNIE runs with OpenTelemetry.
Package observe traces BONNIE runs with OpenTelemetry.
langfuse
Package langfuse sends BONNIE traces to Langfuse.
Package langfuse sends BONNIE traces to Langfuse.
Package presence provides transport-independent records and interfaces for agents that advertise their identity, endpoints, readiness, labels, and state.
Package presence provides transport-independent records and interfaces for agents that advertise their identity, endpoints, readiness, labels, and state.
nats
Package nats provides a JetStream KV presence store.
Package nats provides a JetStream KV presence store.
Package runtime is BONNIE's durable execution layer (L1).
Package runtime is BONNIE's durable execution layer (L1).
Package sandbox provides backends for BONNIE's managed file and command tools.
Package sandbox provides backends for BONNIE's managed file and command tools.
Package schedule starts durable agent or host work from code-defined cron jobs.
Package schedule starts durable agent or host work from code-defined cron jobs.
Package selfmod lets a BONNIE agent change its own authored source.
Package selfmod lets a BONNIE agent change its own authored source.
templ: version: v0.3.1070
templ: version: v0.3.1070
Package wire defines the shared types for BONNIE's transport APIs.
Package wire defines the shared types for BONNIE's transport APIs.
nats
Package nats defines the task protocol that channel/nats serves and client/nats speaks: the JSON messages, the subject rules, and the stream names.
Package nats defines the task protocol that channel/nats serves and client/nats speaks: the JSON messages, the subject rules, and the stream names.
www
scripts/generate-og command
Run from www with: go run ./scripts/generate-og Generate the shared social card from the BONNIE logo without external fonts.
Run from www with: go run ./scripts/generate-og Generate the shared social card from the BONNIE logo without external fonts.

Jump to

Keyboard shortcuts

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