agent

package
v0.1.22 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PermissionModeBypass skips provider approval requests.
	PermissionModeBypass = "bypass"
	// PermissionModeOnRequest forwards provider approval requests to the user.
	PermissionModeOnRequest = "on-request"
	// PermissionModeAuto automatically approves safe operations.
	PermissionModeAuto = "auto"
)
View Source
const (
	// ApprovalActionApprove approves one provider operation.
	ApprovalActionApprove = "approve"
	// ApprovalActionDeny rejects one provider operation.
	ApprovalActionDeny = "deny"
	// ApprovalActionAlways approves matching future provider operations.
	ApprovalActionAlways = "always"
)
View Source
const (
	// RuntimeKindLeros is the built-in Leros agent runtime.
	RuntimeKindLeros = "leros"
	// RuntimeKindClaude is the Claude Code runtime.
	RuntimeKindClaude = "claude"
	// RuntimeKindCodex is the Codex CLI runtime.
	RuntimeKindCodex = "codex"
	// RuntimeKindOpenCode is the OpenCode runtime.
	RuntimeKindOpenCode = "opencode"
)

Variables

This section is empty.

Functions

func ContextWithTodoReporter added in v0.1.22

func ContextWithTodoReporter(
	ctx context.Context,
	reporter TodoReporter,
) context.Context

ContextWithTodoReporter attaches a runtime todo reporter to a tool context.

func MarshalRawJSON added in v0.1.22

func MarshalRawJSON(value any) json.RawMessage

MarshalRawJSON encodes an arbitrary value to json.RawMessage.

Types

type AgentEndedPayload added in v0.1.22

type AgentEndedPayload struct {
	ProviderSessionID string `json:"provider_session_id,omitempty"`
}

AgentEndedPayload signals that the agent execution has ended.

type AgentStartedPayload added in v0.1.22

type AgentStartedPayload struct {
	ProviderSessionID string `json:"provider_session_id"`
}

AgentStartedPayload signals that the agent started and exposed a native provider session ID.

type ApprovalDecision

type ApprovalDecision struct {
	RequestID string
	Action    string // "approve" | "deny" | "always"
	Reason    string
}

ApprovalDecision is the user's response to an approval request.

type ApprovalRequest

type ApprovalRequest struct {
	RequestID   string
	ToolCallID  string
	ToolName    string
	Arguments   json.RawMessage
	Description string
	Runtime     string
}

ApprovalRequest carries the details needed for an approval decision.

type ApprovalRequestedPayload added in v0.1.22

type ApprovalRequestedPayload struct {
	RequestID   string            `json:"request_id"`
	ToolName    string            `json:"tool_name"`
	ToolCallID  string            `json:"tool_call_id"`
	Description string            `json:"description"`
	Arguments   json.RawMessage   `json:"arguments,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
}

ApprovalRequestedPayload describes a tool call that needs user approval.

type ApprovalResolvedPayload added in v0.1.22

type ApprovalResolvedPayload struct {
	RequestID string `json:"request_id"`
	Action    string `json:"action"` // "approve" | "deny" | "always"
	Reason    string `json:"reason,omitempty"`
}

ApprovalResolvedPayload describes the outcome of an approval request.

type ApprovalResponder added in v0.1.22

type ApprovalResponder interface {
	WriteDecision(requestID string, action string) error
}

ApprovalResponder writes an approval decision back to a provider runtime.

type ExecutionMode added in v0.1.18

type ExecutionMode string

ExecutionMode describes how a runtime should handle one request.

const (
	// ExecutionModeDefault keeps the runtime's normal execution behavior.
	ExecutionModeDefault ExecutionMode = "default"
	// ExecutionModePlan requests planning behavior when the runtime supports it.
	ExecutionModePlan ExecutionMode = "plan"
)

type ExecutionPolicy

type ExecutionPolicy struct {
	PermissionMode string
	AllowedTools   []string
}

ExecutionPolicy controls generic runtime behavior.

type ExecutionRequest

type ExecutionRequest struct {
	ExecutionID string
	TraceID     string
	Runtime     string
	SessionKey  string
	InstanceKey string
	Mode        ExecutionMode

	SystemPrompt    string
	Prompt          string
	Messages        []Message
	Model           ModelConfig
	Tools           []Tool
	Policy          ExecutionPolicy
	Filesystem      FilesystemContext
	ProviderSession ProviderSession
}

ExecutionRequest is a fully prepared, business-neutral Runtime input.

type ExecutionResult

type ExecutionResult struct {
	Message                string
	Usage                  *Usage
	ToolCalls              []ToolCallRecord
	ProviderConversationID string
}

ExecutionResult is the low-level result returned by a Runtime before business finalization.

type Executor

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

Executor resolves a Runtime by name and drives the execution lifecycle:

  1. Validate the execution request.
  2. Resolve a Runtime implementation by name.
  3. Wrap observer in SerialObserver for ordered, serial event delivery.
  4. Call Runtime.Execute with the SerialObserver.
  5. Return ExecutionResult.

Executor does NOT emit execution lifecycle events. The function return value (ExecutionResult, error) expresses success, failure, or cancellation.

func NewExecutor

func NewExecutor(registry *Registry) *Executor

NewExecutor creates an Executor backed by the given Registry.

func (*Executor) Execute

func (e *Executor) Execute(
	ctx context.Context,
	request ExecutionRequest,
	observer NodeObserver,
) (ExecutionResult, error)

Execute runs the full execution lifecycle for a prepared run.

func (*Executor) ResolveRuntimeKind added in v0.1.22

func (e *Executor) ResolveRuntimeKind(kind string) (string, error)

ResolveRuntimeKind returns the canonical runtime kind that would be used for execution. If kind is empty, the registry default runtime kind is returned.

type FilesystemContext

type FilesystemContext struct {
	WorkDir string
	RepoDir string
	TaskDir string
}

FilesystemContext contains the already prepared runtime directories.

type InteractionHandler

type InteractionHandler interface {
	// RequestApproval asks for user approval on a tool call.
	// It blocks until a decision is made or the context is cancelled.
	RequestApproval(ctx context.Context, req *ApprovalRequest) (*ApprovalDecision, error)

	// RequestAnswer asks the user to answer a set of questions.
	// It blocks until answers are received or the context is cancelled.
	RequestAnswer(ctx context.Context, req *QuestionRequest) (*QuestionAnswer, error)
}

InteractionHandler handles approval and question requests from a Runtime. It is injected at Runtime construction time; Runtime MUST NOT depend on a package-level default.

type MCPServerConfig added in v0.1.22

type MCPServerConfig struct {
	Name        string
	URL         string
	Command     string
	Args        []string
	Env         map[string]string
	BearerToken string
}

MCPServerConfig describes one MCP endpoint exposed to an external Runtime.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is a business-neutral conversation message supplied to a Runtime.

type MessageEndPayload added in v0.1.22

type MessageEndPayload struct {
	MessageID string `json:"message_id"`
	Content   string `json:"content"`
	Usage     *Usage `json:"usage,omitempty"`
}

MessageEndPayload carries the final assembled message.

type MessageStartPayload added in v0.1.22

type MessageStartPayload struct {
	MessageID string `json:"message_id"`
	Role      string `json:"role"`
}

MessageStartPayload carries the start of a message.

type MessageUpdatePayload added in v0.1.22

type MessageUpdatePayload struct {
	MessageID string `json:"message_id"`
	Role      string `json:"role"`
	Content   string `json:"content"`
}

MessageUpdatePayload carries a streaming text delta.

type ModelConfig

type ModelConfig struct {
	Provider string
	Model    string
	APIKey   string
	BaseURL  string
}

ModelConfig is the fully resolved model configuration for one execution.

type NodeEvent added in v0.1.22

type NodeEvent struct {
	ID          string            `json:"id"`
	ExecutionID string            `json:"execution_id"`
	TraceID     string            `json:"trace_id"`
	Type        NodeEventType     `json:"type"`
	OccurredAt  time.Time         `json:"occurred_at"`
	Payload     NodeEventPayload  `json:"payload,omitempty"`
	Metadata    NodeEventMetadata `json:"metadata,omitempty"`
}

NodeEvent is the stable runtime node event envelope emitted during execution. It describes execution facts, not business state.

func NewAgentEndEvent added in v0.1.22

func NewAgentEndEvent(sessionID string) NodeEvent

NewAgentEndEvent creates an agent.end node event.

func NewAgentStartEvent added in v0.1.22

func NewAgentStartEvent(sessionID string) NodeEvent

NewAgentStartEvent creates an agent.start node event.

func NewApprovalRequestedEvent added in v0.1.22

func NewApprovalRequestedEvent(p ApprovalRequestedPayload) NodeEvent

NewApprovalRequestedEvent creates an approval.requested node event.

func NewApprovalResolvedEvent added in v0.1.22

func NewApprovalResolvedEvent(p ApprovalResolvedPayload) NodeEvent

NewApprovalResolvedEvent creates an approval.resolved node event.

func NewMessageEndEvent added in v0.1.22

func NewMessageEndEvent(content string, usage *Usage) NodeEvent

NewMessageEndEvent creates a message.end node event.

func NewMessageStartEvent added in v0.1.22

func NewMessageStartEvent(messageID, role string) NodeEvent

NewMessageStartEvent creates a message.start node event.

func NewMessageUpdateEvent added in v0.1.22

func NewMessageUpdateEvent(messageID, content string) NodeEvent

NewMessageUpdateEvent creates a message.update node event.

func NewPlanReadyEvent added in v0.1.22

func NewPlanReadyEvent(path, displayPath, sessionID string) NodeEvent

NewPlanReadyEvent creates a plan.ready node event.

func NewQuestionAnsweredEvent added in v0.1.22

func NewQuestionAnsweredEvent(p QuestionAnsweredPayload) NodeEvent

NewQuestionAnsweredEvent creates a question.answered node event.

func NewQuestionAskedEvent added in v0.1.22

func NewQuestionAskedEvent(p QuestionAskedPayload) NodeEvent

NewQuestionAskedEvent creates a question.asked node event.

func NewReasoningUpdateEvent added in v0.1.22

func NewReasoningUpdateEvent(messageID, content string) NodeEvent

NewReasoningUpdateEvent creates a reasoning.update node event.

func NewTodoSnapshotEvent added in v0.1.22

func NewTodoSnapshotEvent(items []RuntimeTodoItem) NodeEvent

NewTodoSnapshotEvent creates a todo.snapshot node event.

func NewTodoUpdatedEvent added in v0.1.22

func NewTodoUpdatedEvent(items []RuntimeTodoItem) NodeEvent

NewTodoUpdatedEvent creates a todo.updated node event.

func NewToolExecutionEndErrorEvent added in v0.1.22

func NewToolExecutionEndErrorEvent(toolCallID, name, detail string, elapsedMS int64) NodeEvent

NewToolExecutionEndErrorEvent creates a tool_execution.end node event for a failed tool call.

func NewToolExecutionEndEvent added in v0.1.22

func NewToolExecutionEndEvent(toolCallID, name string, result json.RawMessage, elapsedMS int64) NodeEvent

NewToolExecutionEndEvent creates a tool_execution.end node event for a successful tool call. For failed tool calls, use NewToolExecutionEndErrorEvent.

func NewToolExecutionStartEvent added in v0.1.22

func NewToolExecutionStartEvent(toolCallID, name string, arguments json.RawMessage) NodeEvent

NewToolExecutionStartEvent creates a tool_execution.start node event.

func NewToolExecutionUpdateEvent added in v0.1.22

func NewToolExecutionUpdateEvent(toolCallID, content string) NodeEvent

NewToolExecutionUpdateEvent creates a tool_execution.update node event.

type NodeEventMetadata added in v0.1.22

type NodeEventMetadata map[string]string

NodeEventMetadata carries typed debug fields. It MUST NOT contain API Key, Authorization Header, or raw environment variables.

type NodeEventPayload added in v0.1.22

type NodeEventPayload interface {
	// contains filtered or unexported methods
}

NodeEventPayload is a sealed set of strongly-typed event payloads. Each concrete payload implements the marker method nodeEventPayload().

type NodeEventType added in v0.1.22

type NodeEventType string

NodeEventType identifies an observable runtime node event emitted during execution.

const (
	NodeEventAgentStart NodeEventType = "agent.start"
	NodeEventAgentEnd   NodeEventType = "agent.end"

	NodeEventMessageStart    NodeEventType = "message.start"
	NodeEventMessageUpdate   NodeEventType = "message.update"
	NodeEventReasoningUpdate NodeEventType = "reasoning.update"
	NodeEventMessageEnd      NodeEventType = "message.end"

	NodeEventToolExecutionStart  NodeEventType = "tool_execution.start"
	NodeEventToolExecutionUpdate NodeEventType = "tool_execution.update"
	NodeEventToolExecutionEnd    NodeEventType = "tool_execution.end"

	NodeEventTodoSnapshot NodeEventType = "todo.snapshot"
	NodeEventTodoUpdated  NodeEventType = "todo.updated"

	NodeEventApprovalRequested NodeEventType = "approval.requested"
	NodeEventApprovalResolved  NodeEventType = "approval.resolved"
	NodeEventQuestionAsked     NodeEventType = "question.asked"
	NodeEventQuestionAnswered  NodeEventType = "question.answered"

	NodeEventPlanReady NodeEventType = "plan.ready"
)

Runtime activity event types emitted by Runtime adapters. Adapters map native provider events into these canonical types.

type NodeObserver added in v0.1.22

type NodeObserver interface {
	Observe(ctx context.Context, event NodeEvent) error
}

NodeObserver receives node events emitted during runtime execution. An observer that returns an error terminates the execution.

type NodeObserverFunc added in v0.1.22

type NodeObserverFunc func(ctx context.Context, event NodeEvent) error

NodeObserverFunc adapts a function to the NodeObserver interface.

func (NodeObserverFunc) Observe added in v0.1.22

func (f NodeObserverFunc) Observe(ctx context.Context, event NodeEvent) error

type PlanReadyPayload added in v0.1.22

type PlanReadyPayload struct {
	Path              string `json:"path"`
	DisplayPath       string `json:"display_path"`
	ProviderSessionID string `json:"provider_session_id,omitempty"`
}

PlanReadyPayload carries the safe path information for a detected plan file. Runtime emits only path info; Worker handles content reading, validation, and upload.

type ProviderSession added in v0.1.22

type ProviderSession struct {
	ID     string
	Resume bool
}

ProviderSession carries pre-resolved provider session information for resume.

type QuestionAnswer

type QuestionAnswer struct {
	RequestID string
	Answers   [][]string
}

QuestionAnswer carries the user's response to a QuestionRequest.

type QuestionAnsweredPayload added in v0.1.22

type QuestionAnsweredPayload struct {
	RequestID string     `json:"request_id"`
	Answers   [][]string `json:"answers"`
}

QuestionAnsweredPayload describes the user's answer to a question request.

type QuestionAskedPayload added in v0.1.22

type QuestionAskedPayload struct {
	RequestID       string            `json:"request_id"`
	SessionID       string            `json:"session_id"`
	Questions       []QuestionItem    `json:"questions"`
	ToolCallID      string            `json:"tool_call_id"`
	MessageID       string            `json:"message_id"`
	InteractionType string            `json:"interaction_type,omitempty"`
	Metadata        map[string]string `json:"metadata,omitempty"`
}

QuestionAskedPayload describes a clarifying question from the runtime.

type QuestionItem

type QuestionItem struct {
	Question    string
	Header      string
	Options     []QuestionOption
	MultiSelect bool
	Custom      bool
}

QuestionItem is a single question in a QuestionRequest.

type QuestionOption

type QuestionOption struct {
	Label       string
	Description string
}

QuestionOption is one option for a QuestionItem.

type QuestionRequest

type QuestionRequest struct {
	RequestID   string
	SessionKey  string
	Questions   []QuestionItem
	ToolCallID  string
	Description string
	Runtime     string
}

QuestionRequest carries one or more questions from a Runtime.

type QuestionResponder added in v0.1.22

type QuestionResponder interface {
	WriteAnswer(requestID string, answers [][]string) error
}

QuestionResponder writes question answers back to a provider runtime.

type ReasoningUpdatePayload added in v0.1.22

type ReasoningUpdatePayload struct {
	MessageID string `json:"message_id"`
	Content   string `json:"content"`
}

ReasoningUpdatePayload carries a reasoning/thinking text update.

type Registry

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

Registry maps runtime kind names to Runtime implementations. It is populated at composition root and is read-only during execution.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new Registry.

func (*Registry) Names

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

Names returns the registered runtime kind names.

func (*Registry) Register

func (r *Registry) Register(name string, rt Runtime)

Register adds a Runtime implementation to the registry. name is normalized to lowercase before storage.

func (*Registry) Resolve

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

Resolve returns the Runtime for the given kind. If kind is empty, the default is returned.

func (*Registry) ResolveWithKind added in v0.1.22

func (r *Registry) ResolveWithKind(kind string) (Runtime, string, error)

ResolveWithKind returns the Runtime and the canonical kind used for lookup. If kind is empty, the configured default kind is returned.

func (*Registry) SetDefault

func (r *Registry) SetDefault(kind string)

SetDefault sets the default runtime kind returned when Resolve receives an empty kind.

type Runtime

type Runtime interface {
	Name() string
	Execute(ctx context.Context, request ExecutionRequest, observer NodeObserver) (ExecutionResult, error)
}

Runtime executes a fully prepared request against a specific provider.

Runtime MUST NOT:

  • Emit run.started, run.completed, run.failed, or run.cancelled events.
  • Mutate ExecutionRequest.
  • Access NATS, messaging, or Session persistence.

type RuntimeAdapterOptions added in v0.1.22

type RuntimeAdapterOptions struct {
	InteractionHandler InteractionHandler
	MCPServers         []MCPServerConfig
}

RuntimeAdapterOptions contains host-provided facilities shared by CLI adapters.

type RuntimeResolver

type RuntimeResolver interface {
	Resolve(kind string) (Runtime, error)
}

RuntimeResolver maps a runtime kind string to a Runtime implementation.

type RuntimeTodoItem added in v0.1.22

type RuntimeTodoItem struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Status   string `json:"status"`
	Priority string `json:"priority,omitempty"`
}

RuntimeTodoItem describes a single runtime planning step.

type SerialObserver added in v0.1.22

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

SerialObserver wraps a NodeObserver to guarantee that all Observe calls are serialized. Concurrent calls from runtime activity (e.g. parallel tool completions) are enqueued and processed in order without blocking the runtime goroutine for longer than the serialization window.

An error from the underlying observer terminates execution — subsequent observes are dropped and the first error is returned.

func NewSerialObserver added in v0.1.22

func NewSerialObserver(inner NodeObserver) *SerialObserver

NewSerialObserver wraps a NodeObserver for serial event delivery.

func (*SerialObserver) Err added in v0.1.22

func (s *SerialObserver) Err() error

Err returns the first observer error, if any.

func (*SerialObserver) Inner added in v0.1.22

func (s *SerialObserver) Inner() NodeObserver

Inner returns the wrapped observer for inspection in tests.

func (*SerialObserver) Observe added in v0.1.22

func (s *SerialObserver) Observe(ctx context.Context, event NodeEvent) error

Observe serializes access to the underlying observer. After the first error, subsequent calls are dropped and return the stored error.

type TodoReporter added in v0.1.22

type TodoReporter interface {
	Snapshot(ctx context.Context, items []RuntimeTodoItem) error
	Update(ctx context.Context, items []RuntimeTodoItem, merge bool) error
	List() []RuntimeTodoItem
}

TodoReporter exposes one execution's current runtime todo state to tools.

func TodoReporterFrom added in v0.1.22

func TodoReporterFrom(ctx context.Context) (TodoReporter, bool)

TodoReporterFrom returns the runtime todo reporter attached to a tool context.

type TodoSnapshotPayload added in v0.1.22

type TodoSnapshotPayload struct {
	Items []RuntimeTodoItem `json:"items"`
}

TodoSnapshotPayload carries a complete todo list snapshot.

type TodoUpdatedPayload added in v0.1.22

type TodoUpdatedPayload struct {
	Items []RuntimeTodoItem `json:"items"`
}

TodoUpdatedPayload carries an updated complete todo list.

type Tool

type Tool interface {
	// Definition returns the tool metadata (name, description, parameters schema).
	Definition() ToolDefinition

	// Execute runs the tool with the given JSON input.
	Execute(ctx context.Context, input json.RawMessage) (ToolResult, error)
}

Tool is the contract for a callable tool within an agent Runtime. Implementations decode json.RawMessage into a typed request struct, execute the operation, and return a ToolResult.

type ToolCallRecord

type ToolCallRecord struct {
	CallID string          `json:"call_id,omitempty"`
	Name   string          `json:"name,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  string          `json:"error,omitempty"`
}

ToolCallRecord is a compact final tool call summary.

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters,omitempty"`
}

ToolDefinition describes a tool exposed to a Runtime.

type ToolExecutionEndPayload added in v0.1.22

type ToolExecutionEndPayload struct {
	ToolCallID string          `json:"tool_call_id"`
	Name       string          `json:"name"`
	IsError    bool            `json:"is_error"`
	Error      string          `json:"error,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	ElapsedMS  int64           `json:"elapsed_ms,omitempty"`
}

ToolExecutionEndPayload carries the result of a tool execution (success or failure).

type ToolExecutionStartPayload added in v0.1.22

type ToolExecutionStartPayload struct {
	ToolCallID string          `json:"tool_call_id"`
	Name       string          `json:"name"`
	Arguments  json.RawMessage `json:"arguments,omitempty"`
}

ToolExecutionStartPayload carries the start of a tool execution.

type ToolExecutionUpdatePayload added in v0.1.22

type ToolExecutionUpdatePayload struct {
	ToolCallID string `json:"tool_call_id"`
	Content    string `json:"content"`
}

ToolExecutionUpdatePayload carries incremental tool execution content.

type ToolResult

type ToolResult struct {
	Content string `json:"content,omitempty"`
	Error   string `json:"error,omitempty"`
	IsError bool   `json:"is_error"`
}

ToolResult is the result returned by a tool execution.

type Usage

type Usage struct {
	TotalTokens       int `json:"total_tokens"`
	InputTokens       int `json:"input_tokens"`
	OutputTokens      int `json:"output_tokens"`
	CacheInputTokens  int `json:"cache_input_tokens"`
	CacheOutputTokens int `json:"cache_output_tokens"`
}

Usage describes model token usage when available.

func EnsureUsage added in v0.1.22

func EnsureUsage(usage *Usage) *Usage

EnsureUsage returns a non-nil usage object with TotalTokens normalized to input + output.

Directories

Path Synopsis
runtime
claude
Package claude adapts Claude Code to the agent Runtime contract.
Package claude adapts Claude Code to the agent Runtime contract.
codex
Package codex adapts the Codex CLI to the agent Runtime contract.
Package codex adapts the Codex CLI to the agent Runtime contract.
internal/cli
Package cli provides shared CLI process infrastructure for external agent runtimes.
Package cli provides shared CLI process infrastructure for external agent runtimes.
native
Package native implements the built-in Eino-backed Leros runtime.
Package native implements the built-in Eino-backed Leros runtime.
opencode
Package opencode adapts the OpenCode CLI to the agent Runtime contract.
Package opencode adapts the OpenCode CLI to the agent Runtime contract.

Jump to

Keyboard shortcuts

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