executor

package
v0.14.3 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package executor provides environment setup utilities shared across all AI executors.

Package executor provides a unified interface for AI coding agent executors. This enables AILANG to use multiple AI backends (Claude Code, Gemini CLI, etc.) through a common interface for directive execution and benchmarking.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildEnvironment

func BuildEnvironment(opts EnvironmentOptions) []string

BuildEnvironment creates the common environment variables for AI executor processes. This consolidates the duplicated setup code from claude.go and gemini.go.

The environment includes:

  • AILANG_STDLIB_PATH: Path to AILANG standard library
  • PWD: Working directory (if workspace specified)
  • TRACEPARENT: W3C trace context for distributed tracing
  • AILANG_TASK_ID, AILANG_SESSION_ID: Correlation IDs
  • AILANG_PARENT_TASK_ID: Parent task for hierarchy tracking
  • AILANG_CHAIN_ID, AILANG_STAGE_ID: Execution chain context (M-CHAINS-SIMPLIFY)
  • AILANG_MESSAGE_ID: Source message that triggered this chain
  • OTEL_RESOURCE_ATTRIBUTES: Resource attributes for trace linking
  • OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint for trace collection
  • GOOGLE_CLOUD_PROJECT: GCP project for cloud tracing

func BuildResourceAttributes

func BuildResourceAttributes(task *Task, sessionID string) string

BuildResourceAttributes creates OTEL_RESOURCE_ATTRIBUTES value. Merges existing attributes from environment with task-specific attributes. Priority: existing env attrs + task Metadata + default attrs.

func FindNVMBinary

func FindNVMBinary(binaryName string) string

FindNVMBinary scans ~/.nvm/versions/node/ for a binary by name, trying the newest Node version first. Returns the full path if found, or empty string. This avoids hardcoding a specific Node version (e.g., v22.20.0) that breaks when NVM upgrades.

func FindNVMNodeBinDir

func FindNVMNodeBinDir(binaryName string) string

FindNVMNodeBinDir returns the bin/ directory for the newest NVM Node version that contains the given binary. Useful for adding to PATH so all Node tools in that version are available.

func FindNativeBinary

func FindNativeBinary(binaryName string) string

FindNativeBinary looks for a native (non-Node.js) binary installed by the VSCode Claude Code extension. Returns the absolute path, or empty string. The native binary is a Mach-O/ELF executable that does not require Node, making it the preferred option when available.

func GetClaudeSettingsPath

func GetClaudeSettingsPath() (string, error)

GetClaudeSettingsPath returns the path to the AILANG-specific Claude settings file. Creates the settings file with hooks configuration if it doesn't exist. The settings and hook script are embedded in the binary from scripts/hooks/.

func RemoveEnvVar

func RemoveEnvVar(env []string, key string) []string

RemoveEnvVar removes all entries for the given environment variable key.

func SetGlobalFactory

func SetGlobalFactory(f *ExecutorFactory)

SetGlobalFactory sets the global factory (for testing)

func UpdateEnvVar

func UpdateEnvVar(env []string, key, value string) []string

UpdateEnvVar updates or appends an environment variable in the given slice.

Types

type Capability

type Capability string

Capability flags for feature detection

const (
	CapStreaming         Capability = "streaming"
	CapToolControl       Capability = "tool_control"
	CapSessionResume     Capability = "session_resume"
	CapApprovalFlow      Capability = "approval_flow"
	CapGitHubIntegration Capability = "github_integration"
	CapLocalWorkspace    Capability = "local_workspace"
	CapStructuredOutput  Capability = "structured_output"
)

type Config

type Config struct {
	// Default executor to use when none specified
	DefaultExecutor string

	// Claude configuration
	ClaudePath       string   // Path to claude CLI binary
	ClaudeModel      string   // Default Claude model
	ClaudeTools      []string // Allowed tools for Claude
	ClaudePermission string   // Permission mode (bypassPermissions, etc.)

	// Gemini configuration
	GeminiPath  string // Path to gemini CLI binary
	GeminiModel string // Default Gemini model
	GeminiTools []string

	// Codex configuration
	CodexPath  string // Path to codex CLI binary
	CodexModel string // Default Codex model

	// opencode configuration
	OpenCodePath  string // Path to opencode CLI binary
	OpenCodeModel string // Default opencode model (provider/model format)

	// pi configuration
	PiPath  string // Path to pi CLI binary
	PiModel string // Default pi model (provider/model format)

	// Common settings
	TimeoutSeconds int
	WorkspaceDir   string
}

Config holds configuration for all executors

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a config with sensible defaults

type ContextAwareHandler

type ContextAwareHandler interface {
	EventHandler
	SetContext(ctx context.Context)
}

ContextAwareHandler is an optional interface for handlers that need the executor's trace context for proper span hierarchy. When implemented, the executor calls SetContext after creating its span, so child spans created by the handler are properly nested.

type CostModel

type CostModel struct {
	ProviderName    string
	InputTokenCost  float64 // Cost per 1K input tokens
	OutputTokenCost float64 // Cost per 1K output tokens
	CacheReadCost   float64 // Cost per 1K cache read tokens
	CacheWriteCost  float64 // Cost per 1K cache write tokens
	MinimumCharge   float64 // Minimum per-request charge
}

CostModel contains pricing information

func (*CostModel) CalculateCost

func (c *CostModel) CalculateCost(usage TokenUsage) float64

CalculateCost computes total cost from token usage

type EnvironmentOptions

type EnvironmentOptions struct {
	// Task is the task being executed
	Task *Task

	// SessionID is the unique session identifier
	SessionID string

	// Context is used for trace context extraction
	Context context.Context

	// EnableClaudeTelemetry enables Claude Code specific telemetry vars
	EnableClaudeTelemetry bool

	// EnableGeminiTelemetry enables Gemini CLI specific telemetry vars
	EnableGeminiTelemetry bool

	// GCPProject overrides GOOGLE_CLOUD_PROJECT for this subprocess.
	// When empty, falls back to the shell environment value.
	GCPProject string

	// GCPLocation overrides GOOGLE_CLOUD_LOCATION for this subprocess.
	// When empty, falls back to the shell environment value.
	GCPLocation string
}

EnvironmentOptions configures the environment building process.

type EventHandler

type EventHandler interface {
	OnTurnStart(turnNum int)
	OnText(text string)
	OnToolUse(toolName string, input string)
	OnToolResult(toolName string, output string)
	OnTurnEnd(turnNum int)
	OnError(err error)
}

EventHandler receives streaming events during execution

type ExecutionMetrics

type ExecutionMetrics struct {
	NumTurns     int
	InputTokens  int
	OutputTokens int
	CostUSD      float64
	DurationMS   int
	SessionID    string
	Success      bool
}

ExecutionMetrics contains cost and token data from the executor.

type Executor

type Executor interface {
	// Name returns the executor identifier (e.g., "claude", "gemini", "codex")
	Name() string

	// Execute runs a task and returns the result
	Execute(ctx context.Context, task *Task) (*Result, error)

	// ExecuteStreaming runs a task with real-time event callbacks
	ExecuteStreaming(ctx context.Context, task *Task, handler EventHandler) (*Result, error)

	// Capabilities returns the list of features this executor supports
	Capabilities() []Capability

	// CostModel returns pricing information for cost calculations
	CostModel() *CostModel

	// HealthCheck verifies the executor is configured and accessible
	HealthCheck(ctx context.Context) error

	// Close releases any resources held by the executor
	Close() error
}

Executor is the common interface for all AI coding agent executors. Each provider (Claude, Gemini, Codex) implements this interface.

type ExecutorBuilder

type ExecutorBuilder func(cfg *Config) (Executor, error)

ExecutorBuilder is a function that creates an executor from config

type ExecutorFactory

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

ExecutorFactory creates and manages executor instances

func GlobalFactory

func GlobalFactory() *ExecutorFactory

GlobalFactory returns the global executor factory

func NewFactory

func NewFactory(cfg *Config) *ExecutorFactory

NewFactory creates a new executor factory

func (*ExecutorFactory) Close

func (f *ExecutorFactory) Close() error

Close closes all created executors

func (*ExecutorFactory) GetDefault

func (f *ExecutorFactory) GetDefault() (Executor, error)

GetDefault returns the default executor

func (*ExecutorFactory) GetExecutor

func (f *ExecutorFactory) GetExecutor(name string) (Executor, error)

GetExecutor returns an executor by name, creating it if needed

func (*ExecutorFactory) ListAvailable

func (f *ExecutorFactory) ListAvailable() []string

ListAvailable returns names of all registered executors

func (*ExecutorFactory) Register

func (f *ExecutorFactory) Register(name string, builder ExecutorBuilder)

Register adds an executor builder to the factory

func (*ExecutorFactory) UpdateConfig

func (f *ExecutorFactory) UpdateConfig(fn func(*Config))

UpdateConfig applies a mutation to the factory's config. Must be called before GetExecutor() for the executor to use the updated config.

type MetricsHandler

type MetricsHandler interface {
	EventHandler
	OnMetrics(metrics ExecutionMetrics)
}

MetricsHandler is an optional interface for handlers that want execution metrics. When implemented, the executor calls OnMetrics after parsing the final result, allowing the handler to broadcast cost/token data before the executor returns. This is used by the cloud event handler to publish cost data to Pub/Sub.

type NoOpEventHandler

type NoOpEventHandler struct{}

NoOpEventHandler is a no-op implementation of EventHandler

func (*NoOpEventHandler) OnError

func (h *NoOpEventHandler) OnError(err error)

func (*NoOpEventHandler) OnText

func (h *NoOpEventHandler) OnText(text string)

func (*NoOpEventHandler) OnToolResult

func (h *NoOpEventHandler) OnToolResult(toolName string, output string)

func (*NoOpEventHandler) OnToolUse

func (h *NoOpEventHandler) OnToolUse(toolName string, input string)

func (*NoOpEventHandler) OnTurnEnd

func (h *NoOpEventHandler) OnTurnEnd(turnNum int)

func (*NoOpEventHandler) OnTurnStart

func (h *NoOpEventHandler) OnTurnStart(turnNum int)

type PluginsConfig

type PluginsConfig struct {
	Marketplaces []string // Marketplaces to register (e.g., "anthropics/claude-code")
	Install      []string // Plugins to install (e.g., "frontend-design@anthropics-claude-code")
}

PluginsConfig specifies third-party plugins to install before execution. This is a copy of coordinator.PluginsConfig to avoid circular imports.

type Result

type Result struct {
	Success bool   // Overall success
	Output  string // Final text output from agent
	Error   string // Error message if failed

	// Metrics
	DurationMS    int     // Total execution time in milliseconds
	NumTurns      int     // Conversation turns
	ToolCallCount int     // Number of tool invocations (file edits, bash, etc.)
	CostUSD       float64 // Total cost in USD

	// Token usage
	InputTokens              int
	OutputTokens             int
	CacheReadInputTokens     int
	CacheCreationInputTokens int

	// Session info
	SessionID  string // Provider's session identifier
	Transcript string // Full conversation log

	// Artifacts
	FilesCreated  []string // Files created in workspace
	FilesModified []string // Files modified

	// Provider-specific data
	ProviderData map[string]any // Raw provider response data
}

Result is the normalized execution result

type Task

type Task struct {
	ID           string            // Unique task identifier
	ParentTaskID string            // Parent task ID for hierarchy tracking (M-TASK-HIERARCHY)
	Directive    string            // The instruction/prompt
	SystemPrompt string            // Optional system-level context
	Workspace    string            // Working directory (local path)
	Timeout      time.Duration     // Hard ceiling execution timeout
	IdleTimeout  time.Duration     // Kill if no events for this long after first event (0 = use default 3m)
	TTFTTimeout  time.Duration     // Kill if no output before first event (prefill budget; 0 = use default 30s)
	AllowedTools []string          // Tools the agent can use
	Model        string            // Model to use (provider-specific)
	Metadata     map[string]string // Provider-specific options

	// Effort level (Claude Code 2.1.47+: "low", "medium", "high")
	Effort string

	// Plugin directories for Claude Code (M-CLOUD-PLUGIN-SKILLS, v0.9.1)
	// Each entry is a path to a plugin directory containing .claude-plugin/plugin.json.
	// Passed as --plugin-dir flags to Claude CLI.
	PluginDirs []string

	// Plugins specifies third-party plugins to install before execution (M-CLOUD-PLUGIN-SKILLS, v0.9.1).
	// Marketplaces are registered first, then plugins installed from those marketplaces.
	Plugins *PluginsConfig

	// Session continuity (M-TRANSCRIPT)
	Iteration       int    // Iteration number (1 = first run, 2+ = re-run with feedback)
	ResumeSessionID string // Previous session ID to resume (for Iteration > 1)

	// GCP override — when set, overrides GOOGLE_CLOUD_PROJECT/LOCATION env vars
	// for the subprocess. Populated from models.yml gcp_project / gcp_location fields.
	GCPProject  string
	GCPLocation string
}

Task represents a coding task to execute

type TokenUsage

type TokenUsage struct {
	InputTokens              int
	OutputTokens             int
	CacheReadInputTokens     int
	CacheCreationInputTokens int
}

TokenUsage captures token metrics

Directories

Path Synopsis
Package claude provides an Executor implementation for Claude Code CLI.
Package claude provides an Executor implementation for Claude Code CLI.
Package codex provides an Executor implementation for OpenAI Codex CLI.
Package codex provides an Executor implementation for OpenAI Codex CLI.
Package gemini provides an Executor implementation for Gemini CLI.
Package gemini provides an Executor implementation for Gemini CLI.
Package opencode provides an Executor implementation for the opencode CLI.
Package opencode provides an Executor implementation for the opencode CLI.
Package pi provides an Executor implementation for the pi CLI (npm: @mariozechner/pi-coding-agent), a deliberately minimal Claude Agent SDK-based coding harness with broad multi-provider reach.
Package pi provides an Executor implementation for the pi CLI (npm: @mariozechner/pi-coding-agent), a deliberately minimal Claude Agent SDK-based coding harness with broad multi-provider reach.

Jump to

Keyboard shortcuts

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