feat: 配置系统重构,添加用户配置和中文注释

This commit is contained in:
2026-04-23 20:11:22 +08:00
parent e070461fe4
commit dd3c8a03e1
10 changed files with 336 additions and 318 deletions

View File

@@ -1,3 +1,5 @@
// Package main 是 hxclaw 应用程序的入口包
// 提供交互式 CLI 界面和流式输出功能
package main
import (
@@ -18,41 +20,53 @@ import (
"github.com/sipeed/picoclaw/pkg/providers"
)
// Logo 应用 Logo 字符常量
const Logo = "🦐"
// main 程序入口函数
// 负责初始化配置、创建 Provider、启动 Agent Loop 和交互式界面
func main() {
// 加载 hxclaw 项目配置
if err := internal.LoadProjectConfig(); err != nil {
fmt.Fprintf(os.Stderr, "错误:加载项目配置失败: %v\n", err)
os.Exit(1)
}
// 打印应用 Logo 和欢迎信息
logo := internal.GetProjectConfig().UI.Logo
fmt.Printf("%s HxClaw - PicoClaw 增强版 CLI\n\n", logo)
// 加载 picoclaw 配置文件
cfg, err := internal.LoadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "错误:加载配置失败: %v\n", err)
os.Exit(1)
}
// 配置日志系统
logger.ConfigureFromEnv()
// 创建 AI Provider支持 OpenAI、Claude 等)
provider, modelID, err := providers.CreateProvider(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "错误:创建 Provider 失败: %v\n", err)
os.Exit(1)
}
// 如果命令行指定了模型 ID覆盖配置文件中的默认模型
if modelID != "" {
cfg.Agents.Defaults.ModelName = modelID
}
// 创建消息总线,用于组件间通信
msgBus := bus.NewMessageBus()
defer msgBus.Close()
// 创建 Agent Loop处理用户交互和 AI 请求
agentLoop := agent.NewAgentLoop(cfg, msgBus, provider)
defer agentLoop.Close()
// 获取启动信息并打印
startupInfo := agentLoop.GetStartupInfo()
logger.InfoCF("hxclaw", "HxClaw 已初始化",
map[string]any{
@@ -61,12 +75,15 @@ func main() {
"skills_available": startupInfo["skills"].(map[string]any)["available"],
})
// 打印交互模式提示
fmt.Printf("%s Interactive mode (Ctrl+C to exit)\n\n", Logo)
// 启动交互模式
interactiveMode(agentLoop, "cli:default")
}
func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
prompt := internal.GetProjectConfig().UI.UserPrefix
prompt := internal.GetProjectConfig().UI.UserIcon
rl, err := internal.NewReadline(prompt)
if err != nil {
@@ -105,7 +122,7 @@ func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
reader := internal.NewSimpleReader()
for {
fmt.Print(internal.GetProjectConfig().UI.UserPrefix)
fmt.Print(internal.GetProjectConfig().UI.UserIcon)
line, err := reader.ReadString()
if err != nil {
if err == internal.ErrEOF {
@@ -130,30 +147,42 @@ func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
}
}
// runWithStreaming 使用 ProcessDirect 处理请求,支持工具调用和结果显示
// runWithStreaming 使用 ProcessDirect 处理请求并以模拟流式方式输出结果
// 1. 显示加载动画表示 AI 正在思考
// 2. 调用 Agent 处理用户输入
// 3. 渲染 Markdown 输出并按行延迟显示
// 4. 打印处理耗时
func runWithStreaming(agentLoop *agent.AgentLoop, input, sessionKey string) {
startTime := time.Now()
// 创建并启动加载动画
spinner := internal.NewSpinner("思考中...")
spinner.Start()
// 调用 AI 处理用户输入
resp, err := agentLoop.ProcessDirect(context.Background(), input, sessionKey)
// 停止加载动画
spinner.Stop()
// 处理错误
if err != nil {
fmt.Printf("错误: %v\n", err)
return
}
// 渲染 Markdown 并输出
rendered := internal.RenderMarkdown(resp)
clearSpinnerLine()
outputLineByLine(rendered)
// 打印处理耗时
elapsed := time.Since(startTime)
printElapsed(elapsed)
}
// clearSpinnerLine 清除 spinner 行
// 使用终端控制字符清除当前行并移动到行首
func clearSpinnerLine() {
output := termenv.DefaultOutput()
output.ClearLine()
@@ -161,6 +190,9 @@ func clearSpinnerLine() {
os.Stdout.Sync()
}
// outputLineByLine 按行输出文本,模拟打字效果
// 每行之间根据配置延迟,最后一行延迟时间较长
// 空行会直接输出不延迟
func outputLineByLine(text string) {
if text == "" {
return
@@ -169,10 +201,12 @@ func outputLineByLine(text string) {
lines := strings.Split(text, "\n")
totalLines := len(lines)
// 获取延迟配置
cfg := internal.GetProjectConfig()
lineDelay := time.Duration(cfg.Streaming.LineDelayMs) * time.Millisecond
lastLineDelay := time.Duration(cfg.Streaming.LastLineDelayMs) * time.Millisecond
// 逐行输出
for i, line := range lines {
if line == "" {
lipgloss.Print("\n")
@@ -181,6 +215,7 @@ func outputLineByLine(text string) {
lipgloss.Print(line + "\n")
// 非最后一行使用普通延迟,最后一行使用较长延迟
if i < totalLines-1 {
time.Sleep(lineDelay)
} else {
@@ -191,11 +226,14 @@ func outputLineByLine(text string) {
lipgloss.Print("\n")
}
// 输出样式定义
var (
iconStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#f0c75e"))
textStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#2b2e32"))
iconStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#f0c75e")) // 图标样式(金色)
textStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#2b2e32")) // 文本样式(深灰)
)
// printElapsed 打印处理耗时信息
// 格式化输出:小于 60 秒显示秒数,否则显示分钟数
func printElapsed(elapsed time.Duration) {
elapsedSec := math.Round(elapsed.Seconds()*10) / 10
elapsedStr := formatDuration(elapsedSec)
@@ -205,6 +243,8 @@ func printElapsed(elapsed time.Duration) {
fmt.Printf(" %s%s\n\n", icon, text)
}
// formatTokens 格式化 token 数量
// 1000 以上显示为 k 单位(如 1.5k
func formatTokens(n int) string {
if n >= 1000 {
return fmt.Sprintf("%.1fk", float64(n)/1000)
@@ -212,6 +252,8 @@ func formatTokens(n int) string {
return fmt.Sprintf("%d", n)
}
// formatDuration 格式化时长字符串
// 小于 60 秒显示秒数(如 12.5s),否则显示分钟数(如 2.5m
func formatDuration(s float64) string {
if s >= 60 {
return fmt.Sprintf("%.1fm", s/60)