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
- Variables
- func ContextWithToolChoiceNone(ctx context.Context) context.Context
- func Correction(cause error, msg string) error
- func Correctionf(cause error, format string, args ...any) error
- func DataURL(mime, data string) string
- func EpisodeKinds() []brain.KindSpec
- func IsPlanDocument(m *Message) bool
- func IsTextMIME(mime string) bool
- func MIMEFromDataURL(u string) string
- func Network(err error) error
- func NormalizeMIME(mime string) string
- func PipeStreamEvents(emit func(StreamEvent)) (chan StreamEvent, func())
- func RegisterDefaults()
- func RegisterInterrupt(factory func() Interrupt)
- func ResolveToolTitle(displayName, toolName, argsJSON string) string
- func ToolChoiceNone(ctx context.Context) bool
- func ToolsAsJson(tools []*Tool) string
- func TypeToJSONSchema(v any) (map[string]any, error)
- func UnsupportedMIMEs(s InferenceStrategy, mimes []string) []string
- func ValidateMessages(messages []*Message) error
- type AbsorbResult
- type Action
- type AgentOptions
- type AgentWatchDog
- type Annotation
- type AuthExpired
- type ChildWaiting
- type ContentPart
- type ContextPolicy
- type Engine
- type FileData
- type HarnessRuntime
- type ImageURL
- type InferenceStep
- type InferenceStrategy
- type Interrupt
- type ItemStatus
- type Job
- type JobHost
- type JobRequest
- type LLMResponseChunk
- type Message
- type MessageRole
- type OnCallFunc
- type PayloadInitializer
- type PayloadValidator
- type PendingToolCall
- type PermissionOption
- type ProviderStatus
- type SessionCheckpoint
- func (c SessionCheckpoint) MarshalJSON() ([]byte, error)
- func (c SessionCheckpoint) Modules() map[string]json.RawMessage
- func (c SessionCheckpoint) PendingInterrupts() []byte
- func (c SessionCheckpoint) PendingToolCalls() map[string]PendingToolCall
- func (c SessionCheckpoint) ResolvedInterrupts() []byte
- func (c *SessionCheckpoint) UnmarshalJSON(data []byte) error
- func (c SessionCheckpoint) UserState() map[string]json.RawMessage
- func (c SessionCheckpoint) Version() int
- func (c SessionCheckpoint) WithModule(name string, raw json.RawMessage) SessionCheckpoint
- func (c SessionCheckpoint) WithUserStateKey(key string, raw json.RawMessage) SessionCheckpoint
- func (c SessionCheckpoint) WithVersion(v int) SessionCheckpoint
- type Specialist
- type SpecialistResult
- type StreamEvent
- type StreamEventType
- type Todo
- type TodoStatus
- type Tool
- type ToolAccess
- type ToolCall
- type ToolCallFunc
- type ToolCategory
- type ToolConfig
- type ToolHandlerFunc
- type ToolInterceptor
- type ToolInvocation
- type ToolOutcome
- type ToolPermission
- type ToolPermissionInterrupt
- func (p *ToolPermissionInterrupt) Error() string
- func (p *ToolPermissionInterrupt) InitFromPayload(payload []byte) error
- func (p *ToolPermissionInterrupt) Return(payload []byte) error
- func (p *ToolPermissionInterrupt) Serialize() ([]byte, error)
- func (p *ToolPermissionInterrupt) TypeName() string
- func (p *ToolPermissionInterrupt) ValidatePayload(payload []byte) error
- type ToolPermissionPayload
- type ToolResultEffect
- type ToolResultHook
- type ToolResultObservation
- type ToolStep
- type TurnManager
- func (a *TurnManager) ApplySessionState(state map[string]any) error
- func (a *TurnManager) BindJobHost(host JobHost)
- func (a *TurnManager) Checkpoint() (*SessionCheckpoint, error)
- func (a *TurnManager) Close()
- func (a *TurnManager) Drive() Engine
- func (a *TurnManager) RestoreCheckpoint(cp SessionCheckpoint) error
- type TurnState
- type URLAnnotation
- type UserChoice
- type UserSelectionInterrupt
- func (c *UserSelectionInterrupt) Error() string
- func (c *UserSelectionInterrupt) InitFromPayload(payload []byte) error
- func (c *UserSelectionInterrupt) Return(payload []byte) error
- func (c *UserSelectionInterrupt) Serialize() ([]byte, error)
- func (c *UserSelectionInterrupt) TypeName() string
- func (c *UserSelectionInterrupt) ValidatePayload(payload []byte) error
- type UserSelectionPayload
Constants ¶
const ( KindEpisode = "Episode" KindEpisodeChunk = "EpisodeChunk" )
const ( ListChildrenName = "list_children" CancelChildName = "cancel_child" )
ListChildrenName and CancelChildName are built-ins on HarnessRuntime.Jobs / CancelJob.
const ( PermissionAllowOnce = "allow_once" PermissionAllowAlways = "allow_always" PermissionRejectOnce = "reject_once" PermissionRejectAlways = "reject_always" )
ACP PermissionOptionKind values.
const ( ContentTypeOutputText = "output_text" ContentTypeInputText = "input_text" ContentTypeInputImage = "input_image" ContentTypeInputFile = "input_file" ContentTypeRefusal = "refusal" )
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.
const CancelledToolResultContent = "cancelled: user interrupted the agent"
CancelledToolResultContent is written into the context window for tool calls aborted by session cancel.
const CheckpointVersion = 2
CheckpointVersion is the current typed session checkpoint schema.
const SpawnSpecialistName = "spawn_specialist"
SpawnSpecialistName is the built-in that calls HarnessRuntime.Schedule.
const TypeAuthExpired = "auth_expired"
TypeAuthExpired parks a tool call until the host rebinds credentials on Resume.Auth.
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 ¶
var ( ErrInterruptNotFound = errors.New("interrupt not found") ErrInvalidPayload = errors.New("invalid payload") )
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.
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") )
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
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
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
Correctionf is Correction with fmt.Sprintf.
func DataURL ¶ added in v0.2.0
DataURL builds a data:<mime>;base64,<data> URL. data may already be a data URL.
func EpisodeKinds ¶ added in v0.3.4
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
IsPlanDocument reports the durable PROJECT PLAN developer message.
func IsTextMIME ¶ added in v0.2.0
IsTextMIME is true for empty and text/* types (always model-safe as text).
func MIMEFromDataURL ¶ added in v0.2.0
MIMEFromDataURL extracts the MIME type from a data: URL, or empty.
func Network ¶ added in v0.4.0
Network marks err as a transport failure. The text stays err.Error().
func NormalizeMIME ¶ added in v0.2.0
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 ¶
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
ToolChoiceNone reports whether ctx was wrapped with ContextWithToolChoiceNone.
func ToolsAsJson ¶
ToolsAsJson serializes tool definitions for model requests. An empty catalog is "[]". Namespaced tools are "namespace__name" (OpenAI rejects '.').
func TypeToJSONSchema ¶
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
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.
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 ¶
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
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 InferenceStep ¶ added in v0.2.0
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
Clone returns a deep copy via JSON for checkpoint snapshots.
func NewInterrupt ¶ added in v0.4.0
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
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
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)
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
PayloadInitializer is an optional capability Interrupt types implement to populate themselves from the raw payload provided to Park.
type PayloadValidator ¶
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 ¶
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
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 ¶
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 ¶
Description is the model-facing tool description.
func (*Tool) DisplayName ¶
DisplayName is the optional human title from ToolConfig. Empty means unset; stream titles fall back to Name via ResolveToolTitle.
type ToolAccess ¶ added in v0.2.0
type ToolAccess uint8
ToolAccess is an immutable permission bitmask. Zero allows nothing.
const ( ToolReadAccess ToolAccess = ToolAccess(ReadPermission) ToolWriteAccess ToolAccess = ToolAccess(WritePermission) ToolReadWriteAccess ToolAccess = ToolAccess(ReadPermission | WritePermission) ToolExecuteAccess ToolAccess = ToolAccess(ExecutePermission) ToolReadExecuteAccess ToolAccess = ToolAccess(ReadPermission | ExecutePermission) ToolFullAccess ToolAccess = ToolAccess(ReadPermission | WritePermission | ExecutePermission) )
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.
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 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
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 URLAnnotation ¶
URLAnnotation references a specific URL as a citation source.
type UserChoice ¶
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
Source Files
¶
- agent.go
- agent_construct.go
- builtins.go
- checkpoint.go
- context_manager.go
- doc.go
- drive.go
- durable_steps.go
- init.go
- interrupt.go
- message.go
- model_tasks.go
- runtime_children.go
- session_checkpointer.go
- session_durable.go
- session_interrupt_map.go
- session_manager.go
- session_oncall.go
- session_permissions.go
- session_plan.go
- session_runtime.go
- subagents.go
- tool_runner.go
- tools.go
- tools_brain.go
- tools_vfs.go
- tools_vfsindex.go
- types.go
- validate.go
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. |
|
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. |
|
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. |
|
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. |