agentenkit

package module
v0.11.0 Latest Latest
Warning

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

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

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

README

go-agentenkit

The Go version of agentenkit: a durable runtime for AI agent runs, as a library. Where the TypeScript package builds on the Vercel AI SDK, this one builds on goai, the Go SDK with the same shape.

It does not own your prompts, models, or tools; goai does. It owns the lifecycle of a run: that a run outlives the request that started it, survives a worker dying mid-step, can be stopped, parked for a human, resumed exactly where it stopped, nested, metered, and watched by several people at once.

The behaviour is the TypeScript package's, port by port and file by file. The full documentation describes it; this README shows the Go shape of each piece.

BillingPreCheck receives a BillingCheck with the thread, the run state and PublishEvent, so a refusal can carry its reason to every client; the platform publishes RUN_REFUSED as well, and TOKEN_BUDGET_EXHAUSTED or COST_BUDGET_EXHAUSTED when a run spends its budget between steps.

A complete, runnable example, a Go server serving a React SPA with tools, approvals, subagents and custom events, lives in examples/go-app.

Install

go get github.com/eadwinCode/agentic-kit/packages/go-agentenkit

Requires Go 1.27+. Adapters live in their own packages, so a program only compiles the drivers it imports.

Running locally, with nothing to stand up

Assembling the platform is five adapters and one wire, and seeing them is the point: swapping any of them for the durable equivalent later is then obvious rather than magic.

package main

import (
	"context"
	"log"

	"github.com/zendev-sh/goai/provider"
	"github.com/zendev-sh/goai/provider/openai"
	_ "modernc.org/sqlite" // any database/sql SQLite driver

	agentenkit "github.com/eadwinCode/agentic-kit/packages/go-agentenkit"
	"github.com/eadwinCode/agentic-kit/packages/go-agentenkit/adapters/inline"
	"github.com/eadwinCode/agentic-kit/packages/go-agentenkit/adapters/memory"
	"github.com/eadwinCode/agentic-kit/packages/go-agentenkit/adapters/sqlite"
	sqliteadmin "github.com/eadwinCode/agentic-kit/packages/go-agentenkit/admin/sqlite"
)

func main() {
	ctx := context.Background()

	// One file holds both: your tables, and, prefixed agentic_, the platform's
	// own operational history.
	db, err := sqlite.Open("agentic-kit.sqlite")
	if err != nil {
		log.Fatal(err)
	}
	storage, _ := sqlite.New(db)
	admin, _ := sqliteadmin.New(db)
	kv, _ := sqlite.NewKv(db)
	streams, _ := sqlite.NewRunStreams(ctx, db, 0) // one short-lived stream per run segment
	queue := inline.New(ctx)

	rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{
		Storage: storage,           // later: adapters/postgres, or your own
		Admin:   admin,             // later: admin/postgres
		Bus:     memory.NewBus(),   // later: adapters/redis
		Kv:      kv,                // later: adapters/redis
		Streams: streams,           // later: adapters/redis, adapters/postgres
		Queue:   queue,             // later: adapters/qstash
		ResolveModel: func(name string) (agentenkit.ResolvedModel, error) {
			return agentenkit.ResolvedModel{
				Instance:      func() provider.LanguageModel { return openai.Chat(name) },
				ContextWindow: 128_000,
			}, nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer rt.Close()

	// The queue and the worker each need the other, so the queue is attached
	// once the core exists. Nothing dispatches until this line runs.
	queue.Bind(rt.Worker.Handler())

	chat := rt.CreateStreamTextAgent(agentenkit.StreamTextAgentSpec{Name: "chat", Model: "gpt-4o"})
	res, err := chat.Run(ctx, agentenkit.RunInput{Prompt: "hi"}) // persisted, dispatched, running
	log.Println(res, err)
}

The inline queue dispatches on its own goroutine, so Run returns at once and a run still outlives the request that started it. It honours delays, so parked approvals expire and blocked jobs redrive exactly as they do against a durable queue. What it does not do is survive a restart.

sqlite.Open uses whichever database/sql SQLite driver the process has registered (modernc.org/sqlite or mattn/go-sqlite3). Pass ":memory:" for a database that dies with the process.

Going to production

Same shape, durable pieces. Each line above swaps for one here.

rdb := goredis.NewClient(&goredis.Options{Addr: os.Getenv("REDIS_ADDR")})
pg, _ := sql.Open("pgx", os.Getenv("DATABASE_URL"))
storage, _ := postgres.New(ctx, pg)

rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{
	Storage: storage,                       // or Mongo / Dynamo / your DB
	Bus:     redis.NewBus(rdb, 0),          // Ably / Kafka / Postgres LISTEN…
	Kv:      redis.NewKv(rdb),
	Streams: redis.NewRunStreams(rdb, redis.StreamsOptions{}),
	Queue: qstash.New(qstash.Client{Token: os.Getenv("QSTASH_TOKEN")},
		qstash.Options{URL: "https://app.example.com/api/queue/agent-run"}),
	// Admin omitted on purpose: with AGENTIC_KIT_ADMIN_DATABASE_URL set, the
	// platform opens Postgres for its own history. Pass one to override.
	ResolveModel: resolve,
})

The QStash consumer URL is public, so check that each delivery came from QStash before it reaches the worker. Otherwise anyone who finds the URL can run any agent under any tenant:

keys := qstash.SigningKeys{
	Current: os.Getenv("QSTASH_CURRENT_SIGNING_KEY"),
	Next:    os.Getenv("QSTASH_NEXT_SIGNING_KEY"),
}
consumer := "https://app.example.com/api/queue/agent-run" // same as Options.URL
http.Handle("/api/queue/agent-run", qstash.Middleware(keys, consumer, http.HandlerFunc(
	func(w http.ResponseWriter, r *http.Request) {
		var job agentenkit.RunJob
		if err := json.NewDecoder(r.Body).Decode(&job); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		if _, err := rt.Worker.HandleJob(r.Context(), job); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})))

Or one Postgres for all five, no Redis and no queue service:

pg, _ := sql.Open("pgx", url)
storage, _ := postgres.New(ctx, pg)
kv, _ := postgres.NewKv(ctx, pg)
queue, _ := postgres.NewQueue(ctx, pg, postgres.QueueOptions{})
bus := postgres.NewBus(pg, pgxlisten.New(url), storage.Events(), kv, postgres.BusOptions{})
streams, _ := postgres.NewRunStreams(ctx, pg, postgres.StreamsOptions{Listener: pgxlisten.New(url)})
rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{
	Storage: storage, Kv: kv, Bus: bus, Queue: queue, Streams: streams, ResolveModel: resolve,
})
queue.Bind(rt.Worker.Handler())

The bus rides LISTEN/NOTIFY and routes an event past the 8000-byte cap by reference; the queue claims with SKIP LOCKED and renews its lease while a job runs; the run streams send NOTIFY when they write, so readers wake without polling. All are in adapters/postgres; the listener is adapters/postgres/pgxlisten.

Leave Streams out and the runtime keeps run streams in memory and logs a warning once. Only that process can read them, so when web servers and workers run apart, pass a real one. Keep StreamGrace short on Redis (it is memory); it can be longer on Postgres or SQLite.

Operations

Runs belong to an agent handle; reads belong to the runtime.

chat.Run(ctx, agentenkit.RunInput{Prompt: "hi", State: agentenkit.AgentRunState{"orgId": orgID}})
chat.Stop(ctx, threadID, nil)                                              // one write: state → CANCELLED
rt.HITL.Respond(ctx, agentenkit.RespondInput{ThreadID: threadID, ToolCallID: id, Approved: true})
rt.GetThreadSnapshot(ctx, threadID, nil)                                   // hydrate a client
stream, _ := rt.Events.SSE(r.Context(), threadID, agentenkit.SSEStateOptions{}) // then stream.ServeHTTP(w, r)
frames, _ := rt.Events.Follow(ctx, threadID, agentenkit.FollowStateOptions{})   // or range frames.Frames()
rt.Streams.Read(ctx, streamID, "")                                         // one run stream, as an iter.Seq2
rt.Events.Since(ctx, threadID, lastSeq, nil)                               // the thread record, raw
rt.Worker.HandleJob(ctx, job)                                              // queue consumer
rt.Events.PublishEvent(ctx, threadID, "MY_EVENT", payload, agentenkit.PublishStateOptions{}) // your own event, live only
rt.PruneEvents(ctx, agentenkit.PruneOptions{DryRun: true})                 // after upgrading: clear old stream-only rows

A follow yields FollowFrames: Kind is "thread" (a record entry or a notice, in Event), "stream" (a run stream item, in StreamID and Item) or "snapshot" (sent once when the stream the client was reading is gone, in Snapshot). The cursor is one string, <seq> <streamId> <offset>; every SSE frame that moves it carries it as its id:, so EventSource sends it back as Last-Event-ID. rt.Events.FollowRecord is the old record-only follow.

An SSE route is a few lines:

http.HandleFunc("/api/agent/stream", func(w http.ResponseWriter, r *http.Request) {
	cursor := r.Header.Get("Last-Event-ID")
	if cursor == "" {
		cursor = r.URL.Query().Get("cursor")
	}
	if cursor == "" {
		cursor = r.URL.Query().Get("since") // a bare record seq, from an older client
	}
	stream, err := rt.Events.SSE(r.Context(), r.URL.Query().Get("threadId"), agentenkit.SSEStateOptions{
		FollowStateOptions: agentenkit.FollowStateOptions{
			Cursor:        cursor,
			LastMessageID: r.URL.Query().Get("lastMessageId"),
		},
		RetryMs: 2000,
	})
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	stream.ServeHTTP(w, r) // returns when the client hangs up, and stops the follow
})

The stream events, the frames and the cursor are the same JSON the TypeScript package sends, so the use-agentenkit React hook works against either runtime. Opt-in: SSEStateOptions{WireFormat: "ag-ui"} sends AG-UI events instead; the default is the native frames.

Tools and approvals

Tools are goai tools. Wrap them, or build them with the run state in hand:

lookup := agentenkit.AgentTool("lookupInvoice", "Find one invoice",
	func(ctx context.Context, in struct{ InvoiceID string `json:"invoiceId"` }, tc agentenkit.ToolContext) (string, error) {
		// tc.State is the run state; tc.PublishEvent publishes on this thread.
		// Live only by default; PublishOptions{Durable: true} keeps it in the thread record.
		_, _ = tc.PublishEvent(ctx, "LOOKUP", map[string]any{"id": in.InvoiceID}, agentenkit.PublishOptions{})
		return db.FindInvoice(ctx, in.InvoiceID, tc.State["orgId"].(string))
	})

// Parked behind a human approval instead of executing.
wipe := agentenkit.RequireConfirmation(goai.NewTool("wipe", "Wipe an account", wipeFn))

chat := rt.CreateStreamTextAgent(agentenkit.StreamTextAgentSpec{
	Name:   "chat",
	Model:  "gpt-4o",
	System: "You are terse.",
	Tools:  []agentenkit.Tool{lookup, wipe},
	Options: []goai.Option{goai.WithTemperature(0.2)}, // any goai option; the platform's own win
	Subagents: &agentenkit.SubagentsConfig{},         // opt in to delegation
})

The platform owns the model, the messages, the step ceiling and the stop handling. Every other goai option is yours, passed through Options.

Built-in tools

Tools with one name and one input shape in both runtimes, so any model that can call tools can use them. The adapters take their API keys here, at setup; nothing reads the environment later.

search, err := brave.New(os.Getenv("BRAVE_API_KEY"))                // or jina.NewWebSearch
sandbox, err := e2b.New(os.Getenv("E2B_API_KEY"), e2b.Options{})     // or docker.New, localsandbox.New
rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{
	// ... ports ...
	Tools: agentenkit.BuiltinToolPorts{
		Search:  search,
		Fetcher: pagereader.New(pagereader.Options{}),                // or jina.NewReader
		Sandbox: sandbox,
	},
})

tools, err := rt.BuiltinTools(
	[]string{"web_search", "web_fetch", "bash", "code_execution", "text_editor"},
	agentenkit.BuiltinToolOptions{Bash: agentenkit.BashOptions{Timeout: 2 * time.Minute}},
)
coder := rt.CreateStreamTextAgent(agentenkit.StreamTextAgentSpec{Name: "coder", Tools: append(tools, lookup)})
Tool What the model can do Needs Asks for approval
web_search Search; results come back with short ids Search No
web_fetch Read a page, by URL or result id; with a prompt, a small model answers from the page Fetcher No
bash Run a command in the thread's sandbox Sandbox Yes
code_execution Run a Python or JavaScript program; lists the files it made Sandbox No
text_editor View, create and edit files by exact replacement, with undo Sandbox For changes

A thread has one sandbox, kept between messages; it ends when the thread is deleted or has been idle for SandboxIdleTTL (30 minutes). With SandboxScope: agentenkit.SandboxScopeRun, each run gets its own, ended with the run. Each tool call is a usage row, so pricing.Tools{"brave": {PerUse: 0.005}, "e2b": {PerSecond: 0.000028}} puts tool spend on the bill. Approval takes agentenkit.AskAlways, agentenkit.AskNever, or a check per call. Your own tools reach the sandbox with agentenkit.WithSandbox(ctx, fn).

The spec's hooks

rt.CreateStreamTextAgent(agentenkit.StreamTextAgentSpec{
	Name: "designer",
	// Built per step with the run's state; wins over System.
	SystemFn: func(ctx context.Context, threadID string, state agentenkit.AgentRunState) (string, error) {
		return persona + projectBrief(ctx, state), nil
	},
	// Runs after the last step and BEFORE the terminal state is written: commit
	// what the run produced, bill it. An error fails the run; a stop arrives
	// with Cancelled set. Idempotent on RunID, please.
	OnSettle: func(ctx context.Context, info agentenkit.RunFinishInfo) error {
		return repo.Commit(ctx, info.RunID)
	},
	OnFinish: func(info agentenkit.RunFinishInfo) { log.Println("done", info.RunID, info.State) },
	Subagents: &agentenkit.SubagentsConfig{Profiles: map[string]agentenkit.SubagentProfile{
		"page-manager": {Description: "edits pages", SystemFn: pagePrompt, Tools: pageTools, MaxSteps: 20},
	}},
})

// A run can name itself, cap its own steps, and carry images.
chat.Run(ctx, agentenkit.RunInput{
	Prompt: "make the hero bolder", RunID: myRunID, MaxSteps: 8,
	Attachments: []agentenkit.Attachment{{URL: "https://cdn.example/ref.png", MediaType: "image/png"}},
})

Run state

Whatever you attach to a run reaches every storage call it makes, every tool, and every nested run, including in a worker that picks the job up hours later, in another process, after an approval. The platform never reads it.

chat.Run(ctx, agentenkit.RunInput{Prompt: "hi", State: agentenkit.AgentRunState{"orgId": "acme"}})

// Your Storage sees it on every method, as a trailing argument.
func (m messages) List(ctx context.Context, threadID string, scope *ports.MessageScope, sc ports.StorageContext) ([]ports.MessageDTO, error) {
	org := sc.State["orgId"]
	// ...
}

// A tool reads it from its context, or takes it as an argument via AgentTool.
state := agentenkit.RunStateFromContext(ctx)
tc := agentenkit.ToolContextFrom(ctx) // state, tool call id, and PublishEvent

Ports: your data

Port Role Reference adapters
Storage threads / messages / the thread record / usage, incl. atomic ClaimState adapters/postgres, adapters/sqlite, adapters/memory
EventBus live fan-out + HITL death notices (at-most-once) adapters/redis, adapters/upstash, adapters/clevixflow, adapters/memory
Queue durable run dispatch (at-least-once) adapters/qstash, adapters/clevixflow, adapters/inline (dev), adapters/memory
Kv hot state cache, HITL handoff keys, segment/attempt counters, run locks adapters/redis, adapters/upstash, adapters/sqlite, adapters/memory
RunStreams one short-lived stream per run segment adapters/redis, adapters/upstash, adapters/postgres, adapters/sqlite, adapters/memory (each NewRunStreams), adapters/clevixflow (NewStreams)

Implement any of them for your own stack; core/ imports nothing else. The memory adapters are a complete implementation used by the test suite and double as a template.

Cost

Give the runtime a Pricer and every usage row carries the money as well as the tokens, so spend is read from the store the engine already fills:

import "github.com/eadwinCode/agentic-kit/packages/go-agentenkit/pricing"

rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{
    // ... ports ...
    Pricer: pricing.Table{
        // dollars per MILLION tokens, typed off the provider's pricing page
        "gpt-4o": {InputPerMillion: 2.5, CacheReadPerMillion: 1.25, OutputPerMillion: 10},
    },
})

One row per model call: main run, nested run or compaction, streamed or not, finished or cut short. Reading it back:

rt.GetThreadUsage(ctx, threadID, nil)                        // the thread header
storage.Usage().Total(ctx, threadID, ports.UsageFilter{RunID: runID}, sc) // one run's bill

Every total carries CostMicros, Currency, Unpriced and Lines — the same spend grouped by agent and model, which is what a credit system charges for. A spec's OnFinish receives it ready-made as info.Usage, and RunInput.CostBudgetMicros caps a run by money the way TokenBudget caps it by tokens.

pricing also ships Receipt, for the figure a gateway already computed, and Chain, to try one then the other. See Cost and pricing.

The admin store: not yours

Run records, step timings and a thread index are the platform's data, in the platform's own tables. You do not implement AdminStore; you read it back:

rt.Admin.Overview(ctx, nil)                     // threads and runs by state, plus what's in flight
rt.Admin.ListRuns(ctx, agentenkit.RunFilter{State: []agentenkit.ExecutionState{agentenkit.StateFailed}})
rt.Admin.Stats(ctx, agentenkit.StatsRange{})   // p50/p95 duration and queue wait, tokens, failures
rt.Admin.GetRun(ctx, runID)                     // one run: steps, nested runs, its record entries, spend

Its schema migrates itself, from numbered .sql files embedded in the binary (admin/migrate/sql). SetupAgentCore opens the connection and returns; the schema is brought up to date on a goroutine behind it, and every admin call waits for that before its first query. Several workers starting at once queue on a Postgres advisory lock rather than racing. An existing database needs nothing: migration 0001 is the schema as it stood before the migrator. Your own Storage is never touched by any of this.

Configure nothing and it is SQLite on disk (AGENTIC_KIT_ADMIN_DB moves the file). Set AGENTIC_KIT_ADMIN_DATABASE_URL and it is Postgres. Either way the platform uses whichever database/sql driver the process has registered, like the TypeScript package uses whichever SQLite driver the runtime has. Import one:

import _ "modernc.org/sqlite"             // or github.com/mattn/go-sqlite3
import _ "github.com/jackc/pgx/v5/stdlib" // or github.com/lib/pq

File map

Every TypeScript file has a Go twin. The one structural change: Go cannot have an import cycle between core and ports, so the shared types (core/types.ts, the type half of core/state.ts) live in ports/.

TypeScript Go
src/index.ts agentenkit.go (re-exports)
src/runtime.ts runtime.go (SetupAgentCore, AgentCore)
src/ports/*.ts, src/core/types.ts, src/core/state.ts (types) ports/*.go
src/core/*.ts core/*.go (core/messages.go is new: JSON ⇄ goai messages)
src/adapters/memory.ts, inline.ts, sqlite.ts, redis.ts, qstash.ts, upstash.ts adapters/<name>/<name>.go
src/adapters/flow.ts adapters/clevixflow/clevixflow.go
src/adapters/prisma.ts adapters/postgres/postgres.go
src/adapters/brave.ts, jina.ts, page-reader.ts adapters/brave, adapters/jina, adapters/pagereader
src/adapters/docker.ts, e2b.ts, local-sandbox.ts adapters/docker, adapters/e2b, adapters/localsandbox
src/adapters/computesdk.ts none: ComputeSDK is a TypeScript library
src/admin/memory.ts, sqlite.ts, postgres.ts, default.ts admin/<name>/<name>.go, admin/default.go
test/*.test.ts *_test.go

The stored message and event JSON is the same as the TypeScript package's, and the SQLite and Postgres admin schemas are identical, so a Go worker and a TypeScript worker can share one database.

Differences worth knowing

  • Durations, not milliseconds. AgentConfig uses time.Duration (HITLTTL, StopPoll, RunLockLease, …). TokenBudget zero means unbounded.
  • Results and errors are separate. A refusal (Accepted: false) comes back in the result; an infrastructure failure comes back as an error.
  • Config is a value. cfg := agentenkit.DefaultConfig(), change what you need, pass &cfg. CompactionModel names the cheap model used for context summaries.
  • Compaction recovers and can be asked for. A model call refused as too long ("prompt is too long", context_length_exceeded…) compacts the thread at once, keeping only the latest user turn, and the run goes on (once per segment). rt.CompactThread(ctx, threadID, state) does the same on request, refused while a run is queued or running. The TypeScript package does the same (compactThread).
  • A mixed step keeps its results. When one tool parks and another runs in the same step, the executed result is persisted, in both packages.
  • Total tokens are always input + cached + output, for every provider.

Development

go test ./...                               # memory + SQLite; Postgres tests skip
TEST_ADMIN_PG=postgres://... go test ./...  # also runs the Postgres store tests
TEST_DOCKER_SANDBOX=1 go test ./...         # also runs the sandbox suite on Docker

Documentation

Overview

Package agentenkit is a durable runtime for AI agent runs, as a library.

It does not own your prompts, models, or tools; goai does. It owns the lifecycle of a run: that a run outlives the request that started it, survives a worker dying mid-step, can be stopped, parked for a human, resumed exactly where it stopped, nested, metered, and watched by several people at once.

This is the Go port of the TypeScript agentenkit package, file for file:

ports/     the four ports you implement, the admin store, every DTO
core/      the behaviors (engine, loop, HITL, subagents, follow, admin reads)
adapters/  memory, inline, sqlite, postgres, redis, qstash, clevixflow, upstash
admin/     memory, sqlite, postgres operational stores

This root package re-exports the public surface, the way index.ts does, and holds SetupAgentCore (runtime.ts). Adapters are imported from their own packages so a program only compiles the drivers it uses.

Index

Constants

View Source
const (
	KindStep       = ports.KindStep
	KindCompaction = ports.KindCompaction
	KindTool       = ports.KindTool
	// ToolUsePrefix starts the Model of a row for one use of a paid tool service.
	ToolUsePrefix = ports.ToolUsePrefix

	UsageFinished = ports.UsageFinished
	UsageAborted  = ports.UsageAborted
	UsageErrored  = ports.UsageErrored

	StateIdle            = ports.StateIdle
	StateQueued          = ports.StateQueued
	StateRunning         = ports.StateRunning
	StateWaitingForInput = ports.StateWaitingForInput
	StateCancelled       = ports.StateCancelled
	StateCompleted       = ports.StateCompleted
	StateFailed          = ports.StateFailed

	RoleUser      = ports.RoleUser
	RoleAssistant = ports.RoleAssistant
	RoleSystem    = ports.RoleSystem
	RoleTool      = ports.RoleTool

	KindStreamText   = ports.KindStreamText
	KindGenerateText = ports.KindGenerateText

	JobDispatch = ports.JobDispatch
	JobRetry    = ports.JobRetry
	JobRedrive  = ports.JobRedrive
	JobResume   = ports.JobResume
	JobExpiry   = ports.JobExpiry
	JobReclaim  = ports.JobReclaim
	PriorityLow = ports.PriorityLow

	BillingAtDispatch = ports.BillingAtDispatch
	BillingAtPickup   = ports.BillingAtPickup

	RefusedActiveRun = ports.RefusedActiveRun
	RefusedQueueFull = ports.RefusedQueueFull
	RefusedBilling   = ports.RefusedBilling
)
View Source
const (
	OutcomeExecuted     = core.OutcomeExecuted
	OutcomeLockConflict = core.OutcomeLockConflict
	OutcomeStale        = core.OutcomeStale
	OutcomeLockLost     = core.OutcomeLockLost

	// SettleClaimTTL is how long a settle claim holds (§5.6).
	SettleClaimTTL = core.SettleClaimTTL

	HITLParked          = core.HITLParked
	ReasonApproval      = core.ReasonApproval
	HITLTTL             = core.HITLTTL
	ContextTokenCeiling = core.ContextTokenCeiling
	ContextSummaryType  = core.ContextSummaryType
	DefaultModel        = core.DefaultModel
)
View Source
const (
	SandboxScopeThread = ports.SandboxScopeThread
	SandboxScopeRun    = ports.SandboxScopeRun
)

SandboxScopeThread keeps one sandbox per thread (the default); SandboxScopeRun gives each run its own. See AgentConfig.SandboxScope.

Variables

View Source
var (
	ErrQueueFull       = ports.ErrQueueFull
	ErrPayloadTooLarge = ports.ErrPayloadTooLarge
	ErrDuplicateJob    = ports.ErrDuplicateJob
	ErrUnsupported     = ports.ErrUnsupported
)

Errors a queue answers with, so a host can tell them apart.

View Source
var (
	// IsToolUse says whether a usage row's or line's Model is one use of a
	// paid tool service rather than a model call.
	IsToolUse = ports.IsToolUse
	// MainAgent scopes a message listing to the main agent's stream.
	MainAgent = ports.MainAgent
	// AgentScope scopes a message listing to one nested run's stream.
	AgentScope = ports.AgentScope
	// DefaultConfig returns the shipped defaults.
	DefaultConfig = ports.DefaultConfig
	// ResolveConfig validates a config.
	ResolveConfig = ports.ResolveConfig
	// WrapTool lifts a plain goai tool into the platform's Tool.
	WrapTool = ports.WrapTool
	// WrapTools lifts several goai tools.
	WrapTools = ports.WrapTools
	// BindStorage attaches a run's context to every storage method once.
	BindStorage = ports.BindStorage
	// MergeProviderOptions is a shallow per-provider merge.
	MergeProviderOptions = ports.MergeProviderOptions
)
View Source
var (
	Execute                  = core.Execute
	ExecuteStep              = core.ExecuteStep
	ExecuteWithPolicy        = core.ExecuteWithPolicy
	Finalize                 = core.Finalize
	RunLoop                  = core.RunLoop
	IsParked                 = core.IsParked
	MarkRequiresConfirmation = core.MarkRequiresConfirmation
	RequireConfirmation      = core.RequireConfirmation

	FollowEvents = core.FollowEvents
	ToSSEStream  = core.ToSSEStream
	SSEFrame     = core.SSEFrame
	ParseCursor  = core.ParseCursor
	FormatCursor = core.FormatCursor
	SSEHeaders   = core.SSEHeaders

	ContextWithRunID = core.ContextWithRunID
	RunIDFromContext = core.RunIDFromContext
	ClaimRun         = core.ClaimRun
	ClaimRunAs       = core.ClaimRunAs
	UserContent      = core.UserContent
	CurrentRunID     = core.CurrentRunID
	RunIDKey         = core.RunIDKey
	RedriveKey       = core.RedriveKey
	AttemptsKey      = core.AttemptsKey
	IsActive         = core.IsActive
	StateKey         = core.StateKey
	SeqKey           = core.SeqKey

	RunLockKey     = core.RunLockKey
	ParseLockValue = core.ParseLockValue
	NewID          = core.NewID

	CountTokens     = core.CountTokens
	AttributeTokens = core.AttributeTokens

	Respond         = core.Respond
	ParkForApproval = core.ParkForApproval
	ParkForInput    = core.ParkForInput
	AsParkRequest   = core.AsParkRequest
	LoadPendingHitl = core.LoadPendingHitl
	LoadOpenHitls   = core.LoadOpenHitls
	WithHitl        = core.WithHitl
	HitlKey         = core.HitlKey

	ReclaimIfOrphaned = core.ReclaimIfOrphaned
	ContextBudget     = core.ContextBudget
	ContextUsageOf    = core.ContextUsage
	CompactContext    = core.CompactContext

	NewSemaphore      = core.NewSemaphore
	RunNestedAgent    = core.RunNestedAgent
	SpawnSubagentTool = core.SpawnSubagentTool

	Run          = core.Run
	Stop         = core.Stop
	StopRun      = core.StopRun
	DeleteThread = core.DeleteThread

	RunStateFromContext = core.RunStateFromContext
	ContextWithRunState = core.ContextWithRunState
	WithRunState        = core.WithRunState

	MarkPromptCaching  = core.MarkPromptCaching
	SystemCacheMessage = core.SystemCacheMessage
	ChunkPayload       = core.ChunkPayload

	ContentFromMessage      = core.ContentFromMessage
	MessageFromDTO          = core.MessageFromDTO
	MessagesFromDTOs        = core.MessagesFromDTOs
	RepairDanglingToolCalls = core.RepairDanglingToolCalls
	ParseContent            = core.ParseContent
	TextContent             = core.TextContent
	PartsContent            = core.PartsContent

	Publish              = core.Publish
	PublishNotice        = core.PublishNotice
	PublishEvent         = core.PublishEvent
	WithPublishEvent     = core.WithPublishEvent
	ToolContextFrom      = core.ToolContextFrom
	ToolRunFromContext   = core.ToolRunFromContext
	SandboxFor           = core.SandboxFor
	IsPermanentError     = core.IsPermanentError
	BuiltinToolNames     = core.BuiltinToolNames
	DecodeEntities       = core.DecodeEntities
	HTMLToText           = core.HTMLToText
	ApprovalFromContext  = core.ApprovalFromContext
	PublisherFromContext = core.PublisherFromContext
	ReservedEventTypes   = core.ReservedEventTypes
	SetThreadState       = core.SetThreadState
	Summarise            = core.Summarise
)
View Source
var (
	ErrSandboxGone         = ports.ErrSandboxGone
	ErrSandboxFileNotFound = ports.ErrSandboxFileNotFound
	ErrSandboxUnsupported  = ports.ErrSandboxUnsupported
)

The sandbox errors, for errors.Is.

View Source
var (
	AskAlways = core.AskAlways
	AskNever  = core.AskNever
)

AskAlways and AskNever are the two fixed approval rules for the sandbox tools.

View Source
var ErrUnknownAgent = errors.New("agentenkit: no agent registered for this job")

ErrUnknownAgent is a job for an agent this process has not registered, with no default handle to fall back on. It is an error rather than a quiet refusal: the queue keeps the job and retries it, so a process that registers its agents a moment after it starts consuming heals on its own, and one that never does leaves a dead row and a log line, not silence.

Functions

func Ptr

func Ptr[T any](v T) *T

Ptr is a small helper for building a RunPatch.

func WithSandbox added in v0.5.0

func WithSandbox[T any](ctx context.Context, fn func(ThreadSandbox) (T, error)) (T, error)

WithSandbox runs fn on the thread's sandbox, from inside a tool. When the sandbox turns out to be gone part way (it ended on its own), a fresh one is made and fn runs once more, told Lost.

Types

type AdminAPI

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

AdminAPI reads operational history (§2.9). Everything here comes from the platform's OWN store; it never reads the caller's database, except for a thread's or a run's spend and a run's events, which live in Storage.

func (*AdminAPI) GetRun

func (a *AdminAPI) GetRun(ctx context.Context, runID string) (*RunDetail, error)

GetRun: one run with steps, nested runs and timeline. Nil when unknown.

func (*AdminAPI) GetThread

func (a *AdminAPI) GetThread(ctx context.Context, threadID string) (*ThreadDetail, error)

GetThread: one thread opened up. Nil when nothing was recorded for it.

func (*AdminAPI) ListRuns

func (a *AdminAPI) ListRuns(ctx context.Context, filter RunFilter) ([]RunRecord, error)

ListRuns lists runs, newest first, bounded.

func (*AdminAPI) ListRunsByThread

func (a *AdminAPI) ListRunsByThread(ctx context.Context, threadID string) ([]RunRecord, error)

ListRunsByThread: every run on a thread, newest first.

func (*AdminAPI) ListSteps

func (a *AdminAPI) ListSteps(ctx context.Context, runID string) ([]StepRecord, error)

ListSteps: a run's steps in order.

func (*AdminAPI) ListThreads

func (a *AdminAPI) ListThreads(ctx context.Context, filter AdminThreadFilter) ([]ThreadSummary, error)

ListThreads: threads with their runs rolled up.

func (*AdminAPI) Overview

func (a *AdminAPI) Overview(ctx context.Context, since *time.Time) (AdminOverview, error)

Overview: threads and runs by state, plus what is in flight.

func (*AdminAPI) Stats

func (a *AdminAPI) Stats(ctx context.Context, r StatsRange) (RunStats, error)

Stats: p50/p95 duration and queue wait, tokens, failures.

func (*AdminAPI) WithState added in v0.6.0

func (a *AdminAPI) WithState(state AgentRunState) *AdminAPI

WithState is the admin API with its Storage reads (a thread's or a run's spend, a run's events) made with state, as a run's are. A storage that needs a tenant to open the right database reads them from state; without it those reads fail, and the view shows no spend.

type AdminOverview

type AdminOverview = core.AdminOverview

Core: behaviors, all ports-only.

type AdminStore

type AdminStore = ports.AdminStore

Ports: the interfaces users implement.

type AdminThread

type AdminThread = ports.AdminThread

Ports: the interfaces users implement.

type AdminThreadFilter

type AdminThreadFilter = ports.AdminThreadFilter

Ports: the interfaces users implement.

type AdminThreadStore

type AdminThreadStore = ports.AdminThreadStore

Ports: the interfaces users implement.

type AgentConfig

type AgentConfig = ports.AgentConfig

Types: the DTOs that cross the ports.

type AgentCore

type AgentCore struct {

	// HITL answers approvals and heals orphans (§2.5).
	HITL *HITLAPI
	// Events replays and tails a thread (§2.2).
	Events *EventsAPI
	// Admin reads operational history (§2.9).
	Admin *AdminAPI
	// Worker is the queue dispatch side (§2.8).
	Worker *WorkerAPI
	// Streams reads run streams by id.
	Streams *StreamsAPI
	// contains filtered or unexported fields
}

AgentCore is the bound platform: ports plus behaviors (§3.3).

func SetupAgentCore

func SetupAgentCore(ctx context.Context, opts RuntimeOptions) (*AgentCore, error)

SetupAgentCore binds the ports to the core behaviors (§3.3). This is the package's public entry point: the only place where anything is wired.

Operational history is the platform's own (§2.9). Nothing configured means SQLite on disk, opened here, eagerly: a store that cannot be opened is a startup error you see immediately, rather than a surprise on the first run.

func (*AgentCore) AdminStore

func (c *AgentCore) AdminStore() AdminStore

AdminStore is the operational store in use.

func (*AgentCore) BuiltinTools added in v0.5.0

func (c *AgentCore) BuiltinTools(names []string, opts BuiltinToolOptions) ([]Tool, error)

BuiltinTools returns the built-in tools, ready to put in an agent's Tools: one name and one input shape in every runtime, so any model that can call tools can use them. An error when a tool's adapter was not given in RuntimeOptions.Tools.

tools, err := rt.BuiltinTools([]string{"web_search", "web_fetch"}, agentenkit.BuiltinToolOptions{})

func (*AgentCore) Close

func (c *AgentCore) Close() error

Close releases the admin store.

func (*AgentCore) CompactThread added in v0.8.0

func (c *AgentCore) CompactThread(ctx context.Context, threadID string, state AgentRunState) (CompactResult, error)

CompactThread summarizes a thread's history now, whatever its size: the recent tail stays as it is and everything before it goes into a durable summary (§2.6), as an automatic compaction would write it. Refused while a run is queued or running. The summary call is recorded without a run.

func (*AgentCore) Config

func (c *AgentCore) Config() AgentConfig

Config is the resolved config.

func (*AgentCore) CreateGenerateTextAgent

func (c *AgentCore) CreateGenerateTextAgent(spec GenerateTextAgentSpec) *AgentHandle

CreateGenerateTextAgent registers a generate-text handle under spec.Name.

func (*AgentCore) CreateStreamTextAgent

func (c *AgentCore) CreateStreamTextAgent(spec StreamTextAgentSpec) *AgentHandle

CreateStreamTextAgent registers a stream-text handle under spec.Name (§4).

func (*AgentCore) DeleteThread

func (c *AgentCore) DeleteThread(ctx context.Context, threadID string, state AgentRunState) (DeleteThreadResult, error)

DeleteThread deletes a thread and everything that follows it (§3.2). Refused while a run is active; Stop first.

func (*AgentCore) GetAgent

func (c *AgentCore) GetAgent(name string) *AgentHandle

GetAgent resolves a registered handle by name, or nil.

func (*AgentCore) GetThreadSnapshot

func (c *AgentCore) GetThreadSnapshot(ctx context.Context, threadID string, state AgentRunState) (*ThreadSnapshot, error)

GetThreadSnapshot is one call for UIs: thread + messages + runs + the unfinished run's record entries + its run stream. Nil when the thread is gone.

func (*AgentCore) GetThreadUsage

func (c *AgentCore) GetThreadUsage(ctx context.Context, threadID string, state AgentRunState) (*ThreadUsage, error)

GetThreadUsage is tokens spent so far and the §2.6 context load. Nil when the thread is gone.

func (*AgentCore) ListThreads

func (c *AgentCore) ListThreads(ctx context.Context, state AgentRunState) ([]ThreadDTO, error)

ListThreads lists threads most recent first. Takes the run state (§2.10) so a tenant-scoped Storage can filter; a read has no dispatch ticket.

func (*AgentCore) Ports

func (c *AgentCore) Ports(state AgentRunState) RuntimePorts

Ports returns the ports bundle for reads on behalf of no particular run, or for a run when state is given.

func (*AgentCore) PruneEvents added in v0.4.0

func (c *AgentCore) PruneEvents(ctx context.Context, opts core.PruneOptions) (core.PruneReport, error)

PruneEvents deletes the stream-only rows (chunks, step markers, state changes…) releases before run streams left in the event table, a batch at a time. Nothing reads them any more; an app's own types are kept. Run it when it suits you, after upgrading: DryRun counts first. With a storage that keeps a database per tenant, run it once per tenant with State.

func (*AgentCore) ReclaimStuckRuns added in v0.3.0

func (c *AgentCore) ReclaimStuckRuns(ctx context.Context, olderThan time.Duration) (ReclaimReport, error)

ReclaimStuckRuns is the backstop for a run that nothing is working on (§2.5, §2.8): a QUEUED or RUNNING record older than olderThan whose lock nobody holds and whose job the queue no longer has is re-dispatched, and an ended record older than olderThan whose settle never ran is settled. Call it from a periodic job. It pages through every such run, not only the first page. A record with no recorded state (RecordPayloads off) is read with an empty state, so a tenant-scoped storage sees no tenant.

func (*AgentCore) ResolveModel

func (c *AgentCore) ResolveModel(modelName string) (ResolvedModel, error)

ResolveModel resolves a registry key to the identity and provider instance used by execution, compaction and usage attribution.

type AgentEvent

type AgentEvent = ports.AgentEvent

Types: the DTOs that cross the ports.

type AgentHandle

type AgentHandle = core.Handle

Core: behaviors, all ports-only.

type AgentKind

type AgentKind = ports.AgentKind

Types: the DTOs that cross the ports.

type AgentRunState

type AgentRunState = ports.AgentRunState

Ports: the interfaces users implement.

type Approval

type Approval = core.Approval

Core: behaviors, all ports-only.

type ApprovalRule added in v0.5.0

type ApprovalRule = core.ApprovalRule

Core: behaviors, all ports-only.

type Attachment

type Attachment = ports.Attachment

Ports: the interfaces users implement.

type BashOptions added in v0.5.0

type BashOptions = core.BashOptions

Core: behaviors, all ports-only.

type BillingCheck

type BillingCheck = ports.BillingCheck

Types: the DTOs that cross the ports.

type BillingStage added in v0.3.0

type BillingStage = ports.BillingStage

Types: the DTOs that cross the ports.

type BoundStorage

type BoundStorage = ports.BoundStorage

Ports: the interfaces users implement.

type BuiltinToolDefinition added in v0.5.0

type BuiltinToolDefinition = core.BuiltinToolDefinition

Core: behaviors, all ports-only.

type BuiltinToolOptions added in v0.5.0

type BuiltinToolOptions = core.BuiltinToolOptions

Core: behaviors, all ports-only.

type BuiltinToolPorts added in v0.5.0

type BuiltinToolPorts = ports.BuiltinToolPorts

Types: the DTOs that cross the ports.

type CodeExecutionOptions added in v0.5.0

type CodeExecutionOptions = core.CodeExecutionOptions

Core: behaviors, all ports-only.

type CommandResult added in v0.5.0

type CommandResult = ports.CommandResult

Types: the DTOs that cross the ports.

type CompactResult added in v0.8.0

type CompactResult struct {
	// Compacted is false when there was nothing older than the recent tail
	// to summarize, or the thread is gone.
	Compacted bool `json:"compacted"`
	// Reason says why nothing was compacted.
	Reason string `json:"reason,omitempty"`
}

CompactResult is what CompactThread did.

type ContentPart

type ContentPart = core.ContentPart

Core: behaviors, all ports-only.

type ContextUsage

type ContextUsage = ports.ContextUsage

Types: the DTOs that cross the ports.

type Cost

type Cost = ports.Cost

Types: the DTOs that cross the ports.

type CreateSandboxOptions added in v0.5.0

type CreateSandboxOptions = ports.CreateSandboxOptions

Types: the DTOs that cross the ports.

type DeleteThreadResult

type DeleteThreadResult = ports.DeleteThreadResult

Ports: the interfaces users implement.

type EnqueueOptions

type EnqueueOptions = ports.EnqueueOptions

Ports: the interfaces users implement.

type EventBus

type EventBus = ports.EventBus

Ports: the interfaces users implement.

type EventPublisher

type EventPublisher = core.EventPublisher

Core: behaviors, all ports-only.

type EventStore

type EventStore = ports.EventStore

Ports: the interfaces users implement.

type EventStream

type EventStream = core.EventStream

Core: behaviors, all ports-only.

type EventsAPI

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

EventsAPI replays and tails a thread (§2.2).

func (*EventsAPI) Follow

func (e *EventsAPI) Follow(ctx context.Context, threadID string, opts FollowStateOptions) (*core.FrameStream, error)

Follow is a thread live, as one sequence of frames (§2.2): its record entries and notices, and its run streams — the stream the cursor names read on from its offset, the next segment's from its RUN_STARTED, and one SNAPSHOT frame when the stream the client was reading is gone. Cancel ctx, or the follow outlives the client.

func (*EventsAPI) FollowRecord added in v0.4.0

func (e *EventsAPI) FollowRecord(ctx context.Context, threadID string, opts FollowStateOptions) (*EventStream, error)

FollowRecord is the thread record and its notices alone, as before run streams: no stream frames.

func (*EventsAPI) PublishEvent

func (e *EventsAPI) PublishEvent(ctx context.Context, threadID, typ string, payload any, opts PublishStateOptions) (AgentEvent, error)

PublishEvent publishes an event of your own on a thread, from anywhere on the server: a webhook, a cron job, a route. Tools get the same thing bound to their thread through ToolContext.PublishEvent. Live only by default; Durable also keeps it in the thread record. Platform event types are refused.

func (*EventsAPI) SSE

func (e *EventsAPI) SSE(ctx context.Context, threadID string, opts SSEStateOptions) (*core.FollowSSE, error)

SSE is Follow, encoded as Server-Sent Events: each frame that moves the cursor carries it as its id:. Serve it with ServeHTTP or WriteTo.

func (*EventsAPI) Since

func (e *EventsAPI) Since(ctx context.Context, threadID string, sinceSeq int64, state AgentRunState) ([]AgentEvent, error)

Since is the raw replay: every event after the cursor.

func (*EventsAPI) Subscribe

func (e *EventsAPI) Subscribe(ctx context.Context, threadID string, handler func(AgentEvent)) (func() error, error)

Subscribe is the raw tail. Returns an unsubscribe function. A bus that reads storage itself (the Postgres bus, after a reconnect) takes the run state from ctx: wrap it with ContextWithRunState on scoped storage.

type ExecuteFunc

type ExecuteFunc = core.ExecuteFunc

Core: behaviors, all ports-only.

type ExecuteInput

type ExecuteInput = core.ExecuteInput

Core: behaviors, all ports-only.

type ExecuteOutcome

type ExecuteOutcome = core.ExecuteOutcome

Core: behaviors, all ports-only.

type ExecutionState

type ExecutionState = ports.ExecutionState

Types: the DTOs that cross the ports.

type FetchOptions added in v0.5.0

type FetchOptions = ports.FetchOptions

Types: the DTOs that cross the ports.

type FetchedPage added in v0.5.0

type FetchedPage = ports.FetchedPage

Types: the DTOs that cross the ports.

type Fetcher added in v0.5.0

type Fetcher = ports.Fetcher

Types: the DTOs that cross the ports.

type FileEntry added in v0.5.0

type FileEntry = ports.FileEntry

Types: the DTOs that cross the ports.

type FinalizeInput

type FinalizeInput = core.FinalizeInput

Core: behaviors, all ports-only.

type FollowFrame added in v0.4.0

type FollowFrame = core.FollowFrame

Core: behaviors, all ports-only.

type FollowOptions

type FollowOptions = core.FollowOptions

Core: behaviors, all ports-only.

type FollowSSE added in v0.4.0

type FollowSSE = core.FollowSSE

Core: behaviors, all ports-only.

type FollowStateOptions

type FollowStateOptions struct {
	// Since is a bare record seq, as older clients send; used when Cursor
	// is empty.
	FollowOptions
	// Cursor is where the client is: the SSE id it last saw
	// (Last-Event-ID), "<seq> <streamId> <offset>".
	Cursor string
	// LastMessageID is the last message the client has, so a SNAPSHOT
	// carries only newer ones.
	LastMessageID string
	State         AgentRunState
}

FollowStateOptions says where a follow starts, with the run state.

type FrameStream added in v0.4.0

type FrameStream = core.FrameStream

Core: behaviors, all ports-only.

type GenerateTextAgentSpec

type GenerateTextAgentSpec = ports.GenerateTextAgentSpec

Ports: the interfaces users implement.

type HITLAPI

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

HITLAPI answers approvals (§2.5).

func (*HITLAPI) ReclaimIfOrphaned

func (h *HITLAPI) ReclaimIfOrphaned(ctx context.Context, threadID string, state AgentRunState) (bool, error)

ReclaimIfOrphaned re-dispatches a thread whose approvals all expired.

func (*HITLAPI) Respond

func (h *HITLAPI) Respond(ctx context.Context, input RespondInput) (RespondResult, error)

Respond records an answer and resumes the run through the queue. Scoped like the run it resumes (§2.10). An orphaned wait is healed first; if reclamation claims the thread, the response is rejected as late.

type HandleJobResult

type HandleJobResult struct {
	Accepted bool   `json:"accepted"`
	Reason   string `json:"reason,omitempty"`
}

HandleJobResult says whether a job was accepted.

type HitlCtx

type HitlCtx = core.HitlCtx

Core: behaviors, all ports-only.

type HitlFrame

type HitlFrame = core.HitlFrame

Core: behaviors, all ports-only.

type HitlResponse

type HitlResponse = core.HitlResponse

Core: behaviors, all ports-only.

type JobKind added in v0.3.0

type JobKind = ports.JobKind

Ports: the interfaces users implement.

type Kv

type Kv = ports.Kv

Ports: the interfaces users implement.

type LoopInput

type LoopInput = core.LoopInput

Core: behaviors, all ports-only.

type LoopOutcome

type LoopOutcome = core.LoopOutcome

Core: behaviors, all ports-only.

type MessageDTO

type MessageDTO = ports.MessageDTO

Types: the DTOs that cross the ports.

type MessageRole

type MessageRole = ports.MessageRole

Types: the DTOs that cross the ports.

type MessageScope

type MessageScope = ports.MessageScope

Ports: the interfaces users implement.

type MessageStore

type MessageStore = ports.MessageStore

Ports: the interfaces users implement.

type NestedDescriptor

type NestedDescriptor = ports.NestedDescriptor

Types: the DTOs that cross the ports.

type NewAdminThread

type NewAdminThread = ports.NewAdminThread

Ports: the interfaces users implement.

type NewMessage

type NewMessage = ports.NewMessage

Types: the DTOs that cross the ports.

type NewRunRecord

type NewRunRecord = ports.NewRunRecord

Types: the DTOs that cross the ports.

type NewStepRecord

type NewStepRecord = ports.NewStepRecord

Ports: the interfaces users implement.

type NewUsage

type NewUsage = ports.NewUsage

Types: the DTOs that cross the ports.

type ParkInput

type ParkInput = core.ParkInput

Core: behaviors, all ports-only.

type ParkRequest added in v0.2.1

type ParkRequest = core.ParkRequest

Core: behaviors, all ports-only.

type PendingHitl

type PendingHitl = core.PendingHitl

Core: behaviors, all ports-only.

type Percentiles

type Percentiles = core.Percentiles

Core: behaviors, all ports-only.

type Policy

type Policy = core.Policy

Core: behaviors, all ports-only.

type PrepareStepFunc

type PrepareStepFunc = ports.PrepareStepFunc

Ports: the interfaces users implement.

type Pricer

type Pricer = ports.Pricer

Types: the DTOs that cross the ports.

type PricerFunc

type PricerFunc = ports.PricerFunc

Types: the DTOs that cross the ports.

type ProviderOptions

type ProviderOptions = ports.ProviderOptions

Types: the DTOs that cross the ports.

type PruneOptions added in v0.4.0

type PruneOptions = core.PruneOptions

Core: behaviors, all ports-only.

type PruneReport added in v0.4.0

type PruneReport = core.PruneReport

Core: behaviors, all ports-only.

type PublishOptions

type PublishOptions = core.PublishOptions

Core: behaviors, all ports-only.

type PublishStateOptions

type PublishStateOptions struct {
	PublishOptions
	State AgentRunState
}

PublishStateOptions carries the run state alongside the publish options.

type Queue

type Queue = ports.Queue

Ports: the interfaces users implement.

type QueueStats added in v0.3.0

type QueueStats = ports.QueueStats

Ports: the interfaces users implement.

type QueuedJob added in v0.3.0

type QueuedJob = ports.QueuedJob

Ports: the interfaces users implement.

type ReclaimReport added in v0.3.0

type ReclaimReport struct {
	// Checked is how many open run records the sweep looked at.
	Checked int `json:"checked"`
	// Redispatched is how many runs went back on the queue or were moved
	// to their record's end state.
	Redispatched int `json:"redispatched"`
	// Settled is how many ended runs had their settle run late.
	Settled int `json:"settled"`
	// Errors is how many runs the sweep could not act on.
	Errors int `json:"errors"`
}

ReclaimReport is what a stuck-run sweep did.

type RegisteredAgent

type RegisteredAgent = core.RegisteredAgent

Core: behaviors, all ports-only.

type ResolvedModel

type ResolvedModel = ports.ResolvedModel

Types: the DTOs that cross the ports.

type RespondInput

type RespondInput = ports.RespondInput

Ports: the interfaces users implement.

type RespondResult

type RespondResult = ports.RespondResult

Ports: the interfaces users implement.

type ResumeInfo

type ResumeInfo = ports.ResumeInfo

Types: the DTOs that cross the ports.

type RunBudget added in v0.3.0

type RunBudget = ports.RunBudget

Types: the DTOs that cross the ports.

type RunCommandOptions added in v0.5.0

type RunCommandOptions = ports.RunCommandOptions

Types: the DTOs that cross the ports.

type RunDetail

type RunDetail = core.RunDetail

Core: behaviors, all ports-only.

type RunFilter

type RunFilter = ports.RunFilter

Ports: the interfaces users implement.

type RunFinishInfo

type RunFinishInfo = ports.RunFinishInfo

Ports: the interfaces users implement.

type RunInput

type RunInput = ports.RunInput

Ports: the interfaces users implement.

type RunJob

type RunJob = ports.RunJob

Types: the DTOs that cross the ports.

type RunLedger

type RunLedger = core.RunLedger

Core: behaviors, all ports-only.

type RunPatch

type RunPatch = ports.RunPatch

Types: the DTOs that cross the ports.

type RunRecord

type RunRecord = ports.RunRecord

Types: the DTOs that cross the ports.

type RunResult

type RunResult = ports.RunResult

Ports: the interfaces users implement.

type RunStats

type RunStats = core.RunStats

Core: behaviors, all ports-only.

type RunStore

type RunStore = ports.RunStore

Ports: the interfaces users implement.

type RunStreams added in v0.4.0

type RunStreams = ports.RunStreams

Ports: the interfaces users implement.

type RuntimeOptions

type RuntimeOptions = ports.RuntimeOptions

Ports: the interfaces users implement.

type RuntimePorts

type RuntimePorts = ports.RuntimePorts

Ports: the interfaces users implement.

type SSEOptions

type SSEOptions = core.SSEOptions

Core: behaviors, all ports-only.

type SSEStateOptions

type SSEStateOptions struct {
	FollowStateOptions
	// RetryMs is emitted once, up front: how long a browser waits before
	// reconnecting. Zero omits it.
	RetryMs int
	// WireFormat is "agentenkit" (the default) or "ag-ui" to send AG-UI
	// events instead of our frames (opt-in).
	WireFormat string
}

SSEStateOptions is FollowStateOptions with the SSE retry hint and wire format.

type SSEStream

type SSEStream = core.SSEStream

Core: behaviors, all ports-only.

type Sandbox added in v0.5.0

type Sandbox = ports.Sandbox

Types: the DTOs that cross the ports.

type SandboxCall added in v0.10.0

type SandboxCall = ports.SandboxCall

Types: the DTOs that cross the ports.

type SandboxFileSystem added in v0.5.0

type SandboxFileSystem = ports.SandboxFileSystem

Types: the DTOs that cross the ports.

type SandboxInfo added in v0.5.0

type SandboxInfo = ports.SandboxInfo

Types: the DTOs that cross the ports.

type SandboxMetadata added in v0.5.0

type SandboxMetadata = ports.SandboxMetadata

Types: the DTOs that cross the ports.

type SandboxNetwork added in v0.5.0

type SandboxNetwork = ports.SandboxNetwork

Types: the DTOs that cross the ports.

type SandboxProvider added in v0.5.0

type SandboxProvider = ports.SandboxProvider

Types: the DTOs that cross the ports.

type SandboxResources added in v0.5.0

type SandboxResources = ports.SandboxResources

Types: the DTOs that cross the ports.

type SandboxScope added in v0.10.0

type SandboxScope = ports.SandboxScope

Types: the DTOs that cross the ports.

type Search = ports.Search

Types: the DTOs that cross the ports.

type SearchHit added in v0.5.0

type SearchHit = ports.SearchHit

Types: the DTOs that cross the ports.

type SearchOptions added in v0.5.0

type SearchOptions = ports.SearchOptions

Types: the DTOs that cross the ports.

type SearchRecency added in v0.5.0

type SearchRecency = ports.SearchRecency

Types: the DTOs that cross the ports.

type Semaphore

type Semaphore = core.Semaphore

Core: behaviors, all ports-only.

type SetOptions

type SetOptions = ports.SetOptions

Ports: the interfaces users implement.

type SettleFunc

type SettleFunc = ports.SettleFunc

Ports: the interfaces users implement.

type SnapshotStream added in v0.4.0

type SnapshotStream = ports.SnapshotStream

Ports: the interfaces users implement.

type StatsRange

type StatsRange = core.StatsRange

Core: behaviors, all ports-only.

type StepCall

type StepCall = core.StepCall

Core: behaviors, all ports-only.

type StepRecord

type StepRecord = ports.StepRecord

Ports: the interfaces users implement.

type StepResult

type StepResult = core.StepResult

Core: behaviors, all ports-only.

type StepStore

type StepStore = ports.StepStore

Ports: the interfaces users implement.

type StepToolCall

type StepToolCall = ports.StepToolCall

Ports: the interfaces users implement.

type StopOptions added in v0.2.3

type StopOptions = core.StopOptions

Core: behaviors, all ports-only.

type StopResult

type StopResult = ports.StopResult

Ports: the interfaces users implement.

type Storage

type Storage = ports.Storage

Ports: the interfaces users implement.

type StorageContext

type StorageContext = ports.StorageContext

Ports: the interfaces users implement.

type StreamEnd added in v0.4.0

type StreamEnd = ports.StreamEnd

Ports: the interfaces users implement.

type StreamEvent added in v0.4.0

type StreamEvent = ports.StreamEvent

Ports: the interfaces users implement.

type StreamItem added in v0.4.0

type StreamItem = ports.StreamItem

Ports: the interfaces users implement.

type StreamMeta added in v0.4.0

type StreamMeta = ports.StreamMeta

Ports: the interfaces users implement.

type StreamTextAgentSpec

type StreamTextAgentSpec = ports.StreamTextAgentSpec

Ports: the interfaces users implement.

type StreamsAPI added in v0.4.0

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

StreamsAPI reads run streams by id, for a caller that only cares about one run.

func (*StreamsAPI) Read added in v0.4.0

func (s *StreamsAPI) Read(ctx context.Context, streamID, after string) iter.Seq2[ports.StreamItem, error]

Read yields a run stream's items after `after`, live until it closes. It yields ErrStreamGone once the stream is past its grace window.

func (*StreamsAPI) Snapshot added in v0.4.0

func (s *StreamsAPI) Snapshot(ctx context.Context, streamID, after string) (*ports.StreamSnapshot, error)

Snapshot is a run stream as it stands now; nil when it is gone.

type SubagentCtx

type SubagentCtx = core.SubagentCtx

Core: behaviors, all ports-only.

type SubagentProfile

type SubagentProfile = ports.SubagentProfile

Ports: the interfaces users implement.

type SubagentsConfig

type SubagentsConfig = ports.SubagentsConfig

Ports: the interfaces users implement.

type SystemFunc

type SystemFunc = ports.SystemFunc

Ports: the interfaces users implement.

type TextEditorOptions added in v0.5.0

type TextEditorOptions = core.TextEditorOptions

Core: behaviors, all ports-only.

type ThreadCursor added in v0.4.0

type ThreadCursor = core.ThreadCursor

Core: behaviors, all ports-only.

type ThreadDTO

type ThreadDTO = ports.ThreadDTO

Types: the DTOs that cross the ports.

type ThreadDetail

type ThreadDetail = core.ThreadDetail

Core: behaviors, all ports-only.

type ThreadInit

type ThreadInit = ports.ThreadInit

Ports: the interfaces users implement.

type ThreadSandbox added in v0.5.0

type ThreadSandbox = core.ThreadSandbox

Core: behaviors, all ports-only.

type ThreadSnapshot

type ThreadSnapshot = ports.ThreadSnapshot

Ports: the interfaces users implement.

type ThreadStart

type ThreadStart = ports.ThreadStart

Ports: the interfaces users implement.

type ThreadStore

type ThreadStore = ports.ThreadStore

Ports: the interfaces users implement.

type ThreadSummary

type ThreadSummary = core.ThreadSummary

Core: behaviors, all ports-only.

type ThreadUsage

type ThreadUsage = ports.ThreadUsage

Ports: the interfaces users implement.

type TokenAttribution

type TokenAttribution = core.TokenAttribution

Core: behaviors, all ports-only.

type Tool

type Tool = ports.Tool

Types: the DTOs that cross the ports.

func AgentTool

func AgentTool[In any](name, description string, execute func(ctx context.Context, input In, tc ToolContext) (string, error)) Tool

AgentTool is goai.NewTool with the platform's ToolContext handed to the handler: the run state (§2.10) and PublishEvent.

type ToolContext

type ToolContext = core.ToolContext

Core: behaviors, all ports-only.

type ToolRun added in v0.5.0

type ToolRun = core.ToolRun

Core: behaviors, all ports-only.

type UsageFilter

type UsageFilter = ports.UsageFilter

Types: the DTOs that cross the ports.

type UsageKind

type UsageKind = ports.UsageKind

Types: the DTOs that cross the ports.

type UsageLine

type UsageLine = ports.UsageLine

Types: the DTOs that cross the ports.

type UsageOutcome

type UsageOutcome = ports.UsageOutcome

Types: the DTOs that cross the ports.

type UsageStore

type UsageStore = ports.UsageStore

Ports: the interfaces users implement.

type UsageTotals

type UsageTotals = ports.UsageTotals

Types: the DTOs that cross the ports.

type WebFetchOptions added in v0.5.0

type WebFetchOptions = core.WebFetchOptions

Core: behaviors, all ports-only.

type WebSearchOptions added in v0.5.0

type WebSearchOptions = core.WebSearchOptions

Core: behaviors, all ports-only.

type WorkdirRestorer added in v0.10.0

type WorkdirRestorer = ports.WorkdirRestorer

Types: the DTOs that cross the ports.

type WorkerAPI

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

WorkerAPI is the queue dispatch side of the platform (§2.8).

func (*WorkerAPI) HandleDeadJob added in v0.3.0

func (w *WorkerAPI) HandleDeadJob(ctx context.Context, job RunJob, attempts int, cause error)

HandleDeadJob is what a queue calls when it gives up on a job (§2.8): the run behind it is failed with the reason, so its thread does not read QUEUED or RUNNING for ever and its spend is settled. A job whose run has already moved on (a newer run, a stop, a finished run) is left alone.

func (*WorkerAPI) HandleJob

func (w *WorkerAPI) HandleJob(ctx context.Context, job RunJob) (HandleJobResult, error)

HandleJob resolves the handle, applies the failure policy, and is idempotent under at-least-once delivery. The HTTP layer only verifies signatures, parses JSON, and calls this.

func (*WorkerAPI) Handler

func (w *WorkerAPI) Handler() func(ctx context.Context, job RunJob) error

Handler adapts the worker to a queue's handler signature. A refused job is logged with its reason before the error goes back to the queue.

Directories

Path Synopsis
adapters
brave
Package brave is web search on the Brave Search API: its own index of the web, $5 per 1,000 searches with $5 free each month (checked 2026-09-26).
Package brave is web search on the Brave Search API: its own index of the web, $5 per 1,000 searches with $5 free each month (checked 2026-09-26).
clevixflow
Package clevixflow holds the Queue adapter over Clevix Flow, and the Flow function that runs its jobs.
Package clevixflow holds the Queue adapter over Clevix Flow, and the Flow function that runs its jobs.
docker
Package docker runs sandboxes as Docker containers on the machine the docker CLI talks to: for self-hosting.
Package docker runs sandboxes as Docker containers on the machine the docker CLI talks to: for self-hosting.
e2b
Package e2b runs sandboxes on E2B: each is a small VM that starts in under a second.
Package e2b runs sandboxes on E2B: each is a small VM that starts in under a second.
inline
Package inline holds an in-process queue that actually dispatches (§2.8).
Package inline holds an in-process queue that actually dispatches (§2.8).
internal/redisstreams
Package redisstreams is RunStreams over Redis Streams, shared by the Redis and Upstash adapters.
Package redisstreams is RunStreams over Redis Streams, shared by the Redis and Upstash adapters.
internal/sandboxsh
Package sandboxsh holds what the sandbox adapters share.
Package sandboxsh holds what the sandbox adapters share.
internal/sqlstreams
Package sqlstreams is RunStreams over two SQL tables, shared by the SQLite and Postgres adapters.
Package sqlstreams is RunStreams over two SQL tables, shared by the SQLite and Postgres adapters.
internal/websearch
Package websearch holds what the search adapters share: the domain lists.
Package websearch holds what the search adapters share: the domain lists.
jina
Package jina is web search and page reading through Jina AI (checked 2026-09-26): s.jina.ai for search, about $0.50 per 1,000 searches ($0.05 per million tokens, at least 10,000 a search, 100 requests a minute), and r.jina.ai for pages built with JavaScript, PDFs and sites that block plain fetches, about $0.25–$0.50 per 1,000 pages.
Package jina is web search and page reading through Jina AI (checked 2026-09-26): s.jina.ai for search, about $0.50 per 1,000 searches ($0.05 per million tokens, at least 10,000 a search, 100 requests a minute), and r.jina.ai for pages built with JavaScript, PDFs and sites that block plain fetches, about $0.25–$0.50 per 1,000 pages.
localsandbox
Package localsandbox is a sandbox that is only a folder on this machine: for development, where you want the sandbox tools without Docker or an account.
Package localsandbox is a sandbox that is only a folder on this machine: for development, where you want the sandbox tools without Docker or an account.
mcp
Package mcp connects an agent to MCP servers.
Package mcp connects an agent to MCP servers.
memory
Package memory holds the in-memory adapters: a full implementation used by the test suite, and a template for custom adapters.
Package memory holds the in-memory adapters: a full implementation used by the test suite, and a template for custom adapters.
pagereader
Package pagereader is our own page reader for the web_fetch built-in tool: it fetches the page itself and turns it into markdown, with no service in between and nothing to pay.
Package pagereader is our own page reader for the web_fetch built-in tool: it fetches the page itself and turns it into markdown, with no service in between and nothing to pay.
postgres
Package postgres holds a complete Storage over Postgres (§3.2): the production storage adapter, the Go stand-in for the TypeScript package's PrismaStorage.
Package postgres holds a complete Storage over Postgres (§3.2): the production storage adapter, the Go stand-in for the TypeScript package's PrismaStorage.
postgres/pgxlisten
Package pgxlisten is the postgres bus's Listener over pgx v5: one dedicated connection that LISTENs and hands every notification over.
Package pgxlisten is the postgres bus's Listener over pgx v5: one dedicated connection that LISTENs and hands every notification over.
qstash
Package qstash holds the reference Queue adapter over Upstash QStash HTTP queues, talking to the REST API directly.
Package qstash holds the reference Queue adapter over Upstash QStash HTTP queues, talking to the REST API directly.
redis
Package redis holds the reference Kv and EventBus adapters over Redis (github.com/redis/go-redis/v9).
Package redis holds the reference Kv and EventBus adapters over Redis (github.com/redis/go-redis/v9).
sqlite
Package sqlite holds a complete Storage over SQLite (§3.2): every table the platform needs, created on construction.
Package sqlite holds a complete Storage over SQLite (§3.2): every table the platform needs, created on construction.
upstash
Package upstash holds the reference Kv and EventBus adapters over the Upstash Redis REST API.
Package upstash holds the reference Kv and EventBus adapters over the Upstash Redis REST API.
Package admin picks the operational store SetupAgentCore uses when none is configured (§2.9).
Package admin picks the operational store SetupAgentCore uses when none is configured (§2.9).
memory
Package memory holds operational history in memory: tests, and a template.
Package memory holds operational history in memory: tests, and a template.
migrate
Package migrate applies the platform's OWN schema to the admin store (§2.9), from numbered .sql files.
Package migrate applies the platform's OWN schema to the admin store (§2.9), from numbered .sql files.
postgres
Package postgres holds operational history in Postgres (§2.9): the production store, reached through AGENTIC_KIT_ADMIN_DATABASE_URL.
Package postgres holds operational history in Postgres (§2.9): the production store, reached through AGENTIC_KIT_ADMIN_DATABASE_URL.
sqlite
Package sqlite holds operational history in SQLite (§2.9): the development store.
Package sqlite holds operational history in SQLite (§2.9): the development store.
Package core holds the platform's behaviors.
Package core holds the platform's behaviors.
Package ports holds the contract between the platform and the code around it: the four ports a caller implements (Storage, EventBus, Queue, Kv), the platform's own AdminStore, and every DTO that crosses those boundaries.
Package ports holds the contract between the platform and the code around it: the four ports a caller implements (Storage, EventBus, Queue, Kv), the platform's own AdminStore, and every DTO that crosses those boundaries.
Package pricing holds the pricers that ship with the platform (§4).
Package pricing holds the pricers that ship with the platform (§4).

Jump to

Keyboard shortcuts

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