agentenkit

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 7 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.25+. 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 four 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) // the seq counters live here: keep them as durable as the log
	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
		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),
	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,
})

Or one Postgres for all four, 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{})
rt, err := agentenkit.SetupAgentCore(ctx, agentenkit.RuntimeOptions{Storage: storage, Kv: kv, Bus: bus, Queue: queue, 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. Both are in adapters/postgres; the listener is adapters/postgres/pgxlisten.

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)
events, _ := rt.Events.Follow(ctx, threadID, agentenkit.FollowStateOptions{})   // or range events.Events()
rt.Events.Since(ctx, threadID, lastSeq, nil)                               // raw replay
rt.Worker.HandleJob(ctx, job)                                              // queue consumer
rt.Events.PublishEvent(ctx, threadID, "MY_EVENT", payload, agentenkit.PublishStateOptions{}) // your own event

An SSE route is a few lines:

http.HandleFunc("/api/agent/events", func(w http.ResponseWriter, r *http.Request) {
	stream, err := rt.Events.SSE(r.Context(), r.URL.Query().Get("threadId"), agentenkit.SSEStateOptions{
		SSEOptions: agentenkit.SSEOptions{FollowOptions: agentenkit.FollowOptions{Since: lastEventID(r)}},
	})
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	stream.ServeHTTP(w, r) // returns when the client hangs up, and unsubscribes
})

The CHUNK and SUBAGENT_CHUNK payloads use the same part shapes the TypeScript package publishes, so the use-agentenkit React hook works against either runtime.

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.
		_, _ = tc.PublishEvent(ctx, "LOOKUP", map[string]any{"id": in.InvoiceID}, agentenkit.PublishOptions{Notice: true})
		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.

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 on a cancelled ctx. Idempotent on RunID, please.
	OnSettle: func(ctx context.Context, info agentenkit.RunFinishInfo) error {
		return repo.Commit(context.WithoutCancel(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 / events / 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/memory
Queue durable run dispatch (at-least-once) adapters/qstash, adapters/inline (dev), adapters/memory
Kv hot state cache, HITL handoff keys, seq/attempt counters, run locks adapters/redis, adapters/upstash, adapters/sqlite, adapters/memory

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, timeline, 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/prisma.ts adapters/postgres/postgres.go
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.
  • A mixed step keeps its results. When one tool parks and another runs in the same step, the executed result is persisted. The TypeScript package drops the whole message.
  • 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

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, 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

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

	StateIdle            = ports.StateIdle
	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
)
View Source
const (
	OutcomeExecuted     = core.OutcomeExecuted
	OutcomeLockConflict = core.OutcomeLockConflict
	OutcomeStale        = core.OutcomeStale

	HITLParked          = core.HITLParked
	ReasonApproval      = core.ReasonApproval
	HITLTTL             = core.HITLTTL
	ContextTokenCeiling = core.ContextTokenCeiling
	ContextSummaryType  = core.ContextSummaryType
	DefaultModel        = core.DefaultModel
)

Variables

View Source
var (
	// 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
	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
	StateKey         = core.StateKey
	RunLockKey       = core.RunLockKey
	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
	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
	ApprovalFromContext  = core.ApprovalFromContext
	PublisherFromContext = core.PublisherFromContext
	ReservedEventTypes   = core.ReservedEventTypes
	SetThreadState       = core.SetThreadState
	Summarise            = core.Summarise
)

Functions

func Ptr

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

Ptr is a small helper for building a RunPatch.

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.

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.

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
	// 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) Close

func (c *AgentCore) Close() error

Close releases the admin store.

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 events. 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) 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 Attachment

type Attachment = ports.Attachment

Ports: the interfaces users implement.

type BillingCheck

type BillingCheck = ports.BillingCheck

Types: the DTOs that cross the ports.

type BoundStorage

type BoundStorage = ports.BoundStorage

Ports: the interfaces users implement.

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 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) (*EventStream, error)

Follow is replay then live, as one sequence, with the cursor discipline already applied (§2.2). Cancel ctx, or the subscription outlives the client.

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. Durable by default; Notice sends a bus-only notice. Platform event types are refused.

func (*EventsAPI) SSE

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

SSE is Follow, encoded as Server-Sent Events. 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.

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 FinalizeInput

type FinalizeInput = core.FinalizeInput

Core: behaviors, all ports-only.

type FollowOptions

type FollowOptions = core.FollowOptions

Core: behaviors, all ports-only.

type FollowStateOptions

type FollowStateOptions struct {
	FollowOptions
	State AgentRunState
}

FollowStateOptions carries the run state alongside the follow options.

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 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 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 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 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 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 {
	SSEOptions
	State AgentRunState
}

SSEStateOptions carries the run state alongside the SSE options.

type SSEStream

type SSEStream = core.SSEStream

Core: behaviors, all ports-only.

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 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 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 StreamTextAgentSpec

type StreamTextAgentSpec = ports.StreamTextAgentSpec

Ports: the interfaces users implement.

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 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 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 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 WorkerAPI

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

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

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 an inline queue's handler signature.

Directories

Path Synopsis
adapters
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).
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.
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