types

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ModelCacheTTL           = 5 * time.Minute
	HealthCheckInterval     = 60 * time.Second
	MaxFileSize             = 5 * 1024 * 1024
	MaxToolOutputChars      = 10_000
	MaxHealAttempts         = 2
	MaxPlanRetries          = 3
	MaxPlanRefinements      = 5
	SessionIDLength         = 8
	AutoDreamThreshold      = 0.60
	ContextWarningThreshold = 0.80
	HTTPDialTimeout         = 30 * time.Second
	BashTimeout             = 30 * time.Minute
	BashOutputLimit         = 50_000
	DefaultContextLength    = 128_000
	MaxLLMResponseBytes     = 1 << 20
	// MaxSessionFileSize is the maximum allowed size for session files
	// (session.json, messages.json, checkpoint.json) to prevent OOM from
	// corrupted or maliciously crafted files (WP-H05).
	MaxSessionFileSize = 50 * 1024 * 1024 // 50 MB
	// DefaultPermissionTimeout is the default permission modal timeout in seconds.
	// Used by both the TUI permission modal and the tool dispatcher.
	DefaultPermissionTimeout = 300
	// StaleCacheTTL is the fallback TTL for stale model cache entries.
	StaleCacheTTL = 24 * time.Hour
	// DefaultHealthLiveMs is the default health check latency threshold for "live" status.
	DefaultHealthLiveMs = 500
	// DefaultHealthSlowMs is the default health check latency threshold for "slow" status.
	DefaultHealthSlowMs = 2000

	// Health status string constants
	HealthStatusLive     = "live"
	HealthStatusSlow     = "slow"
	HealthStatusOffline  = "offline"
	HealthStatusDegraded = "degraded"

	// MaxProviderErrorChars is the max chars for sanitized provider errors
	MaxProviderErrorChars = 200

	// DefaultOpenRouterBaseURL is the default OpenRouter API base URL
	DefaultOpenRouterBaseURL = "https://openrouter.ai/api/v1"

	// DefaultZenBaseURL is the default Zen API base URL
	DefaultZenBaseURL = "https://opencode.ai/zen/v1"

	// DefaultNvidiaBaseURL is the default NVIDIA NIM API base URL
	DefaultNvidiaBaseURL = "https://integrate.api.nvidia.com/v1"

	// DefaultReferer is the default HTTP-Referer header for OpenRouter
	DefaultReferer = "https://github.com/eshanized/M31A"

	// DefaultMaxRecentModels is the default number of recent models to remember
	DefaultMaxRecentModels = 10

	// DirPermission is the default directory permission (0755)
	DirPermission = 0755
	// FilePermission is the default file permission (0644)
	FilePermission = 0644

	// Tool default values (referenced by internal/tools/constants.go)
	DefaultMaxGlobResults       = 1000
	DefaultMaxGrepResults       = 100
	DefaultBashKillGraceSecs    = 5
	DefaultMaxBackupsPerFile    = 10
	DefaultWebfetchMaxRedirects = 5

	// CompressCooldown is the cooldown between /compress commands
	CompressCooldown = 60 * time.Second
	// ChannelSendTimeout is the timeout for sending on tea.Cmd channels
	ChannelSendTimeout = 500 * time.Millisecond
	// ToastDuration is how long toast messages display
	ToastDuration = 10 * time.Second

	// FetchModelsTimeout is the timeout for fetching model catalogs
	FetchModelsTimeout = 15 * time.Second
	// HealthCheckRetryDelay is the delay before retrying a failed health check
	HealthCheckRetryDelay = 5 * time.Second
	// MaxRetryAfterWait is the maximum wait time for retry-after headers
	MaxRetryAfterWait = 120 * time.Second

	// EMACorrectionAlpha is the default EMA correction rate for token estimation calibration.
	EMACorrectionAlpha = 0.3

	// MaxToolsPerCall is the max tool calls allowed per LLM response
	MaxToolsPerCall = 16
	// MaxCwdFileDepth is the max directory depth for cwd file schema
	MaxCwdFileDepth = 3

	// ConfigWatchInterval is the interval for watching config file changes
	ConfigWatchInterval = 5 * time.Second
	// MaxProjectConfigDepth is the max parent directory depth for project config discovery
	MaxProjectConfigDepth = 3

	// DefaultSessionCacheTTL is the default TTL for the session list cache.
	DefaultSessionCacheTTL = 2 * time.Second

	// DefaultVerifyTimeout is the default timeout for a single verify phase task.
	DefaultVerifyTimeout = 5 * time.Minute

	// DefaultFetchModelsTimeout is an alias for FetchModelsTimeout (M-32: removed duplicate constant).
	DefaultFetchModelsTimeout = FetchModelsTimeout

	// DefaultUserAgent is the default User-Agent header for API requests
	DefaultUserAgent = "M31A/dev"
	// DefaultXTitle is the default X-Title header for OpenRouter
	DefaultXTitle = "M31A"
	// DateFormat is the standard date format used across the application
	DateFormat = "2006-01-02"
	// DateTimeFormat is the date+time format used for file listings
	DateTimeFormat = "2006-01-02 15:04"

	// DefaultMaxParallelTasks is the default maximum number of tasks to execute
	// concurrently within a group. Configurable via Runner.MaxParallel.
	DefaultMaxParallelTasks = 4
)
View Source
const (
	FileActionCreate = "create"
	FileActionModify = "modify"
	FileActionDelete = "delete"
)

FilePrediction action constants for consistent action values.

Variables

View Source
var SkipDirs = []string{"node_modules", "vendor", ".next", "dist", "build", "target", ".venv", "venv", "__pycache__"}

SkipDirs is the list of directories to skip during file traversal.

Functions

func SkipDirsMap

func SkipDirsMap() map[string]bool

SkipDirsMap returns a cached map for O(1) lookup of skip directories. Computed lazily on first access via sync.Once.

Types

type ArchInfo

type ArchInfo struct {
	TokenizerFamily string `json:"tokenizer_family"`
}

type CapFlags

type CapFlags struct {
	Tools     bool `json:"tools"`
	Reasoning bool `json:"reasoning"`
	Vision    bool `json:"vision"`
	Chat      bool `json:"chat"`
}

type CommitInfo

type CommitInfo struct {
	Hash      string    `json:"hash"`
	ShortHash string    `json:"short_hash"`
	Author    string    `json:"author"`
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
}

CommitInfo represents metadata about a git commit.

type ComplexityLevel

type ComplexityLevel string

ComplexityLevel represents the estimated complexity of a user's goal.

const (
	ComplexityTrivial  ComplexityLevel = "trivial"
	ComplexitySimple   ComplexityLevel = "simple"
	ComplexityModerate ComplexityLevel = "moderate"
	ComplexityComplex  ComplexityLevel = "complex"
)

type GitClient

type GitClient interface {
	Init() error
	IsRepo() bool
	Add(paths ...string) error
	AddAll() error
	Commit(message string) error
	Log(lastN int) ([]CommitInfo, error)
	LogSince(since time.Time) ([]CommitInfo, error)
	Diff(target ...string) (string, error)
	DiffStat(target ...string) (string, error)
	CurrentBranch() (string, error)
	RevParse(ref string) (string, error)
	IsDirty() (bool, error)
	HasUncommittedChanges() (bool, error)
	Run(args ...string) (string, error)
}

GitClient abstracts git operations for testability. Consumers (rollback, bisect, workflow) should depend on this interface rather than the concrete *git.Git implementation.

type HealthStatus

type HealthStatus struct {
	Status    string `json:"status"`
	LatencyMs int64  `json:"latency_ms"`
	Error     string `json:"error,omitempty"`
}

type IntentResult added in v1.2.0

type IntentResult struct {
	Intent     IntentType      `json:"intent"`
	Complexity ComplexityLevel `json:"complexity"`
	Confidence float64         `json:"confidence"`
	Scope      []string        `json:"scope"`
	Summary    string          `json:"summary"`
}

IntentResult holds the outcome of LLM-based intent classification.

func (IntentResult) IsWorkflowWorthy added in v1.2.0

func (ir IntentResult) IsWorkflowWorthy() bool

IsWorkflowWorthy returns true if the intent should trigger a structured workflow.

type IntentType added in v1.2.0

type IntentType string

IntentType classifies the user's prompt intent for routing.

const (
	IntentFeature     IntentType = "feature"
	IntentBugfix      IntentType = "bugfix"
	IntentRefactor    IntentType = "refactor"
	IntentQuestion    IntentType = "question"
	IntentExplanation IntentType = "explanation"
	IntentExploration IntentType = "exploration"
	IntentChore       IntentType = "chore"
)

type Message

type Message struct {
	Role       string           `json:"role"`
	Content    string           `json:"content"`
	Segments   []MessageSegment `json:"segments"`
	ToolCalls  []ToolCall       `json:"tool_calls,omitempty"`
	ToolCallID string           `json:"tool_call_id,omitempty"`
	Usage      *Usage           `json:"usage,omitempty"`
	CreatedAt  time.Time        `json:"created_at"`
	SkipForLLM bool             `json:"skip_for_llm,omitempty"`
}

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON ensures Segments is never serialized as null by initializing a nil slice to an empty slice before default marshaling.

type MessageSegment

type MessageSegment struct {
	Type       string    `json:"type"`
	Content    string    `json:"content"`
	DurationMs int64     `json:"duration_ms"`
	Visible    bool      `json:"visible"`
	StartedAt  time.Time `json:"started_at,omitempty"`
}

type ModelInfo

type ModelInfo struct {
	ID            string   `json:"id"`
	Provider      string   `json:"provider"`
	Name          string   `json:"name"`
	Description   string   `json:"description"`
	ContextLength int64    `json:"context_length"`
	Pricing       Pricing  `json:"pricing"`
	Architecture  ArchInfo `json:"architecture"`
	TopProvider   string   `json:"top_provider"`
	Capabilities  CapFlags `json:"capabilities"`
	Variant       *string  `json:"variant,omitempty"` // nil by default; "thinking", "fast", "extended", "vision"
}

type OpenQuestion

type OpenQuestion struct {
	Question   string `json:"question"`
	Suggestion string `json:"suggestion,omitempty"`
}

OpenQuestion represents a question the plan raises for the user, optionally with a suggested default answer.

type Plan

type Plan struct {
	Title           string                `json:"title"`
	Summary         string                `json:"summary"`
	ReviewNotes     []ReviewNote          `json:"review_notes,omitempty"`
	OpenQuestions   []OpenQuestion        `json:"open_questions,omitempty"`
	ProposedChanges []ProposedChangeGroup `json:"proposed_changes,omitempty"`
	Verification    VerificationPlan      `json:"verification_plan"`
	Tasks           []Task                `json:"tasks"`
	Version         int                   `json:"version"`
	RawMarkdown     string                `json:"raw_markdown"`
	CreatedAt       time.Time             `json:"created_at"`
}

Plan represents a rich implementation plan generated by the Plan phase. It contains human-readable sections describing the approach, proposed changes, open questions, and verification strategy, along with the machine-parseable task list extracted from the document.

type Pricing

type Pricing struct {
	InputPerMToken  float64 `json:"input_per_m_token"`
	OutputPerMToken float64 `json:"output_per_m_token"`
}

type ProjectState

type ProjectState struct {
	Goal        string            `json:"goal"`
	ProjectType string            `json:"project_type"`
	Framework   string            `json:"framework"`
	Answers     map[string]string `json:"answers"`
	CreatedAt   time.Time         `json:"created_at"`
}

type ProposedChange

type ProposedChange struct {
	Action      string `json:"action"` // "NEW" or "MODIFY"
	File        string `json:"file"`
	Description string `json:"description"`
}

ProposedChange describes a single file to create or modify, with a human-readable description of what the change accomplishes.

type ProposedChangeGroup

type ProposedChangeGroup struct {
	Category string           `json:"category"`
	Changes  []ProposedChange `json:"changes"`
}

ProposedChangeGroup groups related file changes under a category heading (e.g., "Setup & Configuration", "Core Components").

type ReviewNote

type ReviewNote struct {
	Level string `json:"level"`
	Text  string `json:"text"`
}

ReviewNote represents a "User Review Required" callout in the plan. Level is typically "IMPORTANT" or "WARNING".

type RiskLevel

type RiskLevel string
const (
	RiskSafe        RiskLevel = "safe"
	RiskMedium      RiskLevel = "medium"
	RiskDangerous   RiskLevel = "dangerous"
	RiskDestructive RiskLevel = "destructive"
)

type SchemaProvider

type SchemaProvider interface {
	ParameterSchema() string
}

SchemaProvider is an optional interface that tools can implement to provide JSON Schema parameter definitions to the LLM. Tools that implement this interface will have their schemas included in tool definitions sent to the provider.

type Session

type Session struct {
	ID            string        `json:"id"`
	ParentID      string        `json:"parent_id,omitempty"`
	ChildrenIDs   []string      `json:"children_ids,omitempty"`
	Label         string        `json:"label,omitempty"`
	Tags          []string      `json:"tags,omitempty"`
	Model         string        `json:"model"`
	Provider      string        `json:"provider"`
	StartedAt     time.Time     `json:"started_at"`
	MessageCount  int           `json:"message_count"`
	WorkflowPhase WorkflowPhase `json:"workflow_phase"`
	Project       *ProjectState `json:"project,omitempty"`
}

type StreamChunk

type StreamChunk struct {
	Type             string `json:"type"`
	Delta            string `json:"delta"`
	ThinkingDuration int64  `json:"thinking_duration"`
	Usage            *Usage `json:"usage,omitempty"`
	ToolCallID       string `json:"tool_call_id,omitempty"`
	ToolName         string `json:"tool_name,omitempty"`
	ToolInput        string `json:"tool_input,omitempty"`
	Index            int    `json:"index,omitempty"`
}

type StreamChunkMsg

type StreamChunkMsg struct {
	Chunk  *StreamChunk
	Source string // "discuss", "plan", "execute", etc.
}

StreamChunkMsg is emitted by workflow phases that stream LLM responses (currently only the Discuss phase). The TUI renders each chunk in the active screen via the REPL streaming infrastructure.

type StreamIterator

type StreamIterator struct {
	Next  func() (*StreamChunk, error)
	Close func() error
}

type Task

type Task struct {
	ID                 int        `json:"id"`
	Description        string     `json:"description"`
	Action             string     `json:"action"`
	Category           string     `json:"category,omitempty"`
	PlanSection        string     `json:"plan_section,omitempty"`
	Dependencies       []int      `json:"dependencies"`
	Files              []string   `json:"files"`
	AcceptanceCriteria []string   `json:"acceptance_criteria"`
	Status             TaskStatus `json:"status"`
	HealsAttempted     int        `json:"heals_attempted"`
	CommitHash         string     `json:"commit_hash,omitempty"`
}

func (*Task) ClampHealsAttempted

func (t *Task) ClampHealsAttempted()

ClampHealsAttempted ensures HealsAttempted does not exceed MaxHealAttempts. Call this after incrementing HealsAttempted to enforce the type-level bound.

type TaskStatus

type TaskStatus string
const (
	StatusPending       TaskStatus = "pending"
	StatusRunning       TaskStatus = "running"
	StatusDone          TaskStatus = "done"
	StatusFailed        TaskStatus = "failed"
	StatusSkipped       TaskStatus = "skipped"
	StatusUnrecoverable TaskStatus = "unrecoverable"
)

type Tool

type Tool interface {
	Name() string
	Description() string
	RiskLevel() RiskLevel
	Execute(ctx context.Context, input ToolInput) (ToolResult, error)
}

type ToolCall

type ToolCall struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

type ToolError added in v1.2.0

type ToolError struct {
	Err  error  // The underlying error message
	Hint string // Actionable hint for the LLM to recover
}

ToolError is a structured error type that carries both an error message and a hint for LLM self-recovery. Tools should return this when they want to provide actionable guidance alongside the error.

func NewToolError added in v1.2.0

func NewToolError(err error, hint string) *ToolError

NewToolError creates a new ToolError with an error and hint.

func (*ToolError) Error added in v1.2.0

func (e *ToolError) Error() string

func (*ToolError) Unwrap added in v1.2.0

func (e *ToolError) Unwrap() error

type ToolInput

type ToolInput struct {
	Name   string         `json:"name"`
	Params map[string]any `json:"params"`
}

type ToolResult

type ToolResult struct {
	ToolCallID string `json:"tool_call_id"`
	Output     string `json:"output"`
	Error      string `json:"error,omitempty"`
	DurationMs int64  `json:"duration_ms"`
	Truncated  bool   `json:"truncated"`
}

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

type VerificationPlan

type VerificationPlan struct {
	Automated []string `json:"automated,omitempty"`
	Manual    []string `json:"manual,omitempty"`
}

VerificationPlan describes how the implementation will be validated. Automated steps are run programmatically; manual steps require user action.

type WorkflowMode

type WorkflowMode string

WorkflowMode controls how aggressively the workflow skips phases.

const (
	ModeAuto   WorkflowMode = "auto"   // classify and choose automatically (default)
	ModeFull   WorkflowMode = "full"   // all 6 phases: Init→Discuss→Plan→Exec→Verify→Ship
	ModeFast   WorkflowMode = "fast"   // skip Plan: Init→Discuss→Exec→Verify→Ship
	ModeDirect WorkflowMode = "direct" // skip Discuss, Plan, Verify: Init→Exec→Ship
)

func WorkflowModeForIntent added in v1.2.0

func WorkflowModeForIntent(ir IntentResult) WorkflowMode

WorkflowModeForIntent returns the recommended workflow mode for an intent result.

func WorkflowModeForIntentComplexity added in v1.2.0

func WorkflowModeForIntentComplexity(c ComplexityLevel) WorkflowMode

WorkflowModeForIntentComplexity maps complexity to workflow mode (intent-aware).

type WorkflowPhase

type WorkflowPhase string
const (
	PhaseIdle       WorkflowPhase = "idle"
	PhaseInitialize WorkflowPhase = "initialize"
	PhaseDiscuss    WorkflowPhase = "discuss"
	PhasePlan       WorkflowPhase = "plan"
	PhaseExecute    WorkflowPhase = "execute"
	PhaseVerify     WorkflowPhase = "verify"
	PhaseShip       WorkflowPhase = "ship"
)

Jump to

Keyboard shortcuts

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