agent

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 11 Imported by: 1 module, 0 packages

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

README

CMDOP Go Harness

An embeddable AI agent runtime for Go. Bring your own model and tools.

v0.2.0 — renamed repository and Go module path. MIT-licensed; APIs may change before v1.0.

What works

  • In-process agent loop with a provider-neutral model interface
  • Typed custom tools, bounded execution and conversation history
  • Streaming text, cancellation and per-step reported token usage
  • Optional OpenAI-compatible Chat Completions, OpenAI Responses (stateless text/function and experimental native-history subset), and native Anthropic Messages and Gemini Developer API adapters
  • Optional bounded workspace discovery, text search and file tools with content revisions
  • JSON Schema validation for typed tool inputs
  • Optional named verification suite and final success gate
  • Optional local SQLite archive of completed conversations with opt-in full-text search
  • Optional reviewed MCP tool bindings over caller-owned streams or bounded Streamable HTTP, plus a separate metadata-only discovery catalog
  • Optional offline text token counting and complete-turn context selection
  • Optional bounded local SKILL.md catalog and explicit revision-matched activation
  • Optional synchronous child-agent delegation with separate tools and reservation budgets

Install

Requires Go 1.26.

go get github.com/commandoperator/cmdop-go-harness@v0.2.0

See the release notes, MIT license, and third-party notices.

Try the offline example

git clone --branch v0.2.0 https://github.com/commandoperator/cmdop-go-harness.git
cd cmdop-go-harness
go run ./examples/basic

Expected output:

Tool result: 5

Read the runtime contracts, OpenAI-compatible guide and Anthropic guide, and Responses guide, and Gemini guide. See workspace tools for explicit file access and limitations, verification for caller-approved checks, and local conversation archive for explicit history storage. Provider adapters have local HTTP integration tests; live interoperability with individual model services has not yet been verified.

Embedding

See the embedding guide for a complete offline consumer example using the agent, workspace tools and local session archive.

Platform verification

Native regression, race, and offline consumer tests use Linux amd64. CGO-free compilation is checked for Linux, macOS, and Windows on amd64 and arm64. Cross-compilation does not establish native runtime behavior.

Architecture and contributing

See the package architecture and contribution guide. The root API is independent of optional adapters.

Development

go test ./...
go vet ./...
go test -race ./...

More providers and lossless MCP structured results are planned. This library does not require a CMDOP account or server.

Related project: CMDOP.

Documentation

Overview

Package agent provides an embeddable model-and-tool runtime for Go.

The root package owns the provider-neutral contracts and synchronous run lifecycle. New constructs an agent from an explicitly supplied Model and caller-approved Tools; Run executes one bounded turn. NewTool binds a typed Go handler to a reviewed JSON Schema.

Optional provider adapters, conversation archives, workspace tools, MCP, skills and delegation live in separate packages. The root runtime does not load them automatically or discover credentials, start background work, or grant access to local or remote resources.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrToolLimit       = errors.New("agent: tool call limit reached")
	ErrStepLimit       = errors.New("agent: model step limit reached")
	ErrInvalidHistory  = errors.New("agent: invalid or incomplete conversation history")
	ErrInvalidResponse = errors.New("agent: invalid model response")
)
View Source
var (
	ErrVerificationFailed      = errors.New("agent: final verification did not pass")
	ErrVerificationUnavailable = errors.New("agent: final verification unavailable")
	ErrInvalidVerification     = errors.New("agent: invalid verification evidence")
)

Functions

func ValidateHistory

func ValidateHistory(messages []Message, nativeFormat string) error

ValidateHistory validates complete prior turns and the shape of optional native assistant data for the declared model format. Empty format rejects native attachments. It does not establish successful execution, validate provider-specific payloads or authorize effects.

Types

type Agent

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

Agent executes model calls and explicitly registered tools in sequence. A run owns its conversation; concurrent runs require concurrency-safe implementations of the supplied model and tool handlers.

func New

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

New constructs an agent without discovering credentials, starting processes, accessing the filesystem, or registering implicit tools.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, req Request) (Result, error)

Run executes a bounded turn. The model's final text is authoritative; streamed text is incremental display data, not an additional message.

type CheckResult

type CheckResult struct {
	Name           string      `json:"name"`
	Status         CheckStatus `json:"status"`
	DurationMillis int64       `json:"duration_ms"`
	ExitCode       *int        `json:"exit_code,omitempty"`
}

CheckResult is bounded, structured evidence. It deliberately carries no command line, raw output, arbitrary error text or sensitive environment.

type CheckStatus

type CheckStatus string

CheckStatus distinguishes an observed failure from a check that could not run.

const (
	CheckPassed   CheckStatus = "passed"
	CheckFailed   CheckStatus = "failed"
	CheckError    CheckStatus = "error"
	CheckTimedOut CheckStatus = "timed_out"
	CheckCanceled CheckStatus = "canceled"
	CheckNotRun   CheckStatus = "not_run"
)

type Config

type Config struct {
	Model Model
	Tools []Tool
	// FinalVerifier optionally runs after the model's final response. A run
	// succeeds only if its evidence passes. It is explicitly caller-owned.
	FinalVerifier Verifier
	MaxSteps      int // Zero selects the default of eight model calls.
	MaxToolCalls  int // Zero selects the default of 32 tool calls per run.
}

Config defines an agent. Only explicitly supplied tools can be invoked.

type Event

type Event struct {
	Kind       EventKind
	Text       string
	ToolName   string
	ToolCallID string
	ToolError  bool
}

Event intentionally omits tool arguments and results.

type EventKind

type EventKind string
const (
	EventText         EventKind = "text"
	EventToolStarted  EventKind = "tool_started"
	EventToolFinished EventKind = "tool_finished"
)

type Message

type Message struct {
	Role       Role
	Text       string
	ToolCalls  []ToolCall
	ToolCallID string
	ToolError  bool
	Native     *NativeHistory // Assistant-only, for the declaring model format.
}

Message contains text, an assistant's tool calls, or a tool's response.

type Model

type Model interface {
	Complete(ctx context.Context, req ModelRequest, emit func(string) error) (ModelResponse, error)
}

Model is the provider boundary. Complete must honor context cancellation and may emit text incrementally. Calls to emit must be synchronous and serial, must stop after an error, and must not outlive Complete.

type ModelRequest

type ModelRequest struct {
	Messages []Message
	Tools    []ToolSpec
}

ModelRequest is an isolated snapshot of the conversation and available tools.

type ModelResponse

type ModelResponse struct {
	Text      string
	ToolCalls []ToolCall
	Usage     *Usage
	Native    *NativeHistory // Optional same-provider assistant data.
}

ModelResponse is the complete assistant response, including any tool calls.

type NativeHistory

type NativeHistory struct {
	Format string
	Data   json.RawMessage
}

NativeHistory carries adapter-owned assistant data for the same provider context only. Treat Data as sensitive. It is not tool authority, a portable session, or a cryptographic integrity guarantee.

type NativeHistoryModel

type NativeHistoryModel interface {
	NativeHistoryFormat() string
}

NativeHistoryModel is an optional Model capability. A nonempty format opts into retaining and accepting assistant metadata of exactly that format. The model must validate the provider context and payload before network use.

type Request

type Request struct {
	Prompt  string
	History []Message
	OnEvent func(Event) error
}

Request starts a turn, optionally continuing a complete conversation. OnEvent is synchronous; an error stops the run. Callbacks must not block indefinitely and must arrange their own cancellation if they perform I/O.

type Result

type Result struct {
	Text         string
	Messages     []Message
	Steps        int
	ToolCalls    int
	Usage        []StepUsage         // Only steps with reported usage; missing steps are unknown.
	Verification *VerificationReport // Nil when no final gate returned valid evidence.
}

Result retains messages even when a run stops with an error. Partial history is diagnostic evidence, not a guarantee that retrying a tool is safe.

type Role

type Role string

Role describes a message's position in a conversation.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type StepUsage

type StepUsage struct {
	Step  int
	Usage Usage
}

StepUsage associates reported usage with its one-based model step.

type Tool

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

Tool is a caller-defined, typed operation. Construct one with NewTool.

func NewTool

func NewTool[In, Out any](spec ToolSpec, handler func(context.Context, In) (Out, error)) (Tool, error)

NewTool builds a typed operation with an explicit model-facing input schema. JSON arguments must be an object; struct decoding rejects unknown fields. The caller-owned JSON Schema is compiled once and checked before typed decoding. Handlers remain responsible for semantic validation and authority. Handler errors are not exposed verbatim unless explicitly marked ToolFailure.

type ToolCall

type ToolCall struct {
	ID        string
	Name      string
	Arguments string
}

ToolCall identifies a requested invocation. Arguments holds raw JSON text.

type ToolFailure

type ToolFailure struct {
	Message string
}

ToolFailure explicitly opts a short, safe recovery message into model-facing output. Never include secrets, raw filesystem errors or untrusted data. Other handler errors remain redacted.

func (*ToolFailure) Error

func (e *ToolFailure) Error() string

type ToolSpec

type ToolSpec struct {
	Name        string
	Description string
	InputSchema json.RawMessage
}

ToolSpec describes a tool to a model. InputSchema is a caller-owned JSON Schema with root type object; NewTool compiles and enforces it.

type Usage

type Usage struct {
	InputTokens  int64
	OutputTokens int64
	TotalTokens  int64
}

Usage reports provider-supplied token counts for one completion. A nil usage pointer means usage is unknown, not zero.

type VerificationReport

type VerificationReport struct {
	Checks []CheckResult `json:"checks"`
}

func (VerificationReport) Passed

func (r VerificationReport) Passed() bool

Passed reports true only for nonempty, valid, entirely successful evidence.

type Verifier

type Verifier interface {
	Verify(context.Context) (VerificationReport, error)
}

Verifier is an explicitly trusted caller capability. Verify must return bounded evidence and honor cancellation; it may perform effects. A report is an observation at check time, not a proof of immutability or correctness.

Directories

Path Synopsis
Package contextbudget provides explicit, local history budgeting helpers.
Package contextbudget provides explicit, local history budgeting helpers.
examples
anthropic command
This example makes a real provider request only when explicitly run.
This example makes a real provider request only when explicitly run.
archive command
basic command
The basic example runs a model/tool conversation without external services.
The basic example runs a model/tool conversation without external services.
gemini command
Live example; requires explicit authorized endpoint, model and key.
Live example; requires explicit authorized endpoint, model and key.
openai command
This example makes a real provider request only when explicitly run.
This example makes a real provider request only when explicitly run.
responses command
Example makes a live request only when explicitly run with caller configuration.
Example makes a live request only when explicitly run with caller configuration.
verification command
workspace command
Offline example: use a caller-selected temporary workspace without a model API.
Offline example: use a caller-selected temporary workspace without a model API.
internal
nativepayload
Package nativepayload validates the shape and size of opaque model metadata.
Package nativepayload validates the shape and size of opaque model metadata.
providerio
Package providerio implements shared, per-completion I/O policy for SDKs.
Package providerio implements shared, per-completion I/O policy for SDKs.
toolcall
Package toolcall implements the private validation and invocation path of a caller-registered typed tool.
Package toolcall implements the private validation and invocation path of a caller-registered typed tool.
Package mcp adapts explicitly reviewed MCP tools to the local agent runtime.
Package mcp adapts explicitly reviewed MCP tools to the local agent runtime.
providers
anthropic
Package anthropic implements the text and client-tool subset of the Anthropic streaming Messages API.
Package anthropic implements the text and client-tool subset of the Anthropic streaming Messages API.
gemini
Package gemini integrates the Gemini Developer API text/function subset using official Google GenAI SDK content types and bounded streaming I/O.
Package gemini integrates the Gemini Developer API text/function subset using official Google GenAI SDK content types and bounded streaming I/O.
openai
Package openai implements the text and function-tool subset of the OpenAI-compatible streaming Chat Completions protocol.
Package openai implements the text and function-tool subset of the OpenAI-compatible streaming Chat Completions protocol.
Package session provides an explicit local archive of completed library conversations.
Package session provides an explicit local archive of completed library conversations.
internal/recordcodec
Package recordcodec owns the private version-one persisted record format.
Package recordcodec owns the private version-one persisted record format.
internal/sqlitefile
Package sqlitefile owns the archive's private SQLite file and connection policy.
Package sqlitefile owns the archive's private SQLite file and connection policy.
Package skills loads explicitly selected local Agent Skills documents.
Package skills loads explicitly selected local Agent Skills documents.
Package subagents provides explicit, synchronous child-agent delegation.
Package subagents provides explicit, synchronous child-agent delegation.
tools
verify
Package verify runs explicitly configured, named checks and exposes their structured results to the caller and optionally to an agent.
Package verify runs explicitly configured, named checks and exposes their structured results to the caller and optionally to an agent.
Package workspace provides opt-in, bounded text-file operations in a caller-selected directory.
Package workspace provides opt-in, bounded text-file operations in a caller-selected directory.
internal/pathpolicy
Package pathpolicy validates portable relative names and restricted glob syntax.
Package pathpolicy validates portable relative names and restricted glob syntax.
internal/textedit
Package textedit implements the workspace's pure text and revision policy.
Package textedit implements the workspace's pure text and revision policy.

Jump to

Keyboard shortcuts

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