8 Commits

Author SHA1 Message Date
724981b50a fix: 修复 TTS JSON 请求格式,兼容 Windows daemon
Some checks failed
Release / build (push) Failing after 23s
2026-04-26 03:54:29 +08:00
94328d4f28 删除 hxclaw 2026-04-26 03:17:03 +08:00
a7c240c833 docs: 全面更新文档(agents.md, taolun.md)包含 TTS 功能说明 2026-04-26 03:16:02 +08:00
1c73fb469c docs: 更新目前进度 2026-04-26 03:13:37 +08:00
73b480323d docs: 清理 changelog 重复内容 2026-04-26 03:12:59 +08:00
6c74d4032c docs: 更新 changelog,修正已实现功能状态 2026-04-26 03:12:35 +08:00
b12378df10 docs: 更新 changelog.md,修正版本状态 2026-04-26 03:10:54 +08:00
e4e5cd82c3 feat: 添加 TTS 语音朗读功能 (v0.2.0)
Some checks failed
Release / build (push) Failing after 6m27s
2026-04-26 03:01:28 +08:00
12 changed files with 684 additions and 382 deletions

View File

@@ -16,16 +16,15 @@ jobs:
- name: Checkout
run: |
apk add git bash
git clone https://hub.gaomia.site/titor/HxClaw.git /workspace/hxclaw
cp -r /workspace/hxclaw/* /workspace/hxclaw/
cp -r /workspace/hxclaw/.* /workspace/hxclaw/ 2>/dev/null || true
rm -rf /workspace
git clone https://hub.gaomia.site/titor/hxclaw.git /workspace
- name: Download dependencies
run: go mod download
run: cd /workspace && go mod download
- name: Build
run: |
cd /workspace/hxclaw
cd /workspace
for p in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64; do
os=${p%/*}
arch=${p#*/}
@@ -35,12 +34,13 @@ jobs:
done
- name: Checksums
run: sha256sum hxclaw-* > checksums.txt
run: cd /workspace && sha256sum hxclaw-* > checksums.txt
- name: Release
env:
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITEA_TOKEN: "${{ secrets.release_token }}"
run: |
cd /workspace
apk add curl jq
TAG_NAME="${GITHUB_REF#refs/tags/}"

57
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,57 @@
name: Release
on:
push:
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
container:
image: golang:1.26-alpine
env:
GOPROXY: "https://mirrors.aliyun.com/goproxy/,direct"
steps:
- name: Checkout
run: |
apk add git bash
- name: Download dependencies
run: go mod download
- name: Build
run: |
for p in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64; do
os=${p%/*}
arch=${p#*/}
ext=""
[ "$os" = "windows" ] && ext=".exe"
GOOS=$os GOARCH=$arch go build -o "hxclaw-${os}-${arch}${ext}" ./cmd/hxclaw
done
- name: Checksums
run: sha256sum hxclaw-* > checksums.txt
- name: Release
env:
GITEA_TOKEN: ${{ secrets.release_token }}
run: |
apk add curl jq
TAG_NAME="${GITHUB_REF#refs/tags/}"
RELEASE_BODY=$(git tag -l --format='%(contents)' "$TAG_NAME" 2>/dev/null || git log -1 --format="%s%n%n%b" "$TAG_NAME" 2>/dev/null || echo "Release $TAG_NAME")
RELEASE_RESPONSE=$(curl -s -X POST "https://hub.gaomia.site/api/v1/repos/titor/hxclaw/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":\"${RELEASE_BODY}\"}")
RELEASE_ID=$(echo "$RELEASE_RESPONSE" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
for f in hxclaw-* checksums.txt; do
[ -f "$f" ] && curl -s -X POST "https://hub.gaomia.site/api/v1/repos/titor/hxclaw/releases/${RELEASE_ID}/assets" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@$f"
done

4
.gitignore vendored
View File

@@ -1,8 +1,8 @@
.DS_Store
*.ini
hxclaw*
hxclaw.exe*
hxclaw
hxclaw.exe
.idea/
.fleet/

103
agents.md
View File

@@ -41,36 +41,43 @@
## 当前任务
### v0.1.0 目标
### v0.2.0 目标
实现流式输出功能:
1. 创建 go.mod 配置依赖
2. 实现 main.go 入口
3. 实现流式 Provider 调用
4.时打印 token
5. 处理非流式 Provider 回退
6. Markdown 终端渲染glamour
实现 TTS 语音朗读功能:
1. 集成 mimo-tts clientTCP 连接本地 daemon
2. 添加配置文件 TTS 开关
3. 实现命令行切换(/tts on/off/status
4.现临时 TTS 前缀(`T 消息`
5. 动态提示符显示状态(👀 🔊)
---
## 实现进度
### v0.1.0 已完成功能
### v0.2.0 已完成功能
1. **流式输出(新流程)**
1. **TTS 语音朗读**
- 集成 mimo-tts clientTCP 连接)
- 配置文件开关tts.enabled
- 命令行切换(/tts on/off/status
- 临时 TTS 前缀(`T 消息`
- 动态提示符显示状态(👀 🔊)
- 静默失败处理(网络异常时仅记录日志)
2. **流式输出(新流程)**
- 等待 AI 返回完整响应
- Markdown 转译
- 模拟流式输出(从配置读取速度)
- 效果更好,无残留问题
2. **Markdown 渲染**
3. **Markdown 渲染**
- 使用 glamour 库渲染 Markdown
- 支持多种主题dark, light, dracula, tokyo-night 等)
- 通过 project.config.yml 配置主题
3. **项目配置**
4. **项目配置**
- 通过 project.config.yml 统一管理配置项
- 支持流式速度、渲染主题、Logo 等配置
- 支持流式速度、渲染主题、Logo、TTS 等配置
---
@@ -78,11 +85,10 @@
### project.config.yml
项目配置文件位于项目根目录:
配置文件位于项目根目录:
```yaml
# hxclaw 项目配置文件
# 项目级配置,会覆盖默认配置但被用户配置覆盖
# 模拟流式输出配置
streaming:
@@ -91,20 +97,48 @@ streaming:
# Markdown 渲染配置
markdown:
theme: dark # 渲染主题dark, light, dracula, tokyo-night 等
line_width: 0 # 自动换行宽度0=自动,>0=固定宽度,-1=禁用)
glamour_style: dark # 渲染主题dark, light, dracula, tokyo-night 等
# UI 配置
ui:
logo: "🦐" # Logo
user_icon: "👀 " # 用户输入提示符
logo: "🦐"
user_prefix: "👀 "
# TTS 语音配置
tts:
enabled: false # 全局开关(默认关闭)
port: 9876 # mimo-tts daemon 端口
auto: true # AI 回复后自动朗读
```
配置加载优先级(从高到低)
1. 用户配置 `~/.config/hxclaw/config.yml`
2. 环境变量 `HXCLAW_CONFIG` 指定路径
3. 项目根目录 `project.config.yml`
4. 代码中的默认值
配置加载优先级:
1. 环境变量 `HXCLAW_CONFIG` 指定路径
2. 项目根目录 `project.config.yml`
---
## TTS 使用指南
### 命令
| 输入 | 行为 |
|------|------|
| `/tts` | 切换 TTS 开关 |
| `/tts on` | 开启 TTS |
| `/tts off` | 关闭 TTS |
| `/tts status` | 显示 TTS 状态 |
| `T 消息` | 临时开启 TTS 并发送消息 |
### 动态提示符
- 关闭:`👀 `
- 开启:`👀 🔊 `
### 注意事项
- 需要先安装并启动 mimo-tts daemon`mimo-tts daemon start`
- TTS 服务端地址:本地 9876 端口(默认)
- 网络异常时会静默失败,仅记录日志
---
@@ -117,21 +151,30 @@ ui:
- `charm.land/x/term` - 终端控制
- `github.com/muesli/termenv` - 终端环境工具
- `gopkg.in/yaml.v3` - 配置文件解析
- `github.com/ergochat/readline` - 终端输入
### 配置文件
- `cmd/hxclaw/main.go` - 主入口逻辑
- `cmd/hxclaw/internal/config.go` - 配置加载(支持用户配置和项目配置合并)
- `cmd/hxclaw/internal/markdown.go` - Markdown 渲染器
- `cmd/hxclaw/internal/helpers.go` - 辅助函数Readline、SimpleReader
- `cmd/hxclaw/internal/spinner.go` - 加载动画组件
- `cmd/hxclaw/internal/markdown_test.go` - Markdown 测试
- `cmd/hxclaw/internal/helpers.go` - 辅助函数Readline
- `cmd/hxclaw/internal/config.go` - 项目配置加载
- `cmd/hxclaw/internal/tts.go` - TTS 客户端
---
## 已解决
## 已知问题
1. ~~**重绘残留**:某些情况下有轻微文本重复~~ - 已通过新流程解决
1. **重绘残留**:某些情况下有轻微文本重复已通过新流程解决
2. **终端兼容性**termenv 在某些终端可能不完全工作
---
## 待优化
1. 打印和 TTS 朗读同时进行(而非先打印完再读)
2. 添加更多主题支持
3. 添加命令行参数支持主题选择
---

View File

@@ -2,26 +2,68 @@
## 版本记录
### v0.1.0 (当前)
### v0.2.1
- [x] 流式输出功能
- [x] Markdown 渲染功能
- [x] 配置系统(支持用户配置和项目配置)
- [x] 代码中文注释
- 修复 TTS JSON 请求格式,兼容 Windows daemon
- 发送格式改为 `{"text": "内容"}`
---
### v0.2.0 (计划)
### v0.2.0
- [ ] 代码块渲染
- [ ] 表格渲染
- [ ] 列表渲染
- 新增 TTS 语音朗读功能
- 集成 mimo-tts client 功能,通过 TCP 连接本地 daemon
- 支持配置文件开关tts.enabled
- 支持命令行切换(/tts on/off/status
- 支持临时 TTS 前缀(`T 消息` 临时开启)
- 动态提示符显示 TTS 状态(👀 🔊)
- 静默失败处理(网络异常时警告日志)
---
### v0.1.0
- 创建 hxclaw 项目
- 实现流式输出功能
- Markdown 渲染glamour自动代码高亮
- 项目配置化project.config.yml
---
## 待实现功能
### v0.2.0 (当前)
- [x] TTS 语音朗读功能
- [x] 集成 mimo-tts client (TCP 连接)
- [x] 配置文件开关 (tts.enabled)
- [x] 命令行切换 (/tts on/off/status)
- [x] 临时 TTS 前缀 (T 消息)
- [x] 动态提示符显示状态
- [x] 静默失败处理
### v0.3.0 (计划)
- [ ] 代码高亮
- [ ] 集成 glow 或类似库
- [ ] 支持常见语言语法高亮
- [ ] 命令行参数支持(--theme, --tts 等)
- [ ] 多语言支持
- [ ] 会话历史持久化
---
## 目前进度
- [x] 创建项目目录结构
- [x] 编写讨论记录taolun.md
- [x] 编写更新日志changelog.md
- [x] 编写 AI 行为指南agents.md
- [x] 创建 go.mod
- [x] 实现 main.go 入口
- [x] 实现流式输出核心逻辑
- [x] 编译成功,生成 hxclaw 二进制
- [x] 添加 spinner 加载动画组件
- [x] 实现 Markdown 渲染glamour
- [x] 实现项目配置化project.config.yml
- [x] 实现 TTS 语音朗读功能
---
@@ -53,7 +95,14 @@
**问题**:不是所有 Provider 都支持流式输出
**纠正**:需要使用类型断言判断 Provider 是否实现 `providers.StreamingProvider` 接口
**纠正**:需要使用类型断言判断 Provider 是否实现 `providers.StreamingProvider` 接口
```go
if sp, ok := provider.(providers.StreamingProvider); ok {
// 使用 ChatStream
} else {
// 使用普通 Chat
}
```
**知识点**picoclaw 的 Provider 设计使用了接口分离原则,流式是可选能力
@@ -64,8 +113,8 @@
**问题**:如何实现 Markdown 终端渲染
**纠正**:使用 charmbracelet 家族:
- glamourMarkdown 渲染
- lipgloss样式定义
- glow代码高亮
**知识点**charmbracelet 是 Go 终端UI 的事实标准API 设计优雅
@@ -83,16 +132,133 @@
---
### AgentRegistry 没有 BuildMessages 方法
**问题**:最初尝试调用 agentLoop.GetRegistry().BuildMessages() 构建消息
**纠正**BuildMessages 属于 ContextBuilder不是 AgentRegistry
```go
// 正确方式
agentInstance.ContextBuilder.BuildMessages(history, summary, input, media, channel, chatID, senderID, senderDisplayName)
```
**知识点**picoclaw 代码结构中ContextBuilder 负责消息构建AgentRegistry 负责 agent 管理
---
### ToolDefinitions 获取方式
**问题**:如何获取可用的工具定义列表
**纠正**:通过 ToolRegistry 的 ToProviderDefs 方法:
```go
toolDefs := agentInstance.Tools.ToProviderDefs()
```
**知识点**ToolRegistry 维护工具注册ToProviderDefs 转换为 provider 可用的格式
---
### 流式输出实时刷新
**问题**:流式输出时字符不是实时显示,要等很久才一次性出现
**纠正**:在 onChunk 回调中添加 `os.Stdout.Sync()` 强制刷新 stdout
```go
func(token string) {
fmt.Print(token)
os.Stdout.Sync() // 强制刷新
}
```
**知识点**Go 的 `fmt.Print` 使用缓冲输出,需要手动刷新才能实时显示
---
### Session 历史消息获取
**问题**:如何获取会话历史用于流式调用
**纠正**:通过 `SessionStore` 接口:
```go
history := agentInstance.Sessions.GetHistory(sessionKey)
summary := agentInstance.Sessions.GetSummary(sessionKey)
```
**知识点**`AgentInstance.Sessions` 实现了 `SessionStore` 接口,支持 `GetHistory``GetSummary` 方法
---
### 流式调用后的消息保存
**问题**:流式调用绕过了 agent loop消息没有保存到 session
**纠正**:流式调用后手动保存消息:
```go
agentInstance.Sessions.AddMessage(sessionKey, "user", input)
agentInstance.Sessions.AddMessage(sessionKey, "assistant", result)
```
**知识点**`SessionStore` 接口提供 `AddMessage` 方法,支持 "user" 和 "assistant" 角色
---
### onChunk 回调接收累积文本导致重复输出
**问题**picoclaw 的 `StreamingProvider` 接口定义 `onChunk func(accumulated string)`,注释说明每次回调时参数是累积的完整文本(如 "你好" → "你好!再次" → "你好!再次见到"),而不是增量。
**问题**picoclaw 的 `StreamingProvider` 接口定义
```go
onChunk func(accumulated string)
```
**纠正**:使用 `printedLen` 跟踪已打印位置,只打印新增部分
注释说明:"onChunk receives the accumulated text so far (not individual deltas)"。每次回调时参数是累积的完整文本(如 "你好" → "你好!再次" → "你好!再次见到"),而不是增量。
**纠正**:使用 `printedLen` 跟踪已打印位置,只打印新增部分:
```go
var printedLen int
func(accumulated string) {
if len(accumulated) > printedLen {
fmt.Print(accumulated[printedLen:])
printedLen = len(accumulated)
}
}
```
**知识点**picoclaw 故意设计为累积文本,这样可以在任意时刻获取完整内容用于调试
---
### 尝试 uilive 库但只显示最后一行
**问题**:为了实现同行流动效果,尝试使用 `github.com/gosuri/uilive`
**现象**:该库会覆盖每一行,只显示最后一行内容
**纠正**:移除 uilive直接使用 `fmt.Print` + `os.Stdout.Sync()`,让终端自然处理换行
**知识点**uilive 适用于进度条等场景,不适合长文本流式输出
---
### 流式输出期望同行流动但实际换行显示
**问题**:用户期望像 ollama 那样在同行逐字符流动
**最终方案**
```go
fmt.Print(accumulated[printedLen:])
os.Stdout.Sync()
```
效果:
- 字符串自然累积增长
- 终端自动处理换行(满一行自动 wrap
- 保留所有历史输出
- 每次刷新缓冲区确保立即显示
**知识点**:最简单的方案就是最有效的方案,不需要额外库
---
### spinner 组件的 model 更新必须使用返回值
**问题**spinner 动画不动
@@ -101,7 +267,21 @@
**纠正**spinner model 是值类型,需要使用返回值更新:
```go
// 错误写法
func (s *Spinner) tick() {
msg := s.spinner.Tick()
if msg, ok := msg.(spinner.TickMsg); ok {
s.spinner.Update(msg) // 动画不会动!
}
}
// 正确写法
func (s *Spinner) tick() {
msg := s.spinner.Tick()
if msg, ok := msg.(spinner.TickMsg); ok {
s.spinner, _ = s.spinner.Update(msg) // 必须使用返回值更新
}
}
```
**知识点**bubbletea v2 的组件遵循 TEA 架构模式Update 方法返回更新后的 model需要显式使用返回值。
@@ -112,37 +292,36 @@ s.spinner, _ = s.spinner.Update(msg) // 必须使用返回值更新
**问题**spinner 使用 `\r` 回到行首刷新,流式输出也在同一行打印,导致内容混在一起
**纠正**在第一个 token 时停止 spinner让 spinner 输出 "思考完成." 并换行,然后再开始流式打印
**现象**
```
⠋ 回答中... 好
⠋ 回答中... 注于
```
**纠正**:在第一个 token 时停止 spinner让 spinner 输出 "思考完成." 并换行,然后再开始流式打印:
```go
if firstToken && len(accumulated) > 0 {
spinner.Stop() // 停止 spinner会打印 "思考完成."
firstToken = false
}
```
**知识点**spinner 和流式输出需要分时工作,不能同时占用同一行。
---
### 配置系统设计
### spinner 动画位置和换行策略
**问题**:用户需要自定义主题、延迟等配置,但项目配置只有一份
**问题**:用户期望动画在前,文字在后,且需要正确的换行
**纠正**设计多级配置系统:
- 用户配置:`~/.config/hxclaw/config.yml`(优先级最高)
- 项目配置:`project.config.yml`
- 环境变量:`HXCLAW_CONFIG` 指定路径
- 代码默认值
**效果**
```
思考中... ⠋ -> 用户期望 ⠋ 思考中...
思考完成. -> 用户期望 ⠋ 思考完成.
```
**合并规则**用户配置优先于项目配置,项目配置优先于默认值
**纠正**
- 动画在前,文字在后:`fmt.Printf("\r%s %s", s.spinner.View(), s.text)`
- 换行:"思考完成.\n" + 流式输出后 "fmt.Println()\n"
**实现**`mergeConfig` 函数实现配置合并逻辑
---
### 代码注释规范
**问题**:代码缺少注释,后续维护困难
**纠正**:所有代码添加详细中文注释:
- 包级别注释
- 结构体注释
- 字段注释(使用行内注释 `//`
- 函数注释
- 关键逻辑注释
**知识点**:详细注释是团队协作和后续维护的基础
**知识点**终端输出需要精确控制位置和换行,否则会导致格式错乱。

View File

@@ -1,5 +1,3 @@
// Package internal 包含 hxclaw 的内部工具模块
// 提供配置管理、Markdown 渲染、输入读取等功能
package internal
import (
@@ -10,233 +8,118 @@ import (
"gopkg.in/yaml.v3"
)
// Config 是项目配置结构体包含流式输出、Markdown 渲染和 UI 相关配置
type Config struct {
// Streaming 流式输出配置
type ProjectConfig struct {
Streaming StreamingConfig `yaml:"streaming"`
// Markdown Markdown 渲染配置
Markdown MarkdownConfig `yaml:"markdown"`
// UI UI 显示配置
UI UIConfig `yaml:"ui"`
TTS TTSConfig `yaml:"tts"`
}
// StreamingConfig 流式输出配置,控制模拟打字效果的延迟时间
type StreamingConfig struct {
// LineDelayMs 每行输出延迟(毫秒)
LineDelayMs int `yaml:"line_delay_ms"`
// LastLineDelayMs 最后一行输出延迟(毫秒)
LastLineDelayMs int `yaml:"last_line_delay_ms"`
}
// MarkdownConfig Markdown 渲染配置,控制渲染主题和换行行为
type MarkdownConfig struct {
// Theme 渲染主题,支持 dark、light、dracula、tokyo-night 等
Theme string `yaml:"theme"`
// LineWidth 自动换行宽度0=自动,>0=固定宽度,-1=禁用)
LineWidth int `yaml:"line_width"`
GlamourStyle string `yaml:"glamour_style"`
WrapWidth int `yaml:"wrap_width"`
}
// UIConfig UI 显示配置,控制 Logo 和用户提示符
type UIConfig struct {
// Logo 应用 Logo 字符
Logo string `yaml:"logo"`
// UserIcon 用户输入提示符
UserIcon string `yaml:"user_icon"`
UserPrefix string `yaml:"user_prefix"`
}
type TTSConfig struct {
Enabled bool `yaml:"enabled"`
Port int `yaml:"port"`
Auto bool `yaml:"auto"`
}
var (
// defaultCfg 默认配置值,当配置文件不存在或字段为空时使用
defaultCfg = Config{
defaultCfg = ProjectConfig{
Streaming: StreamingConfig{
LineDelayMs: 1000,
LastLineDelayMs: 600,
},
Markdown: MarkdownConfig{
Theme: "dark",
LineWidth: 0,
GlamourStyle: "dark",
WrapWidth: 0,
},
UI: UIConfig{
Logo: "🦐",
UserIcon: "👀 ",
UserPrefix: "👀 ",
},
TTS: TTSConfig{
Enabled: false,
Port: 9876,
Auto: true,
},
}
cfg *Config // 已合并的配置(用户配置 + 项目配置)
cfgLock sync.RWMutex // 配置读写锁
userCfg *Config // 用户配置文件解析结果
userLock sync.RWMutex // 用户配置读写锁
projCfg *ProjectConfig
projCfgLock sync.RWMutex
)
// 用户配置文件路径常量
const (
userConfigDir = ".config/hxclaw" // 用户配置目录(相对于用户家目录)
userConfigFile = "config.yml" // 用户配置文件名
)
// LoadProjectConfig 加载并合并项目配置
// 加载顺序:用户配置(~/.config/hxclaw/config.yml > 项目配置project.config.yml
// 最终配置由两者合并得出,用户配置优先于项目配置
func LoadProjectConfig() error {
cfgLock.Lock()
defer cfgLock.Unlock()
userLock.Lock()
defer userLock.Unlock()
projCfgLock.Lock()
defer projCfgLock.Unlock()
userCfg = loadUserConfig()
projCfg := loadProjectConfig()
merged := mergeConfig(userCfg, projCfg)
cfg = merged
return nil
}
// loadUserConfig 加载用户配置文件
// 路径:~/.config/hxclaw/config.yml
// 如果文件不存在,则自动创建默认配置文件
func loadUserConfig() *Config {
userPath := getUserConfigPath()
if userPath == "" {
return nil
}
data, err := os.ReadFile(userPath)
if err != nil {
if os.IsNotExist(err) {
createUserConfig(userPath)
return &defaultCfg
}
return nil
}
var userCfg Config
if err := yaml.Unmarshal(data, &userCfg); err != nil {
return nil
}
return &userCfg
}
// createUserConfig 创建默认的用户配置文件
// userPath: 配置文件完整路径
func createUserConfig(userPath string) error {
dir := filepath.Dir(userPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
defaultContent := `# hxclaw 用户配置文件
# 此文件位于 ~/.config/hxclaw/config.yml
# Markdown 渲染配置
markdown:
theme: dark # 渲染主题dark, light, dracula, tokyo-night 等
line_width: 0 # 自动换行宽度0=自动,>0=固定宽度,-1=禁用)
# UI 配置
ui:
logo: "🦐"
user_icon: "👀 "
`
return os.WriteFile(userPath, []byte(defaultContent), 0644)
}
// loadProjectConfig 加载项目级配置文件
// 路径优先级:环境变量 HXCLAW_CONFIG 指定路径 > ./project.config.yml
func loadProjectConfig() *Config {
cfgPath := getProjectConfigPath()
cfgPath := getConfigPath()
if cfgPath == "" {
return &defaultCfg
projCfg = &defaultCfg
return nil
}
data, err := os.ReadFile(cfgPath)
if err != nil {
if os.IsNotExist(err) {
projCfg = &defaultCfg
return nil
}
return err
}
var cfg ProjectConfig
if err := yaml.Unmarshal(data, &cfg); err != nil {
return err
}
if cfg.Streaming.LineDelayMs <= 0 {
cfg.Streaming.LineDelayMs = defaultCfg.Streaming.LineDelayMs
}
if cfg.Streaming.LastLineDelayMs <= 0 {
cfg.Streaming.LastLineDelayMs = defaultCfg.Streaming.LastLineDelayMs
}
if cfg.Markdown.GlamourStyle == "" {
cfg.Markdown.GlamourStyle = defaultCfg.Markdown.GlamourStyle
}
if cfg.Markdown.WrapWidth < 0 {
cfg.Markdown.WrapWidth = 0
}
if cfg.UI.Logo == "" {
cfg.UI.Logo = defaultCfg.UI.Logo
}
if cfg.UI.UserPrefix == "" {
cfg.UI.UserPrefix = defaultCfg.UI.UserPrefix
}
if cfg.TTS.Port <= 0 {
cfg.TTS.Port = defaultCfg.TTS.Port
}
projCfg = &cfg
return nil
}
func GetProjectConfig() *ProjectConfig {
projCfgLock.RLock()
defer projCfgLock.RUnlock()
if projCfg == nil {
return &defaultCfg
}
return &defaultCfg
return projCfg
}
var projCfg Config
if err := yaml.Unmarshal(data, &projCfg); err != nil {
return &defaultCfg
}
return &projCfg
}
// mergeConfig 合并用户配置和项目配置
// 合并规则:用户配置优先于项目配置,项目配置优先于默认配置
// 仅当配置值非空/非零时才覆盖默认值
func mergeConfig(userCfg, projCfg *Config) *Config {
result := defaultCfg
if projCfg != nil {
if projCfg.Streaming.LineDelayMs > 0 {
result.Streaming.LineDelayMs = projCfg.Streaming.LineDelayMs
}
if projCfg.Streaming.LastLineDelayMs > 0 {
result.Streaming.LastLineDelayMs = projCfg.Streaming.LastLineDelayMs
}
if projCfg.Markdown.Theme != "" {
result.Markdown.Theme = projCfg.Markdown.Theme
}
if projCfg.Markdown.LineWidth != 0 {
result.Markdown.LineWidth = projCfg.Markdown.LineWidth
}
if projCfg.UI.Logo != "" {
result.UI.Logo = projCfg.UI.Logo
}
if projCfg.UI.UserIcon != "" {
result.UI.UserIcon = projCfg.UI.UserIcon
}
}
if userCfg != nil {
if userCfg.Markdown.Theme != "" {
result.Markdown.Theme = userCfg.Markdown.Theme
}
if userCfg.Markdown.LineWidth != 0 {
result.Markdown.LineWidth = userCfg.Markdown.LineWidth
}
if userCfg.UI.Logo != "" {
result.UI.Logo = userCfg.UI.Logo
}
if userCfg.UI.UserIcon != "" {
result.UI.UserIcon = userCfg.UI.UserIcon
}
}
return &result
}
// GetProjectConfig 获取当前生效的配置(线程安全)
// 如果配置未加载,返回默认配置
func GetProjectConfig() *Config {
cfgLock.RLock()
defer cfgLock.RUnlock()
if cfg == nil {
return &defaultCfg
}
return cfg
}
// getUserConfigPath 获取用户配置文件路径
// 路径格式:~/.config/hxclaw/config.yml
// 支持 Windows (USERPROFILE) 和 Unix (HOME) 环境变量
func getUserConfigPath() string {
homeDir := os.Getenv("USERPROFILE")
if homeDir == "" {
homeDir = os.Getenv("HOME")
}
if homeDir == "" {
return ""
}
return filepath.Join(homeDir, userConfigDir, userConfigFile)
}
// getProjectConfigPath 获取项目配置文件路径
// 优先使用环境变量 HXCLAW_CONFIG 指定的路径,否则使用当前目录的 project.config.yml
func getProjectConfigPath() string {
func getConfigPath() string {
if path := os.Getenv("HXCLAW_CONFIG"); path != "" {
return path
}

View File

@@ -50,6 +50,7 @@ func GetConfigPath() string {
// Readline 实例包装
type Readline struct {
rl *readline.Instance
basePrompt string
}
// NewReadline 创建一个新的 Readline 实例
@@ -68,7 +69,18 @@ func NewReadline(prompt string) (*Readline, error) {
if err != nil {
return nil, err
}
return &Readline{rl: rl}, nil
return &Readline{rl: rl, basePrompt: prompt}, nil
}
// SetPrompt 更新提示符
func (r *Readline) SetPrompt(prompt string) {
r.basePrompt = prompt
r.rl.SetPrompt(prompt)
}
// GetBasePrompt 返回基础提示符
func (r *Readline) GetBasePrompt() string {
return r.basePrompt
}
// Readline 读取一行输入

View File

@@ -1,5 +1,3 @@
// Package internal 包含 hxclaw 的内部工具模块
// 提供配置管理、Markdown 渲染、输入读取等功能
package internal
import (
@@ -11,8 +9,6 @@ import (
"github.com/charmbracelet/x/term"
)
// RenderMarkdown 将 Markdown 文本渲染为终端友好的格式
// 支持通过配置或环境变量指定渲染主题和换行宽度
func RenderMarkdown(md string) string {
if md == "" {
return ""
@@ -71,8 +67,8 @@ func RenderParagraph(text string) string {
func getStyle() string {
if cfg := GetProjectConfig(); cfg != nil {
if cfg.Markdown.Theme != "" {
return cfg.Markdown.Theme
if cfg.Markdown.GlamourStyle != "" {
return cfg.Markdown.GlamourStyle
}
}
if s := os.Getenv("GLAMOUR_STYLE"); s != "" {
@@ -83,11 +79,8 @@ func getStyle() string {
func getWrapWidth() int {
if cfg := GetProjectConfig(); cfg != nil {
if cfg.Markdown.LineWidth > 0 {
return cfg.Markdown.LineWidth
}
if cfg.Markdown.LineWidth < 0 {
return 0
if cfg.Markdown.WrapWidth > 0 {
return cfg.Markdown.WrapWidth
}
}
@@ -97,15 +90,9 @@ func getWrapWidth() int {
}
}
if cols := os.Getenv("LINES"); cols != "" {
if w, err := strconv.Atoi(cols); err == nil && w > 0 {
return w
}
}
width, _, err := term.GetSize(0)
if err != nil || width <= 0 {
return 0
return 80
}
return width
}

View File

@@ -1,5 +1,3 @@
// Package internal 包含 hxclaw 的内部工具模块
// 提供配置管理、Markdown 渲染、输入读取等功能
package internal
import (
@@ -11,26 +9,22 @@ import (
"charm.land/lipgloss/v2"
)
// SpinnerState 表示加载动画的状态
type SpinnerState int
const (
StateThinking SpinnerState = iota // 思考中状态
StateAnswering // 回答中状态
StateDone // 完成状态
StateThinking SpinnerState = iota
StateAnswering
StateDone
)
// Spinner 加载动画组件,用于显示思考状态
type Spinner struct {
text string // 显示的文本内容
state SpinnerState // 当前状态
spinner spinner.Model // 底层动画模型
stopCh chan struct{} // 停止信号通道
doneCh chan struct{} // 完成信号通道
text string
state SpinnerState
spinner spinner.Model
stopCh chan struct{}
doneCh chan struct{}
}
// NewSpinner 创建一个新的加载动画实例
// text: 初始显示的文本内容
func NewSpinner(text string) *Spinner {
s := spinner.New(
spinner.WithSpinner(spinner.MiniDot),

View File

@@ -1,5 +1,3 @@
// Package main 是 hxclaw 应用程序的入口包
// 提供交互式 CLI 界面和流式输出功能
package main
import (
@@ -20,53 +18,41 @@ 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{
@@ -75,15 +61,13 @@ 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.UserIcon
basePrompt := internal.GetProjectConfig().UI.UserPrefix
prompt := internal.GetTTSPrompt(basePrompt)
rl, err := internal.NewReadline(prompt)
if err != nil {
@@ -94,6 +78,11 @@ func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
}
defer rl.Close()
ttsCfg := internal.GetProjectConfig().TTS
if ttsCfg.Enabled {
internal.SetTTSEnabled(true)
}
for {
line, err := rl.Readline()
if err != nil {
@@ -115,14 +104,37 @@ func interactiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
return
}
runWithStreaming(agentLoop, input, sessionKey)
isTempTTS := false
if len(input) > 0 && input[0] == 'T' && (len(input) == 1 || input[1] == ' ') {
input = strings.TrimPrefix(input, "T")
input = strings.TrimPrefix(input, " ")
isTempTTS = true
}
if strings.HasPrefix(input, "/tts") {
handleTTSCommand(input, rl, basePrompt)
continue
}
if isTempTTS {
enabled := internal.ToggleTTS()
if enabled {
rl.SetPrompt(internal.GetTTSPrompt(basePrompt))
}
}
runWithStreaming(agentLoop, input, sessionKey, isTempTTS)
}
}
func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
reader := internal.NewSimpleReader()
ttsCfg := internal.GetProjectConfig().TTS
if ttsCfg.Enabled {
internal.SetTTSEnabled(true)
}
for {
fmt.Print(internal.GetProjectConfig().UI.UserIcon)
fmt.Print(internal.GetTTSPrompt(internal.GetProjectConfig().UI.UserPrefix))
line, err := reader.ReadString()
if err != nil {
if err == internal.ErrEOF {
@@ -143,46 +155,55 @@ func simpleInteractiveMode(agentLoop *agent.AgentLoop, sessionKey string) {
return
}
runWithStreaming(agentLoop, input, sessionKey)
isTempTTS := false
if len(input) > 0 && input[0] == 'T' && (len(input) == 1 || input[1] == ' ') {
input = strings.TrimPrefix(input, "T")
input = strings.TrimPrefix(input, " ")
isTempTTS = true
}
if strings.HasPrefix(input, "/tts") {
handleTTSCommandSimple(input)
continue
}
if isTempTTS {
internal.ToggleTTS()
}
runWithStreaming(agentLoop, input, sessionKey, isTempTTS)
}
}
// runWithStreaming 使用 ProcessDirect 处理请求并以模拟流式方式输出结果
// 1. 显示加载动画表示 AI 正在思考
// 2. 调用 Agent 处理用户输入
// 3. 渲染 Markdown 输出并按行延迟显示
// 4. 打印处理耗时
func runWithStreaming(agentLoop *agent.AgentLoop, input, sessionKey string) {
// runWithStreaming 使用 ProcessDirect 处理请求,支持工具调用和结果显示
func runWithStreaming(agentLoop *agent.AgentLoop, input, sessionKey string, tempTTS bool) {
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)
// 打印处理耗时
ttsCfg := internal.GetProjectConfig().TTS
if ttsCfg.Enabled || tempTTS || internal.IsTTSEnabled() {
go internal.SpeakText(resp)
}
elapsed := time.Since(startTime)
printElapsed(elapsed)
}
// clearSpinnerLine 清除 spinner 行
// 使用终端控制字符清除当前行并移动到行首
func clearSpinnerLine() {
output := termenv.DefaultOutput()
output.ClearLine()
@@ -190,9 +211,6 @@ func clearSpinnerLine() {
os.Stdout.Sync()
}
// outputLineByLine 按行输出文本,模拟打字效果
// 每行之间根据配置延迟,最后一行延迟时间较长
// 空行会直接输出不延迟
func outputLineByLine(text string) {
if text == "" {
return
@@ -201,21 +219,18 @@ 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")
fmt.Println()
continue
}
lipgloss.Print(line + "\n")
fmt.Println(line)
// 非最后一行使用普通延迟,最后一行使用较长延迟
if i < totalLines-1 {
time.Sleep(lineDelay)
} else {
@@ -223,17 +238,14 @@ func outputLineByLine(text string) {
}
}
lipgloss.Print("\n")
fmt.Println()
}
// 输出样式定义
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)
@@ -243,8 +255,6 @@ 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)
@@ -252,11 +262,72 @@ 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)
}
return fmt.Sprintf("%.1fs", s)
}
func handleTTSCommand(input string, rl *internal.Readline, basePrompt string) {
args := strings.Fields(input)
if len(args) == 1 {
enabled := internal.ToggleTTS()
rl.SetPrompt(internal.GetTTSPrompt(basePrompt))
status := "关闭"
if enabled {
status = "开启"
}
fmt.Printf("TTS 已%s\n", status)
return
}
switch args[1] {
case "on":
internal.SetTTSEnabled(true)
rl.SetPrompt(internal.GetTTSPrompt(basePrompt))
fmt.Println("TTS 已开启")
case "off":
internal.SetTTSEnabled(false)
rl.SetPrompt(internal.GetTTSPrompt(basePrompt))
fmt.Println("TTS 已关闭")
case "status":
status := "关闭"
if internal.IsTTSEnabled() {
status = "开启"
}
fmt.Printf("TTS 状态: %s\n", status)
default:
fmt.Println("用法: /tts [on|off|status]")
}
}
func handleTTSCommandSimple(input string) {
args := strings.Fields(input)
if len(args) == 1 {
internal.ToggleTTS()
status := "关闭"
if internal.IsTTSEnabled() {
status = "开启"
}
fmt.Printf("TTS 已%s\n", status)
return
}
switch args[1] {
case "on":
internal.SetTTSEnabled(true)
fmt.Println("TTS 已开启")
case "off":
internal.SetTTSEnabled(false)
fmt.Println("TTS 已关闭")
case "status":
status := "关闭"
if internal.IsTTSEnabled() {
status = "开启"
}
fmt.Printf("TTS 状态: %s\n", status)
default:
fmt.Println("用法: /tts [on|off|status]")
}
}

View File

@@ -1,5 +1,4 @@
# hxclaw 项目配置文件
# 项目级配置,会覆盖用户配置
# 模拟流式输出配置
streaming:
@@ -8,10 +7,16 @@ streaming:
# Markdown 渲染配置
markdown:
theme: light # 渲染主题dark, light, dracula, tokyo-night 等
line_width: 100 # 自动换行宽度0=自动>0=固定宽度,-1=禁用
glamour_style: dark # 渲染主题dark, light, dracula, tokyo-night 等
wrap_width: 0 # 自动换行宽度0=自动获取终端宽度
# UI 配置
ui:
logo: "🦐"
user_icon: "👀 "
user_prefix: "👀 "
# TTS 语音配置
tts:
enabled: false # 全局开关(默认关闭)
port: 9876 # mimo-tts daemon 端口
auto: true # AI 回复后自动朗读

View File

@@ -46,8 +46,8 @@ hxclaw/
### 6. Markdown 终端渲染
- 使用 charmbracelet 家族库
- glamourMarkdown 渲染(自带代码高亮)
- lipgloss终端样式
- glow代码高亮
- 流程Markdown → ANSI 转义序列 → 终端显示
### 7. 部署方式
@@ -326,7 +326,6 @@ func outputLineByLine(text string) {
```yaml
# hxclaw 项目配置文件
# 项目级配置,会覆盖用户配置
# 模拟流式输出配置
streaming:
@@ -335,21 +334,25 @@ streaming:
# Markdown 渲染配置
markdown:
theme: dark # 渲染主题dark, light, dracula, tokyo-night 等
line_width: 0 # 自动换行宽度0=自动获取终端宽度)
glamour_style: dark # 渲染主题dark, light, dracula, tokyo-night 等
wrap_width: 0 # 自动换行宽度0=自动获取终端宽度)
# UI 配置
ui:
logo: "🦐" # Logo
user_icon: "👀 " # 用户输入提示符
user_prefix: "👀 " # 用户输入前缀
# TTS 语音配置
tts:
enabled: false # 全局开关(默认关闭)
port: 9876 # daemon 端口
auto: true # AI 回复后自动朗读
```
#### 配置加载优先级
1. 用户配置 `~/.config/hxclaw/config.yml`
2. 环境变量 `HXCLAW_CONFIG` 指定路径
3. 项目根目录 `project.config.yml`
4. 代码中的默认值
1. 环境变量 `HXCLAW_CONFIG` 指定路径
2. 项目根目录 `project.config.yml`
#### 代码实现
@@ -385,3 +388,71 @@ func getConfigPath() string {
- 人眼需要约 30-50ms 才能感知单次视觉变化
- 空白字符不应逐个输出,应批量处理
- 终端宽度 100% 时 Markdown 渲染会显著增加行数和字符数
---
### 19. TTS 语音朗读集成
#### 架构设计
hxclaw 作为 mimo-tts 的客户端,通过 TCP Socket 连接本地 daemon
```
hxclaw (客户端) --TCP:9876--> mimo-tts daemon (服务端)
|
v
API 调用 (mimo-v2.5-tts)
|
v
返回音频文件路径
|
v
afplay 播放
```
#### 配置文件
```yaml
tts:
enabled: false # 全局开关(默认关闭)
port: 9876 # daemon 端口
auto: true # AI 回复后自动朗读
```
#### 命令支持
| 输入 | 行为 |
|------|------|
| `/tts` | 切换 TTS 开关 |
| `/tts on` | 开启 TTS |
| `/tts off` | 关闭 TTS |
| `/tts status` | 显示状态 |
| `T 消息` | 临时开启并发送 |
#### 动态提示符
- 关闭:`👀 `
- 开启:`👀 🔊 `
#### 实现要点
1. TCP 连接:使用 Go 标准库 `net` 包
2. JSON 请求:发送格式 `{"text": "内容"}`
3. 异步朗读:使用 `go func()` 异步调用
4. 静默失败:网络异常只记录警告日志,不阻塞用户
#### 踩坑记录
**ergochat/readline SetPrompt 无返回值**
```go
// 错误
func (r *Readline) SetPrompt(prompt string) error {
return r.rl.SetPrompt(prompt) // SetPrompt 返回 void
}
// 正确
func (r *Readline) SetPrompt(prompt string) {
r.rl.SetPrompt(prompt) // void 类型
}
```