agent

package
v0.0.8 Latest Latest
Warning

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

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

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

Documentation

Overview

Package agent defines the Runtime's native Harness adapter contract. Start with this file when adding a Harness; the onboarding guide is at contracts/agents-api/harness-onboarding.md.

Required lifecycle: ExecutorFactory prepares a fixed Session-owned Executor; each StartTurn returns a fresh Turn with its own output and settlement. Turn includes the public text DurableSteerer requirement. Keep extension interfaces separate, but implement each explicitly: unsupported operations return ErrUnsupportedOperation before any native effects. Interface presence does not advertise support; the capability declaration controls admission. MCP, images, structured output and Subagent observations use protocol messages rather than additional Go interfaces; qualify and advertise them separately.

Registration: each adapter exports one Declaration. The Runtime discovers the static declaration list and installs each resulting Runtime through Register. Availability and factory selection belong to the adapter. RegisterKind resets the other factories, so Register installs it first. Preparation capabilities are derived from the declared factories.

Runtime registration and Core service qualification remain separate. A public Harness also needs a profile in services/core/internal/engine; advertising a capability cannot authorize it. Requests, events and capability descriptors use the existing internal/agentdaemon/proto types. An Environment execution request carries the Runtime's bound workspace directory in LocalEnvironment.WorkspaceRoot; the native Harness runs there.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWorkspaceReadUnsupported = fmt.Errorf("%w: workspace read", ErrUnsupportedOperation)
	ErrWorkspaceReadUnavailable = errors.New("workspace read unavailable")
	ErrWorkspaceReadBusy        = errors.New("workspace read busy")
	ErrWorkspaceReadInvalid     = errors.New("workspace read invalid")
	ErrWorkspaceReadUncertain   = errors.New("workspace read outcome uncertain")
	// ErrWorkspaceNotDirectory reports that a directory request's own path is
	// missing, a regular file or a symbolic link; the link was not followed.
	ErrWorkspaceNotDirectory = errors.New("workspace path is not a directory")
)
View Source
var (
	ErrWorkspaceWriteUnsupported = fmt.Errorf("%w: workspace write", ErrUnsupportedOperation)
	ErrWorkspaceWriteUnavailable = errors.New("workspace write unavailable")
	ErrWorkspaceWriteBusy        = errors.New("workspace write busy")
	ErrWorkspaceWriteInvalid     = errors.New("workspace write invalid")
	ErrWorkspaceWriteRejected    = errors.New("workspace write rejected")
	ErrWorkspaceWriteUncertain   = errors.New("workspace write outcome uncertain")
)
View Source
var (
	ErrWorkspaceWriteDirectory = fmt.Errorf("%w: destination is a directory", ErrWorkspaceWriteRejected)
	ErrWorkspaceWriteUnsafe    = fmt.Errorf("%w: destination exists or its path is not a plain directory chain", ErrWorkspaceWriteRejected)
)

Known Files.create destination refusals. Both wrap ErrWorkspaceWriteRejected: nothing was installed.

View Source
var ErrSteeringInactive = errors.New("agent: run is no longer active")

ErrSteeringInactive means no input was sent because the run ended or was cancelled.

View Source
var ErrSteeringNotReady = errors.New("agent: turn is not ready for input")

ErrSteeringNotReady means no input was sent because the turn is starting.

View Source
var ErrSteeringRejected = errors.New("agent: input rejected")

ErrSteeringRejected means the engine explicitly rejected the input.

View Source
var ErrUnknownAsk = errors.New("agent: unknown ask id")

ErrUnknownAsk is returned by UserChoiceResponder.SubmitPromptForUserChoice when the askID doesn't match any outstanding ask. Same race semantics as ErrUnknownPermission.

View Source
var ErrUnknownFunctionCall = errors.New("agent: function call is no longer pending")
View Source
var ErrUnknownPermission = errors.New("agent: unknown permission id")

ErrUnknownPermission is returned by PermissionResponder.SubmitPermission when the permID doesn't match any outstanding request. The router uses this to distinguish a benign race from a real forwarding failure.

View Source
var ErrUnsupportedKind = errors.New("agent: unsupported agent_kind")
View Source
var ErrUnsupportedOperation = errors.New("agent: unsupported operation")

ErrUnsupportedOperation marks an intentional absence of optional behavior. Implementations wrap it with a static reason and perform no native effects. It is distinct from unavailable resources, failures and uncertain outcomes.

Functions

func ManagedSkillsRoot

func ManagedSkillsRoot(agentKind, agentStateKey, conversationID, runID string) (string, error)

ManagedSkillsRoot returns an adapter-owned skill directory scoped to one agent state. It never derives runtime state from the subprocess cwd.

func ValidMCPHTTPBearerToken

func ValidMCPHTTPBearerToken(token string) bool

ValidMCPHTTPBearerToken accepts RFC 6750 b64token bytes without normalization. Credential resource storage has a separate, opaque-string contract.

Types

type Declaration

type Declaration struct {
	Info          proto.SupportedAgentKind
	Configuration harnessconfig.Configuration
	Discover      func(context.Context, DiscoveryOptions, proto.SupportedAgentKind) *Runtime
}

Declaration is the complete startup contract for a Harness implementation. Discover returns nil when the adapter is not configured. An unavailable configured adapter returns a Runtime with Available=false and a session factory. Discovery owns runtime-specific configuration, readiness and feature gates.

type DiscoveryOptions

type DiscoveryOptions struct {
	Profile        string
	Stdout, Stderr io.Writer
}

DiscoveryOptions provides process context without naming an implementation.

type DurableSteerer

type DurableSteerer interface {
	SteerWithReceipt(context.Context, proto.PromptSteerPayload, func()) error
}

DurableSteerer reports one complete write synchronously, then waits for the native receipt. It is independent of Steerer and is mandatory on every public Turn. Required input receipts cannot be implemented by returning Unsupported.

type Executor

type Executor interface {
	// A nil Turn guarantees no input was submitted or output retained and leaves
	// out with the caller. A non-nil Turn owns out, including on error; input
	// may have been submitted and must never be replayed automatically.
	StartTurn(context.Context, string, proto.MessageInput, chan<- proto.Envelope) (Turn, error)
	// Success confirms all native work and owned output streams have stopped.
	// It does not establish an otherwise unknown Turn result. An error retains
	// resource ownership; another caller may await or retry Close.
	Close(context.Context) error
}

Executor retains a fixed native configuration across independently owned Turns.

type ExecutorFactory

type ExecutorFactory func(context.Context, proto.PromptRequestPayload) (Executor, error)

ExecutorFactory prepares without model input. A failed factory retains any unconfirmed cleanup in its non-nil Executor.

type Factory

type Factory func(ctx context.Context, req proto.PromptRequestPayload, out chan<- proto.Envelope) (Session, error)

Factory builds a Session for one prompt_request. out is the upstream channel the agent writes into and closes exactly once after terminal output. ctx is cancelled by the router to wind the session down.

type FunctionResultSubmitter

type FunctionResultSubmitter interface {
	SubmitFunctionResult(context.Context, proto.FunctionResultPayload) error
}

FunctionResultSubmitter delivers a result for an outstanding native call. A successful return requires its native application receipt.

type Installation

type Installation struct {
	AgentKind   string
	Version     string
	Supported   func() bool
	Environment func(directory, node string) map[string]string
	Check       func(context.Context, string, string, []string) error
}

Installation is an optional adapter-owned native distribution contract. It supplies activation paths and readiness checks, never execution or model configuration. Runtime owns copying, checksums, publication and installation locks.

type MCPBinding

type MCPBinding struct {
	ServerLabel         string
	ConnectionOrigin    string
	CredentialAuthority string
	Transport           string
	ServerURL           string
	AllowedTools        *[]string
	Required            bool
	BearerToken         *string
	HTTPHeaders         map[string]string
	// Stdio retains the installed package identity for the fixed Runtime launcher.
	Stdio *proto.EnvironmentMCP
}

MCPBinding is the Runtime's transient effective declaration. Adapters project it into their native configuration without resolving credentials or packages. Never serialize or log bindings: headers and bearer values may be confidential.

func ResolveMCPBindings

func ResolveMCPBindings(req proto.PromptRequestPayload) ([]MCPBinding, error)

ResolveMCPBindings combines public declarations with the frozen installation. Public declarations retain explicit origin and Vault authority; installed MCP retains Environment configuration authority. Neither may relocate implicitly.

type PermissionResponder

type PermissionResponder interface {
	SubmitPermission(context.Context, string, proto.PermissionDecisionPayload) error
}

PermissionResponder accepts decisions for qualified permission requests. An adapter that never supports these interactions returns ErrUnsupportedOperation. Unknown or expired requests return ErrUnknownPermission.

type PreparationFactory

type PreparationFactory func(context.Context, proto.PromptRequestPayload) (Prepared, error)

A factory may return both a resource and an error when construction failed but cleanup remains unconfirmed. The caller must retain and close that resource.

type Prepared

type Prepared interface {
	// Start transfers output ownership only when it returns a non-nil Session.
	// A nil Session leaves the caller as the sole owner of closing out, and the
	// implementation must not retain or write to it after Start returns.
	Start(context.Context, string, proto.MessageInput, chan<- proto.Envelope) (Session, error)
	// Close retains unused ownership on error; callers may retry settlement.
	Close() error
}

Prepared owns native resources until Start returns a non-nil Session. The preparation owner context spans the eventual Session; Start's context is local to that operation. A nil Session leaves preparation cleanup with the caller.

type PreparedCancellation

type PreparedCancellation interface {
	Prepared
	Session
	// Cancel returns after local cleanup and all output writes have stopped.
	// An error retains ownership so callers can retry this exact object serially.
	Cancel(context.Context) error
}

PreparedCancellation is required for executable preparations and follows the same native resource across Start. Read-only preparations need only Prepared.

type Registry

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

Registry maps agent_kind → Factory and keeps the daemon-advertised capability descriptor for each kind. Safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Configuration

func (r *Registry) Configuration(kind string) (harnessconfig.Configuration, error)

Configuration returns an owned declaration for registry wrappers. Wrappers transfer it with the factory; they must not infer configuration from kind names.

func (*Registry) Kinds

func (r *Registry) Kinds() []string

Kinds returns the list of registered kinds sorted lexicographically.

func (*Registry) Register

func (r *Registry) Register(declaration Declaration, runtime Runtime)

Register installs a discovered Runtime with its declaration's configuration.

func (*Registry) RegisterExecutor

func (r *Registry) RegisterExecutor(kind string, factory ExecutorFactory)

RegisterExecutor installs the shared lifecycle after RegisterKind and derives the Preparation capability. It does not enable other public operations.

func (*Registry) RegisterKind

func (r *Registry) RegisterKind(info proto.SupportedAgentKind, configuration harnessconfig.Configuration, f Factory)

RegisterKind installs f and the heartbeat descriptor for an agent_kind. Callers may set Available=false when an adapter exists but its underlying CLI is not usable.

func (*Registry) RegisterPreparation

func (r *Registry) RegisterPreparation(kind string, workspaceRead bool, prepare PreparationFactory)

RegisterPreparation installs a separate execution-only path. Product factory wrappers must not add authoring or capability-download side effects to it.

func (*Registry) Resolve

func (r *Registry) Resolve(kind string) (Factory, error)

Resolve returns the factory for kind, or wraps ErrUnsupportedKind.

func (*Registry) ResolveExecutor

func (r *Registry) ResolveExecutor(kind string) (ExecutorFactory, error)

func (*Registry) ResolvePreparation

func (r *Registry) ResolvePreparation(kind string) (PreparationFactory, error)

func (*Registry) SupportedAgentKinds

func (r *Registry) SupportedAgentKinds() []proto.SupportedAgentKind

SupportedAgentKinds returns the daemon-advertised capability descriptors sorted by kind so heartbeat payloads are stable.

type Runtime

type Runtime struct {
	Info                      proto.SupportedAgentKind
	Session                   Factory
	Preparation               PreparationFactory
	Executor                  ExecutorFactory
	WorkspaceReadPreparation  bool
	SessionCapabilityContext  bool
	ExecutorCapabilityContext bool
}

Runtime binds one discovered descriptor to its native factories. SessionCapabilityContext and ExecutorCapabilityContext request the Runtime's capability-download URL and scoped product-upload context for those factories. Preparation never receives those execution-only effects.

type Session

type Session interface {
	// Cancel signals the session to abort. Idempotent. Actual teardown
	// happens asynchronously and is signalled via the out channel close.
	Cancel(ctx context.Context) error
	// CancellationOutcome snapshots observed native identity, usage and output.
	// It remains readable after Cancel; missing evidence stays unset. An empty
	// result means no observed evidence, not unsupported cancellation or success.
	// Reading it does not wait for or establish native settlement.
	CancellationOutcome() proto.DonePayload
}

Session is the cancellation and outcome surface shared by direct prompt runs and Turns. Every owner exposes observed state, including direct-call sessions. For Executor-owned Turns, AwaitSettlement and Executor.Close define settlement and resource retirement; Cancel alone does not transfer resource ownership.

type Steerer

type Steerer interface {
	Steer(context.Context, proto.PromptSteerPayload) error
}

Steerer delivers non-durable input when qualified; otherwise it explicitly returns ErrUnsupportedOperation without submitting input.

type Turn

type Turn interface {
	Session
	DurableSteerer
	// Success confirms closed output and settled native input, function,
	// interaction and child-work obligations. Errors cannot prove cancellation.
	AwaitSettlement(context.Context) (TurnSettlement, error)
}

Turn owns one output stream and never retargets cancellation to a successor.

type TurnSettlement

type TurnSettlement struct {
	Reusable bool
	Reason   string
}

TurnSettlement describes native readiness after this Turn has fully drained. A false result must carry a reason; it requires confirmed Executor.Close.

type UserChoiceResponder

type UserChoiceResponder interface {
	SubmitPromptForUserChoice(context.Context, string, proto.PromptForUserChoiceDecisionPayload) error
}

UserChoiceResponder accepts answers for qualified user-choice requests. An adapter that never supports these interactions returns ErrUnsupportedOperation. Unknown or expired requests return ErrUnknownAsk.

type WorkspaceDirectoryEntry

type WorkspaceDirectoryEntry struct {
	Name      string
	Kind      string
	SizeBytes *int64
}

WorkspaceDirectoryEntry describes an entry observed without following its final symlink.

type WorkspaceDirectoryLister

type WorkspaceDirectoryLister interface {
	ListWorkspaceDirectory(context.Context, string, int) (WorkspaceDirectoryResult, error)
}

WorkspaceDirectoryLister reads one directory through an existing workspace owner. An empty directory selects the root; other paths contain only relative components. Entry names are single components. Kind is file, directory, symlink or other; SizeBytes is present and nonnegative only for regular files. Results have no prescribed order, and Truncated must not be presented as a complete inventory. maxEntries is positive; adapters may reject limits above their private bound. Successful return requires settled directory/metadata access and handle cleanup. Implementations retain workspace authorization and isolation and use the existing WorkspaceRead errors for unsupported, unavailable, busy, invalid or uncertain reads. This interface does not establish public Files pagination or feature admission.

type WorkspaceDirectoryResult

type WorkspaceDirectoryResult struct {
	Entries   []WorkspaceDirectoryEntry
	Truncated bool
}

WorkspaceDirectoryResult is a live, bounded observation, not a filesystem snapshot.

type WorkspaceReadResult

type WorkspaceReadResult struct {
	Data      []byte
	Truncated bool
}

type WorkspaceReader

type WorkspaceReader interface {
	ReadWorkspaceFile(context.Context, string, int) (WorkspaceReadResult, error)
}

WorkspaceReader returns success only after acknowledged native close on an existing owner.

type WorkspaceWriteResult

type WorkspaceWriteResult struct {
	SizeBytes int64
}

type WorkspaceWriter

type WorkspaceWriter interface {
	WriteWorkspaceFile(context.Context, string, []byte) (WorkspaceWriteResult, error)
}

WorkspaceWriter confirms a native commit on an already authorized prepared owner.

Directories

Path Synopsis
Package binpath resolves which executable each agent adapter should probe and spawn.
Package binpath resolves which executable each agent adapter should probe and spawn.
Package codex is the agent_kind="codex" adapter.
Package codex is the agent_kind="codex" adapter.
Package contracttest provides shared assertions for Harness adapter tests.
Package contracttest provides shared assertions for Harness adapter tests.
Package installroot coordinates adapter installations within one daemon process.
Package installroot coordinates adapter installations within one daemon process.
Package mcode drives MiniMax Code through its native ACP stdio interface.
Package mcode drives MiniMax Code through its native ACP stdio interface.

Jump to

Keyboard shortcuts

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