Documentation
¶
Index ¶
- Constants
- Variables
- func SkipDirsMap() map[string]bool
- type ArchInfo
- type CapFlags
- type CommitInfo
- type ComplexityLevel
- type DiffSummary
- type FileDiff
- type GitClient
- type HealthStatus
- type IntentResult
- type IntentType
- type Message
- type MessageSegment
- type ModelInfo
- type OpenQuestion
- type Plan
- type Pricing
- type ProjectState
- type ProposedChange
- type ProposedChangeGroup
- type ReviewNote
- type RiskLevel
- type SchemaProvider
- type Session
- type StreamChunk
- type StreamChunkMsg
- type StreamIterator
- type Task
- type TaskStatus
- type Tool
- type ToolCall
- type ToolCallAcc
- type ToolError
- type ToolInput
- type ToolResult
- type Usage
- type VerificationPlan
- type WorkflowMode
- type WorkflowPhase
Constants ¶
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 // Tool output bounding defaults DefaultOutputMaxLines = 2000 DefaultOutputMaxBytes = 51200 // 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 )
const ( FileActionCreate = "create" FileActionModify = "modify" FileActionDelete = "delete" )
FilePrediction action constants for consistent action values.
const MessageCompaction = "compaction"
MessageCompaction is the segment type for auto-compaction summaries.
Variables ¶
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 ¶
SkipDirsMap returns a cached map for O(1) lookup of skip directories. Computed lazily on first access via sync.Once.
Types ¶
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 DiffSummary ¶ added in v1.3.0
type DiffSummary struct {
Files []FileDiff `json:"files"`
Additions int `json:"additions"`
Deletions int `json:"deletions"`
}
DiffSummary holds the diff footprint of a session turn.
type FileDiff ¶ added in v1.3.0
type FileDiff struct {
File string `json:"file"`
Status string `json:"status"` // added, deleted, modified
Additions int `json:"additions"`
Deletions int `json:"deletions"`
}
FileDiff holds per-file diff metadata.
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 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 ¶
MarshalJSON ensures Segments is never serialized as null by initializing a nil slice to an empty slice before default marshaling.
type MessageSegment ¶
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 ProjectState ¶
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 ¶
ReviewNote represents a "User Review Required" callout in the plan. Level is typically "IMPORTANT" or "WARNING".
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 ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
}
func BuildToolCallsFromAcc ¶ added in v1.4.0
func BuildToolCallsFromAcc(accMap map[int]*ToolCallAcc) []ToolCall
BuildToolCallsFromAcc converts accumulated tool call deltas into []ToolCall sorted by index. This is the shared implementation used by streaming.go, agent_loop.go, and subagent/loop.go.
func BuildToolCallsFromAccFiltered ¶ added in v1.4.0
func BuildToolCallsFromAccFiltered(accMap map[int]*ToolCallAcc) []ToolCall
BuildToolCallsFromAccFiltered is like BuildToolCallsFromAcc but skips entries with empty names. Used by the subagent loop which discards unnamed tool call fragments.
type ToolCallAcc ¶ added in v1.4.0
ToolCallAcc accumulates streaming tool call deltas by index. Used by both the TUI streaming layer and the subagent loop to reconstruct complete tool calls from provider stream chunks.
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
NewToolError creates a new ToolError with an error and hint.
type ToolResult ¶
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 7 active phases: Init→Discuss→Plan→Exec→Verify→Runtime→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" PhaseRuntime WorkflowPhase = "runtime" PhaseShip WorkflowPhase = "ship" )