cli

package
v1.46.1 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

Index

Constants

View Source
const (
	SourceTypeUserInput     = agent.SourceTypeUserInput
	SourceTypeFile          = agent.SourceTypeFile
	SourceTypeCommandOutput = agent.SourceTypeCommandOutput
)

Constantes re-exportadas

View Source
const (
	StateNormal InteractionState = iota
	StateSwitchingProvider
	StateProcessing
	StateAgentMode
	ProfileNormal ExecutionProfile = iota
	ProfileAgent
	ProfileCoder
)
View Source
const (
	ColorReset  = "\033[0m"
	ColorGreen  = "\033[32m"
	ColorLime   = "\033[92m"
	ColorCyan   = "\033[36m"
	ColorGray   = "\033[90m"
	ColorPurple = "\033[35m"
	ColorBold   = "\033[1m"
	ColorYellow = "\033[33m"
	ColorRed    = "\033[31m"
)

ANSI Color Codes

View Source
const CoderSystemPrompt = `` /* 932-byte string literal not displayed */

Variables

View Source
var CommandFlags = map[string]map[string][]prompt.Suggest{
	"@file": {
		"--mode": {
			{Text: "full", Description: "Processa o conteúdo completo (padrão, trunca se necessário)"},
			{Text: "summary", Description: "Gera resumo estrutural (árvore de arquivos, tamanhos, sem conteúdo)"},
			{Text: "chunked", Description: "Divide grandes projetos em pedaços gerenciáveis (use /nextchunk para prosseguir)"},
			{Text: "smart", Description: "Seleciona arquivos relevantes com base no seu prompt (IA decide)"},
		},
	},
	"@command": {
		"-i":   {},
		"--ai": {},
	},
	"/switch": {
		"--model":      {},
		"--max-tokens": {},
		"--realm":      {},
		"--agent-id":   {},
	},
	"/session": {
		"new":    {},
		"save":   {},
		"load":   {},
		"list":   {},
		"delete": {},
	},
	"/context": {
		"create":   {},
		"attach":   {},
		"detach":   {},
		"list":     {},
		"delete":   {},
		"show":     {},
		"merge":    {},
		"attached": {},
		"export":   {},
		"import":   {},
		"metrics":  {},
		"help":     {},
	},
}

Functions

func AgentMaxTurns added in v1.41.1

func AgentMaxTurns() int

helper max turns

func HasStdin added in v1.16.1

func HasStdin() bool

Detecta se há dados no stdin (pipe/arquivo ao invés de TTY).

func PreprocessArgs added in v1.16.2

func PreprocessArgs(args []string) []string

PreprocessArgs normaliza o caso de -p/--prompt sem valor, convertendo para -p= / --prompt= Ex.: echo "msg" | chatcli -p -> trata como prompt vazio + stdin (não quebra o flag parser)

Types

type AgentMode

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

AgentMode representa a funcionalidade de agente autônomo no ChatCLI

func NewAgentMode

func NewAgentMode(cli *ChatCLI, logger *zap.Logger) *AgentMode

NewAgentMode cria uma nova instância do modo agente

func (*AgentMode) Run

func (a *AgentMode) Run(ctx context.Context, query string, additionalContext string, systemPromptOverride string) error

Run inicia o modo agente com uma consulta do usuário, utilizando um loop de Raciocínio-Ação (ReAct). Agora aceita systemPromptOverride para definir personas específicas (ex: Coder).

func (*AgentMode) RunOnce added in v1.19.0

func (a *AgentMode) RunOnce(ctx context.Context, query string, autoExecute bool) error

RunOnce executa modo agente one-shot

type AnimationManager

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

func NewAnimationManager

func NewAnimationManager() *AnimationManager

func (*AnimationManager) ShowThinkingAnimation

func (am *AnimationManager) ShowThinkingAnimation(message string)

ShowThinkingAnimation inicia ou atualiza a animação "pensando"

func (*AnimationManager) StopThinkingAnimation

func (am *AnimationManager) StopThinkingAnimation()

StopThinkingAnimation para a animação de forma segura

func (*AnimationManager) UpdateMessage

func (am *AnimationManager) UpdateMessage(message string)

UpdateMessage atualiza a mensagem sem parar e reiniciar a animação

type ChatCLI

type ChatCLI struct {
	Client client.LLMClient

	Provider string
	Model    string

	MaxTokensOverride int
	UserMaxTokens     int
	// contains filtered or unexported fields
}

ChatCLI representa a interface de linha de comando do chat

func NewChatCLI

func NewChatCLI(manager manager.LLMManager, logger *zap.Logger) (*ChatCLI, error)

NewChatCLI cria uma nova instância de ChatCLI

func (*ChatCLI) ApplyOverrides added in v1.16.0

func (cli *ChatCLI) ApplyOverrides(mgr manager.LLMManager, provider, model string) error

ApplyOverrides atualiza provider/model e reobtém o client correspondente

func (*ChatCLI) CancelOperation added in v1.22.0

func (cli *ChatCLI) CancelOperation()

CancelOperation cancela a operação atual se houver uma

func (*ChatCLI) GetContextCommands added in v1.37.0

func (cli *ChatCLI) GetContextCommands() []prompt.Suggest

GetContextCommands retorna a lista de sugestões para comandos com @

func (*ChatCLI) GetInternalCommands added in v1.37.0

func (cli *ChatCLI) GetInternalCommands() []prompt.Suggest

func (*ChatCLI) HandleOneShotOrFatal added in v1.16.3

func (cli *ChatCLI) HandleOneShotOrFatal(ctx context.Context, opts *Options) bool

HandleOneShotOrFatal executa o modo one-shot se solicitado (flag -p usada ou stdin presente). - Em caso de erro, imprime mensagem em Markdown (stderr) e faz logger.Fatal (sem fallback). - Retorna true se o one-shot foi tratado (com sucesso ou erro fatal). Retorna false se não foi acionado.

func (*ChatCLI) IsExecuting added in v1.22.0

func (cli *ChatCLI) IsExecuting() bool

IsExecuting retorna true se uma operação está em andamento

func (*ChatCLI) PrintWelcomeScreen added in v1.18.0

func (cli *ChatCLI) PrintWelcomeScreen()

PrintWelcomeScreen exibe a tela de boas-vindas completa e traduzida.

func (*ChatCLI) RunAgentOnce added in v1.19.0

func (cli *ChatCLI) RunAgentOnce(ctx context.Context, input string, autoExecute bool) error

RunAgentOnce executa o modo agente de forma não-interativa (one-shot)

func (*ChatCLI) RunCoderOnce added in v1.42.0

func (cli *ChatCLI) RunCoderOnce(ctx context.Context, input string) error

RunCoderOnce executa o modo coder de forma não-interativa (one-shot), mas mantendo o loop ReAct do AgentMode (com tool_calls/plugins).

func (*ChatCLI) RunOnce added in v1.16.0

func (cli *ChatCLI) RunOnce(ctx context.Context, input string, disableAnimation bool) error

func (*ChatCLI) Start

func (cli *ChatCLI) Start(ctx context.Context)

type CommandBlock

type CommandBlock = agent.CommandBlock

Aliases de tipos para manter compatibilidade

type CommandContextInfo

type CommandContextInfo = agent.CommandContextInfo

Aliases de tipos para manter compatibilidade

type CommandHandler

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

func NewCommandHandler

func NewCommandHandler(cli *ChatCLI) *CommandHandler

func (*CommandHandler) HandleCommand

func (ch *CommandHandler) HandleCommand(userInput string) bool

type CommandOutput

type CommandOutput = agent.CommandOutput

Aliases de tipos para manter compatibilidade

type ContextHandler added in v1.33.0

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

ContextHandler gerencia comandos relacionados a contextos

func NewContextHandler added in v1.33.0

func NewContextHandler(logger *zap.Logger) (*ContextHandler, error)

NewContextHandler cria um novo handler de contextos

func (*ContextHandler) GetManager added in v1.33.0

func (h *ContextHandler) GetManager() *ctxmgr.Manager

GetManager retorna o gerenciador de contextos

func (*ContextHandler) HandleContextCommand added in v1.33.0

func (h *ContextHandler) HandleContextCommand(sessionID, input string) error

HandleContextCommand processa comandos /context

type ExecutionProfile added in v1.43.0

type ExecutionProfile int

type FileChunk

type FileChunk struct {
	Index   int
	Total   int
	Content string
}

FileChunk representa um pedaço do conteúdo de arquivos

type HistoryManager

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

func NewHistoryManager

func NewHistoryManager(logger *zap.Logger) *HistoryManager

func (*HistoryManager) AppendAndRotateHistory added in v1.19.1

func (hm *HistoryManager) AppendAndRotateHistory(newCommands []string) error

AppendAndRotateHistory salva o histórico no arquivo e faz backup se o tamanho exceder o limite

func (*HistoryManager) LoadHistory

func (hm *HistoryManager) LoadHistory() ([]string, error)

LoadHistory carrega o histórico do arquivo

type InteractionState added in v1.22.0

type InteractionState int

type Logger

type Logger interface {
	Info(msg string, fields ...zap.Field)
	Error(msg string, fields ...zap.Field)
	Warn(msg string, fields ...zap.Field)
	Sync() error
}

Logger interface para facilitar a testabilidade

type Options added in v1.16.0

type Options struct {
	// Geral
	Version bool // --version | -v
	Help    bool // --help | -h

	// Modo one-shot
	Prompt         string        // -p | --prompt
	Provider       string        // --provider
	Model          string        // --model
	Timeout        time.Duration // --timeout
	NoAnim         bool          // --no-anim
	PromptFlagUsed bool          // indica se -p/--prompt foi passado explicitamente
	AgentAutoExec  bool          // --agent-auto-exec
	MaxTokens      int           // --max-tokens
	Realm          string        // --realm
	AgentID        string        // --agent-id
}

Options representa as flags suportadas pelo binário

func NewFlagSet added in v1.16.0

func NewFlagSet() (*flag.FlagSet, *Options)

NewFlagSet cria um FlagSet isolado e as Options para parsing

func Parse added in v1.16.0

func Parse(args []string) (*Options, error)

Parse analisa os args, valida e retorna Options

type SessionManager added in v1.23.0

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

SessionManager gerencia o salvamento e carregamento de sessões de conversa.

func NewSessionManager added in v1.23.0

func NewSessionManager(logger *zap.Logger) (*SessionManager, error)

NewSessionManager cria uma nova instância do SessionManager.

func (*SessionManager) DeleteSession added in v1.23.0

func (sm *SessionManager) DeleteSession(name string) error

DeleteSession apaga um arquivo de sessão.

func (*SessionManager) ListSessions added in v1.23.0

func (sm *SessionManager) ListSessions() ([]string, error)

ListSessions lista todas as sessões salvas.

func (*SessionManager) LoadSession added in v1.23.0

func (sm *SessionManager) LoadSession(name string) ([]models.Message, error)

LoadSession carrega o histórico de uma conversa de um arquivo JSON.

func (*SessionManager) SaveSession added in v1.23.0

func (sm *SessionManager) SaveSession(name string, history []models.Message) error

SaveSession salva o histórico da conversa em um arquivo JSON.

type SourceType

type SourceType = agent.SourceType

Aliases de tipos para manter compatibilidade

Directories

Path Synopsis
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

Jump to

Keyboard shortcuts

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