tacklr

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

README

Tacklr

CI Coverage Go Reference Go Version License

Tacklr is an opinionated Go SDK for building agent harnesses. It is a framework: it says how a turn should run, how tools execute, how context is structured around a plan, and how a session survives interrupts and restarts.

You bring a model, tools, and the storage you already use. Tacklr sits in the middle of that stack and keeps the run deterministic from the harness’s point of view — even though the model is not.

go get github.com/ryanaldo34/tacklr

Why it exists

Work spans many model calls, tools hit real systems, and the window fills with things that no longer matter. Tacklr is built around four ideas that show up in every design choice.

Context is structured around the current work. The harness runs planning cycles (Adaptive Case Management): the agent writes a plan, works a to-do, and on complete_todo the window is rebuilt as a hand-off for what comes next. Unused history does not stay in the prompt just because it happened earlier. Specialists are the same idea at a larger grain — a nested session that returns only what the parent asked for.

The agent’s world is bounded. A virtual filesystem gives one path API over the mounts you attach: local disk, S3, Azure Blob, Google Drive and Docs, Microsoft Graph, and knowledge objects. The agent sees /workspace/work/notes.md, not a host path or a bucket key. Credentials live on the turn (Prompt.Auth / Resume.Auth), not in checkpoints or Temporal event history.

Sessions are meant to live in the cloud. Hosts call session.Runtime. The Temporal backend is session/temporal. Human-in-the-loop parks a session until Resume. JSON-RPC protocols (ACP is the native one) map to that Runtime; autonomous hosts call it directly.

Knowledge is queried, not stuffed into the window. The optional brain is a host-owned store: first-class objects as Markdown files, hybrid search, an optional graph for relationships, and namespaces so retrieval stays scoped. The agent asks when it needs a fact.

Those four are the ethos. If a change fights them, it does not belong.


A turn

One Prompt or Resume is a turn: infer, run tools, maybe park for the user, then complete, error, or cancel.

create_plan → tools → complete_todo → handoff → next work

A model round may emit several tool calls. The harness does not infer again until every call in that batch has a result, or a call is parked. Planning builtins (create_plan, list_plan, edit_plan, complete_todo) are harness-owned. Your tools cannot rewrite the plan store.


Get started

This is a host: a model, a brain, a /workspace tree, a Temporal runtime, and ACP on HTTP. The protocol consumes tacklr.StreamEvent from Runtime.

Session data is three frozen planes. Do not mix them:

Plane You pass Holds
SnapshotStore Config.Snapshots (zero: memory, kept on the runtime) Window, plan, parked interrupt, userState, VFS recipes, session identity
Wait loop temporal.Open then StartWorker Scheduler: leftover tool calls, child workflows, Status
SecretStorage temporal.Config.Secrets (zero: memory, kept on the runtime) VFS tokens. Not in snapshots. Not in Temporal history

Temporal puts work-item tokens in Secrets before signaling. Prompt.Auth / Resume.Auth is how the host hands tokens in.

package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"go.temporal.io/sdk/client"

	"github.com/ryanaldo34/tacklr"
	"github.com/ryanaldo34/tacklr/brain"
	"github.com/ryanaldo34/tacklr/brain/helixgraph"
	"github.com/ryanaldo34/tacklr/brain/postgres"
	"github.com/ryanaldo34/tacklr/session"
	"github.com/ryanaldo34/tacklr/session/temporal"
	"github.com/ryanaldo34/tacklr/web"
	"github.com/ryanaldo34/tacklr/openai"
	"github.com/ryanaldo34/tacklr/server"
	"github.com/ryanaldo34/tacklr/server/acp"
	"github.com/ryanaldo34/tacklr/telemetry"
	"github.com/ryanaldo34/tacklr/vfs"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	shutdown, err := telemetry.Init(ctx, telemetry.Config{
		ServiceName:  "tacklr-host",
		OTLPEndpoint: os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"),
		Insecure:     true,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = shutdown(context.Background()) }()

	model := openai.NewOpenAIInferenceStrategy(&http.Client{Timeout: 2 * time.Minute})
	model.WithURL(os.Getenv("OPENAI_BASE_URL")).
		WithApiKey(os.Getenv("OPENAI_API_KEY")).
		WithModel(os.Getenv("OPENAI_MODEL"))

	cfg, err := postgres.PoolConfig(os.Getenv("DATABASE_URL"), "")
	if err != nil {
		log.Fatal(err)
	}
	pool, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()
	kinds := []brain.KindSpec{
		{Kind: "Discovery", Description: "Research finding", IsParent: true},
		{Kind: "Fact", Description: "Verified fact", IsParent: true},
		{Kind: "Memory", Description: "Durable memory", IsParent: true},
	}
	store, err := postgres.New(pool)
	if err != nil {
		log.Fatal(err)
	}
	if err := store.Setup(ctx, kinds...); err != nil {
		log.Fatal(err)
	}
	g, err := helixgraph.New(os.Getenv("HELIX_URL"))
	if err != nil {
		log.Fatal(err)
	}
	if err := g.Bootstrap(ctx, false); err != nil {
		log.Fatal(err)
	}
	eng, err := brain.NewEngine(store, brain.WithGraph(g), brain.WithLexicalOnly())
	if err != nil {
		log.Fatal(err)
	}
	if err := eng.LoadKindsFromStore(ctx); err != nil {
		log.Fatal(err)
	}
	ns, err := brain.ParseNamespace("org", "acme")
	if err != nil {
		log.Fatal(err)
	}

	jail := filepath.Join(os.TempDir(), "tacklr-workspace")
	if err := os.MkdirAll(filepath.Join(jail, "skills"), 0o750); err != nil {
		log.Fatal(err)
	}
	client := web.NewExa(os.Getenv("EXA_API_KEY"))

	agent := tacklr.AgentOptions{
		Name:            "Agent",
		MaxWindowSize:   8192,
		SystemPrompt:    "You are a concise assistant.",
		Model:           model,
		Brain:           eng,
		SearchNamespace: ns,
		BrainWriteKinds: brain.WriteKinds{
			Discovery: "Discovery",
			Fact:      "Fact",
			Memory:    "Memory",
		},
		Tools: []*tacklr.Tool{
			web.WebSearch(client),
			web.WebFetch(client),
		},
		OpenVFS:    openVFS(jail),
		SkillsPath: "/workspace/skills",
	}

	c, err := temporal.Dial(client.Options{HostPort: os.Getenv("TEMPORAL_ADDRESS")})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	cfg := temporal.Config{
		Agent: agent,
	}
	rt := temporal.Open(c, cfg)
	w := rt.StartWorker()
	if err := w.Start(); err != nil {
		log.Fatal(err)
	}
	defer w.Stop()
	srv := server.NewServer(rt, agent, acp.New(nil)).AllowAnonymousNetwork()
	log.Printf("ACP on http://127.0.0.1:8080/acp")
	if err := srv.ServeHTTP(ctx, "127.0.0.1:8080"); err != nil && !errors.Is(err, context.Canceled) {
		log.Fatal(err)
	}
}

func openVFS(jail string) vfs.OpenVFS {
	return func(ctx context.Context, sessionID string, req vfs.Request) (*vfs.MountSession, error) {
		members := []vfs.Member{
			vfs.At("work", vfs.Local(jail)),
		}
		if b, ok := vfs.BindingByName(req.Bindings, "drive"); ok && strings.TrimSpace(b.Auth.Token) != "" {
			h := vfs.NewTokenHolder(b.Auth)
			api, err := vfs.NewGoogleDrive(ctx, h)
			if err != nil {
				return nil, err
			}
			members = append(members, vfs.At("drive", vfs.Drive(api)))
		}
		if b, ok := vfs.BindingByName(req.Bindings, "sharepoint"); ok && strings.TrimSpace(b.Auth.Token) != "" {
			h := vfs.NewTokenHolder(b.Auth)
			api, err := vfs.NewGraph(h, "", nil)
			if err != nil {
				return nil, err
			}
			members = append(members, vfs.At("sharepoint", vfs.Graph(api, h, b.Params[vfs.ParamAccount])))
		}
		return vfs.Tree(members...)(ctx, sessionID, req)
	}
}

Pass an external snapshot store and secret store when more than one process must share them. Open keeps those pointers, and StartWorker uses the same ones:

import (
	"go.temporal.io/sdk/client"

	tacklrtemporal "github.com/ryanaldo34/tacklr/session/temporal"
)

c, err := tacklrtemporal.Dial(client.Options{HostPort: os.Getenv("TEMPORAL_HOST")})
if err != nil {
	log.Fatal(err)
}
cfg := tacklrtemporal.Config{
	Agent:     agent,
	Snapshots: snaps,   // production: shared store
	Secrets:   secrets, // production: Redis / Postgres / Vault
}
rt := tacklrtemporal.Open(c, cfg)
w := rt.StartWorker()

ACP _tacklr/vfs/bind still maps onto Prompt.Auth. The worker never sees those tokens in workflow history.

Importing tacklr registers built-in interrupts, Word/Excel codecs, and the durable driver adapter. The agent sees /workspace/work. Skills load from SkillsPath and reach the model only through read_skill. Knowledge records are brain rows, found with search and written with save_*. A Drive or SharePoint bind on the prompt adds /workspace/drive or /workspace/sharepoint for that turn. Tests point the Drive/Graph SDKs at httptest servers with documented REST shapes (NewGoogleDriveHTTP, NewGraph + vfs/testhttp). WithLexicalOnly is the explicit no-embedder choice; production hosts pass brain.WithEmbedder.

telemetry.Init installs the process-wide OpenTelemetry providers. With OTLPEndpoint (or OTEL_EXPORTER_OTLP_ENDPOINT) it exports traces, metrics, and logs over OTLP (gRPC by default, or HTTP). Without an endpoint the tracer does not export. session/temporal.Dial replaces that tracer with a replay-safe one that keeps the same export configuration, so workflow replay does not leak spans. Each Prompt or Resume is one tacklr.turn span; inference, tools, hand-off, and compress nest under it. postgres.Store Query/Exec spans join that same trace. Hosts must not start tacklr.* spans themselves. Metrics include turn duration and count, tool calls, model tokens, interrupts, hand-offs, compress, sessions, and checkpoints. Call Init before Dial when traces should be exported. Details: telemetry.

Tools

Tools are ordinary Go functions. Give a tool a client by closing over it in the constructor. That is the dependency injection. Tests pass a fake into the same constructor.

HarnessRuntime is park, progress, children, and session key-values (StateGet). Put facts like the current user on CreateSession.State (also Prompt.State / Resume.State). Close over clients in the constructor: NewSearchRecordsTool(liveStore) in production, NewSearchRecordsTool(fakeStore) in tests. Construct with NewTool(ToolConfig{...}). After construction, read metadata through getters (Name(), Access(), and the rest).

Built-in tools that need a client use the same pattern. You construct them and put them on AgentOptions.Tools:

You construct Closed into
email.ReadInbox / email.SendEmail read_inbox, send_email
web.WebSearch / web.WebFetch web_search, web_fetch
MountSession read, write, write_document, write_spreadsheet, run_command
SkillsPath read_skill
Brain knowledge tools (search, save_*, …)
Brain + workspace + search namespace index_file, unindex

Put optional tools on AgentOptions.Tools. Swap the fake the same way: Tools: []*tacklr.Tool{email.ReadInbox(fakeMail)}, Brain: testEngine, a temp MountSession. Details: docs/tools.md.

Session data

session.Runtime is the host API (the snippets above). TurnManager is the per-turn infer/tools/checkpoint object the runtime constructs; hosts do not call it.

Plane Canonical store
Conversation, plan, parked interrupt, userState, VFS recipes, identity session.SnapshotStore (tacklr.SessionCheckpoint plus Snapshot.Mounts)
Leftover unstarted tool calls, MCP config, child futures, Status Session wait loop (Temporal workflow replay)
VFS tokens session.SecretStorage

CreateSession.State / Prompt.State / Resume.State merge into checkpoint userState. They are not a second Temporal copy of that map. File bytes are never snapshotted; VFS writes persist as they happen. Close deletes the snapshot and the secret bag. Details: docs/session.md.

Specialists

Register nested agents on AgentOptions.Specialists. Tools start work through HarnessRuntime: RunSpecialist (in line, tool result) or Schedule / Jobs / CancelJob (async job, later inbox message). The stock tools spawn_specialist, list_children, and cancel_child call those methods; host tools can too. A specialist is a nested session with the parent’s MCP Durable topology and mount recipes, overlaid with the specialist’s model, tools, and instructions. Named workers register on Runtime Config.Jobs. Tokens come from SecretStorage (child, then parent). spawn_specialist block=false schedules a job; block=true (default) runs the specialist in line. Parent park does not stop children. Cancel (including the original Prompt context) and Close do.


What you can wire in

Piece What it does Where to read
Planning create_plan, todos, hand-off on complete this README · tacklr
Interrupts Park a tool, collect structured input, Resume docs/session.md
Specialists Nested sessions (spawn_specialist and children) docs/session.md
VFS Mounts and content IR; file tools read / write / run_command docs/vfs.md
Brain Host-owned knowledge: Engrams, search, optional graph docs/knowledge.md
Host tools Your functions; close over clients in the constructor docs/tools.md
MCP External tool servers mcp
Skills SKILL.md catalogs from SkillsPath; the model reads them only through read_skill skills
Model tacklr.InferenceStrategy; OpenAI-compatible client is openai.NewOpenAIInferenceStrategy openai
Web web_search and web_fetch via web.WebSearch / web.WebFetch web
Email read_inbox and permission-gated send_email via email.ReadInbox / email.SendEmail email
Server Protocol over Runtime; ACP is the native option server
Telemetry telemetry.Init: OTLP traces/metrics/logs; one tacklr.turn span per prompt or resume telemetry

When VFS is wired, the harness injects file tools over virtual paths only. run_command requires permission by default. Live names and grep go through run_command (ls / fd / rg). With Brain and a search namespace, knowledge tools call the engine. Details: docs/vfs.md and docs/knowledge.md.


Documentation

Doc What it covers
docs/session.md session.Runtime, Temporal backend, HITL, children, auth
docs/tools.md Tool clients: constructor closures and tests
docs/vfs.md Mounts, content IR, providers, FUSE
docs/knowledge.md Brain: Engrams, search, graph, tools
docs/fuse-vfs-run-command.md How run_command and the FUSE projection fit
pkg.go.dev/tacklr Harness, tools, types
AGENTS.md Goals, coding standards, how we test

Packages

Package Role
tacklr Harness, tools, plan loop, specialists, messages, checkpoints
vfs Virtual filesystem, mounts, backend constructors
vfsindex Optional mount → brain ingest
brain Knowledge engine, store/graph interfaces, in-memory backends
brain/postgres Optional Postgres brain.Store
brain/helixgraph Optional Helix graph adapter
brain Knowledge records, hybrid search, and the graph
openai OpenAI-compatible model client
email Optional inbox and send tools. email/gmail and email/outlook are the adapters
web Optional web search and fetch. Exa is the current client
server Protocol host over Runtime. server/acp is the ACP built-in
durable Session Runtime, SnapshotStore, SecretStorage
interrupt Pause / resume types
mcp MCP config types
skills Skill loading from SkillsPath
telemetry OpenTelemetry helpers

Contributing

This repo is a Go module. It requires Go 1.27. Start with AGENTS.md for goals and coding standards. Short version:

  • Prefer the standard library. Third-party packages are a last resort.
  • Prefer small, explicit pieces over hidden abstractions.
  • Tests are outcome-oriented integration tests. Assert what should happen, not that a private helper ran. Avoid duplicate coverage of the same return path.
make test         # includes brain Postgres + Helix (Docker)
make vet
make lint

Where to look:

Area Start here
Turn loop, tools, plan agent.go, agent_run.go, tools.go
Messages / checkpoints message.go, checkpoint.go
Specialists / children subagents.go, session/temporal/child.go
Runtime session/runtime.go, docs/session.md
VFS vfs/, docs/vfs.md
Model client openai/ (tacklr.InferenceStrategy)
Knowledge brain/, brain/postgres/, brain/helixgraph/, docs/knowledge.md
ACP / protocols server/, server/acp/

Issues and pull requests are welcome. Match the surrounding code: gofmt, go vet, golangci-lint.


License

Apache 2.0. See LICENSE.

Documentation

Overview

Package tacklr is the stable harness SDK facade.

The root package owns agent construction, turn execution, tool registration, conversation types (Message, StreamEvent, Todo), and the session checkpoint blob. Domain packages:

  • brain owns knowledge retrieval. brain/postgres, brain/helixgraph, and brain/postgres and brain/helixgraph are the store and graph adapters.
  • vfs owns virtual filesystem mounts and the backend constructors.
  • openai, email, and web are optional host tools and the model client.
  • mcp owns MCP connection configuration.

Process-wide registrations (built-in interrupts, common VFS codecs, the session driver adapter) run in this package's init. Hosts import tacklr once; they do not register those defaults themselves.

New APIs should use the canonical domain packages and must not add server transport, wire protocol, persistence backend, or provider-client details here.

Index

Constants

View Source
const (
	KindEpisode      = "Episode"
	KindEpisodeChunk = "EpisodeChunk"
)
View Source
const (
	ListChildrenName = "list_children"
	CancelChildName  = "cancel_child"
)

ListChildrenName and CancelChildName are built-ins on HarnessRuntime.Jobs / CancelJob.

View Source
const (
	PermissionAllowOnce    = "allow_once"
	PermissionAllowAlways  = "allow_always"
	PermissionRejectOnce   = "reject_once"
	PermissionRejectAlways = "reject_always"
)

ACP PermissionOptionKind values.

View Source
const (
	ContentTypeOutputText = "output_text"
	ContentTypeInputText  = "input_text"
	ContentTypeInputImage = "input_image"
	ContentTypeInputFile  = "input_file"
	ContentTypeRefusal    = "refusal"
)
View Source
const (
	JobRunning     = "running"
	JobCompleted   = "completed"
	JobFailed      = "failed"
	ChildRunning   = JobRunning
	ChildCompleted = JobCompleted
	ChildFailed    = JobFailed
)

Parent-facing job states. A specialist child waiting for input stays running.

View Source
const CancelledToolResultContent = "cancelled: user interrupted the agent"

CancelledToolResultContent is written into the context window for tool calls aborted by session cancel.

View Source
const CheckpointVersion = 2

CheckpointVersion is the current typed session checkpoint schema.

View Source
const SpawnSpecialistName = "spawn_specialist"

SpawnSpecialistName is the built-in that calls HarnessRuntime.Schedule.

View Source
const TypeAuthExpired = "auth_expired"

TypeAuthExpired parks a tool call until the host rebinds credentials on Resume.Auth.

View Source
const TypeChildWaiting = "child_waiting"

TypeChildWaiting is kept for old checkpoints. A blocking specialist now reports its child id on the tool step, and the session loop waits. The payload is forwarded to the child session; Return is a no-op.

Variables

View Source
var (
	ErrInterruptNotFound = errors.New("interrupt not found")
	ErrInvalidPayload    = errors.New("invalid payload")
)
View Source
var (
	ErrNotFound    = errors.New("not found")
	ErrInvalid     = errors.New("invalid")
	ErrFailed      = errors.New("failed")
	ErrCorrection  = errors.New("correction")
	ErrAuthExpired = errors.New("auth expired")
)

Coarse categories for errors.Is. Wrap a specific message at the call site (fmt.Errorf("tool %q: %w", name, ErrNotFound)) instead of a sentinel per situation. Named sentinels below are distinct handling branches, not children of these categories.

ErrCorrection is a model-facing tool failure: Error() is the correction the model should follow. Construct with Correction(cause, msg). Distinct from ErrFailed (harness/runtime). errors.Is matches both ErrCorrection and cause.

View Source
var (
	ErrModelRefused         = errors.New("model refused")
	ErrMaxTokens            = errors.New("max tokens reached")
	ErrMaxTurnRequests      = errors.New("max turn model requests exceeded")
	ErrModelAfterTools      = errors.New("model request failed after tools completed")
	ErrApiKeyNotSet         = errors.New("api key not set")
	ErrModelNotSet          = errors.New("model not set")
	ErrUnknownModel         = errors.New("unknown model")
	ErrToolTimeout          = errors.New("tool timed out")
	ErrToolPermissionDenied = errors.New("tool permission denied")
)
View Source
var ErrNetwork = errors.New("network")

ErrNetwork is a transport failure: the dial, the read, a timeout, or an upstream 408, 429, or 5xx. Wrap it at the call that hit the network. The durable runtime retries a wrapped network error. Any other error stops on the first attempt.

Functions

func ContextWithToolChoiceNone added in v0.3.4

func ContextWithToolChoiceNone(ctx context.Context) context.Context

ContextWithToolChoiceNone asks the provider to keep tool definitions on the wire but not call them (Responses tool_choice=none). Handoff and compress use this so the cached tools prefix matches a normal turn.

func Correction added in v0.2.0

func Correction(cause error, msg string) error

Correction wraps cause with model-facing correction text. msg is Error(); errors.Is matches ErrCorrection and cause. A nil/empty msg uses cause.Error().

func Correctionf added in v0.2.0

func Correctionf(cause error, format string, args ...any) error

Correctionf is Correction with fmt.Sprintf.

func DataURL added in v0.2.0

func DataURL(mime, data string) string

DataURL builds a data:<mime>;base64,<data> URL. data may already be a data URL.

func EpisodeKinds added in v0.3.4

func EpisodeKinds() []brain.KindSpec

EpisodeKinds are SDK-owned kinds for collapse residue. Hosts with a non-empty catalog should pass these to store.Setup / ApplyKinds (same pattern as vfsindex.MountIndexKinds).

func IsPlanDocument added in v0.3.4

func IsPlanDocument(m *Message) bool

IsPlanDocument reports the durable PROJECT PLAN developer message.

func IsTextMIME added in v0.2.0

func IsTextMIME(mime string) bool

IsTextMIME is true for empty and text/* types (always model-safe as text).

func MIMEFromDataURL added in v0.2.0

func MIMEFromDataURL(u string) string

MIMEFromDataURL extracts the MIME type from a data: URL, or empty.

func Network added in v0.4.0

func Network(err error) error

Network marks err as a transport failure. The text stays err.Error().

func NormalizeMIME added in v0.2.0

func NormalizeMIME(mime string) string

NormalizeMIME lowercases a MIME type and strips parameters (after ';').

func PipeStreamEvents added in v0.2.0

func PipeStreamEvents(emit func(StreamEvent)) (chan StreamEvent, func())

PipeStreamEvents copies channel events to emit. Durable backends adapt emit callbacks to the harness chan StreamEvent API.

func RegisterDefaults added in v0.4.0

func RegisterDefaults()

RegisterDefaults registers the built-in interrupt types. Safe to call more than once. init calls this. NewInterrupt also ensures defaults so a checkpoint can rehydrate before any tool runs.

func RegisterInterrupt

func RegisterInterrupt(factory func() Interrupt)

RegisterInterrupt registers a custom interrupt factory for session rehydrate.

func ResolveToolTitle

func ResolveToolTitle(displayName, toolName, argsJSON string) string

ResolveToolTitle fills {param} in DisplayName from top-level string args. Empty displayName → toolName. Missing/non-string args → empty slot.

func ToolChoiceNone added in v0.3.4

func ToolChoiceNone(ctx context.Context) bool

ToolChoiceNone reports whether ctx was wrapped with ContextWithToolChoiceNone.

func ToolsAsJson

func ToolsAsJson(tools []*Tool) string

ToolsAsJson serializes tool definitions for model requests. An empty catalog is "[]". Namespaced tools are "namespace__name" (OpenAI rejects '.').

func TypeToJSONSchema

func TypeToJSONSchema(v any) (map[string]any, error)

TypeToJSONSchema builds a JSON Schema for v. Prefer NewTool typed handlers for tools; this is mainly for structured model output.

func UnsupportedMIMEs

func UnsupportedMIMEs(s InferenceStrategy, mimes []string) []string

UnsupportedMIMEs returns mimes for which s.SupportsMIME is false (first-seen order).

func ValidateMessages added in v0.2.0

func ValidateMessages(messages []*Message) error

ValidateMessages validates structural invariants shared by live context and durable checkpoints. Open assistant tool calls are valid while interrupted; pairing is repaired by the harness before the next model invocation.

Types

type AbsorbResult

type AbsorbResult struct {
	// SummaryChunks are compress summaries to stream when StreamFitSummary is true.
	SummaryChunks []LLMResponseChunk
	Compressed    bool
	Summary       string
	Discarded     []*Message
}

AbsorbResult is returned by Absorb after incorporating a message.

type Action added in v0.2.0

type Action int

Action is the wait-loop leftover/HITL decision. In-process and Temporal adapters interpret this; they do not fork leftover-tool rules.

const (
	ActionInfer Action = iota
	ActionRunTools
	ActionYield
	ActionComplete
	ActionWait
)

func Next added in v0.2.0

func Next(runnable int, parked bool, inferComplete bool, jobsRemain bool) Action

Next chooses the next wait-loop step from leftover tools, park, inference completion, and remaining jobs.

type AgentOptions

type AgentOptions struct {
	// MaxWindowSize is the context window in tokens. Zero uses the model's
	// reported window.
	MaxWindowSize uint
	SystemPrompt  string
	// MaxTurnRequests limits Model.Invoke calls per turn. Zero means no limit.
	MaxTurnRequests uint
	Model           InferenceStrategy

	// Name is the label used in logs. It does not select behavior.
	Name     string
	WatchDog AgentWatchDog
	// Tools are host tools, including optional tools from email and web.
	// Give each tool its clients by closing
	// over them in the constructor (see NewTool). Session-world tools
	// (VFS, brain, index) still inject from the fields below.
	Tools      []*Tool
	MCPConfigs []mcp.MCPConfig
	// MCPCredentialResolver resolves durable references immediately before
	// connection. Inline client credentials remain session-scoped.
	MCPCredentialResolver mcp.CredentialResolver
	Specialists           []*Specialist
	// ContextPolicy sets pressure/compress ratios when non-zero fields are set.
	ContextPolicy ContextPolicy
	// ToolInterceptors wrap each tool call (outermost first). Built-in
	// planning lock and OnCall middleware are installed after these.
	// Hosts cannot omit the planning lock; specialists skip it via WithSpecialist.
	ToolInterceptors []ToolInterceptor
	// UnattendedWrite injects write without ToolPermissionOnCall.
	// Default false: write parks for permission.
	UnattendedWrite bool
	// ToolResultHooks map tool name → post-success window effects for host tools.
	// Plan builtins use ToolOutcome instead.
	ToolResultHooks map[string]ToolResultHook
	// SkillsLoader loads skills. When nil, SkillsPath is walked with skills.Loader.
	SkillsLoader skills.SkillLoader
	// SkillsPath is the skills directory. When the turn has a workspace mount,
	// it is a virtual path and empty means /workspace/skills. When it does not,
	// it is a local directory and empty means no skills.
	SkillsPath string
	// Brain enables knowledge builtins when non-nil. Workers inherit the same engine.
	// Configure Store, optional QueryEmbedder, and optional GraphReader/GraphWriter on the Engine
	// before NewTurnManager (e.g. brain.WithGraph(g) after helixgraph.New). The harness
	// does not construct store or graph backends.
	Brain *brain.Engine
	// BrainWriteKinds maps save_discovery / save_fact / save_memory to host kind names.
	// Empty fields skip that tool. Kinds should be registered via brain.ApplyKinds / WithKinds.
	// Ignored when Brain is nil.
	BrainWriteKinds brain.WriteKinds
	// SearchNamespace is the host ceiling for brain tools (session-owned, checkpointed).
	// Each tool call may add attrs to narrow the search; it cannot change ceiling values.
	// Empty means no ceiling. Workers get a copy at spawn.
	SearchNamespace brain.Namespace
	// OpenVFS builds the /workspace tree for each turn. Nil means no VFS.
	OpenVFS vfs.OpenVFS

	// UnattendedRunCommand injects run_command without ToolPermissionOnCall.
	// Default false: run_command parks for permission.
	UnattendedRunCommand bool
	// contains filtered or unexported fields
}

AgentOptions is the one agent, and the argument to NewTurnManager. A session runtime uses OpenVFS to build the workspace for each turn, then BindTurn attaches the session id and that tree. SkillsPath is a directory on that tree when it is mounted, and a local directory when it is not.

ContextPolicy knobs stay host-settable. Adaptive Case Management itself is harness-owned and cannot be replaced.

func BindTurn added in v0.4.0

func BindTurn(opts AgentOptions, id string, mount *vfs.MountSession) AgentOptions

BindTurn attaches the per-turn session id and the workspace tree. Hosts set OpenVFS and SkillsPath. The session runtime calls BindTurn.

func (*AgentOptions) Validate added in v0.2.0

func (opts *AgentOptions) Validate() error

Validate checks the construction contract and fills MaxWindowSize from the model when the host left it at zero.

func (AgentOptions) WithSpecialist added in v0.2.0

func (o AgentOptions) WithSpecialist(spec *Specialist) AgentOptions

WithSpecialist overlays a worker spec onto the parent session world. The child keeps parent MCP, brain, interceptors, and the turn binding from BindTurn. Model, tools, nested workers, and instructions come from spec. Planning write lock is off. The session runtime opens a new tree for the child.

type AgentWatchDog

type AgentWatchDog interface {
	RecordOutput(*Message) error
	RecordToolResult(*Message) error
}

AgentWatchDog records assistant output and tool results for a turn. Nil on AgentOptions means no watchdog.

type Annotation

type Annotation struct {
	Type   string         `json:"type"`
	Text   string         `json:"text,omitempty"`
	FileID string         `json:"file_id,omitempty"`
	URL    *URLAnnotation `json:"url,omitempty"`
}

Annotation attaches file/URL citations to output_text content.

type AuthExpired added in v0.3.1

type AuthExpired struct {
	Tool     string `json:"tool,omitempty"`
	Provider string `json:"provider,omitempty"`
}

AuthExpired is raised when a tool or VFS mount unwraps to expired credentials. Return is a no-op; tokens travel on Resume.Auth, not the interrupt payload.

func (*AuthExpired) Error added in v0.4.0

func (p *AuthExpired) Error() string

func (*AuthExpired) Return added in v0.4.0

func (p *AuthExpired) Return([]byte) error

func (*AuthExpired) Serialize added in v0.4.0

func (p *AuthExpired) Serialize() ([]byte, error)

func (*AuthExpired) TypeName added in v0.4.0

func (p *AuthExpired) TypeName() string

func (*AuthExpired) ValidatePayload added in v0.4.0

func (p *AuthExpired) ValidatePayload([]byte) error

type ChildWaiting added in v0.4.0

type ChildWaiting struct {
	Kind    string `json:"kind"`
	Message string `json:"message,omitempty"`
}

ChildWaiting accepts any resume payload (child HITL forwarded through the parent session).

func (*ChildWaiting) Error added in v0.4.0

func (p *ChildWaiting) Error() string

func (*ChildWaiting) Return added in v0.4.0

func (p *ChildWaiting) Return([]byte) error

func (*ChildWaiting) Serialize added in v0.4.0

func (p *ChildWaiting) Serialize() ([]byte, error)

func (*ChildWaiting) TypeName added in v0.4.0

func (p *ChildWaiting) TypeName() string

func (*ChildWaiting) ValidatePayload added in v0.4.0

func (p *ChildWaiting) ValidatePayload([]byte) error

type ContentPart

type ContentPart struct {
	Type        string       `json:"type"`
	Text        string       `json:"text,omitempty"`
	Refusal     string       `json:"refusal,omitempty"`
	ImageURL    *ImageURL    `json:"image_url,omitempty"`
	FileData    *FileData    `json:"file_data,omitempty"`
	Annotations []Annotation `json:"annotations,omitempty"`
}

ContentPart is a single content block within a message. Discriminated by Type — oneOf{output_text, input_text, input_image, input_file, refusal}.

type ContextPolicy

type ContextPolicy struct {
	// PressureRatio is the max-size fraction that triggers compress (for example 0.85).
	PressureRatio float64
	// CompressFraction seeds how much of the window to summarize.
	CompressFraction float64
	// StreamFitSummary streams compress summary chunks to the client when true.
	StreamFitSummary bool
}

ContextPolicy controls window compress under pressure (used by ModelTasks.Absorb).

func DefaultContextPolicy

func DefaultContextPolicy() ContextPolicy

DefaultContextPolicy is the product default pressure and compress settings.

func (ContextPolicy) Validate added in v0.2.0

func (p ContextPolicy) Validate() error

Validate checks non-zero context policy overrides.

type Engine added in v0.2.0

type Engine interface {
	AbsorbUser(ctx context.Context, user *Message, out chan StreamEvent) error
	PendingToolCalls() []ToolCall
	RunInference(ctx context.Context, st *TurnState, out chan StreamEvent) (InferenceStep, error)
	RunToolCall(ctx context.Context, tc ToolCall, out chan StreamEvent) (ToolStep, error)
	ApplyResume(finishedInterrupts map[string][]byte) error
	// RecordToolResult appends a RoleTool message for a tool call that already
	// ran. A waited child session uses this once its result is known.
	RecordToolResult(tc ToolCall, output string)
	Messages() []*Message
}

Engine is the session-runtime view of a TurnManager.

type FileData

type FileData struct {
	FileID   string `json:"file_id,omitempty"`
	URL      string `json:"url,omitempty"`
	Data     string `json:"data,omitempty"`
	MIMEType string `json:"mime_type,omitempty"`
	// Filename is preferred by providers for input_file (e.g. PDF data URLs).
	Filename string `json:"filename,omitempty"`
}

FileData represents an image or file input by ID, URL, or base64 data.

type HarnessRuntime

type HarnessRuntime interface {
	EmitUpdate(message string)
	StateGet(key string) (any, bool)
	StateSet(key string, value any) error
	StateDelete(key string)
	// Park writes pending for this tool call and returns the interrupt as
	// error. After Resume it returns the resolved interrupt and a nil error.
	Park(kind string, payload []byte) (Interrupt, error)
	CurrentToolCallID() string

	// RunSpecialist queues a blocking specialist session.
	// WaitFor is the child session the caller must wait on. Output is the
	// child's text when the host already finished that session. A host sets
	// one of them. This is not a background job: no inbox message.
	RunSpecialist(ctx context.Context, name, task string) (SpecialistResult, error)
	// Schedule starts a job of this session. It does not wait.
	// Name is a registered specialist or Runtime job worker. The result
	// arrives later as an inbox message. Pass the id to Jobs or CancelJob.
	Schedule(ctx context.Context, job JobRequest) (Job, error)
	// Jobs lists this session's jobs. Waiting specialist children appear as running.
	Jobs() []Job
	// CancelJob stops one job of this session and drops it from Jobs.
	CancelJob(ctx context.Context, id string) error
}

HarnessRuntime is the tool-facing hook for one harness turn. Tools emit progress, read/write user session state, Park, and run specialists or schedule jobs of this session. Session modules (plan, permissions, on-call) are not on this interface.

Built-in spawn_specialist / list_children / cancel_child call these. Host tools may call them too. The loop never matches those tool names.

type ImageURL

type ImageURL struct {
	URL    string `json:"url"`
	Detail string `json:"detail,omitempty"`
}

ImageURL represents an image input by URL or data URI.

type InferenceStep added in v0.2.0

type InferenceStep struct {
	ToolCalls []ToolCall
	Complete  bool
}

InferenceStep is the result of one model invocation for the session driver.

type InferenceStrategy

type InferenceStrategy interface {
	Invoke(ctx context.Context, messages []*Message, tools []*Tool, systemPrompt string) (chan LLMResponseChunk, error)
	CountTokens(context.Context, []*Message, []*Tool) (int, error)
	MaxContextWindow() (int, error)
	// SupportsMIME reports whether the currently selected model accepts the
	// given MIME type as user input. Empty and text/* are always true.
	// Probe representatives for ads (e.g. image/png); do not enumerate all types.
	SupportsMIME(mimeType string) bool
}

InferenceStrategy is the model provider interface used by the harness. Fluent With* builders and SetSystemPrompt live on concrete providers (for example *openai.OpenAIInferenceStrategy), not this interface.

type Interrupt

type Interrupt interface {
	// TypeName returns a stable, unique name for this interrupt type. It is
	// used as the JSON discriminator when persisting interrupts to session
	// storage and as the lookup key in the interrupt registry.
	TypeName() string
	// Serialize the interrupt to a byte slice for transmission.
	Serialize() ([]byte, error)
	// Return the interrupt to the agent workflow with a serialized
	// payload of the interrupt result.
	Return([]byte) error
	// Error makes Interrupt compatible with the error interface.
	Error() string
}

Interrupt represents a pending interrupt in an agent workflow requesting the user for additional input or approval. Implementations must also satisfy the error interface so they can be returned from tool handlers and detected via errors.As.

func CloneInterrupt added in v0.4.0

func CloneInterrupt(intr Interrupt) (Interrupt, error)

Clone returns a deep copy via JSON for checkpoint snapshots.

func NewInterrupt added in v0.4.0

func NewInterrupt(typeName string) (Interrupt, bool)

NewInterrupt returns a fresh Interrupt for a registered type name.

func ToolPermissionOnCall added in v0.2.0

func ToolPermissionOnCall(inv ToolInvocation) Interrupt

ToolPermissionOnCall parks a tool_permission interrupt before the handler. Session allow-always / reject-always are applied by on-call middleware.

type ItemStatus

type ItemStatus string

ItemStatus tracks the lifecycle state of an output item.

const (
	StatusInProgress ItemStatus = "in_progress"
	StatusCompleted  ItemStatus = "completed"
	StatusIncomplete ItemStatus = "incomplete"
)

type Job added in v0.3.3

type Job struct {
	ID     string
	Name   string
	State  string
	Result string
}

Job is one background job of the current session as tools may see it. State is running, completed, or failed. A specialist child waiting for input stays running. Name is the specialist or registered worker.

type JobHost added in v0.3.3

type JobHost interface {
	RunSpecialist(ctx context.Context, name, task, callID string) (SpecialistResult, error)
	Schedule(ctx context.Context, job JobRequest, callID string) (Job, error)
	Jobs() []Job
	CancelJob(ctx context.Context, id string) error
}

JobHost is the session-side implementation of HarnessRuntime job methods. Durable runtimes bind nested sessions and named workers; nil host means jobs are unavailable.

type JobRequest added in v0.3.3

type JobRequest struct {
	Name string
	Task string
}

JobRequest is Schedule input. Name is a specialist or a Runtime job worker.

type LLMResponseChunk

type LLMResponseChunk struct {
	TurnId     string
	MessageId  string
	ToolCalls  []ToolCall
	Type       StreamEventType
	Content    string
	IsComplete bool
	// Error is set on terminal provider failures (Type == StreamEventError).
	// Harness copies it onto StreamEvent.Error so protocols can errors.Is
	// stop-reason sentinels (refusal, max_tokens, …).
	Error error

	// Token usage when the provider reports it (typically on StreamEventComplete
	// after response.completed). Zero means unknown / not reported.
	InputTokens      int
	OutputTokens     int
	ReasoningTokens  int
	CachedTokens     int
	CacheWriteTokens int

	// EncryptedContent is Responses reasoning.encrypted_content. Provider parse
	// only; copied onto Message so the next turn can replay the item statelessly.
	EncryptedContent string
}

LLMResponseChunk is the streaming unit emitted by an InferenceStrategy's Invoke call. Provider parse only — not client-facing wire.

type Message

type Message struct {
	Role    MessageRole `json:"role"`
	Content string      `json:"content,omitempty"`

	// MessageID is the provider-assigned identifier for this output item,
	// used when serializing prior assistant or reasoning turns as typed
	// response items.
	MessageID string `json:"message_id,omitempty"`

	// EncryptedContent is the Responses API reasoning ciphertext
	// (include=reasoning.encrypted_content). Required to replay a reasoning
	// item by id without a provider store lookup.
	EncryptedContent string `json:"encrypted_content,omitempty"`

	ContentParts     []ContentPart `json:"content_parts,omitempty"`
	ToolCalls        []ToolCall    `json:"tool_calls,omitempty"`
	ToolCallID       string        `json:"tool_call_id,omitempty"`
	StructuredOutput any           `json:"-"`
}

Message is the primary conversation unit in the context window. It handles both simple text and structured content, tool calls, tool results, and reasoning content produced by reasoning models. The Role field determines the purpose:

  • system/developer: system instructions
  • user: user input (Content or ContentParts)
  • assistant: model response (Content + optional ToolCalls)
  • reasoning: model reasoning content (a distinct previous-response item)
  • tool: result of a tool execution (ToolCallID + Content)

func (*Message) MIMETypes added in v0.2.0

func (m *Message) MIMETypes() []string

MIMETypes returns unique binary MIME types from ContentParts (images/files). Producers set FileData.MIMEType (and image parts via FileData or data URL). Text and refusal parts are ignored. Order is first-seen.

type MessageRole

type MessageRole string

MessageRole indicates who sent the message.

const (
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
	RoleReasoning MessageRole = "reasoning"
	RoleSystem    MessageRole = "system"
	RoleDeveloper MessageRole = "developer"
	RoleTool      MessageRole = "tool"
)

type OnCallFunc added in v0.2.0

type OnCallFunc func(ToolInvocation) Interrupt

OnCallFunc builds a pre-invoke Return nil to skip that layer.

type PayloadInitializer added in v0.4.0

type PayloadInitializer interface {
	InitFromPayload([]byte) error
}

PayloadInitializer is an optional capability Interrupt types implement to populate themselves from the raw payload provided to Park.

type PayloadValidator

type PayloadValidator interface {
	ValidatePayload([]byte) error
}

PayloadValidator is an optional capability Interrupt types may implement for standalone payload checks. Session Resume calls Return only; types that still need field-presence checks do that inside Return.

type PendingToolCall added in v0.2.0

type PendingToolCall struct {
	ToolCall        *ToolCall `json:"toolCall,omitempty"`
	InterruptActive bool      `json:"interruptActive,omitempty"`
	// AwaitJob is true while the durable loop waits on an inline specialist.
	// The call is not runnable and is not a human interrupt.
	AwaitJob bool `json:"awaitJob,omitempty"`
}

PendingToolCall is a parked or in-flight tool call in a checkpoint.

type PermissionOption

type PermissionOption struct {
	OptionID string `json:"optionId"`
	Name     string `json:"name"`
	Kind     string `json:"kind"`
}

PermissionOption is a single choice offered when a tool requires user approval. Field names match ACP session/request_permission options.

func DefaultPermissionOptions

func DefaultPermissionOptions() []PermissionOption

DefaultPermissionOptions are the standard ACP permission choices.

type ProviderStatus

type ProviderStatus interface {
	ProviderHTTPStatus() int
	ProviderErrorCode() string
}

ProviderStatus supplies HTTP status and error code from a provider error. Optional on InferenceStrategy errors for model-span attributes.

type SessionCheckpoint added in v0.2.0

type SessionCheckpoint struct {
	ContextWindow []*Message `json:"contextWindow"`
	// contains filtered or unexported fields
}

SessionCheckpoint is the agent harness checkpoint blob. Wire protocols must not store protocol envelopes here — use a ProtocolWireStore (or equivalent) owned by the protocol. Harness-owned module/interrupt bytes are opaque to store implementations.

func NewCheckpoint added in v0.2.0

func NewCheckpoint(
	contextWindow []*Message,
	pendingToolCalls map[string]PendingToolCall,
	userState, modules map[string]json.RawMessage,
	pendingInterrupts, resolvedInterrupts any,
) (*SessionCheckpoint, error)

NewCheckpoint builds the current checkpoint schema. modules contain framework-owned typed JSON; userState contains host-owned arbitrary JSON.

func (SessionCheckpoint) MarshalJSON added in v0.2.0

func (c SessionCheckpoint) MarshalJSON() ([]byte, error)

func (SessionCheckpoint) Modules added in v0.2.0

func (c SessionCheckpoint) Modules() map[string]json.RawMessage

func (SessionCheckpoint) PendingInterrupts added in v0.2.0

func (c SessionCheckpoint) PendingInterrupts() []byte

func (SessionCheckpoint) PendingToolCalls added in v0.2.0

func (c SessionCheckpoint) PendingToolCalls() map[string]PendingToolCall

func (SessionCheckpoint) ResolvedInterrupts added in v0.2.0

func (c SessionCheckpoint) ResolvedInterrupts() []byte

func (*SessionCheckpoint) UnmarshalJSON added in v0.2.0

func (c *SessionCheckpoint) UnmarshalJSON(data []byte) error

func (SessionCheckpoint) UserState added in v0.2.0

func (c SessionCheckpoint) UserState() map[string]json.RawMessage

func (SessionCheckpoint) Version added in v0.2.0

func (c SessionCheckpoint) Version() int

func (SessionCheckpoint) WithModule added in v0.2.0

func (c SessionCheckpoint) WithModule(name string, raw json.RawMessage) SessionCheckpoint

WithModule returns a copy with one harness module blob replaced.

func (SessionCheckpoint) WithUserStateKey added in v0.2.0

func (c SessionCheckpoint) WithUserStateKey(key string, raw json.RawMessage) SessionCheckpoint

WithUserStateKey returns a copy with one user-state blob replaced.

func (SessionCheckpoint) WithVersion added in v0.2.0

func (c SessionCheckpoint) WithVersion(v int) SessionCheckpoint

WithVersion returns a copy with the schema version set. Tests use this to exercise apply reject paths.

type Specialist added in v0.2.0

type Specialist struct {
	Tools        []*Tool
	Instructions string
	Model        InferenceStrategy
	Name         string
	Description  string
	// Specialists are nested workers available to this worker when it runs.
	Specialists []*Specialist
}

Specialist describes a nested session a harness can spawn via spawn_specialist. Specs may nest via Specialists. Child sessions inherit the parent world through AgentOptions.WithSpecialist (VFS, brain, MCP, interceptors). Spec fields replace model, instructions, tools, and nested Specialists. They skip planningWriteLock.

func FindSpecialist added in v0.2.0

func FindSpecialist(specs []*Specialist, name string) *Specialist

FindSpecialist returns the named worker from specs, including nested Specialists.

type SpecialistResult added in v0.4.0

type SpecialistResult struct {
	Output  string
	WaitFor string
}

SpecialistResult is the outcome of a blocking specialist request. WaitFor means the child session is not finished. The session loop waits for that id, then records the tool result. Output is set when the child already finished inside the call.

type StreamEvent

type StreamEvent struct {
	Type      StreamEventType
	TurnID    string
	MessageID string
	Content   string
	Data      []byte
	ToolCalls []ToolCall
	// Error is in-process only. Workflow Streams cannot encode error values;
	// Fail is the durable stand-in (sentinel Error() text).
	Error error  `json:"-"`
	Fail  string `json:"fail,omitempty"`
}

StreamEvent is the harness interior event bus. Protocols map these events to wire formats; the harness does not own protocol framing.

type StreamEventType

type StreamEventType string

StreamEventType categorizes events sent to the caller.

const (
	StreamEventMessage      StreamEventType = "message"
	StreamEventReasoning    StreamEventType = "reasoning"
	StreamEventFunctionCall StreamEventType = "function_call"
	StreamEventToolResult   StreamEventType = "tool_result"
	StreamEventComplete     StreamEventType = "complete"
	StreamEventError        StreamEventType = "error"
	StreamEventInterrupt    StreamEventType = "yield"
	StreamEventToolUpdate   StreamEventType = "tool_update"
	StreamEventPlanUpdate   StreamEventType = "plan_update"
)

type Todo

type Todo struct {
	Title       string     `json:"title" desc:"Todo title. Must be unique in the list."`
	Status      TodoStatus `json:"status" desc:"pending, in_progress, or completed."`
	Description string     `json:"description" desc:"Objective, expected outcomes, and acceptance criteria."`
}

Todo is one item in an agent plan list (create_plan / plan_update stream data).

type TodoStatus added in v0.2.0

type TodoStatus string
const (
	TodoStatusPending    TodoStatus = "pending"
	TodoStatusCompleted  TodoStatus = "completed"
	TodoStatusInProgress TodoStatus = "in_progress"
)

type Tool

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

Tool is a registered harness tool. Construct with NewTool(ToolConfig{...}). Fields are unexported; hosts read metadata through the getters below.

func NewTool

func NewTool(cfg ToolConfig) *Tool

func (*Tool) Access

func (t *Tool) Access() ToolAccess

Access is the permission bitmask for this tool.

func (*Tool) AsJson

func (t *Tool) AsJson() map[string]any

AsJson returns the OpenAI-style function tool definition for this tool. parameters is never nil on the returned map.

func (*Tool) Category

func (t *Tool) Category() ToolCategory

Category is the coarse streaming category for client presentation.

func (*Tool) Description

func (t *Tool) Description() string

Description is the model-facing tool description.

func (*Tool) DisplayName

func (t *Tool) DisplayName() string

DisplayName is the optional human title from ToolConfig. Empty means unset; stream titles fall back to Name via ResolveToolTitle.

func (*Tool) Name

func (t *Tool) Name() string

Name is the programmatic tool name presented to the model.

func (*Tool) Namespace

func (t *Tool) Namespace() string

Namespace is the optional tool namespace (MCP server name, host grouping).

func (*Tool) Timeout

func (t *Tool) Timeout() time.Duration

Timeout is the optional per-invocation deadline. Zero means none.

type ToolAccess added in v0.2.0

type ToolAccess uint8

ToolAccess is an immutable permission bitmask. Zero allows nothing.

func (ToolAccess) Allows added in v0.2.0

func (a ToolAccess) Allows(p ToolPermission) bool

Allows reports whether a includes p.

type ToolCall

type ToolCall struct {
	ID        string       `json:"id,omitempty"`
	Type      string       `json:"type,omitempty"`
	CallID    string       `json:"call_id"`
	Name      string       `json:"name,omitempty"`  // programmatic tool id (model-facing)
	Title     string       `json:"title,omitempty"` // human-readable invocation label for UIs/protocols
	Category  ToolCategory `json:"category,omitempty"`
	Namespace string       `json:"namespace,omitempty"`
	Arguments string       `json:"arguments,omitempty"`
	Status    string       `json:"status,omitempty"`
}

ToolCall represents an assistant request to invoke a tool.

func (ToolCall) Key added in v0.2.0

func (tc ToolCall) Key() string

Key is the client/lifecycle id: provider item id, else call_id.

func (ToolCall) WireID added in v0.2.0

func (tc ToolCall) WireID() string

WireID is the Responses API call_id field: CallID, else ID.

type ToolCallFunc

type ToolCallFunc func(ctx context.Context, inv ToolInvocation) (string, error)

ToolCallFunc is the next interceptor step or the final tool invoke.

type ToolCategory added in v0.2.0

type ToolCategory string
const (
	ToolCategoryRead    ToolCategory = "read"
	ToolCategoryEdit    ToolCategory = "edit"
	ToolCategorySearch  ToolCategory = "search"
	ToolCategoryFetch   ToolCategory = "fetch"
	ToolCategoryMove    ToolCategory = "move"
	ToolCategoryThink   ToolCategory = "think"
	ToolCategoryExecute ToolCategory = "execute"
	ToolCategoryDelete  ToolCategory = "delete"
)

type ToolConfig

type ToolConfig struct {
	Name        string
	Description string
	DisplayName string
	Namespace   string
	Category    ToolCategory
	Access      ToolAccess
	Timeout     time.Duration
	// OnCall is the pre-invoke middleware stack. Each constructor may park.
	// Return nil from a constructor to skip that layer. Types must be registered.
	OnCall []OnCallFunc

	// Handler is a Go function. Close over clients in the constructor that calls NewTool.
	// Optional parameters: context.Context, an args struct, HarnessRuntime.
	Handler any
}

type ToolHandlerFunc

type ToolHandlerFunc func(ctx context.Context, args map[string]any, runtime HarnessRuntime) (string, error)

type ToolInterceptor

type ToolInterceptor func(ctx context.Context, inv ToolInvocation, next ToolCallFunc) (string, error)

ToolInterceptor wraps a tool call. Call next to continue, or return early to short-circuit. Host interceptors on AgentOptions wrap outside the built-in planning lock and OnCall middleware; they never replace that chain.

type ToolInvocation

type ToolInvocation struct {
	Tool     *Tool
	ArgsJSON string
	Runtime  HarnessRuntime
}

ToolInvocation is one tool call in the interceptor chain.

type ToolOutcome added in v0.2.0

type ToolOutcome struct {
	Output string
	// Effect is merged for the batch and applied once at batch end.
	Effect ToolResultEffect
	// SuppressWindowMessage omits the tool Message from the window.
	// The client still receives StreamEventToolResult.
	SuppressWindowMessage bool
}

ToolOutcome is the single post-tool result: model-visible output plus a window effect. Plan builtins return this. A host ToolResultHook may also set Output to replace the model-visible result, for example to cap a large one.

type ToolPermission

type ToolPermission uint8
const (
	ReadPermission ToolPermission = 1 << iota
	WritePermission
	ExecutePermission
)

type ToolPermissionInterrupt

type ToolPermissionInterrupt struct {
	ToolName string             `json:"toolName,omitempty"`
	Title    string             `json:"title,omitempty"` // human-readable invocation label
	Options  []PermissionOption `json:"options"`

	// Set by Return after the consumer selects an option. Checkpointed so a
	// later activity can TakeResolved and see the decision. Serialize omits
	// these so the client park payload stays unresolved.
	SelectedOptionID string `json:"selectedOptionId,omitempty"`
	SelectedKind     string `json:"selectedKind,omitempty"`
	Allowed          bool   `json:"allowed,omitempty"`
}

ToolPermissionInterrupt asks the user to approve or reject a tool call.

func (*ToolPermissionInterrupt) Error added in v0.4.0

func (p *ToolPermissionInterrupt) Error() string

func (*ToolPermissionInterrupt) InitFromPayload added in v0.4.0

func (p *ToolPermissionInterrupt) InitFromPayload(payload []byte) error

func (*ToolPermissionInterrupt) Return added in v0.4.0

func (p *ToolPermissionInterrupt) Return(payload []byte) error

func (*ToolPermissionInterrupt) Serialize added in v0.4.0

func (p *ToolPermissionInterrupt) Serialize() ([]byte, error)

func (*ToolPermissionInterrupt) TypeName added in v0.4.0

func (p *ToolPermissionInterrupt) TypeName() string

func (*ToolPermissionInterrupt) ValidatePayload added in v0.4.0

func (p *ToolPermissionInterrupt) ValidatePayload(payload []byte) error

type ToolPermissionPayload added in v0.4.0

type ToolPermissionPayload struct {
	InterruptId string `json:"interruptId,omitempty"`
	OptionID    string `json:"optionId"`
}

ToolPermissionPayload is the consumer resolution for a tool permission interrupt.

type ToolResultEffect

type ToolResultEffect int

ToolResultEffect is applied once after a successful tool batch (no open interrupts).

const (
	EffectNone ToolResultEffect = iota
	// EffectInstallPlanDocument sets the window to [user, plan document].
	EffectInstallPlanDocument
	// EffectHandoff rebuilds the window for the next open todos.
	EffectHandoff
)

type ToolResultHook

type ToolResultHook func(ctx context.Context, obs ToolResultObservation) ToolOutcome

ToolResultHook runs after a successful host tool and before the tool result is emitted. Effects apply at batch end. Plan builtins return ToolOutcome instead.

type ToolResultObservation

type ToolResultObservation struct {
	Name     string
	ArgsJSON string
	Output   string
	Runtime  HarnessRuntime
}

ToolResultObservation is a successful tool result seen by a ToolResultHook.

type ToolStep added in v0.2.0

type ToolStep struct {
	Interrupted   bool
	InterruptID   string
	InterruptData []byte
	AwaitJobID    string
}

ToolStep is the result of one tool invocation for the session driver. Interrupted means the tool parked; the driver must persist, publish yield, and wait for Resume. AwaitJobID means the tool is still open: the session loop waits for that child session, then RecordToolResult.

type TurnManager added in v0.2.0

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

TurnManager runs one turn slice: infer, tool batch, checkpoint. Durable runtimes construct it; hosts use session.Runtime.

func NewTurnManager added in v0.2.0

func NewTurnManager(ctx context.Context, opts AgentOptions) (*TurnManager, error)

NewTurnManager builds a TurnManager for one turn slice. Session runtimes call this after BindTurn. Hosts use session.Runtime.

func (*TurnManager) ApplySessionState added in v0.2.0

func (a *TurnManager) ApplySessionState(state map[string]any) error

ApplySessionState upserts host-owned userState after construct/restore. Durable runtimes apply CreateSession/Prompt/Resume.State here so tools see it via HarnessRuntime.StateGet.

func (*TurnManager) BindJobHost added in v0.3.3

func (a *TurnManager) BindJobHost(host JobHost)

BindJobHost installs job operations. Durable runtimes call this after NewTurnManager. Nil: job methods fail.

func (*TurnManager) Checkpoint added in v0.2.0

func (a *TurnManager) Checkpoint() (*SessionCheckpoint, error)

Checkpoint captures the session blob for SnapshotStore.

func (*TurnManager) Close added in v0.2.0

func (a *TurnManager) Close()

Close releases turn resources (MCP and the indexer this turn started). The MountSession is closed by the session runtime. Call after the Run events channel is drained, or when construct fails.

func (*TurnManager) Drive added in v0.2.0

func (a *TurnManager) Drive() Engine

Drive is the turn-step API in-process and Temporal adapters call after NewTurnManager.

func (*TurnManager) RestoreCheckpoint added in v0.2.0

func (a *TurnManager) RestoreCheckpoint(cp SessionCheckpoint) error

RestoreCheckpoint applies a SnapshotStore blob onto this harness.

type TurnState added in v0.2.0

type TurnState struct {
	ModelRequests int
	HadToolRound  bool
}

TurnState is per-slice counters for the session inference loop.

type URLAnnotation

type URLAnnotation struct {
	URL   string `json:"url"`
	Title string `json:"title"`
}

URLAnnotation references a specific URL as a citation source.

type UserChoice

type UserChoice struct {
	Title         string `json:"title"`
	Description   string `json:"description"`
	IsRecommended bool   `json:"isRecommended"`
}

type UserSelectionInterrupt

type UserSelectionInterrupt struct {
	Question        string       `json:"question,omitempty"`
	Options         []UserChoice `json:"options"`
	ConfirmedChoice *UserChoice
}

func (*UserSelectionInterrupt) Error added in v0.4.0

func (c *UserSelectionInterrupt) Error() string

func (*UserSelectionInterrupt) InitFromPayload added in v0.4.0

func (c *UserSelectionInterrupt) InitFromPayload(payload []byte) error

func (*UserSelectionInterrupt) Return added in v0.4.0

func (c *UserSelectionInterrupt) Return(payload []byte) error

func (*UserSelectionInterrupt) Serialize added in v0.4.0

func (c *UserSelectionInterrupt) Serialize() ([]byte, error)

func (*UserSelectionInterrupt) TypeName added in v0.4.0

func (c *UserSelectionInterrupt) TypeName() string

func (*UserSelectionInterrupt) ValidatePayload added in v0.4.0

func (c *UserSelectionInterrupt) ValidatePayload(payload []byte) error

type UserSelectionPayload added in v0.4.0

type UserSelectionPayload struct {
	InterruptId  string `json:"interruptId"`
	SelectionIdx int    `json:"selectionIdx"`
}

Directories

Path Synopsis
Package brain is Tacklr's knowledge-base retrieval engine.
Package brain is Tacklr's knowledge-base retrieval engine.
helixgraph
Package helixgraph adapts HelixDB to brain.GraphReader / GraphWriter / searchers.
Package helixgraph adapts HelixDB to brain.GraphReader / GraphWriter / searchers.
postgres
Package postgres is the optional Postgres implementation of brain.Store.
Package postgres is the optional Postgres implementation of brain.Store.
internal
command
Package command contains the host command execution mechanism.
Package command contains the host command execution mechanism.
mcp
temporaldocker
Package temporaldocker starts the same Temporal server the live tests use: Postgres and temporalio/server in Docker.
Package temporaldocker starts the same Temporal server the live tests use: Postgres and temporalio/server in Docker.
testdrive
Package testdrive is an internal httptest fixture for Drive, Docs, and Sheets.
Package testdrive is an internal httptest fixture for Drive, Docs, and Sheets.
testgit
Package testgit runs an in-process git host for one bare repository: smart HTTP (git http-backend over net/http/cgi) behind a basic-auth token, and SSH (git upload-pack / receive-pack) behind one deploy key.
Package testgit runs an in-process git host for one bare repository: smart HTTP (git http-backend over net/http/cgi) behind a basic-auth token, and SSH (git upload-pack / receive-pack) behind one deploy key.
testkit
Package testkit provides shared test doubles for harness and server integration tests.
Package testkit provides shared test doubles for harness and server integration tests.
Package server serves a session.Runtime over host-defined wire protocols.
Package server serves a session.Runtime over host-defined wire protocols.
acp
Package acp is the Agent Client Protocol built into the server.
Package acp is the Agent Client Protocol built into the server.
internal
Package adapter is the Runtime wait-loop glue.
Package adapter is the Runtime wait-loop glue.
temporal
Package temporal is the Temporal adapter for session.Runtime.
Package temporal is the Temporal adapter for session.Runtime.
Package skills discovers and parses application-owned SKILL.md files.
Package skills discovers and parses application-owned SKILL.md files.
Package telemetry configures OpenTelemetry for Tacklr hosts and process tools.
Package telemetry configures OpenTelemetry for Tacklr hosts and process tools.
vfs
Package vfs is Tacklr's virtual filesystem: session mounts, path I/O, and content IR.
Package vfs is Tacklr's virtual filesystem: session mounts, path I/O, and content IR.
adapters
Package adapters contains source-format codecs for rich text documents.
Package adapters contains source-format codecs for rich text documents.
Package vfsindex bridges a vfs.MountSession into brain knowledge objects.
Package vfsindex bridges a vfs.MountSession into brain knowledge objects.

Jump to

Keyboard shortcuts

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