agentkit

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 16 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

agentkit-go

AgentKit is a Go library for building AI coding agents. It gives an agent the hands it needs to work on a real codebase — tools to read, search, edit and run code, and a guard that decides which shell commands may run — together with a small agent loop that drives a model over them on Anthropic, OpenRouter or Ollama.

Why AgentKit

Letting a language model work on a repository takes much more than an API call. Every agent has to answer the same questions:

  • Which files may it touch? File tools must stay inside the project, honour .gitignore, and cope with large files and outputs.
  • Which commands may it run? An unattended agent with an unrestricted shell is one bad completion away from damage.
  • Where does it run? Untrusted, model-written code belongs in an isolated environment, not on the developer's machine. AgentKit runs inside the sandbox your platform provides; it does not create one.
  • How is the run bounded? Turns, cost and wall-clock time all need limits.

AgentKit answers them once, as a library:

Need What AgentKit provides
Work on a codebase Eleven built-in tools — read, write, edit, list, find, search, outline, find symbols, find references, run commands — contained to one workspace and its ignore rules.
Stay in control of the shell A shell guard that reads every command on a line and allows only the programs you list. An agent with a shell tool and no guard is refused at construction.
Fewer round trips Code mode: the model writes one short Starlark script that calls many tools, instead of one tool call per turn.
Connect other tools An MCP client that imports the tools of any MCP server, and an MCP server that serves AgentKit's tools to another harness such as Claude Code.
Serve the tools without Go agentkit-tools, one command that serves the tools for a directory as an MCP session on stdio or as a single call read from a file, inside a sandbox someone else runs.
Run the model A minimal agent loop with turn, cost and time limits, an event stream, and providers for Anthropic (direct, Vertex AI, Bedrock), OpenRouter and Ollama.

Each part works on its own: you can use the tools and the guard in your own agent loop, or AgentKit's loop with tools of your own.

Example

An agent that answers a question about the current directory, allowed to run only go and git:

package main

import (
	"context"
	"fmt"
	"log"

	agentkit "github.com/agent-fox-dev/agentkit-go"
	"github.com/agent-fox-dev/agentkit-go/guard"
	"github.com/agent-fox-dev/agentkit-go/tools"
	"github.com/agent-fox-dev/agentkit-go/workspace"
)

func main() {
	ws, err := workspace.Open(".", workspace.Options{})
	if err != nil {
		log.Fatal(err)
	}
	ts, err := tools.For(ws, tools.Options{})
	if err != nil {
		log.Fatal(err)
	}
	agent, err := agentkit.New(agentkit.Config{
		Provider: "anthropic", // or "openrouter", "ollama"
		Model:    "STANDARD",  // a tier (SIMPLE, STANDARD, ADVANCED) or a model id
		Toolset: agentkit.Toolset{
			Tools: ts,
			Guard: guard.Allow("go", "git"),
		},
		MaxTurns:   20,
		MaxCostUSD: 1.00,
	})
	if err != nil {
		log.Fatal(err) // e.g. a missing ANTHROPIC_API_KEY, reported by name
	}
	res, err := agent.Run(context.Background(), "Which package defines the shell guard?")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.FinalText())
}

The provider reads its credential from the environment: ANTHROPIC_API_KEY (or Vertex AI / Bedrock settings), OPENROUTER_API_KEY, or OLLAMA_HOST for a local Ollama server.

To see the loop work with no API key at all, run the offline demo, which uses a scripted model:

go run ./examples/agentdemo

Installation

AgentKit needs Go 1.27 or later and runs on Linux and macOS (Windows is best effort).

go get github.com/agent-fox-dev/agentkit-go

Two optional parts are separate Go modules, so you only pay for their dependencies when you use them, and the agentkit-tools command is a third:

Module Adds
github.com/agent-fox-dev/agentkit-go/mcpserve Serving a set of tools over MCP to another harness.
github.com/agent-fox-dev/agentkit-go/codesearch An indexed code_search tool for large repositories.
github.com/agent-fox-dev/agentkit-go/cmd/agentkit-tools The agentkit-tools command: go install github.com/agent-fox-dev/agentkit-go/cmd/agentkit-tools@latest.

Documentation

Document Read it to
User guide Learn each part with examples: providers and credentials, tools and the guard, code mode, MCP, running tools without a model, serving tools over MCP, serving them from the command line, code search. Start here.
Examples Run eight small, self-contained programs, most of them offline.
API map Find the package and identifier for a task.
Configuration reference Look up every option, environment variable, default and limit.
Command-line programs Run agentkit-tools: its modes, flags and exit codes.
Architecture Understand how a call and a run flow through the code, and the invariants behind it.
Development Build, test and contribute to AgentKit.
Releasing Tag a release of the Go modules.
Dependencies See why each third-party module is allowed.

The generated package reference (go doc -all for every public package) is in docs/generated/; go doc works as usual too.

Development

git clone https://github.com/agent-fox-dev/agentkit-go
cd agentkit-go
make check     # format, vet, lint and the fast tests in every module; no API key needed

docs/development.md covers the repository layout, the make targets, the opt-in live-provider tests, and the spec-driven workflow.

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package agentkit is a Go agent SDK.

The loop, the tool system and the provider abstraction are ordinary Go you can read and step through. Nothing is hidden inside a subprocess or a graph engine.

The canonical vocabulary — messages, content blocks, events, Tool and every interface seam — lives in the core package and is used directly. What lives here is the driver — Config, New, the Agent and the loop — and the tool side the driver is built on, which stands without a model. A Toolset is the tools, the policy that selects among them, the guard, the after-interceptor and the sink for execution events; NewRunner validates one into a Runner, which runs tool calls (Call, Batch), code mode included, through the pipeline an agent run uses. An Agent holds a Runner, and Config takes a Toolset. The prompt assembler and the execute guard are each their own package beneath this one.

Index

Constants

View Source
const (
	EffortLow    = core.EffortLow
	EffortMedium = core.EffortMedium
	EffortHigh   = core.EffortHigh
	EffortXHigh  = core.EffortXHigh
	EffortMax    = core.EffortMax
)

The efforts a Config can ask for.

View Source
const DefaultMaxTokens = 32768

DefaultMaxTokens is the output bound sent when Config.MaxTokens is zero. It is still capped at the model's own output cap; a caller who wants the whole cap says so. Providers size rate-limit reservations from max_tokens at request start, so defaulting to a 128K cap costs 128K of output-per-minute budget per turn and removes the only bound on a runaway turn. 32K is generous for tool-call-shaped output.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

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

Agent runs prompts against one model with one tool set. It has no global state: a second agent is a second value.

Its surface is seven methods. Run and Stream execute a prompt to a stop condition; Messages, Usage and ReachableTools read its state, Runner returns the runner its tool calls go through, and Resolution reports the provider, model and effort it was built to run, all safe from any goroutine while a run is in flight. A Run or Stream that overlaps another fails with core.ErrBusy rather than queueing: a prompt queued behind a running one was written against a transcript the caller could see, and by the time it ran the transcript would have changed underneath it.

func New

func New(cfg Config) (*Agent, error)

New builds an Agent from cfg. It runs Resolve first, so what it runs is what Resolve reports, and then validates the Toolset with NewRunner. It refuses a config the agent could not run safely, and returns the first error in this order, unchanged: the provider, the model, the effort, the credentials, and a Toolset that NewRunner refuses — an invalid tool hierarchy, or a shell tool reachable with no Guard to authorize it. That is a returned error here, rather than a missing key or an unrestricted shell discovered on the first run, and no request has been sent.

func (*Agent) Messages

func (a *Agent) Messages() core.Messages

Messages returns the agent's transcript: every message of every run, as recorded. It is a copy, safe to read while a run is in flight.

func (*Agent) ReachableTools

func (a *Agent) ReachableTools() []core.Tool

ReachableTools returns every tool a run of this agent can call: the tools Toolset.Policy resolved, and everything those reach through wrappers. A check that a run is read-only, say, has to look at this set rather than at the top-level tools. It is Runner().Reachable().

func (*Agent) Resolution

func (a *Agent) Resolution() Resolution

Resolution returns the provider, model and effort the agent was built with and the client it calls: what Resolve returns for the same Config. It is a copy, so changing its Model does not change the agent's own row.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, prompt string) (core.RunResult, error)

Run sends prompt and runs the loop to a stop condition. The error is the result's own Error: a run that stopped on a limit, a refusal or a failure returns both the result and why.

func (*Agent) Runner

func (a *Agent) Runner() *Runner

Runner returns the agent's runner: the same pointer on every call, safe to use while a run is in flight. The agent's own tool calls go through it, and so can an embedder's. Calls an embedder makes through it are not part of any run: they do not enter the transcript, they are not counted in Usage, they do not claim the run slot, and their events go to Toolset.Events.

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, prompt string) (*core.EventStream, error)

Stream runs the loop and returns its event stream. The producer never blocks on the consumer, so abandoning the stream is safe and the result stays available through RunResult.

It returns an error rather than only a pre-closed stream for the one case a caller most often gets wrong — a second run while one is in flight — because a silent ErrBusy inside a stream nobody reads is indistinguishable from a run that produced nothing.

func (*Agent) Usage

func (a *Agent) Usage() core.Usage

Usage returns cumulative usage for the agent's lifetime.

type Config

type Config struct {
	// Client is the provider client the agent calls: a test double such as
	// provider/faux, or a provider the embedder built or wrapped. When it is
	// set the agent builds none and reads no variable. Provider and Model
	// still choose the catalog row and the effort.
	Client core.ProviderClient
	// Provider names the provider that serves Model: one of catalog.Providers,
	// matched without regard to case and trimmed. Empty means the first. It
	// names the catalog provider even when Client is set.
	Provider string
	// Model is a tier name (SIMPLE, STANDARD or ADVANCED) or the provider's own
	// model id; catalog.Select supplies its limits, prices and, for a tier, its
	// effort.
	Model string
	// Effort is one of the five efforts or empty. Empty takes the tier's effort
	// when Model is a tier, and sends none otherwise.
	Effort Effort
	// Env and Getenv supply the variables the chosen provider reads for its
	// credentials and endpoint. A non-empty Env value is used first; an empty
	// one falls through to Getenv, and with no Getenv to the process
	// environment. An empty value counts as unset. Nothing else reads them.
	Env    map[string]string
	Getenv func(string) string
	System string
	// Prefix is sent after the system prompt on every request, with a cache
	// breakpoint on its last block.
	Prefix []core.Message
	// Toolset is the agent's tools, the policy that selects among them, the
	// guard that authorizes every call and the interceptor that sees every
	// result. The zero Toolset is an agent with no tools. New refuses a
	// Toolset that NewRunner refuses.
	Toolset Toolset
	// MaxTurns, MaxCostUSD and Timeout bound a run; zero means unbounded.
	MaxTurns   int
	MaxCostUSD float64
	Timeout    time.Duration
	// Prune ages old tool results out of the request; the zero value is off.
	Prune PruneOptions
	// MaxTokens caps each response; zero means DefaultMaxTokens.
	MaxTokens int
}

Config is everything an Agent is built from.

Provider, Model and Effort choose what runs the agent, and Env and Getenv supply the credentials and endpoints of the provider they choose. Resolve shows what a Config resolves to; New builds an agent on exactly that.

type Effort

type Effort = core.Effort

Effort is how much thinking a model puts into a turn.

type PruneOptions

type PruneOptions struct {
	// Threshold is the fraction of the model's context window the estimated
	// request must reach before pruning; zero or less disables it.
	Threshold float64
	// KeepTurns is how many recent turns keep their tool results whole.
	KeepTurns int
}

PruneOptions controls how old tool results leave the request.

type Resolution

type Resolution struct {
	// Provider is the canonical provider name: one of catalog.Providers.
	Provider string
	// Tier is the tier Config.Model named, or empty when it named a model id.
	Tier catalog.Tier
	// Model is the catalog row, or the provider's fallback row for an id the
	// catalog does not list. Model.ID is the id the vendor receives.
	Model core.Model
	// Effort is the effort requested, normalized: the explicit one, else the
	// tier's, else empty, which sends none.
	Effort Effort
	// Listed reports whether Model is a catalog row and not a fallback.
	Listed bool
	// Client is the client a run calls: Config.Client when it was set, else the
	// one built for Provider.
	Client core.ProviderClient
}

Resolution is what a Config resolves to: the provider, the model and the effort an agent runs with, and the client it calls. Resolve returns one without building an agent, and Agent.Resolution reports the one an agent was built with.

func Resolve

func Resolve(cfg Config) (Resolution, error)

Resolve turns the selection fields of cfg (Client, Provider, Model, Effort, Env and Getenv) into what New would run: the catalog's choice for the provider, model and effort, and the client to call.

It makes no request and keeps no state, and every call builds a new client. It reads no variable itself: with Config.Client nil, the chosen provider's own constructor looks up that provider's credential and endpoint (Env first, then Getenv, or the process environment when Getenv is nil; an empty value is unset), and no other provider's code runs. A credential that is missing, or an endpoint the provider cannot use, is an error here, before any run. A host that cannot be reached is not: that is found by the first request.

The errors of catalog.Select and of the provider's constructor are returned unchanged, so errors.Is matches catalog.ErrUnknownProvider, catalog.ErrNoModel, catalog.ErrUnknownEffort, openrouter.ErrNoAPIKey and anthropic.ErrNoCredentials, and the message names the value or the variable. The catalog's are returned even when Config.Client is set, which Resolve then returns as it is, reading no variable.

type Runner

type Runner = runner.Runner

Runner runs tool calls with no model: Call runs one and Batch runs several, each through the steps a model's calls go through in an agent run. It is runner.Runner, where its methods are documented: the two names are one type, so a *Runner from NewRunner, from runner.New or from Agent.Runner is accepted wherever either is asked for.

func NewRunner

func NewRunner(ts Toolset) (*Runner, error)

NewRunner validates ts and returns a Runner over it. It is runner.New: it refuses what New refuses, with the same errors, and copies ts.Tools.

type Toolset

type Toolset = runner.Toolset

Toolset is the tool side of an agent: the tools, the policy that selects among them, the guard that authorizes every call, the interceptor that sees every result, and the sink for execution events. It holds no model, so NewRunner builds from one what runs tool calls with no Agent, and Config.Toolset gives an Agent the same set. The zero Toolset has no tools, which is valid.

It is runner.Toolset: the two names are one type. A program that only runs tools imports package runner instead of this one, and so links no provider.

Directories

Path Synopsis
Package catalog embeds AgentKit's model catalog and turns a model id into a core.Model descriptor.
Package catalog embeds AgentKit's model catalog and turns a model id into a core.Model descriptor.
Package codemode provides a tool that runs a model-written Starlark script whose functions are other tools.
Package codemode provides a tool that runs a model-written Starlark script whose functions are other tools.
codesearch module
Package core holds AgentKit's canonical vocabulary and every interface seam.
Package core holds AgentKit's canonical vocabulary and every interface seam.
examples
agentdemo command
Command agentdemo runs AgentKit end to end with no API key and no network.
Command agentdemo runs AgentKit end to end with no API key and no network.
codemode command
Command codemode shows the code-mode tool: the model writes one Starlark script that calls several tools, filters what they return, and hands back only the answer.
Command codemode shows the code-mode tool: the model writes one Starlark script that calls several tools, filters what they return, and hands back only the answer.
codingagent command
Command codingagent is a coding agent with the built-in file and shell tools, a workspace root, an execute policy and a live event stream.
Command codingagent is a coding agent with the built-in file and shell tools, a workspace root, an execute policy and a live event stream.
customtools command
Command customtools is the reference for writing your own tools: schemas built from combinators, the two handler shapes, error results the model can recover from, per-tool argument repair, sequential execution for tools with side effects, and a terminating submit_answer.
Command customtools is the reference for writing your own tools: schemas built from combinators, the two handler shapes, error results the model can recover from, per-tool argument repair, sequential execution for tools with side effects, and a terminating submit_answer.
mcp command
Command mcp is AgentKit as a Model Context Protocol CLIENT: it borrows another program's tools and hands them to a model.
Command mcp is AgentKit as a Model Context Protocol CLIENT: it borrows another program's tools and hands them to a model.
toolbox command
Command toolbox calls AgentKit's built-in tools by hand, with no model: the same tools an agent gets from tools.For, run through the same agentkit.Runner path an agent's calls take, so you can see what each one takes and returns and try your own arguments.
Command toolbox calls AgentKit's built-in tools by hand, with no model: the same tools an agent gets from tools.For, run through the same agentkit.Runner path an agent's calls take, so you can see what each one takes and returns and try your own arguments.
Package guard is the `execute` boundary in non-interactive deployments.
Package guard is the `execute` boundary in non-interactive deployments.
internal
diag
Package diag holds the non-fatal report type shared by the code that loads LOCALLY AUTHORED content: the MCP client's configuration and the TOML subset underneath it.
Package diag holds the non-fatal report type shared by the code that loads LOCALLY AUTHORED content: the MCP client's configuration and the TOML subset underneath it.
providerconformance
Package providerconformance holds the opt-in live tests of the anthropic, openrouter and ollama providers.
Package providerconformance holds the opt-in live tests of the anthropic, openrouter and ollama providers.
testkit
Package testkit holds the Agent-free test doubles the root package's and the runner package's tests use, exported so a test in a package ABOVE the root (such as tools_test) can script a provider the same way.
Package testkit holds the Agent-free test doubles the root package's and the runner package's tests use, exported so a test in a package ABOVE the root (such as tools_test) can script a provider the same way.
testutil
Package testutil holds the test helpers that tests of many packages need and that need nothing of AgentKit: file trees, a git environment that ignores the machine's configuration, polling with a deadline, JSON, tar, golden files, the repository root, and running a program with `go run`.
Package testutil holds the test helpers that tests of many packages need and that need nothing of AgentKit: file trees, a git environment that ignores the machine's configuration, polling with a deadline, JSON, tar, golden files, the repository root, and running a program with `go run`.
toolconformance
Package toolconformance holds the tool conformance case table: every built-in tool returns its documented error codes, and its Data conforms to its declared OutputSchema.
Package toolconformance holds the tool conformance case table: every built-in tool returns its documented error codes, and its Data conforms to its declared OutputSchema.
mcpserve module
Package outline returns the declarations of a source file, with line ranges, and the parse verdict of the parse that produced them: whether the file was parsed, why not if it was not, and the syntax errors the parse found.
Package outline returns the declarations of a source file, with line ranges, and the parse verdict of the parse that produced them: whether the file was parsed, why not if it was not, and the syntax errors the parse found.
Package output is the bounded output buffer the tools and code mode share: an Accumulator keeps the head, the tail or both ends of a long stream within a byte budget, and may spill the whole of it to a file.
Package output is the bounded output buffer the tools and code mode share: an Accumulator keeps the head, the tail or both ends of a long stream within a byte budget, and may spill the whole of it to a file.
Package prompt assembles the system prompt the loop sends.
Package prompt assembles the system prompt the loop sends.
anthropic
Package anthropic implements the Anthropic Messages wire API.
Package anthropic implements the Anthropic Messages wire API.
faux
Package faux is a deterministic provider that replays a scripted sequence of assistant turns.
Package faux is a deterministic provider that replays a scripted sequence of assistant turns.
ollama
Package ollama is a core.ProviderClient for a model served by an Ollama server, local or self-hosted.
Package ollama is a core.ProviderClient for a model served by an Ollama server, local or self-hosted.
openrouter
Package openrouter is a core.ProviderClient for a model served by OpenRouter.
Package openrouter is a core.ProviderClient for a model served by OpenRouter.
Package runner runs tool calls with no model.
Package runner runs tool calls with no model.
Package schema is the structured, transformable tool-schema value type.
Package schema is the structured, transformable tool-schema value type.
Package tools provides AgentKit's built-in tool set.
Package tools provides AgentKit's built-in tool set.
Package wire is the bounded, strict decoder for bytes AgentKit did not produce.
Package wire is the bounded, strict decoder for bytes AgentKit did not produce.
Package workspace is the root every AgentKit scenario opens first: the containment boundary for the file tools, the ignore rules that apply under it and the directory walk that honours them.
Package workspace is the root every AgentKit scenario opens first: the containment boundary for the file tools, the ignore rules that apply under it and the directory walk that honours them.

Jump to

Keyboard shortcuts

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