feat(dream): add memory dream cli and docs

- New memory/deep-dream.mdx (zh/en/ja): memory flow, distillation rules, dream diary, manual trigger, safety mechanisms
- Simplify long-term memory page, link to deep-dream for details
- New cli/memory-knowledge.mdx (zh/en/ja): memory and knowledge commands
- Move knowledge commands from general.mdx to memory-knowledge.mdx
- Register new pages in docs.json navigation for all languages
- Add /memory dream to cli/index.mdx command tables
This commit is contained in:
zhayujie
2026-04-14 11:03:53 +08:00
parent 94d8c7e366
commit acc09543b7
19 changed files with 610 additions and 116 deletions

View File

@@ -42,7 +42,7 @@ DREAM_SYSTEM_PROMPT = """你是一个记忆整理助手,负责定期整理用
1. **当前长期记忆** — MEMORY.md 的全部现有内容
2. **今日日记** — 当天的日常记录
MEMORY.md 会注入每次对话的系统提示词中,因此必须保持精炼。
MEMORY.md 会注入每次对话的系统提示词中,因此必须保持精炼,只存放有价值和值得记忆的内容
**重要:只能基于提供的材料进行整理,严禁编造、推测或添加材料中不存在的信息。**
@@ -52,12 +52,12 @@ MEMORY.md 会注入每次对话的系统提示词中,因此必须保持精炼
在现有记忆基础上进行整理和提炼,输出完整的更新后内容:
- **合并提炼**:将含义相近的多条合并为一条高密度表述,而非简单罗列
- **新增萃取**:从今日日记中提取值得永久记住的新信息(偏好、决策、人物、经验)
- **新增萃取**:从今日日记中提取值得永久记住的新信息(偏好、决策、人物、规则、经验)
- **冲突更新**:当新信息与旧条目矛盾时,以新信息为准,替换旧条目
- **清理无效**:删除临时性记录、空白条目、格式残留等
- **删除冗余**:已被更精炼表述涵盖的旧条目应删除,避免信息重复
- 每条一行,用 "- " 开头,不带日期前缀
- 目标:控制在 30 条以内,每条尽量一句话概括
- 目标:控制在 50 条以内,每条尽量一句话概括
### Part 2: 梦境日记([DREAM]
@@ -300,15 +300,13 @@ class MemoryFlushManager:
# ---- Deep Dream (memory distillation) ----
def deep_dream(self, user_id: Optional[str] = None, lookback_days: int = 1) -> bool:
def deep_dream(self, user_id: Optional[str] = None, lookback_days: int = 1, force: bool = False) -> bool:
"""
Distill recent daily memories into MEMORY.md and generate a dream diary.
Process:
1. Read current MEMORY.md + recent N days of daily files
2. LLM produces updated MEMORY.md (deduped/pruned) + dream diary narrative
3. Overwrite MEMORY.md with the distilled version
4. Write dream diary to memory/dreams/YYYY-MM-DD.md
Args:
lookback_days: How many days of daily files to read (default 1 for scheduled, 3 for manual)
force: Skip input-hash dedup check (used by manual /memory dream trigger)
"""
if not self.llm_model:
logger.warning("[DeepDream] No LLM model available, skipping")
@@ -327,7 +325,7 @@ class MemoryFlushManager:
# Dedup: skip if input materials haven't changed since last dream
import hashlib
input_hash = hashlib.md5((memory_content + daily_content).encode("utf-8")).hexdigest()
if input_hash == self._last_dream_input_hash:
if not force and input_hash == self._last_dream_input_hash:
logger.debug("[DeepDream] Input unchanged since last dream, skipping")
return False
self._last_dream_input_hash = input_hash
@@ -377,16 +375,10 @@ class MemoryFlushManager:
logger.warning("[DeepDream] No [MEMORY] section in LLM output, skipping overwrite")
return False
# Overwrite MEMORY.md (with shrinkage protection)
# Overwrite MEMORY.md
try:
main_file = self.get_main_memory_file(user_id)
old_size = len(memory_content)
if old_size > 200 and len(new_memory) < old_size * 0.3:
logger.warning(
f"[DeepDream] Distilled MEMORY.md is too small "
f"({old_size}{len(new_memory)} chars, <30%), aborting to prevent data loss"
)
return False
main_file.write_text(new_memory + "\n", encoding="utf-8")
logger.info(
f"[DeepDream] Updated MEMORY.md "

View File

@@ -427,6 +427,22 @@ const chatInput = document.getElementById('chat-input');
const sendBtn = document.getElementById('send-btn');
const messagesDiv = document.getElementById('chat-messages');
const fileInput = document.getElementById('file-input');
// Intercept internal navigation links in chat messages
messagesDiv.addEventListener('click', (e) => {
const a = e.target.closest('a');
if (!a) return;
const href = a.getAttribute('href') || '';
if (href === '/memory/dreams') {
e.preventDefault();
navigateTo('memory');
setTimeout(() => switchMemoryTab('dreams'), 50);
} else if (href === '/memory/MEMORY.md') {
e.preventDefault();
navigateTo('memory');
setTimeout(() => { switchMemoryTab('files'); openMemoryFile('MEMORY.md', 'memory'); }, 50);
}
});
const attachmentPreview = document.getElementById('attachment-preview');
// Pending attachments: [{file_path, file_name, file_type, preview_url}]
@@ -566,6 +582,7 @@ const SLASH_COMMANDS = [
{ cmd: '/skill info ', desc: '查看技能详情' },
{ cmd: '/skill enable ', desc: '启用技能' },
{ cmd: '/skill disable ', desc: '禁用技能' },
{ cmd: '/memory dream ', desc: '手动触发记忆蒸馏 (可指定天数, 默认3)' },
{ cmd: '/knowledge', desc: '查看知识库统计' },
{ cmd: '/knowledge list', desc: '查看知识库文件树' },
{ cmd: '/knowledge on', desc: '开启知识库' },

View File

@@ -106,45 +106,6 @@ Session: 12 messages | 8 skills loaded
/logs 50
```
## knowledge
查看和管理个人知识库。默认显示知识库统计信息。
```text
/knowledge
```
输出示例:
```
📚 知识库
- 状态:已开启
- 页面数12
- 总大小45.2 KB
- 分类明细:
- concepts/: 5 篇
- entities/: 4 篇
- sources/: 3 篇
```
**查看目录结构:**
```text
/knowledge list
```
**开启 / 关闭知识库:**
```text
/knowledge on
/knowledge off
```
<Note>
终端 CLI 中 `cow knowledge` 和 `cow knowledge list` 可用,但 `on|off` 仅支持在对话中使用(需实时生效)。
</Note>
## version
显示当前 CowAgent 版本号。

View File

@@ -40,7 +40,8 @@ Service:
Skills:
skill Manage skills (list / search / install / uninstall ...)
Knowledge:
Memory & Knowledge:
memory Memory distillation (dream)
knowledge View knowledge base stats and structure
Others:
@@ -58,6 +59,7 @@ Others:
| `/status` | 查看服务状态和配置 |
| `/config` | 查看或修改运行时配置 |
| `/skill` | 管理技能(安装、卸载、启用、禁用等) |
| `/memory dream [N]` | 手动触发记忆蒸馏(默认 3 天,最大 30 |
| `/knowledge` | 查看知识库统计信息 |
| `/knowledge list` | 查看知识库目录结构 |
| `/knowledge on\|off` | 开启或关闭知识库 |
@@ -82,6 +84,7 @@ Others:
| logs | ✓ | ✓ |
| config | ✗ | ✓ |
| context | — | ✓ |
| memory (子命令) | ✗ | ✓ |
| knowledge (子命令) | ✓ | ✓ |
| skill (子命令) | ✓ | ✓ |
| start / stop / restart | ✓ | ✗ |

View File

@@ -0,0 +1,77 @@
---
title: 记忆与知识库
description: 记忆蒸馏和知识库管理命令
---
## memory
管理 Agent 的长期记忆系统。
### memory dream
手动触发记忆蒸馏Deep Dream整理近期的天级记忆蒸馏合并到 MEMORY.md并生成梦境日记。
```text
/memory dream [N]
```
- `N`:整理近 N 天的记忆,默认 3 天,最大 30 天
- 蒸馏在后台异步执行,完成后会在对话中通知结果
- 无需等待 Agent 初始化,首次对话前即可使用
**示例:**
```text
/memory dream # 整理近 3 天
/memory dream 7 # 整理近 7 天
/memory dream 30 # 整理近 30 天(全量)
```
蒸馏完成后Web 端会收到带有跳转链接的通知,可直接查看更新后的 MEMORY.md 和梦境日记。
<Tip>
系统每天 23:55 会自动执行一次蒸馏lookback 1 天)。手动触发适用于首次部署后的历史整理,或需要立即更新记忆时使用。
</Tip>
## knowledge
查看和管理个人知识库。默认显示知识库统计信息。
```text
/knowledge
```
输出示例:
```
📚 知识库
- 状态:已开启
- 页面数12
- 总大小45.2 KB
- 分类明细:
- concepts/: 5 篇
- entities/: 4 篇
- sources/: 3 篇
```
### knowledge list
查看知识库目录树结构。
```text
/knowledge list
```
### knowledge on / off
开启或关闭知识库。关闭后不再注入知识提示词和索引知识文件。
```text
/knowledge on
/knowledge off
```
<Note>
终端 CLI 中 `cow knowledge` 和 `cow knowledge list` 可用,但 `on|off` 仅支持在对话中使用(需实时生效)。
</Note>

View File

@@ -142,7 +142,8 @@
"group": "记忆系统",
"pages": [
"memory/index",
"memory/context"
"memory/context",
"memory/deep-dream"
]
}
]
@@ -185,6 +186,7 @@
"cli/index",
"cli/process",
"cli/skill",
"cli/memory-knowledge",
"cli/general"
]
}
@@ -314,7 +316,8 @@
"group": "Memory System",
"pages": [
"en/memory/index",
"en/memory/context"
"en/memory/context",
"en/memory/deep-dream"
]
}
]
@@ -357,6 +360,7 @@
"en/cli/index",
"en/cli/process",
"en/cli/skill",
"en/cli/memory-knowledge",
"en/cli/chat"
]
}
@@ -486,7 +490,8 @@
"group": "メモリシステム",
"pages": [
"ja/memory/index",
"ja/memory/context"
"ja/memory/context",
"ja/memory/deep-dream"
]
}
]
@@ -529,6 +534,7 @@
"ja/cli/index",
"ja/cli/process",
"ja/cli/skill",
"ja/cli/memory-knowledge",
"ja/cli/general"
]
}

View File

@@ -92,31 +92,6 @@ View recent service logs. Shows the last 20 lines by default, up to 50.
/logs 50
```
## knowledge
View and manage the personal knowledge base. Shows statistics by default.
```text
/knowledge
```
**View directory structure:**
```text
/knowledge list
```
**Enable / disable knowledge base:**
```text
/knowledge on
/knowledge off
```
<Note>
In the terminal CLI, `cow knowledge` and `cow knowledge list` are available, but `on|off` is only supported in chat (requires runtime effect).
</Note>
## version
Show the current CowAgent version.

View File

@@ -40,7 +40,8 @@ Service:
Skills:
skill Manage skills (list / search / install / uninstall ...)
Knowledge:
Memory & Knowledge:
memory Memory distillation (dream)
knowledge View knowledge base stats and structure
Others:
@@ -58,6 +59,7 @@ In the Web console or any connected channel, type `/` to see command suggestions
| `/status` | View service status and configuration |
| `/config` | View or modify runtime configuration |
| `/skill` | Manage skills (install, uninstall, enable, disable, etc.) |
| `/memory dream [N]` | Manually trigger memory distillation (default 3 days, max 30) |
| `/knowledge` | View knowledge base statistics |
| `/knowledge list` | View knowledge base directory structure |
| `/knowledge on\|off` | Enable or disable knowledge base |
@@ -80,6 +82,7 @@ In the Web console or any connected channel, type `/` to see command suggestions
| logs | ✓ | ✓ |
| config | ✗ | ✓ |
| context | — | ✓ |
| memory (subcommands) | ✗ | ✓ |
| knowledge (subcommands) | ✓ | ✓ |
| skill (subcommands) | ✓ | ✓ |
| start / stop / restart | ✓ | ✗ |

View File

@@ -0,0 +1,63 @@
---
title: Memory & Knowledge
description: Memory distillation and knowledge base management commands
---
## memory
Manage the Agent's long-term memory system.
### memory dream
Manually trigger memory distillation (Deep Dream) — consolidate recent daily memories into MEMORY.md and generate a dream diary.
```text
/memory dream [N]
```
- `N`: Consolidate the last N days of memory (default 3, max 30)
- Runs asynchronously in the background; you'll be notified in chat when complete
- Works without Agent initialization — can be used before the first conversation
**Examples:**
```text
/memory dream # Consolidate last 3 days
/memory dream 7 # Consolidate last 7 days
/memory dream 30 # Consolidate last 30 days (full)
```
On the Web console, the completion notification includes clickable links to view the updated MEMORY.md and dream diary.
<Tip>
The system automatically runs distillation daily at 23:55 (lookback 1 day). Manual trigger is useful for consolidating historical memories after first deployment, or when you need an immediate memory update.
</Tip>
## knowledge
View and manage the personal knowledge base. Shows statistics by default.
```text
/knowledge
```
### knowledge list
View the knowledge base directory tree.
```text
/knowledge list
```
### knowledge on / off
Enable or disable the knowledge base. When disabled, knowledge prompts and file indexing are not injected.
```text
/knowledge on
/knowledge off
```
<Note>
In the terminal CLI, `cow knowledge` and `cow knowledge list` are available, but `on|off` is only supported in chat (requires runtime effect).
</Note>

View File

@@ -0,0 +1,90 @@
---
title: Deep Dream
description: Deep Dream — automatic distillation from conversations to permanent memory
---
Deep Dream is the core consolidation mechanism of CowAgent's memory system, responsible for distilling scattered daily memories into refined long-term memory and generating dream diaries.
## Memory Flow
CowAgent's memory progresses through three stages from short-term to long-term:
```
Conversation context (short-term) → Daily memory (mid-term) → MEMORY.md (long-term)
```
### 1. Conversation → Daily Memory
When conversation context is trimmed or during the daily scheduled summary, the system uses LLM to summarize conversation content into key events, writing them to the daily memory file `memory/YYYY-MM-DD.md`.
Triggers:
- **Context trimming** — Trimmed content is summarized when turn or token limits are exceeded
- **Daily schedule** — Automatically triggered at 23:55
- **API overflow** — Emergency save of current conversation summary
### 2. Daily Memory → MEMORY.md (Distillation)
After the daily summary completes, Deep Dream automatically runs distillation:
1. **Read materials** — Current `MEMORY.md` + today's daily memory
2. **LLM distillation** — Deduplicate, merge, prune, extract new information
3. **Overwrite MEMORY.md** — Output the refined long-term memory
4. **Generate dream diary** — Record discoveries and insights from the consolidation
### 3. Role of MEMORY.md
`MEMORY.md` is injected into the system prompt for every conversation, keeping the Agent aware of user preferences, decisions, and key facts. Therefore it must stay concise — Deep Dream targets approximately 30 entries or fewer.
## Distillation Rules
Deep Dream follows these consolidation rules:
| Operation | Description |
| --- | --- |
| **Merge & refine** | Combine similar entries into single high-density statements |
| **Extract new** | Pull preferences, decisions, people, experiences from daily memory |
| **Conflict update** | When new info contradicts old entries, newer info takes precedence |
| **Clean invalid** | Remove temporary records, blank entries, formatting artifacts |
| **Remove redundancy** | Delete old entries already covered by more refined statements |
## Dream Diary
Each distillation generates a dream diary saved at `memory/dreams/YYYY-MM-DD.md`, written in a narrative style recording:
- Duplications or contradictions found
- New insights extracted from daily memory
- Cleanups and optimizations performed
- Overall observations
Dream diaries can be viewed in the Web console under "Memory → Dream Diary" tab.
<Frame>
<img src="https://cdn.link-ai.tech/doc/20260414110032.png" width="800" />
</Frame>
## Manual Trigger
In addition to the automatic daily run, you can manually trigger distillation in chat:
```text
/memory dream [N]
```
- `N`: Consolidate the last N days of memory (default 3, max 30)
- Runs asynchronously in the background; you'll be notified in chat when complete
- Web notifications include clickable links to view MEMORY.md and dream diary
- Works without Agent initialization — can be used before the first conversation
<Tip>
After first deployment, it's recommended to run `/memory dream 30` once to distill all historical daily memories into MEMORY.md.
</Tip>
## Safety Mechanisms
| Mechanism | Description |
| --- | --- |
| **Skip on no content** | Distillation skipped when no daily memory exists, avoiding empty overwrites |
| **Input dedup** | In scheduled tasks, automatically skipped when input materials haven't changed |
| **Async execution** | Distillation runs in a background thread, never blocking conversation |
| **Sequential guarantee** | In scheduled tasks, daily flush completes before distillation starts |
| **No fabrication** | Prompt explicitly constrains consolidation to existing materials only |

View File

@@ -25,7 +25,7 @@ The Agent automatically persists conversation content to long-term memory throug
- **On context trimming** — When conversation turns or tokens exceed the configured limit, the oldest half of the context is trimmed, and the discarded content is summarized by LLM into key information and written to the daily memory file. The summary is also asynchronously injected into the retained context for conversational continuity
- **Daily scheduled summary** — A full summary is automatically triggered at 23:55 every day, ensuring memory is preserved even on low-activity days (skipped if content hasn't changed)
- **Deep Dream (memory distillation)** — Runs automatically after the daily summary, reading recent daily files and current MEMORY.md, then using LLM to deduplicate, merge, and prune, producing a refined MEMORY.md and a dream diary
- **[Deep Dream (memory distillation)](/en/memory/deep-dream)** — Runs automatically after the daily summary, distilling daily memories into MEMORY.md and generating a dream diary
- **On API context overflow** — When the model API returns a context overflow error, the current conversation summary is saved as an emergency measure
All memory writes run asynchronously in a background thread (LLM summarization + file writing), never blocking normal conversation replies.

View File

@@ -92,31 +92,6 @@ description: ステータスの確認、設定管理、コンテキスト制御
/logs 50
```
## knowledge
パーソナルナレッジベースの表示と管理を行います。デフォルトでは統計情報を表示します。
```text
/knowledge
```
**ディレクトリ構造を表示:**
```text
/knowledge list
```
**ナレッジベースの有効化・無効化:**
```text
/knowledge on
/knowledge off
```
<Note>
ターミナル CLI では `cow knowledge` と `cow knowledge list` が利用可能ですが、`on|off` はチャットでのみサポートされます(実行時に即座に反映するため)。
</Note>
## version
現在の CowAgent のバージョンを表示します。

View File

@@ -40,7 +40,8 @@ Service:
Skills:
skill Manage skills (list / search / install / uninstall ...)
Knowledge:
Memory & Knowledge:
memory Memory distillation (dream)
knowledge View knowledge base stats and structure
Others:
@@ -58,6 +59,7 @@ Web コンソールや接続されたチャネルの会話で `/` を入力す
| `/status` | サービスの状態と設定を表示 |
| `/config` | 実行時設定の表示・変更 |
| `/skill` | スキル管理(インストール、アンインストール、有効化、無効化など) |
| `/memory dream [N]` | 記憶蒸留を手動トリガー(デフォルト 3 日、最大 30 |
| `/knowledge` | ナレッジベースの統計情報を表示 |
| `/knowledge list` | ナレッジベースのディレクトリ構造を表示 |
| `/knowledge on\|off` | ナレッジベースの有効化・無効化 |
@@ -80,6 +82,7 @@ Web コンソールや接続されたチャネルの会話で `/` を入力す
| logs | ✓ | ✓ |
| config | ✗ | ✓ |
| context | — | ✓ |
| memoryサブコマンド | ✗ | ✓ |
| knowledgeサブコマンド | ✓ | ✓ |
| skillサブコマンド | ✓ | ✓ |
| start / stop / restart | ✓ | ✗ |

View File

@@ -0,0 +1,63 @@
---
title: 記憶とナレッジベース
description: 記憶蒸留とナレッジベース管理コマンド
---
## memory
Agent の長期記憶システムを管理します。
### memory dream
記憶蒸留Deep Dreamを手動でトリガーします — 最近の日次記憶を整理し、MEMORY.md に統合し、夢日記を生成します。
```text
/memory dream [N]
```
- `N`:直近 N 日間の記憶を整理(デフォルト 3 日、最大 30 日)
- バックグラウンドで非同期に実行され、完了するとチャットで通知されます
- Agent の初期化不要 — 最初の会話前でも使用可能
**例:**
```text
/memory dream # 直近 3 日間を整理
/memory dream 7 # 直近 7 日間を整理
/memory dream 30 # 直近 30 日間を整理(全量)
```
Web コンソールでは、完了通知にクリック可能なリンクが含まれ、更新された MEMORY.md と夢日記を直接確認できます。
<Tip>
システムは毎日 23:55 に自動で蒸留を実行しますlookback 1 日)。手動トリガーは、初回デプロイ後の履歴整理や、即座に記憶を更新したい場合に使用します。
</Tip>
## knowledge
パーソナルナレッジベースの表示と管理。デフォルトで統計情報を表示します。
```text
/knowledge
```
### knowledge list
ナレッジベースのディレクトリツリーを表示します。
```text
/knowledge list
```
### knowledge on / off
ナレッジベースの有効化・無効化。無効化すると、ナレッジプロンプトとファイルインデックスが注入されなくなります。
```text
/knowledge on
/knowledge off
```
<Note>
ターミナル CLI では `cow knowledge` と `cow knowledge list` が利用可能ですが、`on|off` はチャットでのみサポートされます(ランタイム効果が必要なため)。
</Note>

View File

@@ -0,0 +1,90 @@
---
title: 夢境蒸留
description: Deep Dream — 会話から永続記憶への自動蒸留メカニズム
---
夢境蒸留Deep Dreamは CowAgent の記憶システムの中核的な整理メカニズムであり、散在する日次記憶を精錬された長期記憶に蒸留し、夢日記を生成します。
## 記憶の流れ
CowAgent の記憶は短期から長期まで 3 つの段階を経ます:
```
会話コンテキスト(短期)→ 日次記憶(中期)→ MEMORY.md長期
```
### 1. 会話 → 日次記憶
会話コンテキストがトリミングされた時、または毎日のスケジュール要約時に、LLM が会話内容を重要イベントに要約し、日次記憶ファイル `memory/YYYY-MM-DD.md` に書き込みます。
トリガー:
- **コンテキストトリミング** — ターン数またはトークン制限を超えた時、トリミングされた内容が要約されます
- **毎日のスケジュール** — 23:55 に自動トリガー
- **API オーバーフロー** — 現在の会話要約の緊急保存
### 2. 日次記憶 → MEMORY.md蒸留
毎日の要約完了後、Deep Dream が自動的に蒸留を実行します:
1. **材料の読み込み** — 現在の `MEMORY.md` + 当日の日次記憶
2. **LLM 蒸留** — 重複排除、統合、剪定、新情報の抽出
3. **MEMORY.md の上書き** — 精錬された長期記憶を出力
4. **夢日記の生成** — 整理過程の発見と洞察を記録
### 3. MEMORY.md の役割
`MEMORY.md` は毎回の会話のシステムプロンプトに注入され、Agent がユーザーの好み、決定、重要な事実を常に把握できるようにします。そのため簡潔に保つ必要があり、Deep Dream は約 30 項目以内に制御します。
## 蒸留ルール
Deep Dream は以下の整理ルールに従います:
| 操作 | 説明 |
| --- | --- |
| **統合・精錬** | 類似する複数の項目を 1 つの高密度な表現に統合 |
| **新規抽出** | 日次記憶から好み、決定、人物、経験を抽出 |
| **矛盾更新** | 新情報が古い項目と矛盾する場合、新情報を優先 |
| **無効クリーン** | 一時的な記録、空白項目、フォーマット残留を削除 |
| **冗長削除** | より精錬された表現でカバーされた古い項目を削除 |
## 夢日記
各蒸留で夢日記が生成され、`memory/dreams/YYYY-MM-DD.md` に保存されます。ナラティブスタイルで以下を記録します:
- 発見された重複や矛盾
- 日次記憶から抽出された新しい洞察
- 実行されたクリーンアップと最適化
- 全体的な観察
夢日記は Web コンソールの「メモリ管理 → 夢日記」タブで確認できます。
<Frame>
<img src="https://cdn.link-ai.tech/doc/20260414110032.png" width="800" />
</Frame>
## 手動トリガー
毎日の自動実行に加えて、チャットで手動トリガーできます:
```text
/memory dream [N]
```
- `N`:直近 N 日間の記憶を整理(デフォルト 3 日、最大 30 日)
- バックグラウンドで非同期に実行され、完了するとチャットで通知されます
- Web 通知にはクリック可能なリンクが含まれ、MEMORY.md と夢日記を直接確認できます
- Agent の初期化不要 — 最初の会話前でも使用可能
<Tip>
初回デプロイ後は `/memory dream 30` を一度実行して、すべての履歴日次記憶を MEMORY.md に蒸留することをお勧めします。
</Tip>
## 安全メカニズム
| メカニズム | 説明 |
| --- | --- |
| **コンテンツなしでスキップ** | 日次記憶がない場合、蒸留をスキップし空の上書きを回避 |
| **入力重複排除** | スケジュールタスクで、入力材料が変更されていない場合自動スキップ |
| **非同期実行** | 蒸留はバックグラウンドスレッドで実行、会話をブロックしない |
| **順序保証** | スケジュールタスクで、日次フラッシュ完了後に蒸留を開始 |
| **捏造禁止** | プロンプトで既存の材料のみに基づく整理を明示的に制約 |

View File

@@ -25,7 +25,7 @@ Agent は以下のメカニズムにより、会話内容を長期記憶に自
- **コンテキストトリミング時** — 会話ターン数またはトークン数が設定上限を超えた場合、最も古い半分のコンテキストがトリミングされ、LLM によって要約されて日次記憶ファイルに書き込まれます。要約は保持されたコンテキストにも非同期で注入され、会話の連続性を維持します
- **毎日のスケジュール要約** — 毎日 23:55 に自動的にフル要約がトリガーされ、アクティビティが少ない日でも記憶が保存されます(内容が変更されていない場合はスキップ)
- **Deep Dream(記憶蒸留** — 毎日の要約完了後に自動実行され、最近の日次記憶と現在の MEMORY.md を読み込み、LLM で重複排除・統合・剪定を行い、精錬された新しい MEMORY.md と夢日記を生成します
- **[夢境蒸留(Deep Dream](/ja/memory/deep-dream)** — 毎日の要約完了後に自動実行され、日次記憶 MEMORY.md に蒸留し、夢日記を生成します
- **API コンテキストオーバーフロー時** — モデル API がコンテキストオーバーフローエラーを返した場合、緊急措置として現在の会話要約が保存されます
すべての記憶書き込みはバックグラウンドスレッドで非同期に実行されLLM の要約 + ファイル書き込み)、通常の会話応答をブロックしません。

View File

@@ -0,0 +1,90 @@
---
title: 梦境蒸馏
description: Deep Dream — 从对话到永久记忆的自动蒸馏机制
---
梦境蒸馏Deep Dream是 CowAgent 记忆系统的核心整理机制,负责将分散的天级记忆蒸馏为精炼的长期记忆,并生成梦境日记。
## 记忆流转
CowAgent 的记忆从短期到长期经历三个阶段:
```
对话上下文(短期)→ 天级记忆(中期)→ MEMORY.md长期
```
### 1. 对话 → 天级记忆
当对话上下文被裁剪或每日定时总结时,系统使用 LLM 将对话内容摘要为关键事件,写入当天的天级记忆文件 `memory/YYYY-MM-DD.md`。
触发时机:
- **上下文裁剪** — 轮次或 token 超限时,裁剪的内容被总结写入
- **每日定时** — 23:55 自动触发全量总结
- **API 溢出** — 紧急保存当前对话摘要
### 2. 天级记忆 → MEMORY.md蒸馏
每日总结完成后Deep Dream 自动执行蒸馏:
1. **读取材料** — 当前 `MEMORY.md` + 当天的天级记忆
2. **LLM 蒸馏** — 去重、合并、修剪、提取新信息
3. **覆写 MEMORY.md** — 输出精炼后的长期记忆
4. **生成梦境日记** — 记录整理过程的发现和洞察
### 3. MEMORY.md 的作用
`MEMORY.md` 会被注入到每次对话的系统提示词中,让 Agent 始终了解用户的偏好、决策和关键事实。因此它必须保持精炼——Deep Dream 会控制在约 30 条以内。
## 蒸馏规则
Deep Dream 遵循以下整理规则:
| 操作 | 说明 |
| --- | --- |
| **合并提炼** | 含义相近的多条合并为一条高密度表述 |
| **新增萃取** | 从天级记忆中提取偏好、决策、人物、经验等 |
| **冲突更新** | 新信息与旧条目矛盾时,以新信息为准 |
| **清理无效** | 删除临时性记录、空白条目、格式残留 |
| **删除冗余** | 已被更精炼表述涵盖的旧条目删除 |
## 梦境日记
每次蒸馏会生成一篇梦境日记,保存在 `memory/dreams/YYYY-MM-DD.md`,用叙事风格记录:
- 发现了哪些重复或矛盾
- 从天级记忆中提取了什么新洞察
- 做了哪些清理和优化
- 整体感受和观察
梦境日记可在 Web 控制台的「记忆管理 → 梦境日记」tab 中查看。
<Frame>
<img src="https://cdn.link-ai.tech/doc/20260414110032.png" width="800" />
</Frame>
## 手动触发
除了每日自动执行外,也可以在对话中手动触发:
```text
/memory dream [N]
```
- `N`:整理近 N 天的记忆(默认 3 天,最大 30 天)
- 蒸馏在后台异步执行,完成后在对话中通知结果
- Web 端通知包含可点击链接,直接跳转查看 MEMORY.md 和梦境日记
- 无需 Agent 初始化,首次对话前即可使用
<Tip>
首次部署后可以手动执行一次 `/memory dream 30`,将历史天级记忆全量蒸馏到 MEMORY.md。
</Tip>
## 安全机制
| 机制 | 说明 |
| --- | --- |
| **无新内容跳过** | 没有天级记忆时不执行蒸馏,避免空覆写 |
| **输入去重** | 定时任务中,输入材料未变化时自动跳过 |
| **异步执行** | 蒸馏在后台线程运行,不阻塞对话 |
| **顺序保证** | 定时任务中,天级 flush 全部完成后才启动蒸馏 |
| **禁止编造** | 提示词明确约束只能基于已有材料整理,不得推测或添加 |

View File

@@ -25,7 +25,7 @@ Agent 通过以下机制自动将对话内容持久化为长期记忆:
- **上下文裁剪时** — 当对话轮次或 token 超出配置上限时,裁剪最早一半的上下文,使用 LLM 将被裁剪的内容总结为关键信息写入当天记忆文件,并将摘要异步注入到保留的上下文中,帮助模型保持对话连贯性
- **每日定时总结** — 每天 23:55 自动触发一次全量总结,防止低活跃日无记忆留存(内容无变化时自动跳过)
- **Deep Dream(记忆蒸馏** — 每日总结完成后自动执行,读取近期日记和当前 MEMORY.md通过 LLM 进行去重、合并、修剪,生成精炼的新版 MEMORY.md 并输出梦境日记
- **[梦境蒸馏(Deep Dream](/memory/deep-dream)** — 每日总结完成后自动执行,将天级记忆蒸馏合并到 MEMORY.md并生成梦境日记
- **API 上下文溢出时** — 当模型 API 返回上下文溢出错误时,紧急保存当前对话摘要
所有记忆写入均在后台异步执行LLM 总结 + 文件写入),不阻塞正常对话回复。

View File

@@ -31,7 +31,7 @@ KNOWN_COMMANDS = {
"help", "version", "status", "logs",
"start", "stop", "restart",
"skill", "context", "config",
"knowledge",
"knowledge", "memory",
"install-browser",
}
@@ -158,6 +158,7 @@ class CowCliPlugin(Plugin):
" /config 查看当前配置",
" /config <key> 查看某项配置",
" /config <key> <val> 修改配置",
" /memory dream [N] 手动触发记忆蒸馏 (整理近N天, 默认3, 最多30)",
" /knowledge 查看知识库统计",
" /knowledge list 查看知识库文件树",
" /knowledge on|off 开启/关闭知识库",
@@ -856,6 +857,91 @@ class CowCliPlugin(Plugin):
icon = "" if enabled else ""
return f"{icon} 技能 '{name}'{action}"
# ------------------------------------------------------------------
# memory
# ------------------------------------------------------------------
def _cmd_memory(self, args: str, e_context, session_id: str = "", **_) -> str:
parts = args.strip().split()
sub = parts[0].lower() if parts else ""
if sub == "dream":
days = 3
if len(parts) > 1 and parts[1].isdigit():
days = max(1, min(int(parts[1]), 30))
return self._memory_dream(days, e_context, session_id)
else:
return (
"用法: /memory <子命令>\n\n"
"子命令:\n"
" dream [N] 手动触发记忆蒸馏 (整理近N天, 默认3, 最多30)"
)
def _memory_dream(self, days: int, e_context, session_id: str) -> str:
session_id = self._get_session_id(e_context, fallback=session_id)
agent = self._get_agent(session_id)
flush_mgr = None
if agent and agent.memory_manager:
flush_mgr = agent.memory_manager.flush_manager
# Fallback: construct a temporary MemoryFlushManager when agent is not yet initialized
if not flush_mgr:
try:
flush_mgr = self._create_standalone_flush_manager()
except Exception as e:
return f"⚠️ 无法初始化记忆蒸馏: {e}"
if not flush_mgr.llm_model:
return "⚠️ 未配置 LLM 模型,无法执行记忆蒸馏"
def _run():
try:
result = flush_mgr.deep_dream(lookback_days=days, force=True)
if result:
self._notify(
e_context,
"✅ 记忆蒸馏完成\n\n[MEMORY.md](/memory/MEMORY.md) 已更新,[查看梦境日记](/memory/dreams)"
)
else:
self._notify(e_context, "💤 记忆蒸馏跳过 — 没有新的记忆内容需要整理")
except Exception as e:
logger.warning(f"[CowCli] /memory dream failed: {e}")
self._notify(e_context, f"❌ 记忆蒸馏失败: {e}")
thread = threading.Thread(target=_run, daemon=True)
thread.start()
return f"🌙 记忆蒸馏已启动 (整理近 {days} 天的记忆)\n\n整理在后台执行,完成后会通知你。"
@staticmethod
def _notify(e_context, text: str):
"""Push a notification message back to the chat channel."""
if e_context is None:
logger.info(f"[CowCli] {text}")
return
try:
channel = e_context["channel"]
context = e_context["context"]
if channel and context:
channel.send(Reply(ReplyType.TEXT, text), context)
except Exception as e:
logger.warning(f"[CowCli] notify failed: {e}")
@staticmethod
def _create_standalone_flush_manager():
"""Create a MemoryFlushManager without a running agent (for pre-init dream)."""
from pathlib import Path
from config import conf
from common.utils import expand_path
from agent.memory.summarizer import MemoryFlushManager
from bridge.bridge import Bridge
from bridge.agent_bridge import AgentLLMModel
workspace = Path(expand_path(conf().get("agent_workspace", "~/cow")))
flush_mgr = MemoryFlushManager(workspace_dir=workspace)
flush_mgr.llm_model = AgentLLMModel(Bridge())
return flush_mgr
# ------------------------------------------------------------------
# knowledge
# ------------------------------------------------------------------