Skip to content

Commit 692f2fe

Browse files
author
xcssa
committed
增强技能系统与记忆机制,完善文档说明
- 支持外部技能插件加载,技能与命令工具集成 - 工作记忆文件改为 JSON 格式,优化结构化存储 - 补充记忆注入机制及各类 memory key 说明 - MainAgent 工具调用追踪范围限定为当前轮次 - 对话上下文自动注入当前时间,便于记忆检索 - 配置示例新增 recaller agent,文档同步 .NET 10 正式版 - 行为准则新增技能自省,禁止虚构未授权操作 - 全面更新中英文文档,提升可扩展性与规范性
1 parent b87c787 commit 692f2fe

5 files changed

Lines changed: 69 additions & 28 deletions

File tree

CLAUDE.md

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# CLAUDE.md — Sharpclaw Project Instructions
1+
# CLAUDE.md
22

33
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
44

@@ -91,7 +91,7 @@ Sharpclaw implements a sophisticated three-layer memory pipeline:
9191

9292
| Layer | File | Purpose | Written By |
9393
|-------|------|---------|------------|
94-
| **Working Memory** | `working_memory.md` | Current conversation snapshot | MainAgent (each turn) |
94+
| **Working Memory** | `working_memory.json` | Current conversation snapshot (JSON) | MainAgent (each turn) |
9595
| **Recent Memory** | `recent_memory.md` | Detailed summaries (append-only) | ConversationArchiver (Summarizer) |
9696
| **Primary Memory** | `primary_memory.md` | Consolidated core facts | ConversationArchiver (Consolidator) |
9797
| **Vector Store** | `memories.db` | Semantic embeddings + metadata | VectorMemoryStore |
@@ -102,6 +102,15 @@ Sharpclaw implements a sophisticated three-layer memory pipeline:
102102
2. When context window overflows → Summarizer generates detailed summary → appends to recent memory
103103
3. When recent memory > 30k chars → Consolidator extracts core info → overwrites primary memory
104104

105+
**Memory Injection Mechanism:**
106+
- Injected messages are identified via `AdditionalProperties` dictionary keys:
107+
- `AutoMemoryKey` (`__auto_memories__`) — Vector search results
108+
- `AutoRecentMemoryKey` (`__auto_recent_memory__`) — Recent memory content
109+
- `AutoPrimaryMemoryKey` (`__auto_primary_memory__`) — Primary memory content
110+
- `AutoWorkingMemoryKey` (`__auto_working_memory__`) — Working memory snapshot
111+
- Memory messages are replaced/updated each turn rather than accumulated
112+
- Turn-based message tracking via `turnStartIndex` separates current turn from full history
113+
105114
### IChatIO Abstraction
106115

107116
The AI engine is decoupled from frontend through `Abstractions/IChatIO.cs`:
@@ -111,6 +120,14 @@ The AI engine is decoupled from frontend through `Abstractions/IChatIO.cs`:
111120

112121
All frontends share the same `MainAgent` logic.
113122

123+
### Skills System
124+
125+
External skills are loaded from `~/.sharpclaw/skills/` via `AgentSkillsDotNet`:
126+
- `AgentBootstrap` scans the skills directory at startup and converts discovered skills into `AITool[]`
127+
- Skills are merged with built-in command tools into a unified `CommandSkills` array
128+
- All tools (built-in commands + external skills) are passed to `MainAgent` as a single collection
129+
- The skills directory is auto-created if it doesn't exist
130+
114131
---
115132

116133
## Configuration
@@ -144,6 +161,9 @@ Configuration stored in `~/.sharpclaw/config.json` (version 8):
144161
### Sharpclaw
145162
- `Microsoft.Agents.AI.OpenAI` / `Microsoft.Extensions.AI.OpenAI` — AI agent framework
146163
- `Anthropic` / `GeminiDotnet.Extensions.AI` — Multi-provider LLM support
164+
- `AgentSkillsDotNet` — External skills loading and tool generation
165+
- `ToonSharp` — Lua scripting support
166+
- `Cronos` — Cron expression scheduling
147167
- `Terminal.Gui` v2 (develop) — TUI framework
148168
- `Luolan.QQBot` — QQ Bot SDK
149169
- `Microsoft.Data.Sqlite` — SQLite for vector store
@@ -202,15 +222,16 @@ sharpclaw/
202222
- All sub-agents use **tool calling** (not text parsing) for structured output
203223
- Sub-agents access memory files via standard file command tools with prompt-level write restrictions
204224
- Injected messages use `AdditionalProperties` dictionary keys for identification
205-
- Session persistence via `working_memory.md`, `memories.db`, tiered memory files
225+
- Session persistence via `working_memory.json`, `memories.db`, tiered memory files
206226

207227
### Agent Behavior (From MainAgent System Prompt)
208228
1. **Context-Aware Execution**: Use `CommandDir`/`FindFiles` when unfamiliar with project; skip if memory sufficient
209229
2. **Read Before Write**: Always `CommandCat` before `CommandEditText` to get exact line numbers
210230
3. **Evaluate Impact**: Use `SearchInFiles` before modifying public APIs
211-
4. **Goal Decomposition**: Break complex tasks into subtasks, execute continuously
212-
5. **Auto-Recovery**: On failure, analyze stderr, retry 2-3 times before reporting
213-
6. **Strict Verification**: Check Git Diff after edits, fix immediately if wrong
231+
4. **Skill Introspection**: Check available tools/skills before claiming capabilities; never fabricate unauthorized operations
232+
5. **Goal Decomposition**: Break complex tasks into subtasks, execute continuously
233+
6. **Auto-Recovery**: On failure, analyze stderr, retry 2-3 times before reporting
234+
7. **Strict Verification**: Check Git Diff after edits, fix immediately if wrong
214235

215236
---
216237

README.md

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ By leveraging the `Microsoft.Extensions.AI` abstraction layer, Sharpclaw seamles
2929
* **Web (WebSocket):** A lightweight ASP.NET Core web server with a modern UI (Tokyo Night theme) and real-time streaming.
3030
* **QQ Bot:** Native integration with QQ channels, groups, and private messages.
3131

32+
### 🔌 Extensible Skills System
33+
34+
* **External Skills:** Load custom skills from `~/.sharpclaw/skills/` via `AgentSkillsDotNet`, seamlessly merged with built-in commands as a unified tool collection.
35+
* **Lua Scripting:** Embedded scripting support via `ToonSharp` for user-defined automation.
36+
* **Scheduled Tasks:** Cron expression support via `Cronos` for timed operations.
37+
3238
### 🔒 Secure Configuration
3339

3440
* Cross-platform secure credential storage (Windows Credential Manager, macOS Keychain, Linux libsecret) using AES-256-CBC encryption for API keys.
@@ -41,7 +47,7 @@ By leveraging the `Microsoft.Extensions.AI` abstraction layer, Sharpclaw seamles
4147

4248
### Prerequisites
4349

44-
* [.NET 10.0 SDK (Preview)](https://dotnet.microsoft.com/)
50+
* [.NET 10.0 SDK](https://dotnet.microsoft.com/)
4551
* Git (for cloning submodules)
4652

4753
### Build and Run
@@ -107,15 +113,13 @@ dotnet run --project sharpclaw config
107113
│ ├── VectorMemoryStore — Sharc + SQLite vector search │
108114
│ └── InMemoryMemoryStore — Keyword-based fallback │
109115
├─────────────────────────────────────────────────────────────┤
110-
│ Command System (Commands/) │
111-
│ ├── FileCommands — File operations (cat, edit, find, etc.) │
112-
│ ├── ProcessCommands — Bash/PowerShell execution │
113-
│ ├── HttpCommands — HTTP requests │
114-
│ ├── TaskCommands — Background task management │
115-
│ └── SystemCommands — System info, exit │
116+
│ Skills & Commands (Commands/, ~/.sharpclaw/skills/) │
117+
│ ├── Built-in — File, Process, HTTP, Task, System commands │
118+
│ ├── External Skills — AgentSkillsDotNet plugin loading │
119+
│ └── Memory Tools — SearchMemory, GetRecentMemories │
116120
├─────────────────────────────────────────────────────────────┤
117121
│ Core Infrastructure (Core/) │
118-
│ ├── AgentBootstrap — Shared initialization
122+
│ ├── AgentBootstrap — Shared initialization + skill loading
119123
│ ├── SharpclawConfig — Configuration with encryption │
120124
│ ├── ClientFactory — LLM client creation │
121125
│ ├── DataProtector/KeyStore — AES-256-CBC encryption │
@@ -129,7 +133,7 @@ Sharpclaw implements a sophisticated three-layer memory pipeline:
129133

130134
| Layer | File | Purpose |
131135
|-------|------|---------|
132-
| **Working Memory** | `working_memory.md` | Current conversation snapshot |
136+
| **Working Memory** | `working_memory.json` | Current conversation snapshot |
133137
| **Recent Memory** | `recent_memory.md` | Detailed summaries (append-only) |
134138
| **Primary Memory** | `primary_memory.md` | Consolidated core facts |
135139
| **Vector Store** | `memories.db` | Semantic embeddings + metadata |
@@ -195,6 +199,7 @@ Configuration is stored in `~/.sharpclaw/config.json` (version 8):
195199
},
196200
"agents": {
197201
"main": { "enabled": true },
202+
"recaller": { "enabled": true },
198203
"saver": { "enabled": true },
199204
"summarizer": { "enabled": true }
200205
},

README_CN.md

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ Sharpclaw 是一个基于 **.NET 10** 开发的**自主型 AI 智能体框架**
2929
* **Web 模式 (WebSocket):** 轻量级 ASP.NET Core 服务,内置现代化网页终端(Tokyo Night 暗色主题),支持流式打字机输出。
3030
* **QQ Bot 模式:** 原生接入 QQ 机器人体系,支持频道、群聊及私聊环境。
3131

32+
### 🔌 可扩展技能系统
33+
34+
* **外部技能加载:**`~/.sharpclaw/skills/` 目录通过 `AgentSkillsDotNet` 加载自定义技能,与内置命令无缝合并为统一工具集。
35+
* **Lua 脚本支持:** 通过 `ToonSharp` 嵌入式 Lua 引擎实现用户自定义自动化脚本。
36+
* **定时任务:** 通过 `Cronos` 支持 Cron 表达式调度定时操作。
37+
3238
### 🔒 高安全性配置
3339

3440
* 跨平台凭据安全存储:支持 Windows 凭据管理器、macOS 钥匙串和 Linux libsecret,API Key 等敏感信息默认通过 AES-256-CBC 加密存储。
@@ -41,7 +47,7 @@ Sharpclaw 是一个基于 **.NET 10** 开发的**自主型 AI 智能体框架**
4147

4248
### 环境要求
4349

44-
* [.NET 10.0 SDK (Preview)](https://dotnet.microsoft.com/)
50+
* [.NET 10.0 SDK](https://dotnet.microsoft.com/)
4551
* Git (用于拉取子模块)
4652

4753
### 编译与运行
@@ -107,15 +113,13 @@ dotnet run --project sharpclaw config
107113
│ ├── VectorMemoryStore — Sharc + SQLite 向量搜索 │
108114
│ └── InMemoryMemoryStore — 关键字匹配降级方案 │
109115
├─────────────────────────────────────────────────────────────┤
110-
│ 命令系统 (Commands/) │
111-
│ ├── FileCommands — 文件操作(cat、edit、find 等) │
112-
│ ├── ProcessCommands — Bash/PowerShell 执行 │
113-
│ ├── HttpCommands — HTTP 请求 │
114-
│ ├── TaskCommands — 后台任务管理 │
115-
│ └── SystemCommands — 系统信息、退出 │
116+
│ 技能与命令系统 (Commands/, ~/.sharpclaw/skills/) │
117+
│ ├── 内置命令 — 文件、进程、HTTP、任务、系统 │
118+
│ ├── 外部技能 — AgentSkillsDotNet 插件加载 │
119+
│ └── 记忆工具 — SearchMemory、GetRecentMemories │
116120
├─────────────────────────────────────────────────────────────┤
117121
│ 核心基础设施 (Core/) │
118-
│ ├── AgentBootstrap — 共享初始化逻辑
122+
│ ├── AgentBootstrap — 共享初始化 + 技能加载
119123
│ ├── SharpclawConfig — 带加密的配置管理 │
120124
│ ├── ClientFactory — LLM 客户端创建 │
121125
│ ├── DataProtector/KeyStore — AES-256-CBC 加密 │
@@ -129,7 +133,7 @@ Sharpclaw 实现了复杂的三层记忆管线:
129133

130134
| 层级 | 文件 | 用途 |
131135
|------|------|------|
132-
| **工作记忆** | `working_memory.md` | 当前会话快照 |
136+
| **工作记忆** | `working_memory.json` | 当前会话快照 |
133137
| **近期记忆** | `recent_memory.md` | 详细摘要(追加模式) |
134138
| **核心记忆** | `primary_memory.md` | 整合后的核心事实 |
135139
| **向量库** | `memories.db` | 语义嵌入 + 元数据 |
@@ -195,6 +199,7 @@ sharpclaw/
195199
},
196200
"agents": {
197201
"main": { "enabled": true },
202+
"recaller": { "enabled": true },
198203
"saver": { "enabled": true },
199204
"summarizer": { "enabled": true }
200205
},

sharpclaw/Agents/MainAgent.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ void Append(string type, string text)
222222
// 流式输出
223223
_reducer.UserInput = input;
224224
_reducer.WorkingMemoryBuffer.Add(new ChatMessage(ChatRole.User, input));
225+
var turnStartIndex = _reducer.WorkingMemoryBuffer.Count; // 当前轮次流式消息的起始索引
225226
AIContent? lastContent = null;
226227
AppLogger.SetStatus("AI 思考中...");
227228
_chatIO.BeginAiResponse();
@@ -294,14 +295,16 @@ void Append(string type, string text)
294295
if (message.Contents.Count > 0)
295296
_reducer.WorkingMemoryBuffer.Add(message);
296297

297-
// 检查所有未返回结果的工具调用,补充取消标记
298-
var allCallIds = _reducer.WorkingMemoryBuffer
298+
// 检查当前轮次中未返回结果的工具调用,补充取消标记
299+
var turnMessages = _reducer.WorkingMemoryBuffer.Skip(turnStartIndex);
300+
301+
var allCallIds = turnMessages
299302
.Where(m => m.Role == ChatRole.Assistant)
300303
.SelectMany(m => m.Contents.OfType<FunctionCallContent>())
301304
.Select(c => c.CallId)
302305
.ToHashSet();
303306

304-
var answeredCallIds = _reducer.WorkingMemoryBuffer
307+
var answeredCallIds = turnMessages
305308
.Where(m => m.Role == ChatRole.Tool)
306309
.SelectMany(m => m.Contents.OfType<FunctionResultContent>())
307310
.Select(r => r.CallId)
@@ -310,7 +313,7 @@ void Append(string type, string text)
310313
allCallIds.ExceptWith(answeredCallIds);
311314
if (allCallIds.Count > 0)
312315
{
313-
var unmatchedCalls = _reducer.WorkingMemoryBuffer
316+
var unmatchedCalls = turnMessages
314317
.Where(m => m.Role == ChatRole.Assistant)
315318
.SelectMany(m => m.Contents.OfType<FunctionCallContent>())
316319
.Where(c => allCallIds.Contains(c.CallId))

sharpclaw/Chat/MemoryPipelineChatReducer.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,13 @@ public async Task<IEnumerable<ChatMessage>> ReduceAsync(
9595
if (_systemPrompt is not null && systemMessages.Count == 0)
9696
systemMessages.Add(new ChatMessage(ChatRole.System, _systemPrompt));
9797

98+
// 注入当前时间
99+
systemMessages.Add(new ChatMessage(ChatRole.System,
100+
$"[当前时间] {DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss zzz}")
101+
{
102+
AdditionalProperties = new() { [AutoMemoryKey] = true }
103+
});
104+
98105
// ── 2. 保存工作记忆(从 MainAgent 流式累积的 WorkingMemoryBuffer)──
99106
SaveWorkingMemory();
100107

0 commit comments

Comments
 (0)