engine

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const LinesPerPage = 50

LinesPerPage is the fixed number of lines per page in e-reader mode TODO: Move to constants.go

Variables

View Source
var FileTypes = map[string]FileType{
	"md":    {Name: "markdown", Extensions: []string{".md", ".markdown"}},
	"img":   {Name: "image", Extensions: imageExtensions},
	"vid":   {Name: "video", Extensions: videoExtensions},
	"txt":   {Name: "text", Extensions: []string{".txt", ".log"}},
	"json":  {Name: "json", Extensions: []string{".json"}},
	"yaml":  {Name: "yaml", Extensions: []string{".yaml", ".yml"}},
	"diff":  {Name: "diff", Extensions: []string{".diff", ".patch"}},
	"jsonl": {Name: "jsonl", Extensions: []string{".jsonl"}},
	"csv":   {Name: "csv", Extensions: []string{".csv", ".tsv"}},
	"html":  {Name: "html", Extensions: []string{".html", ".htm", ".xhtml"}},
}
View Source
var ImageExtensions = imageExtensions

ImageExtensions and VideoExtensions are the file extensions the registry treats as image/video content.

View Source
var VideoExtensions = videoExtensions

Functions

func Assets

func Assets() (css string, js string)

Assets returns the CSS and JS a host must place in its <head> for RenderFragment output to style and highlight correctly. Both are inline text (no URLs): css is the engine stylesheet plus highlight.js theme, js is highlight.js itself.

func DetectFileType

func DetectFileType(filePath string) string

DetectFileType returns the type key for a file path based on extension

func ExtractStructuredPatch

func ExtractStructuredPatch(msg map[string]interface{}) string

func FormatQuestionContent

func FormatQuestionContent(data *QuestionData) string

FormatQuestionContent formats QuestionData as display string Use index=0 and total=0 for single question (no Q1/N prefix)

func FormatQuestionContentIndexed

func FormatQuestionContentIndexed(data *QuestionData, index int, total int) string

FormatQuestionContentIndexed formats QuestionData with Q index/total prefix

func GetFileFromDiff

func GetFileFromDiff(diffContent string) string

GetFileFromDiff extracts the filename from diff headers

func HTMLToMarkdown

func HTMLToMarkdown(content string) (string, string)

HTMLToMarkdown converts an HTML document to markdown. The second return is the document <title>, used as the page title on the web/static surfaces.

func HasStructuredPatch

func HasStructuredPatch(msg map[string]interface{}) bool

HasStructuredPatch and ExtractStructuredPatch expose the transcript patch-detection primitives the CLI's follow mode shares with the parser.

func ImageMIME

func ImageMIME(ext string) string

ImageMIME returns the MIME type for an image extension

func IsTableLine

func IsTableLine(line string) bool

IsTableLine, IsTableSeparator, and ParseTableCells are the markdown-table primitives shared by the HTML renderer and the CLI's TUI formatter.

func IsTableSeparator

func IsTableSeparator(line string) bool

func PageTitle

func PageTitle(path string, content string) string

PageTitle derives a title for a file the way the CLI does: frontmatter title wins, else the base filename. (HTML <title> extraction happens in HTMLToMarkdown's second return; callers using Parse on HTML handle that.)

func ParseTableCells

func ParseTableCells(line string) []string

func RenderFragment

func RenderFragment(blocks []Block, opts Options) string

RenderFragment renders blocks as body-level HTML with no <html>, <head>, <body>, or <style> wrapper -- the form a host embeds inside its own page shell. Pair with Assets() in the host's <head>.

func RenderHTMLPage

func RenderHTMLPage(title string, blocks []Block, showLineNums bool) string

RenderHTMLPage renders blocks as a full HTML document with enhanced web features

func RenderIndexPage

func RenderIndexPage(dirName string, docs []DocMeta) string

RenderIndexPage renders a directory listing as an HTML page

func RenderPage

func RenderPage(title string, blocks []Block, opts Options) string

RenderPage renders blocks as a complete, self-contained HTML document (inline CSS + highlight.js, no external fetches). This is what the CLI's --html/--share/push surfaces emit. Hosts with their own page shell use RenderFragment instead.

func RenderStaticHTMLPage

func RenderStaticHTMLPage(title string, blocks []Block, showLineNums bool) string

RenderStaticHTMLPage renders blocks as a self-contained HTML document (no CDN, no SSE)

func VideoMIME

func VideoMIME(ext string) string

VideoMIME returns the MIME type for a video extension

Types

type Block

type Block struct {
	Name          string
	Content       string // Full content (untruncated)
	LineNum       int
	Pages         []string // Content split into pages
	TotalPages    int
	ContentType   BlockContentType   // Default content type (for simple blocks)
	PageTypes     []BlockContentType // Per-page content type (for mixed content blocks)
	PageMeta      []string           // Per-page metadata (e.g., filename for diff pages)
	PageStartLine []int              // 1-indexed file line number for first content line of each page
	Data          interface{}        // Typed payload: *ImageData, *VideoData, *CsvData, etc.
}

Block represents a markdown block with header and content

func Parse

func Parse(content string, typeName string) []Block

Parse parses content already typed by the caller. typeName is one of the FileTypes keys ("md", "html", "csv", "diff", "jsonl", "json", "yaml", "txt") or "" to detect from the content itself. HTML converts to markdown first, exactly as every aster surface does.

func ParseFile

func ParseFile(path string, static bool) ([]Block, error)

ParseFile detects the file's type and parses it. static=true inlines binary assets as data URIs (REQUIRED for hosts; see the invariant above).

type BlockContentType

type BlockContentType int

BlockContentType identifies the type of content within a block

const (
	BlockContentPlain BlockContentType = iota
	BlockContentDiff
	BlockContentTable
	BlockContentCode
	BlockContentTree
	BlockContentJSON
	BlockContentYAML
	BlockContentCSV
	BlockContentImage
	BlockContentVideo
	BlockContentContract
	BlockContentTranscript
	BlockContentShell
)

func DetectBlockContentType

func DetectBlockContentType(content string) BlockContentType

DetectBlockContentType analyzes content and returns its type

func (BlockContentType) String

func (ct BlockContentType) String() string

String returns a human-readable name for the content type

type BlockIndex

type BlockIndex struct {
	Blocks    []Block
	NameIndex map[string]int
}

BlockIndex maps block names to blocks for quick lookup

func NewBlockIndex

func NewBlockIndex(blocks []Block) *BlockIndex

NewBlockIndex creates an index from blocks

func (*BlockIndex) FindBlock

func (bi *BlockIndex) FindBlock(query string) *Block

FindBlock looks up a block by name (fuzzy match)

func (*BlockIndex) GetAllBlockNames

func (bi *BlockIndex) GetAllBlockNames() []string

GetAllBlockNames returns a list of all block names

func (*BlockIndex) GetBlockByPosition

func (bi *BlockIndex) GetBlockByPosition(pos int) *Block

GetBlockByPosition returns block at given position in document

func (*BlockIndex) NextBlock

func (bi *BlockIndex) NextBlock(currentName string) *Block

NextBlock returns the next block after the given block name

func (*BlockIndex) PrevBlock

func (bi *BlockIndex) PrevBlock(currentName string) *Block

PrevBlock returns the previous block before the given block name

type ContentType

type ContentType struct {
	Name    string
	Count   int
	Enabled bool
}

ContentType represents a type of content in JSONL

func ScanContentTypes

func ScanContentTypes(content string) []ContentType

ScanContentTypes scans JSONL content and returns available types with counts

type ContractData

type ContractData struct {
	Preamble  string
	Clauses   []contractClause
	Parties   string
	Effective string
}

ContractData holds payload for BlockContentContract blocks

type ContractParser

type ContractParser struct{}

ContractParser implements Parser for contract-type markdown files Detected via frontmatter type: "contract"

func (*ContractParser) Detect

func (p *ContractParser) Detect(filePath string) bool

Detect checks if file has contract frontmatter type

func (*ContractParser) Parse

func (p *ContractParser) Parse(content string) []Block

Parse reads contract content and returns a single block with ContractData

type ConversationTurn

type ConversationTurn struct {
	Parts   []TurnPart // All parts in order: user, diffs, assistant text
	LineNum int
}

ConversationTurn represents a user message and all subsequent content until next user message. Includes user query, any diffs from edits, and assistant responses.

type CsvData

type CsvData struct {
	Records [][]string // Header + data rows
}

CsvData holds payload for BlockContentCSV blocks

type CsvParser

type CsvParser struct {
	Delimiter rune // ',' for CSV, '\t' for TSV
}

CsvParser implements Parser for CSV and TSV files

func (*CsvParser) Detect

func (p *CsvParser) Detect(filePath string) bool

Detect checks if file is CSV or TSV

func (*CsvParser) Parse

func (p *CsvParser) Parse(content string) []Block

Parse reads CSV/TSV content and returns a single block with table content type

type DiffColors

type DiffColors struct {
	// Text colors
	AddedText   string // White text on added lines
	RemovedText string // White text on removed lines
	ContextText string // Gray for context lines
	HeaderText  string // Gray for headers

	// Background colors (dark terminal style)
	AddedBg   string // Dark green #2d5a2d
	RemovedBg string // Dark magenta #5a2d5a

	Reset string
}

DiffColors defines the color scheme for diff rendering Terminal style: bright highlights on dark backgrounds

func DefaultDiffColors

func DefaultDiffColors() DiffColors

DefaultDiffColors returns the magenta/green terminal color scheme

type DiffFormatter

type DiffFormatter struct {
	Colors          DiffColors
	Width           int
	ShowFuncContext bool
	CurrentHunk     int
	TotalHunks      int
}

DiffFormatter renders diff content with the designed visual style

Example

Run this to see visual output

diffContent := `--- a/file.go
+++ b/file.go
@@ -3,6 +3,8 @@

 import "fmt"

+const TaxRate = 0.08
+
 func calculateTotal(items []int) int {
`

formatter := NewDiffFormatter(80)
output := formatter.Format(diffContent, "file.go")
fmt.Println(output)

func NewDiffFormatter

func NewDiffFormatter(width int) *DiffFormatter

NewDiffFormatter creates a formatter with default settings

func (*DiffFormatter) Format

func (f *DiffFormatter) Format(content string, filename string) string

Format renders the entire diff content

func (*DiffFormatter) FormatHunk

func (f *DiffFormatter) FormatHunk(hunk DiffHunk, hunkIndex int, totalHunks int, filename string) string

FormatHunk renders a single hunk with the designed visual style Returns only the diff content - header/footer handled by FormatDiffPage

type DiffHunk

type DiffHunk struct {
	Header   string // The @@ line (we hide this in display)
	Lines    []DiffLine
	StartOld int // Starting line in old file
	StartNew int // Starting line in new file
}

DiffHunk represents a single hunk from a unified diff

func ParseHunks

func ParseHunks(content string) []DiffHunk

ParseHunks extracts hunks from unified diff content

type DiffLine

type DiffLine struct {
	Type    DiffLineType
	Content string
}

DiffLine represents a single line in a hunk

type DiffLineType

type DiffLineType int

DiffLineType indicates whether a line was added, removed, or context

const (
	DiffContext DiffLineType = iota
	DiffAdded
	DiffRemoved
)

type DiffParser

type DiffParser struct{}

DiffParser implements Parser for diff/patch files

func (*DiffParser) Detect

func (p *DiffParser) Detect(filePath string) bool

Detect checks if file is a diff/patch file

func (*DiffParser) Parse

func (p *DiffParser) Parse(content string) []Block

Parse reads a diff file and creates blocks from hunks

type DocMeta

type DocMeta struct {
	Slug    string
	Title   string
	Created string
	Tags    []string
	ModTime time.Time
}

DocMeta holds metadata for a document in directory mode

type FileParser

type FileParser interface {
	Parser
	ParseFile(filePath string, static bool) ([]Block, error)
}

FileParser extends Parser for binary/file-based content (images, video)

type FileType

type FileType struct {
	Name       string
	Extensions []string
}

FileType defines a supported file type with its extensions

type Frontmatter

type Frontmatter struct {
	Title   string
	Created string
	Tags    []string
	Type    string // e.g. "contract" for Oberon-style interactive rendering
	Raw     map[string]string
}

Frontmatter holds parsed YAML frontmatter from a document

func ParseFrontmatter

func ParseFrontmatter(content string) (Frontmatter, string)

ParseFrontmatter extracts YAML frontmatter delimited by --- from content. Returns the parsed frontmatter and the remaining body. If no frontmatter is found, returns empty Frontmatter and original content.

type HTMLParser

type HTMLParser struct{}

HTMLParser renders HTML documents by converting them to markdown and feeding the result through the existing markdown block pipeline.

The tokenizer, tree builder and emitter below are hand-rolled against the standard library: aster's engine carries no HTML dependency and this parser does not add one. html.UnescapeString (stdlib) handles entities.

Pipeline position: HTML -> markdown -> []Block -> Render. Converting to the markdown intermediate rather than to blocks directly means every existing output surface (terminal, --port, --html, --share) renders HTML for free.

func (*HTMLParser) Detect

func (p *HTMLParser) Detect(filePath string) bool

Detect checks if file is HTML

func (*HTMLParser) Parse

func (p *HTMLParser) Parse(content string) []Block

Parse converts HTML to markdown, then splits it into header-delimited blocks

func (*HTMLParser) ParseContinuous

func (p *HTMLParser) ParseContinuous(content string, termHeight int) []Block

ParseContinuous converts HTML to markdown, then pages it as continuous flow

type ImageData

type ImageData struct {
	Src    string // File path (server mode) or data URI (static mode)
	MIME   string // e.g. "image/png"
	Alt    string // Alt text (defaults to filename)
	Inline bool   // true = data URI, false = file path
}

ImageData holds payload for BlockContentImage blocks

type ImageParser

type ImageParser struct{}

ImageParser implements FileParser for image files

func (*ImageParser) Detect

func (p *ImageParser) Detect(filePath string) bool

Detect checks if file is an image

func (*ImageParser) Parse

func (p *ImageParser) Parse(content string) []Block

Parse is not used for images (binary content); returns nil

func (*ImageParser) ParseFile

func (p *ImageParser) ParseFile(filePath string, static bool) ([]Block, error)

ParseFile reads an image file and returns a single Block with ImageData static=true inlines as base64 data URI; static=false stores file path for server mode

type JSONLParser

type JSONLParser struct {
	Filters map[string]bool // Which content types to include

	// Decorate, when set, styles a transcript part for the surface that will
	// read Block.Content -- the CLI wires tview markup here for the TUI.
	// nil means plain text. HTML surfaces never read Content for transcripts
	// (they consume Block.Data *TranscriptData), so hosts leave this nil.
	Decorate func(partType, content, meta string) string
}

JSONLParser implements Parser for JSONL transcript files

func (*JSONLParser) CreateTurnBlock

func (p *JSONLParser) CreateTurnBlock(turn *ConversationTurn, turnNumber int) Block

CreateTurnBlock creates a Block from a ConversationTurn All parts (user, diff, assistant) are combined into a single scrollable view Parts are rendered in chronological order as they appear in the transcript

func (*JSONLParser) Detect

func (p *JSONLParser) Detect(filePath string) bool

Detect checks if file is JSONL

func (*JSONLParser) ExtractAllQuestions

func (p *JSONLParser) ExtractAllQuestions(msg map[string]interface{}) []*QuestionData

ExtractAllQuestions extracts ALL questions from an AskUserQuestion tool_use

func (*JSONLParser) ExtractAskUserQuestion

func (p *JSONLParser) ExtractAskUserQuestion(msg map[string]interface{}) *QuestionData

ExtractAskUserQuestion checks if an assistant message contains AskUserQuestion tool_use and extracts the first question (for backward compatibility)

func (*JSONLParser) ExtractAssistantContent

func (p *JSONLParser) ExtractAssistantContent(msg map[string]interface{}) string

ExtractAssistantContent extracts text from an assistant message

func (*JSONLParser) ExtractAssistantText

func (p *JSONLParser) ExtractAssistantText(line string) string

ExtractAssistantText extracts text content from an assistant message line

func (*JSONLParser) ExtractToolResultContent

func (p *JSONLParser) ExtractToolResultContent(msg map[string]interface{}) string

ExtractToolResultContent extracts the output from a tool result message Uses ShellFormatter for proper formatting with ANSI stripping and truncation

func (*JSONLParser) ExtractUserContent

func (p *JSONLParser) ExtractUserContent(msg map[string]interface{}) string

ExtractUserContent extracts text from a user message

func (*JSONLParser) GetMessageType

func (p *JSONLParser) GetMessageType(line string) string

GetMessageType returns the message type from a JSONL line ("user", "assistant", or "")

func (*JSONLParser) Parse

func (p *JSONLParser) Parse(content string) []Block

Parse reads a JSONL file and extracts conversation blocks

func (*JSONLParser) ParseLineInfo

func (p *JSONLParser) ParseLineInfo(line string) (map[string]interface{}, string, bool)

ParseLineInfo parses a JSONL line and returns the parsed message, type, and whether it's a tool result

func (*JSONLParser) ParseSingleLine

func (p *JSONLParser) ParseSingleLine(line string, turnNumber int) *Block

ParseSingleLine parses a single JSONL line and returns a block if it matches filters Used for follow mode where we process lines incrementally

type MarkdownParser

type MarkdownParser struct{}

MarkdownParser implements Parser for markdown files

func (*MarkdownParser) Detect

func (p *MarkdownParser) Detect(filePath string) bool

Detect checks if file is markdown

func (*MarkdownParser) Parse

func (p *MarkdownParser) Parse(content string) []Block

Parse reads a markdown file and extracts blocks

func (*MarkdownParser) ParseContinuous

func (p *MarkdownParser) ParseContinuous(content string, termHeight int) []Block

ParseContinuous treats markdown as continuous flow without header-based block cuts Pages are sized to fit the terminal: min(termHeight, maxLines) Tracks header breadcrumbs for each page (e.g., "Title > Section")

type Options

type Options struct {
	// ShowLineNumbers renders a source line-number gutter where supported.
	ShowLineNumbers bool
}

Options controls rendering.

type Parser

type Parser interface {
	Parse(content string) []Block
	Detect(filePath string) bool // Auto-detect if this parser can handle the file
}

Parser interface for extensibility - allows different file formats

func DetectParser

func DetectParser(filePath string) Parser

DetectParser selects the appropriate parser based on file extension

func DetectParserFromContent

func DetectParserFromContent(content string) Parser

DetectParserFromContent tries to detect parser type from content (for stdin)

type QuestionData

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

QuestionData represents an AskUserQuestion from Claude Code

type QuestionOption

type QuestionOption struct {
	Label       string
	Description string
}

QuestionOption represents a single option in a question

type ShellFormatter

type ShellFormatter struct {
	Width           int
	MaxLines        int // 0 = unlimited, default 100
	TruncationLimit int // Chars before truncation, default 5000
}

ShellFormatter renders shell command output with proper styling

func NewShellFormatter

func NewShellFormatter(width int) *ShellFormatter

NewShellFormatter creates a formatter with default settings

func (*ShellFormatter) Format

func (f *ShellFormatter) Format(output *ShellOutput) string

Format renders ShellOutput with visual styling for display Shows only Tool: command/path header (compact mode)

func (*ShellFormatter) StripANSI

func (f *ShellFormatter) StripANSI(content string) string

StripANSI removes all ANSI escape codes from content

type ShellOutput

type ShellOutput struct {
	ToolName  string   // "Bash", "Read", "Glob", "Grep"
	Command   string   // Command that was run or pattern
	Stdout    string   // Standard output
	Stderr    string   // Standard error
	FilePath  string   // For Read tool: file path
	FileCount int      // For Glob/Grep: number of files
	FileList  []string // For Glob/Grep: list of files
}

ShellOutput represents parsed shell/tool output data

func ParseToolResult

func ParseToolResult(toolUseResult map[string]interface{}) *ShellOutput

ParseToolResult converts toolUseResult JSON map to ShellOutput Returns nil for tool results that should be skipped (Edit with diff, Todo, etc.)

type TodoItem

type TodoItem struct {
	Content    string `json:"content"`
	Status     string `json:"status"`
	ActiveForm string `json:"activeForm"`
}

TodoItem represents a single todo from the JSON file

type TodoParser

type TodoParser struct{}

TodoParser implements Parser for JSON todo files

func (*TodoParser) Detect

func (p *TodoParser) Detect(filePath string) bool

Detect checks if content is a JSON todo array

func (*TodoParser) Parse

func (p *TodoParser) Parse(content string) []Block

Parse reads a JSON todo file and creates a single block

type TranscriptData

type TranscriptData struct {
	TurnParts []TurnPart
}

TranscriptData holds payload for BlockContentTranscript blocks

type TurnPart

type TurnPart struct {
	Type    string // "user", "diff", "assistant", "question", "tool_result"
	Content string
	Meta    string // For diffs: filename
}

TurnPart represents a piece of content within a turn

type TxtParser

type TxtParser struct{}

TxtParser implements Parser for plain text / shell output files

func (*TxtParser) Detect

func (p *TxtParser) Detect(filePath string) bool

Detect checks if file is txt

func (*TxtParser) Parse

func (p *TxtParser) Parse(content string) []Block

Parse reads a txt file and extracts blocks Each "shell" line starts a new block, followed by command on next line

type VideoData

type VideoData struct {
	Src    string // File path (server mode) or data URI (static mode)
	MIME   string // e.g. "video/mp4"
	Inline bool   // true = data URI, false = file path

	// Warning carries a non-fatal condition (e.g. too large to inline) for
	// the HOST to surface. The engine is a library: it never writes to
	// stderr itself.
	Warning string
}

VideoData holds payload for BlockContentVideo blocks

type VideoParser

type VideoParser struct{}

VideoParser implements FileParser for video files

func (*VideoParser) Detect

func (p *VideoParser) Detect(filePath string) bool

Detect checks if file is a video

func (*VideoParser) Parse

func (p *VideoParser) Parse(content string) []Block

Parse is not used for video (binary content); returns nil

func (*VideoParser) ParseFile

func (p *VideoParser) ParseFile(filePath string, static bool) ([]Block, error)

ParseFile reads a video file and returns a single Block with VideoData static=true inlines as base64 data URI (if <10MB); static=false stores file path for server mode

Jump to

Keyboard shortcuts

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