edit

package
v0.0.82 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package edit provides editing functionality for the term-llm.

Package edit provides streaming edit parsing and application.

Index

Constants

View Source
const MaxRetryAttempts = 3

MaxRetryAttempts is the maximum number of retry attempts for failed edits.

View Source
const MaxToolCallLoops = 5

MaxToolCallLoops is the maximum iterations for tool call handling.

View Source
const ReadContextToolName = "read_context"

ReadContextToolName is the name of the context reading tool.

Variables

View Source
var ReadContextToolSpec = llm.ToolSpec{
	Name:        ReadContextToolName,
	Description: "Read lines from a file to get additional context. Use this when you need to see more of the file beyond what was initially provided.",
	Schema: map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"path":       map[string]interface{}{"type": "string", "description": "File path"},
			"start_line": map[string]interface{}{"type": "integer", "description": "Start line (1-indexed, defaults to 1)"},
			"end_line":   map[string]interface{}{"type": "integer", "description": "End line (1-indexed, defaults to end of file)"},
		},
		"required": []interface{}{"path"},
	},
}

ReadContextToolSpec defines the tool for lazy context loading.

Functions

func ApplyMatch

func ApplyMatch(content string, match MatchResult, newString string) string

ApplyMatch replaces the matched region with newString.

func BuildRetryPrompt

func BuildRetryPrompt(ctx RetryContext) string

BuildRetryPrompt creates a prompt to help the LLM retry after a failed edit.

Types

type ClosestLine

type ClosestLine struct {
	LineNum    int
	Content    string
	Similarity float64
}

ClosestLine represents a line from the file that closely matches the search.

func FindClosestLines

func FindClosestLines(content, search string, maxResults int) []ClosestLine

FindClosestLines finds the lines in content most similar to the search. Returns the line numbers and content of the closest matches.

type EditResult

type EditResult struct {
	Path        string
	OldContent  string
	NewContent  string
	Format      Format
	MatchLevel  MatchLevel // Only for search/replace
	Error       error
	DiffWarning string // For unified diff with partial failures
}

EditResult represents the result of applying an edit to a file.

type ExecutorConfig

type ExecutorConfig struct {
	// FileContents maps file paths to their current content.
	FileContents map[string]string

	// Guards maps file paths to their allowed line ranges (1-indexed).
	// If a file has a guard, edits are only allowed within that range.
	Guards map[string][2]int // [startLine, endLine]

	// OnProgress is called with progress updates during execution.
	OnProgress func(msg string)

	// OnFileStart is called when a file edit begins.
	OnFileStart func(path string)

	// OnSearchMatch is called when a search matches successfully.
	OnSearchMatch func(path string, level MatchLevel)

	// OnSearchFail is called when a search fails to match.
	OnSearchFail func(path string, search string, err error)

	// OnEditApplied is called when an edit is successfully applied.
	OnEditApplied func(path string, oldContent, newContent string)

	// OnAbout is called when the about section is received.
	OnAbout func(content string)

	// OnTokens is called with output token count updates during streaming.
	OnTokens func(outputTokens int)

	// OnFirstToken is called when the first text token is received from the LLM.
	// Used to indicate the transition from "Thinking" to "Responding".
	OnFirstToken func()

	// OnToolStart is called when a tool execution begins (e.g., read_context).
	OnToolStart func(toolName string)

	// OnRetry is called when an edit fails and will be retried.
	// Provides full context for diagnostics.
	OnRetry func(diag RetryDiagnostic)

	// OnAPIRetry is called when the API returns a rate limit error and will be retried.
	OnAPIRetry func(attempt, maxAttempts int, waitSecs float64)

	// Debug enables debug output.
	Debug bool

	// DebugRaw enables raw request/response output.
	DebugRaw bool

	// LazyContext enables on-demand context loading for guarded edits.
	// When true, only the editable region + padding is sent initially,
	// and the LLM can use read_context tool to fetch more.
	LazyContext bool
}

ExecutorConfig configures the stream edit executor.

type FileEdit

type FileEdit struct {
	Path             string
	Format           Format
	SearchReplaces   []SearchReplaceEdit // For search/replace format
	UnifiedDiffLines []string            // For unified diff format
}

FileEdit represents all edits for a single file.

type Format

type Format int

Format represents the edit format being used within a file block.

const (
	FormatUnknown       Format = iota
	FormatSearchReplace        // <<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE
	FormatUnifiedDiff          // --- +++ @@ with space/minus/plus prefixes
)

func (Format) String

func (f Format) String() string

type InlineEdit added in v0.0.52

type InlineEdit struct {
	Type    InlineEditType
	After   string   // For INSERT: anchor text to insert after
	From    string   // For DELETE: start line text
	To      string   // For DELETE: end line text (empty for single line)
	Content []string // For INSERT: lines to insert
}

InlineEdit represents a parsed inline edit marker.

type InlineEditParser added in v0.0.52

type InlineEditParser struct {
	OnEdit          func(edit InlineEdit)
	OnText          func(text string)               // Text outside of markers
	OnPartialInsert func(after string, line string) // Streaming line during INSERT
	// contains filtered or unexported fields
}

InlineEditParser parses inline edit markers from streaming text. It buffers text and emits edits as complete markers are detected.

func NewInlineEditParser added in v0.0.52

func NewInlineEditParser() *InlineEditParser

NewInlineEditParser creates a new inline edit parser.

func (*InlineEditParser) Feed added in v0.0.52

func (p *InlineEditParser) Feed(chunk string)

Feed processes a chunk of text from the stream.

func (*InlineEditParser) Flush added in v0.0.52

func (p *InlineEditParser) Flush()

Flush processes any remaining buffered content.

type InlineEditType added in v0.0.52

type InlineEditType int

InlineEditType indicates the type of inline edit.

const (
	InlineEditInsert InlineEditType = iota
	InlineEditDelete
)

type MatchLevel

type MatchLevel int

MatchLevel indicates which matching strategy succeeded.

const (
	MatchExact         MatchLevel = iota // Direct string match
	MatchStripped                        // Whitespace-normalized match
	MatchBlankFiltered                   // Match with blank lines filtered out
	MatchNonContiguous                   // Match with ... elision markers
	MatchFuzzy                           // Levenshtein similarity match
)

func (MatchLevel) String

func (m MatchLevel) String() string

type MatchResult

type MatchResult struct {
	Level    MatchLevel // Which matching strategy succeeded
	Start    int        // Byte offset in content (inclusive)
	End      int        // Byte offset in content (exclusive)
	Original string     // The actual matched text from content
}

MatchResult contains the result of a successful match.

func FindMatch

func FindMatch(content, search string) (MatchResult, error)

FindMatch attempts to find the search string in content using multiple strategies. It tries in order: exact, stripped, non-contiguous (if ... present), fuzzy.

func FindMatchWithGuard

func FindMatchWithGuard(content, search string, startLine, endLine int) (MatchResult, error)

FindMatchWithGuard searches only within a guarded line range. startLine and endLine are 1-indexed, inclusive.

type ParseError

type ParseError struct {
	FilePath    string
	Format      Format
	Search      string // For search/replace format
	DiffContext string // For unified diff format
	Reason      string
}

ParseError represents an error during parsing with context.

func (*ParseError) Error

func (e *ParseError) Error() string

type ParserCallbacks

type ParserCallbacks struct {
	// OnFileStart is called when a [FILE: path] block begins.
	OnFileStart func(path string)

	// OnSearchReady is called when a search block is complete (at =======).
	// Return an error to halt parsing (e.g., if search doesn't match).
	OnSearchReady func(path, search string) error

	// OnReplaceReady is called when a search/replace pair is complete.
	OnReplaceReady func(path, search, replace string)

	// OnDiffReady is called when unified diff content is complete for a file.
	// diffLines contains the raw diff lines (including --- +++ @@ prefixes).
	OnDiffReady func(path string, diffLines []string) error

	// OnFileComplete is called when [/FILE] is seen.
	OnFileComplete func(edit FileEdit)

	// OnAboutLine is called for each line in the [ABOUT] section.
	OnAboutLine func(line string)

	// OnAboutComplete is called when [/ABOUT] is seen.
	OnAboutComplete func(content string)

	// OnText is called for non-edit text (before first [FILE:] or after [/ABOUT]).
	OnText func(text string)
}

ParserCallbacks contains callbacks invoked during parsing.

type ParserState

type ParserState int

ParserState represents the current state of the streaming parser.

const (
	StateIdle      ParserState = iota // Looking for [FILE:] or [ABOUT]
	StateInFile                       // Inside [FILE:], detecting format
	StateInSearch                     // Accumulating search content
	StateInReplace                    // Accumulating replace content
	StateInDiff                       // Accumulating unified diff content
	StateInAbout                      // Inside [ABOUT] block
)

func (ParserState) String

func (s ParserState) String() string

type RetryContext

type RetryContext struct {
	FilePath      string   // Path to the file that failed
	FailedSearch  string   // The search string that didn't match (search/replace)
	DiffLines     []string // The diff lines that failed (unified diff)
	FileContent   string   // Current content of the file
	Reason        string   // Why the edit failed
	PartialOutput string   // What the LLM output before failure
	AttemptNumber int      // Which retry attempt this is (0 = first try)
}

RetryContext contains context for building a retry prompt after a failed edit.

type RetryDiagnostic added in v0.0.11

type RetryDiagnostic struct {
	AttemptNumber int           // Which retry attempt (1-indexed)
	RetryContext  *RetryContext // The context that triggered the retry
	SystemPrompt  string        // The system prompt sent to the LLM
	UserPrompt    string        // The user prompt sent to the LLM
	Provider      string        // Provider name (e.g., "Anthropic (claude-sonnet-4-5)")
	Model         string        // Model name
}

RetryDiagnostic contains full context for diagnostic logging when a retry occurs.

type SearchReplaceEdit

type SearchReplaceEdit struct {
	Search  string
	Replace string
}

SearchReplaceEdit represents a single search/replace edit.

type StreamEditExecutor

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

StreamEditExecutor executes streaming edits with validation and retry.

func NewStreamEditExecutor

func NewStreamEditExecutor(provider llm.Provider, model string, config ExecutorConfig) *StreamEditExecutor

NewStreamEditExecutor creates a new executor.

func (*StreamEditExecutor) AboutText

func (e *StreamEditExecutor) AboutText() string

AboutText returns the about section text from the last execution.

func (*StreamEditExecutor) AccumulatedOutput

func (e *StreamEditExecutor) AccumulatedOutput() string

AccumulatedOutput returns the full LLM output accumulated during execution.

func (*StreamEditExecutor) Execute

func (e *StreamEditExecutor) Execute(ctx context.Context, messages []llm.Message) ([]EditResult, string, error)

Execute runs the streaming edit with the given messages. Returns the results and about text, or an error.

func (*StreamEditExecutor) Results

func (e *StreamEditExecutor) Results() []EditResult

Results returns the edit results from the last execution.

type StreamParser

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

StreamParser parses streaming edit output.

func NewStreamParser

func NewStreamParser(callbacks ParserCallbacks) *StreamParser

NewStreamParser creates a new parser with the given callbacks.

func (*StreamParser) CurrentFile

func (p *StreamParser) CurrentFile() string

CurrentFile returns the path of the file currently being parsed.

func (*StreamParser) Feed

func (p *StreamParser) Feed(chunk string) error

Feed processes a chunk of streaming text. Returns an error if parsing should halt (e.g., validation failed).

func (*StreamParser) Finish

func (p *StreamParser) Finish() error

Finish signals that all input has been received. Processes any remaining buffered content.

func (*StreamParser) HaltError

func (p *StreamParser) HaltError() error

HaltError returns the error that caused parsing to halt.

func (*StreamParser) IsHalted

func (p *StreamParser) IsHalted() bool

IsHalted returns true if parsing was halted due to an error.

func (*StreamParser) PartialDiff

func (p *StreamParser) PartialDiff() []string

PartialDiff returns the diff lines accumulated so far.

func (*StreamParser) PartialReplace

func (p *StreamParser) PartialReplace() string

PartialReplace returns the replace content accumulated so far.

func (*StreamParser) PartialSearch

func (p *StreamParser) PartialSearch() string

PartialSearch returns the search content accumulated so far (for error reporting).

func (*StreamParser) Reset

func (p *StreamParser) Reset()

Reset resets the parser to initial state.

func (*StreamParser) State

func (p *StreamParser) State() ParserState

State returns the current parser state.

Jump to

Keyboard shortcuts

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