agent

package
v0.42.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const MaxFileCacheSize = 1024 * 1024

MaxFileCacheSize はキャッシュする最大ファイルサイズ (1MB)

Variables

This section is empty.

Functions

func CheckBeforeImplementation added in v0.31.0

func CheckBeforeImplementation(input string) string

CheckBeforeImplementation は実装前に既存定義をチェック 戻り値: 警告メッセージ(問題なければ空文字列)

func CheckGoModExists

func CheckGoModExists() bool

CheckGoModExists は go.mod があるか確認

func ExtractDefinitionNames added in v0.31.0

func ExtractDefinitionNames(input string) []string

ExtractDefinitionNames は入力テキストから関数/型/変数名を抽出

func FormatFileSize added in v0.29.0

func FormatFileSize(bytes int64) string

FormatFileSize はファイルサイズを人間が読める形式で返す

func GetFileLanguage added in v0.31.0

func GetFileLanguage(filePath string) string

GetFileLanguage はファイル拡張子から言語を判定

func GetSessionFileSize added in v0.29.0

func GetSessionFileSize(sessionPath string) (int64, error)

GetSessionFileSize はセッションファイルのサイズを返す(bytes)

func IsAPIKeyAvailable added in v0.29.0

func IsAPIKeyAvailable(provider string) bool

IsAPIKeyAvailable は指定されたプロバイダーのAPIキーが利用可能かチェック

func IsCodeModificationRequest added in v0.31.0

func IsCodeModificationRequest(input string) bool

IsCodeModificationRequest はコード変更を伴うリクエストかどうかを判定

func RunGoFmt

func RunGoFmt(filePath string) (string, error)

RunGoFmt は go fmt を実行

func RunGoTest

func RunGoTest(filePath string) (string, bool, error)

RunGoTest は go test を実行(該当パッケージのみ)

func RunInteractive

func RunInteractive(model string, provider api.Provider, autoApprove bool)

RunInteractive はインタラクティブモードでエージェントを実行

func RunInteractiveWithResume

func RunInteractiveWithResume(model string, provider api.Provider, autoApprove bool)

RunInteractiveWithResume は前回のセッションを再開してインタラクティブモードを実行

func RunOnce

func RunOnce(query string, model string)

RunOnce は単一のクエリを実行(レガシーAPI)

func RunOnceWithImage added in v0.31.0

func RunOnceWithImage(query string, model string, provider api.Provider, imagePath string, autoApprove bool)

RunOnceWithImage は画像付きの単一クエリを実行(CLIフラグ -i/--image 用)

Types

type Agent

type Agent struct {
	Model           string // 初期モデル(後方互換性のため保持)
	CurrentModel    string // 現在のモデル(再起動なしで切り替え可能)
	CurrentProvider api.Provider
	ProviderName    string
	History         []api.Message
	SystemPrompt    string

	AutoApprove bool          // --auto-approve フラグ
	Stats       *SessionStats // セッション統計情報

	PlanModeEnabled bool       // Plan Mode ON/OFF(デフォルト: false)
	ToolCache       *ToolCache // ツール結果キャッシュ(read_file, list_dir)
	// contains filtered or unexported fields
}

Agent はCLIエージェント

func NewAgent

func NewAgent(model string, provider api.Provider) *Agent

NewAgent は新しいAgentを作成

func (*Agent) AddGitHubHint added in v0.31.0

func (a *Agent) AddGitHubHint(input string) string

AddGitHubHint はGitHub関連リクエストにシステムヒントを追加する

func (*Agent) Cleanup

func (a *Agent) Cleanup()

Cleanup はエージェントのリソースをクリーンアップ

func (*Agent) CompressHistory added in v0.29.0

func (a *Agent) CompressHistory(keepRecent int) error

CompressHistory は会話履歴を圧縮する

func (*Agent) CompressWithCompactAPI added in v0.31.0

func (a *Agent) CompressWithCompactAPI(ctx context.Context) error

CompressWithCompactAPI は OpenAI Compact API で会話履歴を圧縮

func (*Agent) EstimateHistoryTokens added in v0.31.0

func (a *Agent) EstimateHistoryTokens() int

EstimateHistoryTokens は会話履歴のトークン数を推定

func (*Agent) EstimateSystemPromptTokens added in v0.31.0

func (a *Agent) EstimateSystemPromptTokens() int

EstimateSystemPromptTokens はシステムプロンプトのトークン数を推定

func (*Agent) EstimateTokens added in v0.31.0

func (a *Agent) EstimateTokens() int

EstimateTokens は現在のトークン使用量を推定

func (*Agent) GetCompactedItems added in v0.31.0

func (a *Agent) GetCompactedItems() []api.InputItem

GetCompactedItems は API 用の圧縮済みアイテムを返す

func (*Agent) GetLSPClient added in v0.31.0

func (a *Agent) GetLSPClient() *lsp.Client

GetLSPClient はLSPクライアントを返す(コマンド用)

func (*Agent) GetTokenUsagePercentage added in v0.31.0

func (a *Agent) GetTokenUsagePercentage() float64

GetTokenUsagePercentage はトークン使用率を計算

func (*Agent) HasGitHubMCP added in v0.31.0

func (a *Agent) HasGitHubMCP() bool

HasGitHubMCP はGitHub MCPサーバーが接続されているか確認する

func (*Agent) IsCompactedMode added in v0.31.0

func (a *Agent) IsCompactedMode() bool

IsCompactedMode は圧縮モードかどうかを返す

func (*Agent) PrintStatusFooter added in v0.31.0

func (a *Agent) PrintStatusFooter()

PrintStatusFooter prints a short, bilingual status line. This should be called right before showing the input prompt.

func (*Agent) ProposeAndApplyLearning added in v0.31.0

func (a *Agent) ProposeAndApplyLearning(ctx context.Context, extractor LearningExtractor, xelyonPath string) (bool, []string, error)

ProposeAndApplyLearning extracts rules and asks the user whether to append them to XELYON.md. It returns (applied, rules, err). If no rules are found, applied=false and err=nil.

func (*Agent) RestoreCompactedState added in v0.31.0

func (a *Agent) RestoreCompactedState(session *history.Session)

RestoreCompactedState はセッションから圧縮状態を復元

func (*Agent) RunPlanMode added in v0.29.0

func (a *Agent) RunPlanMode(ctx context.Context, userRequest string) error

RunPlanMode は Claude Code 風の Plan Mode を実行 - 調査ツール(SafetyHigh)は即座に実行 - 実装ツール(SafetyMedium/Low)の前に計画を生成・承認

func (*Agent) SetStatus added in v0.31.0

func (a *Agent) SetStatus(state AgentState, reasonEN, reasonJP, nextEN, nextJP string)

SetStatus updates the current agent status.

func (*Agent) SwitchProvider added in v0.29.0

func (a *Agent) SwitchProvider(providerName string) error

SwitchProvider はプロバイダーを切り替える

type AgentState added in v0.31.0

type AgentState string

AgentState represents the current interaction state. This is used to make it obvious whether XELYON is waiting for input, waiting for approval, running, or aborted.

const (
	StateRunning         AgentState = "running"
	StateWaitingInput    AgentState = "waiting_input"
	StateWaitingApproval AgentState = "waiting_approval"
	StateAborted         AgentState = "aborted"
	StateCompleted       AgentState = "completed"
)

type AgentStatus added in v0.31.0

type AgentStatus struct {
	State      AgentState
	ReasonEN   string
	ReasonJP   string
	NextEN     string
	NextJP     string
	LastUpdate int64 // unix nanos (debug/ordering; optional)
}

type CodeCheckResult added in v0.31.0

type CodeCheckResult struct {
	Exists      bool     // 定義が既に存在するか
	Type        string   // "function", "type", "const", "var", "method"
	Name        string   // 定義名
	FilePaths   []string // 定義が存在するファイルパス
	LineNumbers []int    // 各ファイルでの行番号
	Context     string   // 周辺コード(最初の一致のみ)
}

CodeCheckResult はコードスキャン結果

func ScanForDefinition added in v0.31.0

func ScanForDefinition(name string, searchPath string) (*CodeCheckResult, error)

ScanForDefinition は指定された名前の定義をコードベースからスキャン

type ErrorInfo added in v0.29.0

type ErrorInfo struct {
	Type    string `json:"type"`           // エラータイプ(api_error, tool_error, etc.)
	Message string `json:"message"`        // エラーメッセージ
	Code    int    `json:"code,omitempty"` // エラーコード(HTTPステータスなど)
}

ErrorInfo はエラー情報

type HeadlessResult added in v0.29.0

type HeadlessResult struct {
	Status     string           `json:"status"`               // "success" or "error"
	Provider   string           `json:"provider"`             // LLMプロバイダー名
	Model      string           `json:"model"`                // モデル名
	Response   string           `json:"response"`             // AIの最終回答
	ToolCalls  []ToolCallResult `json:"tool_calls,omitempty"` // 実行されたツール呼び出し
	Tokens     *TokenUsage      `json:"tokens,omitempty"`     // トークン使用量
	DurationMs int64            `json:"duration_ms"`          // 実行時間(ミリ秒)
	Timestamp  string           `json:"timestamp"`            // タイムスタンプ(RFC3339)
	Error      *ErrorInfo       `json:"error,omitempty"`      // エラー情報
}

HeadlessResult はHeadlessモードの実行結果

func NewErrorResult added in v0.29.0

func NewErrorResult(provider, model string, errType, errMsg string, durationMs int64) *HeadlessResult

NewErrorResult はエラー結果を生成

func NewSuccessResult added in v0.29.0

func NewSuccessResult(provider, model, response string, toolCalls []ToolCallResult, durationMs int64) *HeadlessResult

NewSuccessResult は成功結果を生成

func RunHeadless added in v0.29.0

func RunHeadless(query string, model string, provider api.Provider) *HeadlessResult

RunHeadless はHeadlessモードでクエリを実行

func (*HeadlessResult) ToJSON added in v0.29.0

func (r *HeadlessResult) ToJSON() (string, error)

ToJSON は HeadlessResult を JSON 文字列に変換

type InitConfig added in v0.31.0

type InitConfig struct {
	ProjectName   string
	Overview      string
	TechStack     []string
	CodingRules   string
	RepoMapData   *repomap.RepoMap
	LanguageStats map[string]int // 言語 → ファイル数
}

InitConfig は/initコマンドで収集する情報

type LLMExtractor added in v0.31.0

type LLMExtractor struct {
	Provider     api.Provider
	SystemPrompt string
}

LLMExtractor uses the current provider to extract rules. It requests JSON output for robust parsing.

func (*LLMExtractor) Extract added in v0.31.0

func (e *LLMExtractor) Extract(ctx context.Context, history []api.Message, model string) ([]string, error)

type LearningExtractor added in v0.31.0

type LearningExtractor interface {
	Extract(ctx context.Context, history []api.Message, model string) ([]string, error)
}

LearningExtractor extracts coding rules/instructions from conversation history. It is interface-based for testability (stub/mocking).

type SessionStats added in v0.29.0

type SessionStats struct {
	StartTime         time.Time
	UserMessages      int
	AssistantMessages int
	ToolExecutions    map[string]int // ツール名 -> 実行回数
	InputTokens       int
	OutputTokens      int
	Provider          string // "deepseek", "openai", "claude", "gemini", "groq", "ollama"
}

SessionStats はセッション統計情報

func NewSessionStats added in v0.29.0

func NewSessionStats(provider string) *SessionStats

NewSessionStats は新しいSessionStatsを作成

func (*SessionStats) AddTokens added in v0.29.0

func (s *SessionStats) AddTokens(input, output int)

AddTokens はトークン使用量を追加

func (*SessionStats) AddToolExecution added in v0.29.0

func (s *SessionStats) AddToolExecution(toolName string)

AddToolExecution はツール実行をカウント

func (*SessionStats) ElapsedTime added in v0.29.0

func (s *SessionStats) ElapsedTime() time.Duration

ElapsedTime はセッション開始からの経過時間を返す

func (*SessionStats) EstimatedCost added in v0.29.0

func (s *SessionStats) EstimatedCost() float64

EstimatedCost は推定コストを計算(USD)

func (*SessionStats) FormatElapsedTime added in v0.29.0

func (s *SessionStats) FormatElapsedTime() string

FormatElapsedTime は経過時間を人間が読める形式で返す

func (*SessionStats) TotalMessages added in v0.29.0

func (s *SessionStats) TotalMessages() int

TotalMessages は合計メッセージ数を返す

func (*SessionStats) TotalTokens added in v0.29.0

func (s *SessionStats) TotalTokens() int

TotalTokens は合計トークン数を返す

func (*SessionStats) TotalToolExecutions added in v0.29.0

func (s *SessionStats) TotalToolExecutions() int

TotalToolExecutions は合計ツール実行回数を返す

type SyncDiff added in v0.31.0

type SyncDiff struct {
	AddedTech    []string
	RemovedTech  []string
	AddedFiles   []string
	RemovedFiles []string
	NewSymbols   int
}

SyncDiff は変更の差分を表す

func (*SyncDiff) HasChanges added in v0.31.0

func (d *SyncDiff) HasChanges() bool

HasChanges は変更があるかどうかを返す

type SyncState added in v0.31.0

type SyncState struct {
	ProjectName  string
	Overview     string
	TechStack    []string
	CodingRules  string
	CodeMapFiles []string // コードマップに含まれるファイル一覧
}

SyncState は現在のXELYON.mdの状態を表す

type TokenUsage added in v0.29.0

type TokenUsage struct {
	Input  int `json:"input"`  // 入力トークン数
	Output int `json:"output"` // 出力トークン数
	Total  int `json:"total"`  // 合計トークン数
}

TokenUsage はトークン使用量

type ToolCache added in v0.42.0

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

ToolCache はツール結果のキャッシュ read_file, list_dir, search_code, search_file の結果をキャッシュしてトークン消費を削減

func NewToolCache added in v0.42.0

func NewToolCache() *ToolCache

NewToolCache は新しい ToolCache を作成

func (*ToolCache) Clear added in v0.42.0

func (c *ToolCache) Clear()

Clear は全キャッシュをクリア

func (*ToolCache) ClearSearchCache added in v0.42.0

func (c *ToolCache) ClearSearchCache()

ClearSearchCache は検索キャッシュをクリア

func (*ToolCache) GetDir added in v0.42.0

func (c *ToolCache) GetDir(path string) (string, bool)

GetDir はディレクトリ一覧のキャッシュを取得

func (*ToolCache) GetFile added in v0.42.0

func (c *ToolCache) GetFile(path string) (string, bool)

GetFile はファイル内容のキャッシュを取得

func (*ToolCache) GetSearch added in v0.42.0

func (c *ToolCache) GetSearch(pattern, path string) (string, bool)

GetSearch は検索結果のキャッシュを取得

func (*ToolCache) InvalidateDir added in v0.42.0

func (c *ToolCache) InvalidateDir(path string)

InvalidateDir は指定ディレクトリのキャッシュを無効化

func (*ToolCache) InvalidateFile added in v0.42.0

func (c *ToolCache) InvalidateFile(path string)

InvalidateFile は指定ファイルのキャッシュを無効化

func (*ToolCache) SetDir added in v0.42.0

func (c *ToolCache) SetDir(path, result string)

SetDir はディレクトリ一覧をキャッシュに保存

func (*ToolCache) SetFile added in v0.42.0

func (c *ToolCache) SetFile(path, content string)

SetFile はファイル内容をキャッシュに保存

func (*ToolCache) SetSearch added in v0.42.0

func (c *ToolCache) SetSearch(pattern, path, result string)

SetSearch は検索結果をキャッシュに保存

func (*ToolCache) Stats added in v0.42.0

func (c *ToolCache) Stats() (files, dirs, searches int)

Stats はキャッシュの統計情報を返す

type ToolCallResult added in v0.29.0

type ToolCallResult struct {
	Tool    string            `json:"tool"`    // ツール名
	Args    map[string]string `json:"args"`    // 引数
	Output  string            `json:"output"`  // 出力
	Success bool              `json:"success"` // 成功フラグ
}

ToolCallResult は個別のツール呼び出し結果

type VerifyResult

type VerifyResult struct {
	NeedsVerify  bool     // 検証が必要か
	FileType     string   // "go", "js", "py" など
	ChangedFiles []string // 変更されたファイル
	FmtResult    string   // go fmt の結果
	TestResult   string   // go test の結果
	TestPassed   bool     // テスト成功したか
}

VerifyResult は検証結果

func ShouldVerify

func ShouldVerify(filePath string) *VerifyResult

ShouldVerify は変更されたファイルが検証対象かを判定

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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