aichat

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package aichat implements `gk do`, `gk explain`, and `gk ask` — AI-powered conversational commands that generate/execute git/gk command sequences, diagnose errors, and answer repository-context questions. All three are single-shot: one prompt, one answer. The multi-turn, tool-calling `gk chat` lives in internal/chat instead — its agentic loop is a different execution model — but reuses this package's RepoContextCollector for its initial system context.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WrapUntrusted

func WrapUntrusted(tag, content string) string

WrapUntrusted fences content in a named tag, escaping embedded tag spellings so untrusted data (repository context, tool output, etc.) cannot terminate the fence early or masquerade as instructions. It is shared by aichat's single-shot prompts and gk chat's multi-turn engine.

Types

type CommandExecutor

type CommandExecutor struct {
	Runner     git.Runner
	Out        io.Writer
	ErrOut     io.Writer
	EasyEngine *easy.Engine
	Dbg        func(string, ...any)

	// GkPath is the path to the gk binary, used to run gk-native commands
	// (sync, ship, …) that have no git equivalent by re-executing gk
	// itself. Empty disables that path (the command is reported as not
	// runnable here). Wire it from os.Executable().
	GkPath string

	// ConfirmFunc is called to ask the user for confirmation.
	// If nil, defaults to reading from stdin (y/n/Enter).
	ConfirmFunc ConfirmFunc
}

CommandExecutor previews and executes an ExecutionPlan.

Dangerous commands (RiskHigh) ALWAYS require an extra confirmation unless --force is passed; there is intentionally no config knob to disable that gate (a removed `SafetyConfirm` option used to imply otherwise but never actually did).

func (*CommandExecutor) Execute

Execute runs the plan's commands sequentially after user confirmation.

Confirmation flow:

  1. NonTTY + no --yes/--dry-run → return error (exit 2)
  2. --dry-run → print plan, return without executing
  3. --json → marshal plan to JSON, return without executing
  4. Normal: show preview + ask y/n (Enter = yes)
  5. Dangerous commands: extra per-command confirmation (always; not configurable)
  6. --yes: skip normal confirmation, dangerous still confirmed
  7. --force: skip ALL confirmations
  8. Create backup ref before first dangerous command
  9. Execute commands sequentially; stop on error

func (*CommandExecutor) Preview

func (e *CommandExecutor) Preview(plan *ExecutionPlan) string

Preview returns a human-readable preview of the execution plan. All commands are numbered. Dangerous commands show a ⚠ 위험 label with an impact description. Easy Mode emoji is inserted when active.

type CommandResult

type CommandResult struct {
	Command  string // the command that was run
	Stdout   string // standard output
	Stderr   string // standard error
	ExitCode int    // process exit code
	Error    error  // non-nil on failure
}

CommandResult is the outcome of a single command execution.

type ConfirmFunc

type ConfirmFunc func(prompt string) (bool, error)

ConfirmFunc asks the user a yes/no question and returns the answer. prompt is the question text. The function should return true for yes.

type ErrorAnalyzer

type ErrorAnalyzer struct {
	Summarizer provider.Summarizer
	Context    *RepoContextCollector
	Lang       string
	Easy       bool // Easy Mode: plain, non-developer language in the explanation
	Timeout    time.Duration
	MaxTokens  int // advisory response cap; 0 = provider default
	Dbg        func(string, ...any)
}

ErrorAnalyzer diagnoses git error messages and explains the most recent git/gk command. It uses the Summarizer interface to communicate with AI providers and RepoContextCollector for repository state.

func (*ErrorAnalyzer) DiagnoseError

func (a *ErrorAnalyzer) DiagnoseError(ctx context.Context, errorMsg string) (string, error)

DiagnoseError analyses an error message and returns a structured explanation with Cause, Solution, and Prevention sections.

If errorMsg is empty, it returns a guidance message listing common git error types and suggesting `gk explain --last`.

func (*ErrorAnalyzer) ExplainLast

func (a *ErrorAnalyzer) ExplainLast(ctx context.Context) (string, error)

ExplainLast identifies the most recent git/gk command from the reflog and returns a step-by-step explanation of what it did internally.

If the reflog is empty (last command unidentifiable), it returns a notice about accuracy limitations.

type ExecuteOptions

type ExecuteOptions struct {
	Yes    bool // --yes: skip normal confirmation
	Force  bool // --force: skip ALL confirmations including dangerous
	DryRun bool // --dry-run: print plan only, execute nothing
	JSON   bool // --json: output in JSON format
	NonTTY bool // true when stdout is not a terminal
}

ExecuteOptions controls CommandExecutor.Execute behaviour.

type ExecutionPlan

type ExecutionPlan struct {
	Commands []PlannedCommand `json:"commands"`
}

ExecutionPlan is a sequence of commands produced by IntentParser from a natural-language input.

func ParseExecutionPlan

func ParseExecutionPlan(raw string) (*ExecutionPlan, error)

ParseExecutionPlan parses a raw AI response string into an ExecutionPlan.

It handles:

  • Plain JSON: {"commands":[...]}
  • JSON wrapped in markdown code fences: ```json ... ```
  • Whitelist validation: commands must start with "git " or "gk "
  • Field validation: Command and Description must be non-empty
  • Maximum command count: capped at maxCommandsPerPlan

Commands that violate the whitelist or have empty fields are silently skipped (with a warning appended to the returned plan). The function returns an error only when the input is fundamentally unparseable.

func (ExecutionPlan) MarshalJSON

func (p ExecutionPlan) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ExecutionPlan.

func (*ExecutionPlan) UnmarshalJSON

func (p *ExecutionPlan) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for ExecutionPlan.

type ExecutionResult

type ExecutionResult struct {
	Executed  []CommandResult // results for each executed command
	BackupRef string          // backup ref created before dangerous commands
	Aborted   bool            // true when user rejected or an error stopped execution
}

ExecutionResult is the outcome of CommandExecutor.Execute.

type IntentParser

type IntentParser struct {
	Summarizer provider.Summarizer
	Context    *RepoContextCollector
	Safety     *SafetyClassifier
	Lang       string
	Easy       bool // Easy Mode: plain, non-developer language in the explanation
	Timeout    time.Duration
	MaxTokens  int // advisory response cap; 0 = provider default
	Dbg        func(string, ...any)
	// Redact, when set, sanitizes the fully-assembled prompt (user input +
	// repo context) before it leaves the process. ai_do wires this to the
	// privacy gate so that context — branch names, paths, reflog — is
	// redacted for remote providers, not just the user input. Returning an
	// error aborts the parse (e.g. too many secrets) rather than uploading.
	Redact func(string) (string, error)
}

IntentParser converts natural-language input into an ExecutionPlan by calling an AI provider through the Summarizer interface.

func (*IntentParser) Parse

func (p *IntentParser) Parse(ctx context.Context, input string) (*ExecutionPlan, error)

Parse analyses the natural-language input and returns an ExecutionPlan.

Flow:

  1. Collect repository context via RepoContextCollector.
  2. Build the user prompt with buildDoUserPrompt.
  3. Call Summarizer.Summarize with Kind "do".
  4. Parse the JSON response into an ExecutionPlan.
  5. Classify each command's risk via SafetyClassifier.

type NonTTYError

type NonTTYError struct{}

NonTTYError is returned when Execute is called in a non-TTY environment without --yes or --dry-run.

func (*NonTTYError) Error

func (e *NonTTYError) Error() string

func (*NonTTYError) ExitCode

func (e *NonTTYError) ExitCode() int

ExitCode returns 2 for NonTTYError.

type PlannedCommand

type PlannedCommand struct {
	Command     string    `json:"command"`     // e.g. "gk push"
	Description string    `json:"description"` // one-line explanation
	Dangerous   bool      `json:"dangerous"`   // flagged by AI or SafetyClassifier
	Risk        RiskLevel `json:"-"`           // set by SafetyClassifier
	RiskReason  string    `json:"-"`           // reason for the risk level
}

PlannedCommand is a single command inside an ExecutionPlan.

func (PlannedCommand) Validate

func (c PlannedCommand) Validate() error

Validate checks that Command starts with "git " or "gk " (case-insensitive) and that the git subcommand is in the allowed set. Returns an error if the command is not whitelisted.

type QAEngine

type QAEngine struct {
	Summarizer provider.Summarizer
	Context    *RepoContextCollector
	Lang       string
	// Easy, when true (Easy Mode), tells the model to answer in plain,
	// non-developer language (no git jargon, proper nouns kept as-is).
	Easy      bool
	Timeout   time.Duration
	MaxTokens int // advisory response cap; 0 = provider default
	Dbg       func(string, ...any)
}

QAEngine answers git/gk questions using repository context. It uses the Summarizer interface to communicate with AI providers and RepoContextCollector for repository state.

func (*QAEngine) Answer

func (q *QAEngine) Answer(ctx context.Context, question string) (string, error)

Answer analyses the question and returns a context-aware answer using the repository state.

If the question is empty, it returns a guidance message. If the question is not about git/gk, it returns a non-git guidance message.

type RepoContext

type RepoContext struct {
	Branch       string   // current branch name
	HeadSHA      string   // HEAD commit hash (short)
	Upstream     string   // upstream tracking ref (e.g. "origin/main")
	Status       string   // git status --porcelain=v2 output
	RecentReflog []string // recent reflog entries (up to 10)
	BranchList   []string // all local branches (for gk ask)
	IsRepo       bool     // true when inside a git repository
	IsDetached   bool     // true when HEAD is detached (not on a branch)
	// contains filtered or unexported fields
}

RepoContext holds the collected repository state.

func (*RepoContext) Format

func (rc *RepoContext) Format() string

Format converts RepoContext into a prompt-insertion string. The output is limited to the token budget set during collection (default 2000).

func (*RepoContext) FormatForCollector

func (rc *RepoContext) FormatForCollector(c *RepoContextCollector) string

FormatForCollector formats with the given collector's token budget.

type RepoContextCollector

type RepoContextCollector struct {
	Runner      git.Runner
	TokenBudget int // default 2000; Format() output limited to this
	Dbg         func(string, ...any)
}

RepoContextCollector gathers repository state for AI prompt context.

func (*RepoContextCollector) Collect

Collect gathers repository state. Individual git command failures leave the corresponding field empty; the method never returns an error. A non-git directory yields IsRepo=false with all fields empty.

func (*RepoContextCollector) CollectForQuestion

func (c *RepoContextCollector) CollectForQuestion(ctx context.Context, question string) *RepoContext

CollectForQuestion collects additional info related to the question, including the branch list for gk ask.

type RiskLevel

type RiskLevel int

RiskLevel indicates how dangerous a command is.

const (
	RiskNone RiskLevel = iota // safe command
	RiskLow                   // use with caution
	RiskHigh                  // destructive — requires extra confirmation
)

func (RiskLevel) String

func (r RiskLevel) String() string

String returns a human-readable label for the risk level.

type SafetyClassifier

type SafetyClassifier struct{}

SafetyClassifier classifies commands by risk level.

func (*SafetyClassifier) Classify

func (s *SafetyClassifier) Classify(command string) (RiskLevel, string)

Classify returns the risk level and a human-readable reason for the given command string. Commands matching a known dangerous pattern return the pattern's risk level (default RiskHigh); everything else returns RiskNone. Patterns are checked in order; the first match wins.

func (*SafetyClassifier) ClassifyPlan

func (s *SafetyClassifier) ClassifyPlan(plan *ExecutionPlan) bool

ClassifyPlan reports whether the plan contains at least one dangerous (RiskHigh) command. It also populates each PlannedCommand's Risk and RiskReason fields as a side effect.

Jump to

Keyboard shortcuts

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