Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .claude/settings.local.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@
"Bash(timeout 60 node:*)",
"Bash(gtimeout 60 node:*)",
"Bash(pnpm approve-builds:*)",
"Bash(git reset:*)"
"Bash(git reset:*)",
"Bash(cloc:*)",
"Bash(grep:*)"
],
"deny": [],
"ask": [],
Expand Down
29 changes: 16 additions & 13 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ jobs:
node-version: ${{ matrix.node-version }}
cache: 'pnpm'

- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Enable corepack
run: corepack enable

- name: Install pnpm
run: corepack prepare pnpm@8 --activate

- name: Install dependencies
run: pnpm install
Expand Down Expand Up @@ -59,10 +60,11 @@ jobs:
node-version: '20.x'
cache: 'pnpm'

- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Enable corepack
run: corepack enable

- name: Install pnpm
run: corepack prepare pnpm@8 --activate

- name: Install dependencies
run: pnpm install
Expand All @@ -89,10 +91,11 @@ jobs:
node-version: ${{ matrix.node-version }}
cache: 'pnpm'

- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 8
- name: Enable corepack
run: corepack enable

- name: Install pnpm
run: corepack prepare pnpm@8 --activate

- name: Install dependencies
run: pnpm install
Expand All @@ -105,4 +108,4 @@ jobs:

env:
CI: true
NODE_ENV: test
NODE_ENV: test
4 changes: 2 additions & 2 deletions BLADE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ always respond in Chinese
### 1. Agent 系统 (`src/agent/`)
- **Agent.ts**: 核心 Agent 类,无状态设计,负责 LLM 交互和工具执行
- **ExecutionEngine.ts**: 执行引擎,处理工具调用循环
- **LoopDetectionService.ts**: 循环检测,防止无限循环
- **Agent.ts**: Agentic Loop 主循环,使用 `maxTurns` + 硬性轮次上限 `SAFETY_LIMIT = 100` 防止无限循环(旧版 LoopDetectionService 已移除)
- **subagents/**: 子 Agent 注册表,支持任务分解

### 2. Hook 系统 (`src/hooks/`)
Expand Down Expand Up @@ -242,4 +242,4 @@ src/
├── tools/ # 工具系统
├── ui/ # UI 组件
└── utils/ # 工具函数
```
```
153 changes: 145 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Root (blade-code)
│ ├── security/ # 安全管理
│ ├── services/ # 共享服务层
│ ├── slash-commands/ # 内置斜杠命令
│ ├── telemetry/ # 遥测和监控
│ ├── telemetry/ # 遥测和监控(历史目录,当前实现中已不再使用)
│ ├── tools/ # 工具系统
│ │ ├── builtin/ # 内置工具(Read/Write/Bash等)
│ │ ├── execution/ # 执行管道
Expand Down Expand Up @@ -96,7 +96,7 @@ Root (blade-code)
- 静态工厂方法 `Agent.create()` 用于创建和初始化实例
- 每次命令可创建新 Agent 实例(用完即弃)
- 通过 `ExecutionEngine` 处理工具执行流程
- 通过 `LoopDetectionService` 防止无限循环(三层检测机制
- **安全保障**: 通过 `maxTurns` + 硬性轮次上限 `SAFETY_LIMIT = 100` 控制循环(已移除 LoopDetectionService,避免与系统提示冲突

- **SessionContext** ([src/ui/contexts/SessionContext.tsx](src/ui/contexts/SessionContext.tsx)): 会话状态管理
- 维护全局唯一 `sessionId`
Expand Down Expand Up @@ -129,12 +129,6 @@ Root (blade-code)
- Discovery → Permission (Zod验证+默认值) → Confirmation → Execution → Formatting
- 事件驱动架构,支持监听各阶段事件
- 自动记录执行历史
- **LoopDetectionService** ([src/agent/LoopDetectionService.ts](src/agent/LoopDetectionService.ts)): 三层循环检测系统
- **层1**: 工具调用循环检测(MD5 哈希 + 动态阈值)
- **层2**: 内容循环检测(滑动窗口 + 动态相似度)
- **层3**: LLM 智能检测(认知循环分析)
- 支持白名单工具、Plan 模式跳过内容检测
- 详见: [循环检测系统文档](docs/development/implementation/loop-detection-system.md)
- **PromptBuilder** ([src/prompts/](src/prompts/)): 提示模板管理和构建
- **ContextManager** ([src/context/ContextManager.ts](src/context/ContextManager.ts)): 上下文管理系统
- **JSONL 格式**: 追加式存储,每行一个 JSON 对象
Expand Down Expand Up @@ -192,6 +186,149 @@ Blade 提供完整的 Markdown 渲染支持,包含以下组件:
- 用户文档:[docs/public/guides/markdown-support.md](docs/public/guides/markdown-support.md)
- 开发者文档:[docs/development/implementation/markdown-renderer.md](docs/development/implementation/markdown-renderer.md)

## State Management Architecture

### Zustand Store 设计

Blade 使用 **Zustand** 作为全局状态管理库,采用 **单一数据源 (SSOT)** 架构:

**核心原则**:
- **Store 是唯一读取源** - 所有组件和服务从 Store 读取状态
- **vanilla.ts actions 是唯一写入入口** - 自动同步内存 + 持久化
- **ConfigManager 仅用于 Bootstrap** - 初始化时加载配置文件
- **ConfigService 负责持久化** - 运行时写入配置文件

**架构图**:
```
Bootstrap (启动时):
ConfigManager.initialize() → 返回 BladeConfig → Store.setConfig()

Runtime (运行时):
UI/Agent → vanilla.ts actions → Store (内存SSOT)
ConfigService (持久化到 config.json/settings.json)
```

### 状态管理最佳实践

**✅ 推荐:从 Store 读取**
```typescript
import { getConfig, getCurrentModel } from '../store/vanilla.js';

const config = getConfig(); // 读取完整配置
const model = getCurrentModel(); // 读取当前模型
```

**✅ 推荐:通过 actions 写入**
```typescript
import { configActions } from '../store/vanilla.js';

// 自动同步内存 + 持久化
await configActions().addModel({...});
await configActions().setPermissionMode('yolo');
```

**❌ 避免:直接调用 ConfigManager**
```typescript
// ❌ 错误:绕过 Store,导致数据不一致
const configManager = ConfigManager.getInstance();
await configManager.addModel({...}); // Store 未更新!
```

**React 组件订阅**:
```typescript
// ✅ 使用选择器(精准订阅)
import { useCurrentModel, usePermissionMode } from '../store/selectors/index.js';

const model = useCurrentModel();
const mode = usePermissionMode();

// ✅ 组合选择器使用 useShallow 优化
import { useShallow } from 'zustand/react/shallow';

const { field1, field2 } = useBladeStore(
useShallow((state) => ({
field1: state.slice.field1,
field2: state.slice.field2,
}))
);
```

### Store 初始化规则

**⚠️ 关键规则**:任何调用 `configActions()` 或读取 `getConfig()` 的代码前,必须确保 Store 已初始化。

**统一防御点(推荐)**:
```typescript
import { ensureStoreInitialized } from '../store/vanilla.js';

// 在执行任何依赖 Store 的逻辑前
await ensureStoreInitialized();
```

**`ensureStoreInitialized()` 特性**:
- ✅ **幂等**:已初始化直接返回(性能无负担)
- ✅ **并发安全**:同一时刻只初始化一次(共享 Promise)
- ✅ **失败重试**:初始化失败后,下次调用会重新尝试
- ✅ **明确报错**:初始化失败抛出详细错误信息

**已添加防御的路径**:
| 路径 | 防御点 | 说明 |
|------|--------|------|
| CLI 命令 | `middleware.ts` | 初始化失败会退出并报错 |
| Slash Commands | `useCommandHandler.ts` | 执行前统一调用 `ensureStoreInitialized()` |
| Agent 创建 | `Agent.create()` | 内置防御性检查 |
| Config Actions | 各方法内部 | 检查 `if (!config) throw` |

**⚠️ 竞态风险**:
- UI 初始化过程中用户立即输入命令
- 多个 slash command 并发执行
- 非 UI 场景(测试/脚本/print mode)复用

**✅ 推荐模式**:
```typescript
// Slash command 执行前
if (isSlashCommand(command)) {
await ensureStoreInitialized(); // 统一防御点
const result = await executeSlashCommand(command, context);
}

// CLI 子命令执行前
export const myCommand: CommandModule = {
handler: async (argv) => {
await ensureStoreInitialized(); // 防御性检查
const config = getConfig();
// ... 使用 config
}
};
```

**❌ 避免模式**:
```typescript
// ❌ 错误:假设已初始化
const config = getConfig();
if (!config) {
// 太迟了,某些路径可能已经踩坑
}

// ❌ 错误:静默吞掉初始化失败
try {
await ensureStoreInitialized();
} catch (error) {
console.warn('初始化失败,继续执行'); // 危险!
}
```

### Store 初始化机制

三层初始化防护:

1. **UI 路径**:`App.tsx` → useEffect 初始化 Store
2. **CLI 路径**:`middleware.ts` → loadConfiguration 初始化 Store
3. **防御路径**:`Agent.create()` → ensureStoreInitialized() 兜底

详见:[Store 与 Config 架构统一文档](docs/development/implementation/store-config-unification.md)

## Slash Commands

Blade 提供内置的斜杠命令系统,用于执行特定的系统操作。所有 slash 命令实现位于 [src/slash-commands/](src/slash-commands/)。
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ src/
├── security/ # 安全管理
├── services/ # 核心服务
├── slash-commands/ # 斜杠命令
├── telemetry/ # 遥测系统
├── telemetry/ # 遥测系统(历史目录,当前实现中已不再使用)
├── tools/ # 工具系统
├── ui/ # 用户界面
├── utils/ # 工具函数
Expand Down
3 changes: 1 addition & 2 deletions docs/archive/TOOL_SYSTEM_RENOVATION_PLAN_archived.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ packages/core/src/tools/
├── types/ # 类型定义
│ ├── ToolTypes.ts # 工具基础类型
│ ├── ExecutionTypes.ts # 执行相关类型
│ ├── SecurityTypes.ts # 安全相关类型
│ └── McpTypes.ts # MCP相关类型
├── base/ # 基础抽象类
│ ├── BaseTool.ts # 工具基类
Expand Down Expand Up @@ -1001,4 +1000,4 @@ Claude Code 通过 MCP (Model Context Protocol) 支持的扩展工具:
3. **MCP深度集成**: DiscoveredMCPTool类,自动发现和注册
4. **富媒体支持**: 支持图片、音频等多媒体内容

这些详细信息为 Blade 工具系统的设计和实现提供了宝贵的参考。
这些详细信息为 Blade 工具系统的设计和实现提供了宝贵的参考。
4 changes: 4 additions & 0 deletions docs/development/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@

## 💻 实现细节

- **[Store 与 Config 架构统一](implementation/store-config-unification.md)** 🆕 - 消除双轨数据源的重构总结
- **[错误处理](implementation/error-handling.md)** - 错误处理机制
- **[日志系统](implementation/logging-system.md)** - 日志系统实现
- **[Markdown 渲染器](implementation/markdown-renderer.md)** ⭐ - 完整 Markdown 渲染系统
- **[流式工具执行显示](implementation/streaming-tool-execution-display.md)** ⭐ - Claude Code 风格的工具执行流
- **[循环检测系统](implementation/loop-detection-system.md)** - 三层循环检测机制
- **[Subagents 系统](implementation/subagents-system.md)** - 子 Agent 架构
- **[MCP 支持](implementation/mcp-support.md)** - Model Context Protocol 实现

## 📋 技术方案

Expand Down
12 changes: 4 additions & 8 deletions docs/development/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
├── mcp/ # MCP 协议支持
├── services/ # 核心业务服务
├── tools/ # 工具系统
├── telemetry/ # 遥测系统
├── telemetry/ # 遥测系统(历史目录,当前实现中已移除)
├── types/ # 共享类型定义
└── utils/ # 通用工具函数
```
Expand Down Expand Up @@ -251,13 +251,9 @@ interface BladeUnifiedConfig {
}>;
};

// 遥测配置
telemetry?: {
enabled?: boolean;
target?: 'local' | 'remote';
otlpEndpoint?: string;
logPrompts?: boolean;
};
// 遥测配置(已废弃)
// 早期版本中曾提供可配置的遥测开关和远程端点,当前实现中已移除内置遥测逻辑,
// 如果需要埋点统计,推荐在宿主应用层自行集成。

// 使用配置
usage: {
Expand Down
23 changes: 1 addition & 22 deletions docs/development/architecture/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,27 +220,6 @@ class SecurityManager {
- ⚠️ 风险评估系统
- 🔒 敏感数据加密

## 📊 遥测系统

### Telemetry SDK
指标收集和错误跟踪系统。

```typescript
// src/telemetry/TelemetrySDK.ts
class TelemetrySDK {
trackEvent(event: string, properties?: any): void
trackError(error: Error, context?: any): void
trackMetric(name: string, value: number): void
setUser(userId: string): void
}
```

**收集指标:**
- 📈 使用统计数据
- 🐛 错误和异常
- ⚡ 性能指标
- 👤 用户行为分析

## 🚨 错误处理

### Error System
Expand Down Expand Up @@ -369,4 +348,4 @@ Infrastructure (基础设施)

---

这种模块化的组件设计使 Blade Code 具有良好的可维护性和扩展性。🏗️✨
这种模块化的组件设计使 Blade Code 具有良好的可维护性和扩展性。🏗️✨
Loading
Loading