Documentation
¶
Overview ¶
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Console bootstrap (non-Windows no-op). * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: Apache-2.0
Index ¶
- func ApplyGlobalTLSTrust(logger *zap.Logger)
- func CountMatchingFiles(dirPath string, options DirectoryScanOptions) (int, error)
- func DetectFileType(filePath string) string
- func EnableVirtualTerminal()
- func ExpandPath(path string) (string, error)
- func FormatDirectoryContent(files []FileInfo, maxTotalSize int64) string
- func GetEnvOrDefault(key, defaultValue string) string
- func GetEnvVariablesSanitized() string
- func GetFileBlame(filepath string) (string, error)
- func GetFileDiff(filepath string) (string, error)
- func GetFileHistory(filepath string) (string, error)
- func GetGitInfo(executor CommandExecutor) (string, error)
- func GetHomeDir() (string, error)
- func GetShellConfigFilePath(shellName string) string
- func GetShellHistory() (string, error)
- func GetShellHistoryFile() (string, error)
- func GetUserShell() string
- func GlobalTLSConfig() *tls.Config
- func InitializeLogger() (*zap.Logger, error)
- func IsSensitivePath(absPath string) bool
- func IsTemporaryError(err error) bool
- func LogStartupInfo(logger *zap.Logger)
- func MaybeUnescapeJSONishArgs(input string) (string, bool)
- func NewChromeTLSTransport() http.RoundTripper
- func NewHTTPClient(logger *zap.Logger, timeout time.Duration) *http.Client
- func NewHTTPClientH1(logger *zap.Logger, timeout time.Duration) *http.Client
- func NewHTTPClientWithTransport(logger *zap.Logger, timeout time.Duration, inner http.RoundTripper) *http.Client
- func NewJSONReader(data []byte) io.Reader
- func ParseSize(sizeStr string) (int64, error)
- func ReadFileContent(filePath string, maxSize int64) (string, error)
- func RepairJSONInvalidEscapes(s string) string
- func Retry[T any](ctx context.Context, logger *zap.Logger, maxAttempts int, ...) (T, error)
- func SanitizeSensitiveText(s string) string
- func ShellQuote(s string) string
- func ShouldSkipDir(dirName string) bool
- type APIClient
- type APIError
- type CommandExecutor
- type DirectoryScanOptions
- type FileInfo
- type LoggingTransport
- type OSCommandExecutor
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyGlobalTLSTrust ¶ added in v1.137.0
ApplyGlobalTLSTrust resolves the CHATCLI_CA_BUNDLE / CHATCLI_TLS_INSECURE_SKIP_VERIFY overrides and wires them into both the transports built by NewHTTPClient and http.DefaultTransport — so bare &http.Client{} instances (gateway channels, MCP transports, registries, version check) inherit the corporate trust as well.
Must run after the dotenv load so overrides set only in the .env file are seen. Idempotent; calling it with no overrides set is a no-op that leaves http.DefaultTransport untouched.
func CountMatchingFiles ¶ added in v1.17.1
func CountMatchingFiles(dirPath string, options DirectoryScanOptions) (int, error)
CountMatchingFiles faz uma varredura rápida para contar quantos arquivos em um diretório correspondem aos critérios das opções, sem ler seu conteúdo.
func DetectFileType ¶
DetectFileType detecta o tipo de arquivo com base na extensão
func EnableVirtualTerminal ¶ added in v1.160.0
func EnableVirtualTerminal()
EnableVirtualTerminal is a no-op outside Windows: Unix terminals process ANSI escapes natively. See console_windows.go for the Windows opt-in.
func ExpandPath ¶
ExpandPath expande o caractere ~ no início de um caminho para o diretório home do usuário. Se o caminho não começar com ~, ele é retornado sem modificações. A função não suporta a expansão de ~username, retornando um erro nesse caso.
func FormatDirectoryContent ¶
FormatDirectoryContent formata o conteúdo de vários arquivos em uma única string organizada com separadores claros e formatação adequada para cada tipo de arquivo.
func GetEnvOrDefault ¶
GetEnvOrDefault retorna o valor da variável de ambiente ou um valor padrão se não estiver definida
func GetEnvVariablesSanitized ¶ added in v1.15.0
func GetEnvVariablesSanitized() string
GetEnvVariablesSanitized retorna variáveis de ambiente com valores sensíveis redigidos.
func GetFileBlame ¶
Função auxiliar para obter blame de um arquivo
func GetFileDiff ¶
Função auxiliar para obter diferenças específicas de um arquivo
func GetFileHistory ¶
Função auxiliar para obter o histórico de um arquivo específico
func GetGitInfo ¶
func GetGitInfo(executor CommandExecutor) (string, error)
GetGitInfo agora aceita um CommandExecutor.
func GetHomeDir ¶
GetHomeDir retorna o diretório home do usuário atual.
func GetShellConfigFilePath ¶
GetShellConfigFilePath retorna o caminho do arquivo de configuração do shell com base no nome do shell.
func GetShellHistory ¶
GetShellHistory lê o arquivo de histórico do shell e retorna seu conteúdo.
func GetShellHistoryFile ¶
GetShellHistoryFile retorna o caminho do arquivo de histórico do shell.
func GlobalTLSConfig ¶ added in v1.137.0
GlobalTLSConfig returns the process-wide TLS overrides resolved by ApplyGlobalTLSTrust, or nil when none are configured. Callers that build their own transports should Clone() the result before mutating it.
func InitializeLogger ¶
InitializeLogger configura e inicializa um logger robusto com base nas variáveis de ambiente. Em ambiente de desenvolvimento ('dev'), os logs são enviados para o console de forma colorida e legível, e também para um arquivo em formato JSON. Em ambiente de produção ('prod'), os logs são enviados apenas para o arquivo em formato JSON. Suporta rotação de logs com lumberjack.
func IsSensitivePath ¶ added in v1.54.0
IsSensitivePath checks whether a file path points to a known sensitive location. The comparison is case-insensitive on every OS: Windows filesystems are case-insensitive (".SSH" is the same directory as ".ssh"), and on Unix over-matching an odd-cased lookalike only errs on the safe side.
func IsTemporaryError ¶
IsTemporaryError verifica se o erro é temporário e pode ser retryado. Agora usa errors.Unwrap para desembrulhar e As para checar APIError com status 429 ou 5xx, além de timeouts.
func LogStartupInfo ¶ added in v1.10.1
func MaybeUnescapeJSONishArgs ¶ added in v1.52.0
MaybeUnescapeJSONishArgs tenta desfazer escape de JSON embutido em uma string quando o conteúdo parece ser um objeto/array JSON com aspas escapadas. Retorna (valor, true) se conseguiu unescape e o resultado parece JSON.
func NewChromeTLSTransport ¶ added in v1.65.3
func NewChromeTLSTransport() http.RoundTripper
NewChromeTLSTransport creates an http.RoundTripper that uses a Chrome-like TLS fingerprint via uTLS with automatic HTTP/1.1 / HTTP/2 support based on ALPN negotiation.
func NewHTTPClient ¶
NewHTTPClient cria um cliente HTTP com LoggingTransport e timeout configurado. Cada chamada cria um http.Transport dedicado para evitar compartilhamento de pool de conexões e cache TLS entre providers diferentes.
func NewHTTPClientH1 ¶ added in v1.143.1
NewHTTPClientH1 is like NewHTTPClient but pins the connection to HTTP/1.1.
Go's bundled HTTP/2 client intermittently fails a POST-with-body with "unexpected EOF" against some Cloudflare-fronted hosts (observed on api.openai.com and api.x.ai image endpoints): the edge closes an idle h2 connection and the next request races the GOAWAY, and net/http does NOT retry requests that carry a body. HTTP/1.1 sidesteps the whole race and is rock-solid for request/response calls. Use it for non-streaming endpoints that send/receive large payloads (image generation), where h2 multiplexing buys nothing. Corporate TLS trust (CHATCLI_CA_BUNDLE / CHATCLI_TLS_INSECURE_SKIP_VERIFY) is preserved; only ALPN is constrained.
func NewHTTPClientWithTransport ¶ added in v1.65.3
func NewHTTPClientWithTransport(logger *zap.Logger, timeout time.Duration, inner http.RoundTripper) *http.Client
NewHTTPClientWithTransport cria um cliente HTTP com um transport customizado envolvido pelo LoggingTransport. Use para injetar transports com TLS customizado.
func NewJSONReader ¶
NewJSONReader cria um io.Reader a partir de um []byte para enviar em requisições HTTP
func ParseSize ¶ added in v1.19.1
ParseSize converte uma string de tamanho legível (como "50MB") para bytes.
func ReadFileContent ¶
ReadFileContent lê o conteúdo de um arquivo, expandindo ~ para o diretório home, mostrando um indicador de progresso para arquivos grandes.
func RepairJSONInvalidEscapes ¶ added in v1.160.1
RepairJSONInvalidEscapes conserta texto JSON-ish em que barras invertidas não foram escapadas — o caso clássico é o LLM embutir um path Windows ("C:\Users\x") numa string JSON, produzindo escapes inválidos como \U.
A decisão é POR LITERAL DE STRING, tudo-ou-nada: uma string que contém qualquer escape inválido é "suja" — o emissor claramente não estava escapando — e então TODAS as suas barras são tratadas como literais de path e duplicadas, inclusive as que por coincidência formariam escapes válidos (\b em "\builder", \t em "\temp\Users"). Preservam-se apenas \" (aspas são ilegais em nomes de arquivo Windows, logo é um escape real) e \\ (já escapada). Strings totalmente válidas ficam intactas, então um "\n" legítimo numa chave irmã sobrevive ao reparo da chave suja.
Retorna o input inalterado quando não há nada a reparar. Limitação inerente: uma string SÓ com escapes coincidentemente válidos (ex.: "C:\temp") é JSON válido e nunca chega a esta função — o erro segue para o chamador, que devolve o problema ao modelo.
func Retry ¶ added in v1.27.1
func Retry[T any](ctx context.Context, logger *zap.Logger, maxAttempts int, initialBackoff time.Duration, fn func(context.Context) (T, error)) (T, error)
Retry executa uma função com retry exponencial para erros temporários. - maxAttempts: Número máximo de tentativas (lido de ENV ou default). - initialBackoff: Tempo inicial de espera entre tentativas (lido de ENV ou default). - fn: Função a executar, que recebe ctx e retorna um resultado genérico T e erro.
func SanitizeSensitiveText ¶ added in v1.15.0
SanitizeSensitiveText remove/mascara tokens em qualquer texto antes de ir para histórico/LLM
func ShellQuote ¶ added in v1.56.1
ShellQuote wraps a string in POSIX-compliant single quotes, escaping any embedded single quotes. The result is safe to embed in a shell command without risk of injection.
func ShouldSkipDir ¶
ShouldSkipDir verifica se um diretório deve ser ignorado
Types ¶
type APIClient ¶
type APIClient struct {
// contains filtered or unexported fields
}
APIClient é um cliente HTTP especializado para APIs REST
func NewAPIClient ¶
NewAPIClient cria um novo cliente API com cabeçalhos padrão
type APIError ¶ added in v1.27.1
APIError é um erro estruturado para respostas HTTP com status code.
type CommandExecutor ¶ added in v1.18.0
type CommandExecutor interface {
Run(name string, arg ...string) error
Output(name string, arg ...string) ([]byte, error)
}
CommandExecutor define uma interface para executar comandos. Isso nos permite mockar a execução de comandos nos testes.
func NewOSCommandExecutor ¶ added in v1.18.0
func NewOSCommandExecutor() CommandExecutor
NewOSCommandExecutor cria um novo executor de comandos do sistema operacional.
type DirectoryScanOptions ¶
type DirectoryScanOptions struct {
MaxTotalSize int64 // Tamanho máximo do conteúdo total (em bytes)
MaxFilesToProcess int // Número máximo de arquivos a processar
Logger *zap.Logger
Extensions []string // Extensões de arquivo a incluir (vazio = todas)
ExcludeDirs []string // Diretórios a excluir
ExcludePatterns []string // Padrões de nome de arquivo a excluir (ex: "*.tmp")
IncludeHidden bool // Incluir arquivos/diretórios ocultos?
OnFileProcessed func(info FileInfo) // Callback para cada arquivo processado
}
DirectoryScanOptions configura opções para escaneamento de diretórios
func DefaultDirectoryScanOptions ¶
func DefaultDirectoryScanOptions(logger *zap.Logger) DirectoryScanOptions
DefaultDirectoryScanOptions retorna opções padrão para escaneamento
type FileInfo ¶
FileInfo armazena informações e conteúdo de um arquivo
func ProcessDirectory ¶
func ProcessDirectory(ctx context.Context, dirPath string, options DirectoryScanOptions) ([]FileInfo, error)
ProcessDirectory processa um diretório recursivamente de forma concorrente e segura.
type LoggingTransport ¶
type LoggingTransport struct {
Logger *zap.Logger
Transport http.RoundTripper
MaxBodySize int
}
LoggingTransport é um http.RoundTripper que adiciona logs às requisições e respostas
type OSCommandExecutor ¶ added in v1.18.0
type OSCommandExecutor struct{}
OSCommandExecutor é a implementação real que usa os/exec.