tools

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const LSPToolTimeout = 30 * time.Second

LSPToolTimeout is the timeout for LSP operations

View Source
const (
	// 最大画像サイズ: 10MB
	MaxImageSize = 10 * 1024 * 1024
)
View Source
const MaxReadLines = 200

MaxReadLines はデフォルトの最大読み込み行数

Variables

View Source
var ConfirmInteractive = func(message string) ConfirmResult {
	reader := bufio.NewReader(os.Stdin)

	ui.ConfirmPromptBox(message)

	for {
		yellow.Print("Choice: ")

		response, err := reader.ReadString('\n')
		if err != nil {

			return ConfirmResult{Action: "no"}
		}
		response = strings.ToLower(strings.TrimSpace(response))

		if response == "" {
			continue
		}

		if response == "y" || response == "yes" || response == "y" || response == "はい" {
			return ConfirmResult{Action: "yes"}
		}

		if response == "n" || response == "no" || response == "n" || response == "いいえ" {
			return ConfirmResult{Action: "no"}
		}

		if response == "c" || response == "comment" || response == "コメント" {
			comment, image := ReadMultiLineComment(reader)
			return ConfirmResult{Action: "comment", Comment: comment, Image: image}
		}

		yellow.Println("Invalid input. Please enter y/n/c.")
	}
}

ConfirmInteractive は拡張確認プロンプト (y/n/c) c (comment) を選択すると複数行コメントを入力できる 外部パッケージからも使用可能なようにエクスポート NOTE: テスト時は環境変数 XELYON_INTERACTIVE_CONFIRM=0 で無効化される

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry はデフォルトのツールレジストリ

View Source
var LSPClient *lsp.Client

LSPClient is set by agent during initialization

View Source
var ValidatePath = validatePathImpl

ValidatePath はパストラバーサル攻撃を防ぐためにパスを検証(テスト用にグローバル変数として定義)

Functions

func CheckUncommittedChanges added in v0.31.0

func CheckUncommittedChanges() (status string, hasChanges bool, err error)

CheckUncommittedChanges は未コミット変更をチェック status: git status --porcelain の出力 hasChanges: 変更があるかどうか

func ConfirmApproved added in v0.31.0

func ConfirmApproved(message string) bool

ConfirmApproved is a compatibility helper that preserves the old bool-based API. NOTE: This drops comment/image information.

func DisplayContentToInsert added in v0.31.0

func DisplayContentToInsert(content string)

DisplayContentToInsert は挿入する内容を表示

func DisplayContextAround added in v0.31.0

func DisplayContextAround(matchIdx int, lines []string, contextLines int)

DisplayContextAround はマッチ行の周囲コンテキストを表示

func DisplayGitConfirmHeader added in v0.31.0

func DisplayGitConfirmHeader(title, subtitle, target string)

DisplayGitConfirmHeader は確認UIのヘッダーを表示

func DisplayMultipleMatches added in v0.31.0

func DisplayMultipleMatches(matchIndices []int, lines []string)

DisplayMultipleMatches は複数マッチ時のエラー表示

func DisplayPatternNotFound added in v0.31.0

func DisplayPatternNotFound(pattern string, lines []string, maxPreview int)

DisplayPatternNotFound はパターンが見つからない場合のエラー表示

func DisplayUncommittedChangesWarning added in v0.31.0

func DisplayUncommittedChangesWarning(status string)

DisplayUncommittedChangesWarning は未コミット変更の警告を表示

func ExecuteGitCommand added in v0.31.0

func ExecuteGitCommand(args ...string) (string, error)

ExecuteGitCommand はGitコマンドを実行し結果を返す

func FormatGitError added in v0.31.0

func FormatGitError(err error, output string) string

FormatGitError はGitコマンドのエラーをフォーマット

func FormatGitSuccess added in v0.31.0

func FormatGitSuccess(action, target string) string

FormatGitSuccess はGit成功メッセージをフォーマット

func FormatReferenceWarning added in v0.31.0

func FormatReferenceWarning(refs []ReferenceInfo) string

FormatReferenceWarning は参照警告メッセージをフォーマット

func FormatSize added in v0.29.0

func FormatSize(bytes int64) string

FormatSize はバイト数を人間が読みやすい形式に変換

func GetSafetyDescription added in v0.29.0

func GetSafetyDescription(safety ToolSafety) string

GetSafetyDescription は安全性レベルの説明を返す

func IsAutoApprovable added in v0.29.0

func IsAutoApprovable(toolName string, autoApprove bool) bool

IsAutoApprovable は --auto-approve フラグで自動承認可能かを判定

func IsInteractiveModeEnabled added in v0.29.0

func IsInteractiveModeEnabled() bool

IsInteractiveModeEnabled は対話的確認モードが有効かチェック デフォルトは有効。

無効化したい場合は以下のいずれかを設定:

  • XELYON_INTERACTIVE_CONFIRM=0
  • XELYON_INTERACTIVE_CONFIRM=false

func IsMediumToolAutoApprovable added in v0.31.0

func IsMediumToolAutoApprovable(toolName string) bool

IsMediumToolAutoApprovable は SafetyMedium ツールを設定に基づいて自動承認するか判定 config.tool_confirm.auto_approve_medium が true の場合、SafetyMedium ツールは確認なしで実行

func IsSafeToolAutoApprovable added in v0.31.0

func IsSafeToolAutoApprovable(toolName string) bool

IsSafeToolAutoApprovable は SafetyHigh ツールを設定に基づいて自動承認するか判定 config.tool_confirm.auto_approve_safe が true の場合、SafetyHigh ツールは確認なしで実行

func PreviewToolCall added in v0.31.0

func PreviewToolCall(tc *ToolCall)

PreviewToolCall displays tool information without executing it

func RegisterBuiltinTools

func RegisterBuiltinTools(r *Registry)

RegisterBuiltinTools はすべての組み込みツールを登録

func RegisterLSPTools added in v0.31.0

func RegisterLSPTools(r *Registry)

RegisterLSPTools registers all LSP tools to the registry

func SetAutoApprove added in v0.29.0

func SetAutoApprove(enabled bool)

SetAutoApprove は --auto-approve フラグを設定

func TruncateOutput added in v0.31.0

func TruncateOutput(output string, maxLines int) string

TruncateOutput は出力を指定行数に切り詰め

func ValidatePathAllowParent

func ValidatePathAllowParent(path string) (string, error)

ValidatePathAllowParent は親ディレクトリへのアクセスを許可 (特定の用途でのみ使用)

Types

type ConfirmAction added in v0.31.0

type ConfirmAction string

ConfirmAction is the normalized action returned by confirmation prompts.

const (
	ConfirmYes     ConfirmAction = "yes"
	ConfirmNo      ConfirmAction = "no"
	ConfirmComment ConfirmAction = "comment"
)

type ConfirmDecision added in v0.31.0

type ConfirmDecision struct {
	Action  ConfirmAction
	Comment string
	Image   *ImageData
}

ConfirmDecision is the unified result for all confirmation prompts. Comment/Image are only set when Action==ConfirmComment.

func Confirm added in v0.31.0

func Confirm(message string) ConfirmDecision

Confirm asks user for confirmation and optionally captures feedback. If interactive confirmation is enabled, it supports y/n/c and multi-line comments. Otherwise it falls back to legacy y/n confirm.

type ConfirmResult added in v0.29.0

type ConfirmResult struct {
	Action  string     // "yes", "no", "comment"
	Comment string     // "comment" の場合のコメント内容
	Image   *ImageData // 画像データ(オプション)
}

ConfirmResult は確認結果

type DiffFilesTool added in v0.31.0

type DiffFilesTool struct{}

DiffFilesTool needs special handling for context lines

func (*DiffFilesTool) Name added in v0.31.0

func (t *DiffFilesTool) Name() string

func (*DiffFilesTool) Run added in v0.31.0

func (t *DiffFilesTool) Run(args map[string]string) (string, *FileChange, error)

type FileChange

type FileChange struct {
	FilePath    string
	BackupPath  string
	Timestamp   time.Time
	Tool        string
	Description string
}

FileChange はファイル変更履歴

func Execute

func Execute(tc *ToolCall) (string, *FileChange)

Execute はツールを実行(Registry経由)

type FileModifyingTool added in v0.31.0

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

FileModifyingTool はファイルを変更しFileChangeを返すツール

func (*FileModifyingTool) Name added in v0.31.0

func (t *FileModifyingTool) Name() string

func (*FileModifyingTool) Run added in v0.31.0

func (t *FileModifyingTool) Run(args map[string]string) (string, *FileChange, error)

type FileReplaceResult added in v0.31.0

type FileReplaceResult struct {
	FilePath   string
	MatchCount int
	BackupPath string
}

FileReplaceResult は1ファイルの置換結果

type GrepReplaceResult added in v0.31.0

type GrepReplaceResult struct {
	FilesModified int
	TotalMatches  int
	FileResults   []FileReplaceResult
	BackupPaths   map[string]string // filepath -> backupPath
}

GrepReplaceResult は一括置換の結果

type GrepReplaceTool added in v0.31.0

type GrepReplaceTool struct{}

GrepReplaceTool requires confirmation prompt

func (*GrepReplaceTool) Name added in v0.31.0

func (t *GrepReplaceTool) Name() string

func (*GrepReplaceTool) Run added in v0.31.0

func (t *GrepReplaceTool) Run(args map[string]string) (string, *FileChange, error)

type HTTPRequestTool added in v0.31.0

type HTTPRequestTool struct{}

HTTPRequestTool needs special handling for timeout

func (*HTTPRequestTool) Name added in v0.31.0

func (t *HTTPRequestTool) Name() string

func (*HTTPRequestTool) Run added in v0.31.0

func (t *HTTPRequestTool) Run(args map[string]string) (string, *FileChange, error)

type HTTPResponse added in v0.31.0

type HTTPResponse struct {
	StatusCode int               `json:"status_code"`
	Status     string            `json:"status"`
	Headers    map[string]string `json:"headers"`
	Body       string            `json:"body"`
	Duration   string            `json:"duration"`
}

HTTPResponse はHTTPリクエストの結果

type ImageData added in v0.29.0

type ImageData struct {
	Path      string // 元のファイルパス
	MediaType string // "image/png", "image/jpeg" 等
	Base64    string // Base64エンコードされた画像データ
	Size      int64  // ファイルサイズ(バイト)
}

ImageData は画像データを表す

func ConfirmWithFeedback added in v0.29.0

func ConfirmWithFeedback(message string) (approved bool, comment string, image *ImageData)

ConfirmWithFeedback は対話的確認を行う(互換ラッパー) interactiveMode=true の場合は y/n/c、false の場合は従来の y/n

NOTE: 新コードでは Confirm() / ConfirmDecision の利用を推奨。

func LoadImage added in v0.29.0

func LoadImage(path string) (*ImageData, error)

LoadImage は画像ファイルを読み込んでBase64エンコードする

func ReadMultiLineComment added in v0.31.0

func ReadMultiLineComment(reader *bufio.Reader) (string, *ImageData)

ReadMultiLineComment は複数行コメントを読み取る 空行2回で入力終了 image:プレフィックスで画像を指定可能 /paste(または /p)で Paste Mode を起動して長文を挿入可能

type LSPDefinitionTool added in v0.31.0

type LSPDefinitionTool struct{}

LSPDefinitionTool finds the definition of a symbol

func (*LSPDefinitionTool) Name added in v0.31.0

func (t *LSPDefinitionTool) Name() string

func (*LSPDefinitionTool) Run added in v0.31.0

func (t *LSPDefinitionTool) Run(args map[string]string) (string, *FileChange, error)

type LSPDiagnosticsTool added in v0.31.0

type LSPDiagnosticsTool struct{}

LSPDiagnosticsTool gets errors and warnings for a file

func (*LSPDiagnosticsTool) Name added in v0.31.0

func (t *LSPDiagnosticsTool) Name() string

func (*LSPDiagnosticsTool) Run added in v0.31.0

func (t *LSPDiagnosticsTool) Run(args map[string]string) (string, *FileChange, error)

type LSPHoverTool added in v0.31.0

type LSPHoverTool struct{}

LSPHoverTool gets type information and documentation for a symbol

func (*LSPHoverTool) Name added in v0.31.0

func (t *LSPHoverTool) Name() string

func (*LSPHoverTool) Run added in v0.31.0

func (t *LSPHoverTool) Run(args map[string]string) (string, *FileChange, error)

type LSPReferencesTool added in v0.31.0

type LSPReferencesTool struct{}

LSPReferencesTool finds all references to a symbol

func (*LSPReferencesTool) Name added in v0.31.0

func (t *LSPReferencesTool) Name() string

func (*LSPReferencesTool) Run added in v0.31.0

func (t *LSPReferencesTool) Run(args map[string]string) (string, *FileChange, error)

type LSPRenameTool added in v0.31.0

type LSPRenameTool struct{}

LSPRenameTool renames a symbol at the given position

func (*LSPRenameTool) Name added in v0.31.0

func (t *LSPRenameTool) Name() string

func (*LSPRenameTool) Run added in v0.31.0

func (t *LSPRenameTool) Run(args map[string]string) (string, *FileChange, error)

type PatternMatchResult added in v0.31.0

type PatternMatchResult struct {
	MatchIdx     int   // マッチした行インデックス(-1 = not found)
	MatchCount   int   // マッチ数
	MatchIndices []int // 全マッチ位置
}

PatternMatchResult はパターンマッチの結果を保持

func FindPatternInLines added in v0.31.0

func FindPatternInLines(lines []string, pattern string) PatternMatchResult

FindPatternInLines は行配列からパターンを検索 Tier 1: Exact match, Tier 2: Normalized whitespace match

type PatternSuggestion added in v0.31.0

type PatternSuggestion struct {
	Pattern string
	Lang    string
	Hint    string
}

PatternSuggestion はパターン提案の構造体

func GetPatternSuggestion added in v0.31.0

func GetPatternSuggestion(query string) PatternSuggestion

GetPatternSuggestion は自然言語クエリから推奨パターンを返す(LLM支援用) この関数はLLMが自然言語をast-grepパターンに変換する際の参考として使用できる

type ReadFileTool

type ReadFileTool struct{}

ReadFileTool needs special handling for optional line range

func (*ReadFileTool) Name

func (t *ReadFileTool) Name() string

func (*ReadFileTool) Run

func (t *ReadFileTool) Run(args map[string]string) (string, *FileChange, error)

type ReferenceInfo added in v0.31.0

type ReferenceInfo struct {
	Symbol   string
	FilePath string
	Line     int  // 1-indexed
	IsLocal  bool // 同一ファイル内の参照
}

ReferenceInfo は参照情報

func CheckReferencesBeforeDelete added in v0.31.0

func CheckReferencesBeforeDelete(filePath string, symbols []SymbolInfo) ([]ReferenceInfo, bool, error)

CheckReferencesBeforeDelete はLSPで参照をチェック 戻り値: 参照リスト, 外部参照あり?, エラー

func GetExternalReferences added in v0.31.0

func GetExternalReferences(refs []ReferenceInfo) []ReferenceInfo

GetExternalReferences は外部参照のみをフィルタして返す

type Registry

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

Registry はツールの登録・管理を行う

func NewRegistry

func NewRegistry() *Registry

NewRegistry は新しいRegistryを作成

func (*Registry) Execute

func (r *Registry) Execute(tc *ToolCall) (string, *FileChange)

Execute はツール呼び出しを実行(スレッドセーフ + 監査ログ記録)

func (*Registry) GetTool added in v0.31.0

func (r *Registry) GetTool(name string) Tool

GetTool は登録されたツールを取得(スレッドセーフ) 主にテスト用途

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register はツールを登録(スレッドセーフ)

type RestoreBackupTool added in v0.31.0

type RestoreBackupTool struct{}

RestoreBackupTool needs special error handling

func (*RestoreBackupTool) Name added in v0.31.0

func (t *RestoreBackupTool) Name() string

func (*RestoreBackupTool) Run added in v0.31.0

func (t *RestoreBackupTool) Run(args map[string]string) (string, *FileChange, error)

type SimpleTool added in v0.31.0

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

SimpleTool は引数を受け取り結果のみ返すシンプルなツール

func (*SimpleTool) Name added in v0.31.0

func (t *SimpleTool) Name() string

func (*SimpleTool) Run added in v0.31.0

func (t *SimpleTool) Run(args map[string]string) (string, *FileChange, error)

type SymbolInfo added in v0.31.0

type SymbolInfo struct {
	Name   string
	Line   int    // 1-indexed
	Column int    // 1-indexed
	Kind   string // func, type, var, const, class, etc.
}

SymbolInfo は削除対象のシンボル情報

func ExtractSymbolsFromContent added in v0.31.0

func ExtractSymbolsFromContent(content, language string) []SymbolInfo

ExtractSymbolsFromContent はファイル内容からシンボル(関数/型/変数)を抽出

func ExtractSymbolsFromOldStr added in v0.31.0

func ExtractSymbolsFromOldStr(oldStr, language string) []SymbolInfo

ExtractSymbolsFromOldStr は削除される文字列からシンボルを抽出

type Tool

type Tool interface {
	// Name はツール名を返す
	Name() string

	// Run はツールを実行
	// output: ツールの実行結果
	// change: ファイル変更情報(変更がない場合はnil)
	// err: エラー(エラーがない場合はnil)
	Run(args map[string]string) (output string, change *FileChange, err error)
}

Tool はツールの共通インターフェース

type ToolCall

type ToolCall struct {
	Tool    string         `json:"tool"`
	RawArgs map[string]any `json:"args"`
	Args    map[string]string
}

ToolCall はAIからのツール呼び出し

func ParseToolCall

func ParseToolCall(response string) *ToolCall

ParseToolCall はレスポンスからツール呼び出しを抽出(最初の1つのみ - 後方互換)

func ParseToolCalls added in v0.31.0

func ParseToolCalls(response string) []*ToolCall

ParseToolCalls はレスポンスから全てのツール呼び出しを抽出 Markdownコードブロック内のJSONは除外する

func (*ToolCall) NormalizeArgs added in v0.31.0

func (tc *ToolCall) NormalizeArgs()

NormalizeArgs はRawArgsをArgsに変換(数値→文字列)

type ToolSafety added in v0.29.0

type ToolSafety int

ToolSafety はツールの安全性レベル

const (
	// SafetyHigh - 読み取り専用操作(常に自動承認OK)
	SafetyHigh ToolSafety = iota
	// SafetyMedium - 書き込み操作(--auto-approve で承認)
	SafetyMedium
	// SafetyLow - 破壊的操作(常に確認必須)
	SafetyLow
)

func GetToolSafety added in v0.29.0

func GetToolSafety(toolName string) ToolSafety

GetToolSafety は指定されたツールの安全性レベルを返す 定義されていないツールは SafetyMedium(中レベル)として扱う

Jump to

Keyboard shortcuts

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