mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-07-17 19:27:11 +08:00
Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8cb53e6129 | ||
|
|
12c0383dc8 | ||
|
|
83b53039f3 | ||
|
|
7e6a309935 | ||
|
|
33c03e30d9 | ||
|
|
1f1abdd7b6 | ||
|
|
16134bd150 | ||
|
|
c887fc71ad | ||
|
|
9fc39f648f | ||
|
|
ec9557e3d8 | ||
|
|
7cf0f7d42d | ||
|
|
b7aa64279d | ||
|
|
26300a8d43 | ||
|
|
8dd21ddb83 | ||
|
|
ff584f8421 | ||
|
|
ca4a8253a1 | ||
|
|
157374401a | ||
|
|
ba777ed706 | ||
|
|
0e4da1d1c5 | ||
|
|
72847e0711 | ||
|
|
3c19614c74 | ||
|
|
a2e4955116 | ||
|
|
c62175c06b | ||
|
|
fde4b6f590 | ||
|
|
3d7c68bac6 | ||
|
|
72a477f10c | ||
|
|
2a16c562a8 | ||
|
|
2b670e73f3 | ||
|
|
3994594019 | ||
|
|
39c9386b54 | ||
|
|
4cc57cc08d | ||
|
|
639a3eac1e | ||
|
|
79323358e5 | ||
|
|
cdb093c74a | ||
|
|
f6f3ce5f05 | ||
|
|
4805f3d4d3 | ||
|
|
1d797cdaf5 | ||
|
|
4d8458669c | ||
|
|
92ec9653e5 | ||
|
|
e861d98007 | ||
|
|
a97eeb1fd9 | ||
|
|
cd88b23b5d | ||
|
|
33eabf937b | ||
|
|
beb5df16a3 | ||
|
|
7fa743f01a | ||
|
|
1f6859d78f | ||
|
|
2853735472 | ||
|
|
04d28f9d2d |
3
.github/PULL_REQUEST_TEMPLATE.md
vendored
3
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,6 +1,6 @@
|
||||
<!--
|
||||
Thanks for your contribution! Please write this PR in English.
|
||||
【中文开发者】请使用英文填写,感谢 ❤️
|
||||
推荐使用英文填写,感谢 ❤️
|
||||
-->
|
||||
|
||||
## What does this PR do?
|
||||
@@ -16,6 +16,7 @@ Thanks for your contribution! Please write this PR in English.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I have read the [Contributing Guide](https://github.com/zhayujie/CowAgent/blob/master/CONTRIBUTING.md)
|
||||
- [ ] I tested this change locally
|
||||
- [ ] Code comments and docs are in English
|
||||
- [ ] Linked related issue (if any): closes #
|
||||
|
||||
27
README.md
27
README.md
@@ -1,13 +1,21 @@
|
||||
<p align="center"><img src="https://github.com/user-attachments/assets/eca9a9ec-8534-4615-9e0f-96c5ac1d10a3" alt="CowAgent" width="420" /></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/github/license/zhayujie/CowAgent" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square" alt="Stars"></a> <br/>
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent?cacheSeconds=3600" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square&cacheSeconds=3600" alt="Stars"></a>
|
||||
<a href="https://docs.cowagent.ai/"><img src="https://img.shields.io/badge/Docs-cowagent.ai-blue?style=flat&logo=readthedocs&logoColor=white" alt="Docs"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/25763" target="_blank"><img src="https://trendshift.io/api/badge/repositories/25763" alt="zhayujie%2FCowAgent | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
[English] | [<a href="docs/zh/README.md">中文</a>] | [<a href="docs/ja/README.md">日本語</a>]
|
||||
</p>
|
||||
|
||||
**CowAgent** is an open-source super AI assistant that proactively plans tasks, controls your computer and external services, creates and runs Skills, and grows alongside you through a personal knowledge base and long-term memory — a reference implementation of Agent Harness engineering.
|
||||
**CowAgent** is an open-source super AI assistant that proactively plans tasks, controls your computer and external services, creates and runs Skills, builds a personal knowledge base and long-term memory, and grows alongside you through self-evolution — a reference implementation of Agent Harness engineering.
|
||||
|
||||
CowAgent is lightweight, easy to deploy, and built to extend. Plug in any major LLM provider and run it 24/7 on a personal computer or server, across the web and all major IM platforms.
|
||||
|
||||
@@ -28,6 +36,7 @@ CowAgent is lightweight, easy to deploy, and built to extend. Plug in any major
|
||||
| [Planning](https://docs.cowagent.ai/intro/architecture) | Decomposes complex tasks and executes them step by step, looping over tools until the goal is reached |
|
||||
| [Memory](https://docs.cowagent.ai/memory/index) | Three-tier architecture (context → daily → core), automatic Deep Dream distillation, hybrid keyword + vector retrieval |
|
||||
| [Knowledge](https://docs.cowagent.ai/knowledge/index) | Auto-curates structured knowledge into a Markdown wiki, builds an evolving knowledge graph with visual browsing |
|
||||
| [Evolution](https://docs.cowagent.ai/memory/self-evolution) | Self-Evolution reviews conversations automatically to improve skills, follow up on unfinished tasks, and consolidate memory and knowledge, growing through everyday use |
|
||||
| [Skills](https://docs.cowagent.ai/skills/index) | One-click install from [Skill Hub](https://skills.cowagent.ai/), GitHub, ClawHub; or create custom skills via natural-language conversation |
|
||||
| [Tools](https://docs.cowagent.ai/tools/index) | Built-in file I/O, terminal, browser, scheduler, memory retrieval, web search, and 10+ more tools — with native MCP integration |
|
||||
| [Channels](https://docs.cowagent.ai/channels/index) | Integrates with Web, WeChat, Feishu, DingTalk, WeCom, QQ, Official Accounts, Telegram, and Slack |
|
||||
@@ -98,11 +107,11 @@ CowAgent supports all mainstream LLM providers. **Chat, vision, image generation
|
||||
| [OpenAI](https://docs.cowagent.ai/models/openai) | gpt-5.5, o-series | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Gemini](https://docs.cowagent.ai/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [DeepSeek](https://docs.cowagent.ai/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [Qwen](https://docs.cowagent.ai/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Qwen](https://docs.cowagent.ai/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [GLM](https://docs.cowagent.ai/models/glm) | glm-5.1, glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [Doubao](https://docs.cowagent.ai/models/doubao) | doubao-seed-2.0 series | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](https://docs.cowagent.ai/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [MiniMax](https://docs.cowagent.ai/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](https://docs.cowagent.ai/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [ERNIE](https://docs.cowagent.ai/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
| [MiMo](https://docs.cowagent.ai/models/mimo) | mimo-v2.5 / pro | ✅ | ✅ | | | ✅ | |
|
||||
| [LinkAI](https://docs.cowagent.ai/models/linkai) | One key for 100+ models | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
@@ -190,6 +199,8 @@ Learn more: [Skills overview](https://docs.cowagent.ai/skills/index) · [Creatin
|
||||
|
||||
## 🏷 Changelog
|
||||
|
||||
> **2026.06.09:** [v2.1.1](https://github.com/zhayujie/CowAgent/releases/tag/2.1.1) — Self-Evolution, Web console upgrades (message management, parallel sessions), cross-platform MCP enhancements with concurrent calls, new models (MiniMax-M3, qwen3.7-plus), Python 3.13 support.
|
||||
|
||||
> **2026.06.01:** [v2.1.0](https://github.com/zhayujie/CowAgent/releases/tag/2.1.0) — Internationalization, new channels (Telegram, Discord, Slack, WeChat Customer Service), CLI interaction upgrades, streamlined one-line install, MCP Streamable HTTP support, new models (claude-opus-4-8, MiMo).
|
||||
|
||||
> **2026.05.22:** [v2.0.9](https://github.com/zhayujie/CowAgent/releases/tag/2.0.9) — Model management, MCP protocol support, persistent browser sessions, new models (gpt-5.5, gemini-3.5-flash, qwen3.7-max), deployment hardening.
|
||||
@@ -238,9 +249,9 @@ For enterprise inquiries: sales@simple-future.tech or [scan the QR code](https:/
|
||||
|
||||
## 🛠️ Development & Contributing
|
||||
|
||||
Contributions are welcome — add a new channel by following the [Feishu channel reference](https://github.com/zhayujie/CowAgent/blob/master/channel/feishu/feishu_channel.py), or contribute new skills to [Skill Hub](https://skills.cowagent.ai/submit).
|
||||
All kinds of contributions are welcome — new features, bug fixes, performance improvements, docs, or sharing your own skills on the [Skill Hub](https://skills.cowagent.ai/submit). See [CONTRIBUTING.md](/CONTRIBUTING.md) to get started, then open an Issue to discuss or send a PR directly.
|
||||
|
||||
⭐ Star the project to follow updates, and feel free to open PRs and Issues.
|
||||
⭐ Star the project to show your support, and Watch → Custom → Releases to get notified of new versions. PRs and Issues are always welcome.
|
||||
|
||||
## 🌟 Contributors
|
||||
|
||||
|
||||
@@ -171,6 +171,12 @@ class ChatService:
|
||||
|
||||
from agent.protocol.agent_stream import AgentStreamExecutor
|
||||
|
||||
# Register a cancel token so /cancel can abort this in-flight run.
|
||||
# IM channels key on session_id (no per-turn request_id here).
|
||||
from agent.protocol import get_cancel_registry
|
||||
registry = get_cancel_registry()
|
||||
cancel_event = registry.register(session_id, session_id=session_id) if session_id else None
|
||||
|
||||
executor = AgentStreamExecutor(
|
||||
agent=agent,
|
||||
model=agent.model,
|
||||
@@ -180,6 +186,7 @@ class ChatService:
|
||||
on_event=on_event,
|
||||
messages=messages_copy,
|
||||
max_context_turns=max_context_turns,
|
||||
cancel_event=cancel_event,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -191,6 +198,13 @@ class ChatService:
|
||||
agent.messages.clear()
|
||||
logger.info("[ChatService] Cleared agent message history after executor recovery")
|
||||
raise
|
||||
finally:
|
||||
# Release cancel token to keep the registry bounded.
|
||||
if session_id:
|
||||
try:
|
||||
registry.unregister(session_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Sync executor messages back to agent (thread-safe).
|
||||
# The executor may have trimmed context, making its list shorter than
|
||||
|
||||
19
agent/evolution/__init__.py
Normal file
19
agent/evolution/__init__.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
Self-evolution subsystem for CowAgent.
|
||||
|
||||
Runs a lightweight, isolated review pass after a conversation goes idle to
|
||||
decide whether anything is worth durably learning (memory / skill) or whether
|
||||
an unfinished task can be pushed forward. Conservative by design: most
|
||||
conversations should produce no change at all.
|
||||
|
||||
Public entry points:
|
||||
from agent.evolution import get_evolution_config
|
||||
from agent.evolution.trigger import start_evolution_trigger, note_user_turn
|
||||
"""
|
||||
|
||||
from agent.evolution.config import EvolutionConfig, get_evolution_config
|
||||
|
||||
__all__ = [
|
||||
"EvolutionConfig",
|
||||
"get_evolution_config",
|
||||
]
|
||||
102
agent/evolution/backup.py
Normal file
102
agent/evolution/backup.py
Normal file
@@ -0,0 +1,102 @@
|
||||
"""File backup / rollback support for self-evolution.
|
||||
|
||||
Before the evolution agent edits MEMORY.md or a skill file, we snapshot the
|
||||
current state into ``memory/.evolution_backups/<backup_id>/`` so a later "undo"
|
||||
can restore it. File-level restore only — simple and reliable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from common.log import logger
|
||||
|
||||
_BACKUP_DIRNAME = ".evolution_backups"
|
||||
_MANIFEST_NAME = "manifest.json"
|
||||
# Keep only the most recent N backups to bound disk usage.
|
||||
_MAX_BACKUPS = 10
|
||||
|
||||
|
||||
def _backups_root(workspace_dir: Path) -> Path:
|
||||
return Path(workspace_dir) / "memory" / _BACKUP_DIRNAME
|
||||
|
||||
|
||||
def create_backup(workspace_dir: Path, files: List[Path]) -> Optional[str]:
|
||||
"""Snapshot ``files`` (those that exist) under a new backup id.
|
||||
|
||||
Returns the backup_id, or None when there is nothing to back up.
|
||||
"""
|
||||
existing = [Path(f) for f in files if Path(f).exists()]
|
||||
if not existing:
|
||||
return None
|
||||
|
||||
backup_id = datetime.now().strftime("%Y%m%d-%H%M%S-") + str(int(time.time() * 1000) % 1000)
|
||||
root = _backups_root(workspace_dir)
|
||||
target = root / backup_id
|
||||
try:
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
ws = Path(workspace_dir)
|
||||
manifest = []
|
||||
for idx, src in enumerate(existing):
|
||||
# Store under a flat index plus the relative path so restore knows
|
||||
# where it came from, even for nested skill files.
|
||||
try:
|
||||
rel = str(src.relative_to(ws))
|
||||
except ValueError:
|
||||
rel = src.name
|
||||
dst = target / f"{idx}.bak"
|
||||
shutil.copy2(src, dst)
|
||||
manifest.append({"rel": rel, "bak": f"{idx}.bak"})
|
||||
(target / _MANIFEST_NAME).write_text(
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
_prune_old_backups(root)
|
||||
# Caller logs a combined backup+review line; keep this at debug.
|
||||
logger.debug(f"[Evolution] Created backup {backup_id} ({len(manifest)} file(s))")
|
||||
return backup_id
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Failed to create backup: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def restore_backup(workspace_dir: Path, backup_id: str) -> bool:
|
||||
"""Restore all files captured under ``backup_id``. Returns success."""
|
||||
if not backup_id:
|
||||
return False
|
||||
target = _backups_root(workspace_dir) / backup_id
|
||||
manifest_path = target / _MANIFEST_NAME
|
||||
if not manifest_path.exists():
|
||||
logger.warning(f"[Evolution] Backup not found: {backup_id}")
|
||||
return False
|
||||
try:
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
ws = Path(workspace_dir)
|
||||
for entry in manifest:
|
||||
bak = target / entry["bak"]
|
||||
dst = ws / entry["rel"]
|
||||
if bak.exists():
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(bak, dst)
|
||||
logger.info(f"[Evolution] Restored backup {backup_id} ({len(manifest)} file(s))")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Failed to restore backup {backup_id}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _prune_old_backups(root: Path) -> None:
|
||||
"""Drop the oldest backups beyond _MAX_BACKUPS (sorted by name = chronological)."""
|
||||
try:
|
||||
dirs = sorted(
|
||||
[d for d in root.iterdir() if d.is_dir()],
|
||||
key=lambda p: p.name,
|
||||
)
|
||||
for old in dirs[:-_MAX_BACKUPS]:
|
||||
shutil.rmtree(old, ignore_errors=True)
|
||||
except Exception as e:
|
||||
logger.debug(f"[Evolution] Backup prune skipped: {e}")
|
||||
76
agent/evolution/config.py
Normal file
76
agent/evolution/config.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""Configuration for the self-evolution subsystem.
|
||||
|
||||
Reads flat ``self_evolution_*`` keys from config.json. All fields have safe
|
||||
defaults so the feature degrades gracefully when keys are absent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
# Defaults — conservative (see executor module docstring). Disabled by default
|
||||
# until release; enable via ``self_evolution_enabled``.
|
||||
DEFAULT_ENABLED = False
|
||||
DEFAULT_IDLE_MINUTES = 15
|
||||
DEFAULT_MIN_TURNS = 8
|
||||
# Max review steps for the isolated evolution agent. Kept small (not exposed as
|
||||
# config): the review is meant to be cheap and focused, not a long autonomous run.
|
||||
DEFAULT_MAX_STEPS = 12
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvolutionConfig:
|
||||
"""Resolved self-evolution settings."""
|
||||
|
||||
enabled: bool = DEFAULT_ENABLED
|
||||
idle_minutes: int = DEFAULT_IDLE_MINUTES
|
||||
min_turns: int = DEFAULT_MIN_TURNS
|
||||
max_steps: int = DEFAULT_MAX_STEPS
|
||||
|
||||
@property
|
||||
def idle_seconds(self) -> int:
|
||||
return max(60, self.idle_minutes * 60)
|
||||
|
||||
|
||||
def _as_bool(value: Any, fallback: bool) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
v = value.strip().lower()
|
||||
if v in ("true", "1", "yes", "on"):
|
||||
return True
|
||||
if v in ("false", "0", "no", "off"):
|
||||
return False
|
||||
return fallback
|
||||
|
||||
|
||||
def _as_pos_int(value: Any, fallback: int) -> int:
|
||||
try:
|
||||
n = int(value)
|
||||
return n if n > 0 else fallback
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
|
||||
def get_evolution_config() -> EvolutionConfig:
|
||||
"""Build EvolutionConfig from the live config.json ``self_evolution_*`` keys."""
|
||||
try:
|
||||
from config import conf
|
||||
c = conf()
|
||||
except Exception:
|
||||
c = {}
|
||||
|
||||
def _get(key, default):
|
||||
try:
|
||||
return c.get(key, default)
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
return EvolutionConfig(
|
||||
enabled=_as_bool(_get("self_evolution_enabled", None), DEFAULT_ENABLED),
|
||||
idle_minutes=_as_pos_int(_get("self_evolution_idle_minutes", None), DEFAULT_IDLE_MINUTES),
|
||||
min_turns=_as_pos_int(_get("self_evolution_min_turns", None), DEFAULT_MIN_TURNS),
|
||||
max_steps=DEFAULT_MAX_STEPS,
|
||||
)
|
||||
546
agent/evolution/executor.py
Normal file
546
agent/evolution/executor.py
Normal file
@@ -0,0 +1,546 @@
|
||||
"""Self-evolution executor.
|
||||
|
||||
Runs an isolated review agent over an idle conversation's transcript and, if a
|
||||
clear signal is found, lets it edit memory / skills via a restricted toolset.
|
||||
Conservative by design: most runs return ``[SILENT]`` and change nothing.
|
||||
|
||||
Flow:
|
||||
1. Build a transcript from the session's new (since last pass) messages.
|
||||
2. Snapshot MEMORY.md + daily file + editable skills (for undo) -> backup_id.
|
||||
3. Run an isolated agent (same model, restricted tools, evolution prompt).
|
||||
4. If output is [SILENT], or no workspace file actually changed -> done.
|
||||
5. Otherwise -> record to the evolution log, inject an [EVOLUTION] note into
|
||||
the user session (so the main agent can honor "undo"), and push the
|
||||
summary to the user's channel.
|
||||
|
||||
Reuses existing infrastructure (AgentBridge.create_agent, ToolManager,
|
||||
remember_scheduled_output, channel_factory) rather than introducing a fork.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from common.log import logger
|
||||
|
||||
from agent.evolution.backup import create_backup
|
||||
from agent.evolution.config import get_evolution_config
|
||||
from agent.evolution.prompts import (
|
||||
EVOLUTION_MARKER,
|
||||
EVOLUTION_SYSTEM_PROMPT,
|
||||
SILENT_TOKEN,
|
||||
build_review_user_message,
|
||||
)
|
||||
from agent.evolution.record import append_session_evolution
|
||||
|
||||
# Tools the isolated evolution agent is allowed to use. Everything else is
|
||||
# withheld so a review pass can only read context, run workspace scripts, and
|
||||
# edit memory/skill files. bash is needed by skill-creator's init script and is
|
||||
# confined to the workspace by _BashWorkspaceGuard.
|
||||
_ALLOWED_TOOLS = {"read", "write", "edit", "ls", "bash", "memory_search", "memory_get"}
|
||||
|
||||
# Cap concurrent evolution passes so a burst of idle sessions can't spawn many
|
||||
# background model runs at once. Extra sessions simply wait for the next scan.
|
||||
_MAX_CONCURRENT = 2
|
||||
_running_lock = threading.Lock()
|
||||
_running_count = 0
|
||||
|
||||
|
||||
def _builtin_skill_names() -> set:
|
||||
"""Names of skills shipped with the product (project-root ``skills/``).
|
||||
|
||||
These are protected: the evolution agent must never edit them, even though
|
||||
a same-named copy exists in the workspace at runtime. The project dir is the
|
||||
authoritative list of what counts as built-in.
|
||||
"""
|
||||
try:
|
||||
# executor.py -> agent/evolution -> agent -> project root
|
||||
project_root = Path(__file__).resolve().parents[2]
|
||||
builtin_dir = project_root / "skills"
|
||||
if not builtin_dir.is_dir():
|
||||
return set()
|
||||
names = set()
|
||||
for entry in builtin_dir.iterdir():
|
||||
if entry.is_dir() and not entry.name.startswith("."):
|
||||
names.add(entry.name)
|
||||
return names
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
|
||||
def _build_transcript(messages: List[dict], max_chars: int = 12000) -> str:
|
||||
"""Render the session messages into a compact text transcript."""
|
||||
lines: List[str] = []
|
||||
for msg in messages:
|
||||
role = msg.get("role", "")
|
||||
if role not in ("user", "assistant"):
|
||||
continue
|
||||
content = msg.get("content", "")
|
||||
text = _extract_text(content)
|
||||
if not text.strip():
|
||||
continue
|
||||
speaker = "User" if role == "user" else "Assistant"
|
||||
lines.append(f"{speaker}: {text.strip()}")
|
||||
transcript = "\n".join(lines)
|
||||
# Keep the most RECENT context if oversized (tail is most relevant).
|
||||
if len(transcript) > max_chars:
|
||||
transcript = "...(earlier omitted)...\n" + transcript[-max_chars:]
|
||||
return transcript
|
||||
|
||||
|
||||
def _extract_text(content) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts = []
|
||||
for block in content:
|
||||
if isinstance(block, dict) and block.get("type") == "text":
|
||||
parts.append(block.get("text", ""))
|
||||
elif isinstance(block, str):
|
||||
parts.append(block)
|
||||
return "\n".join(parts)
|
||||
return ""
|
||||
|
||||
|
||||
def _select_tools(all_tools: list) -> list:
|
||||
return [t for t in all_tools if getattr(t, "name", None) in _ALLOWED_TOOLS]
|
||||
|
||||
|
||||
# Tools whose writes must be confined to the workspace during evolution.
|
||||
_WRITE_TOOLS = {"write", "edit"}
|
||||
|
||||
|
||||
class _WorkspaceWriteGuard:
|
||||
"""Wraps a write/edit tool so it can ONLY write inside the workspace.
|
||||
|
||||
Hard engineering guard (not prompt-based): any write resolving outside the
|
||||
workspace — e.g. the project's bundled ``skills/`` dir — is rejected. This
|
||||
protects built-in skills regardless of what the model attempts.
|
||||
"""
|
||||
|
||||
def __init__(self, inner, workspace_dir: str):
|
||||
self._inner = inner
|
||||
self._ws = Path(workspace_dir).resolve()
|
||||
# Mirror the attributes the agent runtime reads off a tool.
|
||||
self.name = inner.name
|
||||
self.description = inner.description
|
||||
self.params = inner.params
|
||||
|
||||
def __getattr__(self, item):
|
||||
return getattr(self._inner, item)
|
||||
|
||||
def execute_tool(self, params):
|
||||
# The agent runtime calls execute_tool (not execute); route it through
|
||||
# our guarded execute so the path checks always run.
|
||||
try:
|
||||
return self.execute(params)
|
||||
except Exception as e:
|
||||
logger.error(f"[Evolution] guarded tool error: {e}")
|
||||
from agent.tools.base_tool import ToolResult
|
||||
return ToolResult.fail(f"Error: {e}")
|
||||
|
||||
def execute(self, args):
|
||||
path = (args.get("path") or "").strip()
|
||||
if path:
|
||||
try:
|
||||
resolved = Path(self._inner._resolve_path(path)).resolve()
|
||||
from agent.tools.base_tool import ToolResult
|
||||
# Confine writes to the workspace. This protects the product's
|
||||
# bundled skills (which live outside the workspace) from ever
|
||||
# being modified, no matter what path the model attempts.
|
||||
if self._ws not in resolved.parents and resolved != self._ws:
|
||||
return ToolResult.fail(
|
||||
"Error: evolution may only write inside the workspace; "
|
||||
f"path '{path}' is outside and was blocked."
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return self._inner.execute(args)
|
||||
|
||||
|
||||
class _BashWorkspaceGuard:
|
||||
"""Wraps the bash tool so evolution can only run commands inside the
|
||||
workspace.
|
||||
|
||||
Evolution needs bash for skill-creator's init script, but it runs
|
||||
unattended in the background, so a raw shell is too broad. This guard:
|
||||
- forces the command to execute with cwd = workspace,
|
||||
- rejects commands that reference an absolute path or ``..`` segment
|
||||
pointing OUTSIDE the workspace (the common ways to escape it).
|
||||
It is a coarse textual check, not a sandbox — paired with the model's
|
||||
instruction to only run skill-creator scripts, it keeps writes local.
|
||||
"""
|
||||
|
||||
def __init__(self, inner, workspace_dir: str):
|
||||
self._inner = inner
|
||||
self._ws = Path(workspace_dir).resolve()
|
||||
# Pin the shell's working directory to the workspace.
|
||||
try:
|
||||
self._inner.cwd = str(self._ws)
|
||||
except Exception:
|
||||
pass
|
||||
self.name = inner.name
|
||||
self.description = inner.description
|
||||
self.params = inner.params
|
||||
|
||||
def __getattr__(self, item):
|
||||
return getattr(self._inner, item)
|
||||
|
||||
def execute_tool(self, params):
|
||||
try:
|
||||
return self.execute(params)
|
||||
except Exception as e:
|
||||
logger.error(f"[Evolution] guarded bash error: {e}")
|
||||
from agent.tools.base_tool import ToolResult
|
||||
return ToolResult.fail(f"Error: {e}")
|
||||
|
||||
def _escapes_workspace(self, command: str) -> bool:
|
||||
# Absolute paths that are not under the workspace.
|
||||
for tok in re.findall(r'(?:^|\s)(/[^\s\'";|&]+)', command):
|
||||
try:
|
||||
resolved = Path(tok).resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if self._ws != resolved and self._ws not in resolved.parents:
|
||||
return True
|
||||
# Parent-dir traversal that climbs above the workspace.
|
||||
for tok in re.findall(r'[^\s\'";|&]*\.\.[^\s\'";|&]*', command):
|
||||
try:
|
||||
resolved = (self._ws / tok).resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if self._ws != resolved and self._ws not in resolved.parents:
|
||||
return True
|
||||
return False
|
||||
|
||||
def execute(self, args):
|
||||
from agent.tools.base_tool import ToolResult
|
||||
command = (args.get("command") or "").strip()
|
||||
if command and self._escapes_workspace(command):
|
||||
return ToolResult.fail(
|
||||
"Error: evolution may only run commands inside the workspace; "
|
||||
"this command references a path outside it and was blocked."
|
||||
)
|
||||
return self._inner.execute(args)
|
||||
|
||||
|
||||
def _guard_tools(tools: list, workspace_dir: str) -> list:
|
||||
"""Wrap write/edit/bash tools with workspace guards; leave others as-is."""
|
||||
guarded = []
|
||||
for t in tools:
|
||||
name = getattr(t, "name", None)
|
||||
if name in _WRITE_TOOLS:
|
||||
guarded.append(_WorkspaceWriteGuard(t, workspace_dir))
|
||||
elif name == "bash":
|
||||
guarded.append(_BashWorkspaceGuard(t, workspace_dir))
|
||||
else:
|
||||
guarded.append(t)
|
||||
return guarded
|
||||
|
||||
|
||||
# Workspace subtrees worth watching for evolution-induced changes.
|
||||
_WATCH_SUBDIRS = ("MEMORY.md", "skills", "knowledge", "output")
|
||||
# Subpaths under memory/ to ignore: evolution's own bookkeeping + the nightly
|
||||
# dream diary, none of which count as a user-facing change signal.
|
||||
_MEMORY_IGNORE = (".evolution_backups", "dreams", "evolution")
|
||||
# Files the skill subsystem maintains automatically (the enable/disable index).
|
||||
# Not an evolution result, so a rewrite must not count as a change signal.
|
||||
_WATCH_IGNORE_NAMES = ("skills_config.json",)
|
||||
|
||||
|
||||
def _workspace_snapshot(workspace_dir) -> dict:
|
||||
"""Map relative path -> (mtime, size) for watched files. Cheap, no reads."""
|
||||
ws = Path(workspace_dir)
|
||||
snap: dict = {}
|
||||
for name in _WATCH_SUBDIRS:
|
||||
root = ws / name
|
||||
if root.is_file():
|
||||
try:
|
||||
st = root.stat()
|
||||
snap[name] = (st.st_mtime, st.st_size)
|
||||
except OSError:
|
||||
pass
|
||||
continue
|
||||
if not root.is_dir():
|
||||
continue
|
||||
for p in root.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
if p.name in _WATCH_IGNORE_NAMES:
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
snap[str(p.relative_to(ws))] = (st.st_mtime, st.st_size)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Watch the daily memory files (memory/*.md and per-user dailies) since
|
||||
# evolution now records learnings there. Skip backups/dreams bookkeeping.
|
||||
mem_dir = ws / "memory"
|
||||
if mem_dir.is_dir():
|
||||
for p in mem_dir.rglob("*.md"):
|
||||
rel_parts = p.relative_to(mem_dir).parts
|
||||
if rel_parts and rel_parts[0] in _MEMORY_IGNORE:
|
||||
continue
|
||||
try:
|
||||
st = p.stat()
|
||||
snap[str(p.relative_to(ws))] = (st.st_mtime, st.st_size)
|
||||
except OSError:
|
||||
pass
|
||||
return snap
|
||||
|
||||
|
||||
def _workspace_changed(workspace_dir, pre: dict) -> bool:
|
||||
"""True if any watched file was added, removed, or modified since ``pre``."""
|
||||
return _workspace_snapshot(workspace_dir) != pre
|
||||
|
||||
|
||||
def run_evolution_for_session(
|
||||
agent_bridge,
|
||||
session_id: str,
|
||||
channel_type: str = "",
|
||||
receiver: str = "",
|
||||
user_id: Optional[str] = None,
|
||||
idle_minutes: float = 0.0,
|
||||
) -> bool:
|
||||
"""Run one evolution pass for a session. Returns True if it changed anything.
|
||||
|
||||
Safe to call from a background thread. All failures are swallowed and
|
||||
logged — evolution must never disrupt the main pipeline.
|
||||
"""
|
||||
cfg = get_evolution_config()
|
||||
if not cfg.enabled:
|
||||
return False
|
||||
|
||||
# Concurrency gate: bound how many evolution passes run at once.
|
||||
global _running_count
|
||||
with _running_lock:
|
||||
if _running_count >= _MAX_CONCURRENT:
|
||||
logger.info(
|
||||
f"[Evolution] busy ({_running_count}/{_MAX_CONCURRENT} running); "
|
||||
f"skipping session={session_id} this scan"
|
||||
)
|
||||
return False
|
||||
_running_count += 1
|
||||
|
||||
try:
|
||||
agent = agent_bridge.agents.get(session_id) or agent_bridge.default_agent
|
||||
if not agent:
|
||||
return False
|
||||
|
||||
with agent.messages_lock:
|
||||
all_messages = list(agent.messages)
|
||||
total_msgs = len(all_messages)
|
||||
# In-memory evolution cursor: only review messages added since the last
|
||||
# pass so a long session doesn't re-judge (and re-write) old content.
|
||||
# Stored on the agent instance; lost on restart (acceptable — at worst
|
||||
# one redundant pass right after a restart, gated by the file-change
|
||||
# check downstream so it won't double-write identical memory).
|
||||
done = int(getattr(agent, "_evo_done_msg_count", 0))
|
||||
if done > total_msgs:
|
||||
done = 0 # history was trimmed/reset; start fresh
|
||||
new_messages = all_messages[done:]
|
||||
transcript = _build_transcript(new_messages)
|
||||
if not transcript.strip():
|
||||
# Routine no-op: the per-minute scan hits every idle session. Advance
|
||||
# the cursor so we don't re-scan the same tail; no log (pure noise).
|
||||
agent._evo_done_msg_count = total_msgs
|
||||
return False
|
||||
|
||||
logger.info(
|
||||
f"[Evolution] ▶ Reviewing session={session_id} "
|
||||
f"(idle {idle_minutes:.1f}min, {len(new_messages)} new/{total_msgs} msgs, "
|
||||
f"~{len(transcript)} chars)"
|
||||
)
|
||||
|
||||
# Resolve workspace + files to snapshot for undo.
|
||||
from agent.memory.config import get_default_memory_config
|
||||
mem_cfg = get_default_memory_config()
|
||||
workspace_dir = mem_cfg.get_workspace()
|
||||
if user_id:
|
||||
memory_file = Path(workspace_dir) / "memory" / "users" / user_id / "MEMORY.md"
|
||||
else:
|
||||
memory_file = Path(workspace_dir) / "MEMORY.md"
|
||||
skills_dir = mem_cfg.get_skills_dir()
|
||||
|
||||
# Snapshot MEMORY.md + every NON-protected skill's SKILL.md. Protected
|
||||
# built-in skills are excluded from backup because they must never be
|
||||
# edited in the first place.
|
||||
protected_names = _builtin_skill_names()
|
||||
# Back up both MEMORY.md and today's daily file: evolution now writes to
|
||||
# the daily file, but MEMORY.md is cheap to snapshot and keeps undo safe
|
||||
# if the model ever edits it.
|
||||
today_daily = Path(workspace_dir) / "memory" / (
|
||||
datetime.now().strftime("%Y-%m-%d") + ".md"
|
||||
)
|
||||
if user_id:
|
||||
today_daily = Path(workspace_dir) / "memory" / "users" / user_id / (
|
||||
datetime.now().strftime("%Y-%m-%d") + ".md"
|
||||
)
|
||||
backup_files = [Path(memory_file), today_daily]
|
||||
if skills_dir.exists():
|
||||
for skill_md in skills_dir.rglob("SKILL.md"):
|
||||
# The skill dir is the SKILL.md's parent (or an ancestor for
|
||||
# collections); guard by checking the immediate top-level dir.
|
||||
try:
|
||||
top = skill_md.relative_to(skills_dir).parts[0]
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
if top in protected_names:
|
||||
continue
|
||||
backup_files.append(skill_md)
|
||||
backup_id = create_backup(workspace_dir, backup_files)
|
||||
_backup_n = sum(1 for f in backup_files if Path(f).exists())
|
||||
|
||||
# Snapshot the whole workspace (path -> mtime/size) so we can reliably
|
||||
# detect ANY file change — including new output files written when
|
||||
# finishing an unfinished task, which are not in backup_files.
|
||||
pre_snapshot = _workspace_snapshot(workspace_dir)
|
||||
|
||||
# Build the isolated review agent: same model, restricted tools, with a
|
||||
# hard guard that confines all writes to the workspace (protects the
|
||||
# project's bundled skills from ever being modified).
|
||||
review_tools = _guard_tools(
|
||||
_select_tools(list(getattr(agent, "tools", []) or [])),
|
||||
str(workspace_dir),
|
||||
)
|
||||
review_agent = agent_bridge.create_agent(
|
||||
system_prompt="",
|
||||
tools=review_tools,
|
||||
description="Self-evolution review agent",
|
||||
max_steps=cfg.max_steps,
|
||||
workspace_dir=str(workspace_dir),
|
||||
skill_manager=getattr(agent, "skill_manager", None),
|
||||
memory_manager=getattr(agent, "memory_manager", None),
|
||||
enable_skills=True,
|
||||
runtime_info=getattr(agent, "runtime_info", None),
|
||||
)
|
||||
# Reuse the live model so it follows the user's configured model.
|
||||
review_agent.model = agent.model
|
||||
# Inject the evolution task brief AFTER the full system prompt: the agent
|
||||
# gets the full context (tools, workspace, user preferences, memory, time)
|
||||
# AND its evolution-specific instructions on top, instead of one
|
||||
# overwriting the other.
|
||||
review_agent.extra_system_suffix = EVOLUTION_SYSTEM_PROMPT
|
||||
|
||||
logger.info(
|
||||
f"[Evolution] backup {backup_id} ({_backup_n} files) → running review agent"
|
||||
)
|
||||
user_msg = build_review_user_message(transcript, protected_skills=list(protected_names))
|
||||
result = review_agent.run_stream(user_msg, clear_history=True)
|
||||
result = (result or "").strip()
|
||||
|
||||
# These messages are now reviewed; advance the cursor so the next pass
|
||||
# only looks at messages added after this point (silent or not).
|
||||
agent._evo_done_msg_count = total_msgs
|
||||
|
||||
# Respect an explicit silent verdict: empty, exactly [SILENT], or text
|
||||
# that STARTS with [SILENT] means the model chose to stay quiet.
|
||||
if not result or result.startswith(SILENT_TOKEN):
|
||||
logger.info(f"[Evolution] ✗ No change for session={session_id} ([SILENT])")
|
||||
return False
|
||||
|
||||
# Anti-nag backstop: if the model wrote a summary but actually changed no
|
||||
# watched file, stay silent — never notify about work that didn't happen.
|
||||
if not _workspace_changed(workspace_dir, pre_snapshot):
|
||||
logger.info(
|
||||
f"[Evolution] ✗ session={session_id}: text produced but no file "
|
||||
f"changed — staying silent"
|
||||
)
|
||||
return False
|
||||
|
||||
# The model produced a real summary. Strip any stray [SILENT] tokens it
|
||||
# left mid-text, then notify.
|
||||
result = result.replace(SILENT_TOKEN, "").strip()
|
||||
if not result:
|
||||
logger.info(f"[Evolution] ✗ No change for session={session_id} ([SILENT])")
|
||||
return False
|
||||
|
||||
logger.info(f"[Evolution] ✓ session={session_id} evolved:\n{result}")
|
||||
append_session_evolution(workspace_dir, result, backup_id=backup_id, user_id=user_id)
|
||||
# Inject an [EVOLUTION] note so the main agent can honor "undo".
|
||||
_inject_evolution_record(agent_bridge, session_id, channel_type, result, backup_id)
|
||||
# The injection appended its own messages ([SCHEDULED]/[EVOLUTION]).
|
||||
# Advance the cursor past them so the next scan does not treat
|
||||
# evolution's own bookkeeping as new user content and re-trigger.
|
||||
try:
|
||||
with agent.messages_lock:
|
||||
agent._evo_done_msg_count = len(agent.messages)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Push the summary to the user's channel. The "did a file actually
|
||||
# change" gate above is the only throttle we need: real evolutions are
|
||||
# rare, so no extra opt-in switch or daily-count limit is required.
|
||||
if channel_type and receiver:
|
||||
_notify_user(channel_type, receiver, result)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Run failed for session={session_id}: {e}")
|
||||
return False
|
||||
finally:
|
||||
with _running_lock:
|
||||
_running_count -= 1
|
||||
|
||||
|
||||
def _inject_evolution_record(
|
||||
agent_bridge, session_id: str, channel_type: str, summary: str, backup_id: Optional[str]
|
||||
) -> None:
|
||||
"""Add an [EVOLUTION] note to the user session so the main agent can undo."""
|
||||
try:
|
||||
note = f"{EVOLUTION_MARKER} {summary}"
|
||||
if backup_id:
|
||||
note += f"\n(backup_id: {backup_id}; to undo, restore this backup)"
|
||||
# Reuse the scheduler-output injection path: isolated execution, only a
|
||||
# compact record lands in the user session.
|
||||
agent_bridge.remember_scheduled_output(
|
||||
session_id=session_id,
|
||||
content=note,
|
||||
channel_type=channel_type,
|
||||
task_description="self-evolution",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug(f"[Evolution] Failed to inject evolution record: {e}")
|
||||
|
||||
|
||||
def _notify_user(channel_type: str, receiver: str, summary: str) -> None:
|
||||
"""Push the evolution summary to the user's channel as a new message."""
|
||||
try:
|
||||
from bridge.context import Context, ContextType
|
||||
from bridge.reply import Reply, ReplyType
|
||||
from channel.channel_factory import create_channel
|
||||
|
||||
context = Context(ContextType.TEXT, summary)
|
||||
context["receiver"] = receiver
|
||||
context["isgroup"] = False
|
||||
context["session_id"] = receiver
|
||||
# Channels that reply to an original message need msg=None for a fresh push.
|
||||
if channel_type in ("feishu", "dingtalk", "wecom_bot", "qq"):
|
||||
context["msg"] = None
|
||||
if channel_type == "feishu":
|
||||
context["receive_id_type"] = "open_id"
|
||||
|
||||
channel = create_channel(channel_type)
|
||||
if not channel:
|
||||
return
|
||||
|
||||
# Web is request-response: a background push needs a synthetic request_id
|
||||
# plus a request->session mapping so the channel can route the message to
|
||||
# the user's polling queue (same approach the scheduler uses).
|
||||
if channel_type == "web":
|
||||
import uuid
|
||||
request_id = f"evolution_{uuid.uuid4().hex[:8]}"
|
||||
context["request_id"] = request_id
|
||||
if hasattr(channel, "request_to_session"):
|
||||
channel.request_to_session[request_id] = receiver
|
||||
|
||||
channel.send(Reply(ReplyType.TEXT, summary), context)
|
||||
logger.info(f"[Evolution] Notified user via {channel_type}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Failed to notify user: {e}")
|
||||
167
agent/evolution/prompts.py
Normal file
167
agent/evolution/prompts.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""Prompts for the self-evolution review agent.
|
||||
|
||||
The system prompt is intentionally English-only: it governs the agent's
|
||||
internal reasoning and is more stable / cheaper to maintain in one language.
|
||||
The user-facing summary the agent produces should follow the user's own
|
||||
language (instructed at the end of the prompt).
|
||||
|
||||
Design goals (see ref/hermes-agent background_review for inspiration):
|
||||
- Default to doing NOTHING. Evolution is the exception, not the rule.
|
||||
- Signal types: skill, unfinished task, memory, knowledge.
|
||||
- An explicit "do NOT capture" list to avoid self-poisoning over time.
|
||||
- Generic examples only — never bake in domain-specific business terms.
|
||||
"""
|
||||
|
||||
# Sentinel the agent emits when there is nothing worth evolving.
|
||||
SILENT_TOKEN = "[SILENT]"
|
||||
|
||||
# Marker prefix for the evolution record injected into the user session, so the
|
||||
# main chat agent can recognize past evolutions and honor an "undo" request.
|
||||
EVOLUTION_MARKER = "[EVOLUTION]"
|
||||
|
||||
|
||||
EVOLUTION_SYSTEM_PROMPT = """You are a self-evolution review agent for an AI assistant.
|
||||
|
||||
You are given a transcript of a conversation that just went idle. Your job is to
|
||||
decide whether anything from it is worth durably learning so future
|
||||
conversations go better — and if so, to make that change.
|
||||
|
||||
# Top principle: default to doing NOTHING
|
||||
|
||||
Most ordinary conversations need no evolution. Only act when there is a CLEAR
|
||||
signal below. If there is none, reply with exactly `[SILENT]` and stop. Staying
|
||||
silent is the normal, correct outcome — not a failure.
|
||||
|
||||
Greetings, small talk, acknowledgements ("ok", "thanks", "got it"), and casual
|
||||
chat are NOT signals. For these, output exactly `[SILENT]` immediately — do not
|
||||
explore files, do not write a summary, do not be polite. Just `[SILENT]`.
|
||||
|
||||
IMPORTANT: A summary is only allowed if you ACTUALLY made a file change via a
|
||||
tool (write/edit) in this pass. If you did not change any file, you MUST output
|
||||
exactly `[SILENT]` — never describe a change you only intended to make.
|
||||
|
||||
# Signals worth acting on (act only if at least one clearly appears)
|
||||
|
||||
SKILL and UNFINISHED TASK are your PRIMARY value — no other mechanism handles
|
||||
them. When their signal is clear, act; do not be shy here.
|
||||
|
||||
1. SKILL — two cases:
|
||||
a) PATCH an existing skill: a skill used here showed a STRUCTURAL problem (a
|
||||
missing step/section, a wrong or outdated detail, an error in its
|
||||
content), or its OUTPUT repeatedly misses something the user flagged. Read
|
||||
the relevant skill file under the skills directory and make a small
|
||||
incremental edit so it never recurs.
|
||||
b) CREATE a new skill: a clearly reusable, repeatable workflow emerged that
|
||||
no existing skill covers and the user is likely to want again. Follow the
|
||||
`skill-creator` skill's conventions (read its SKILL.md for the required
|
||||
structure), then create `skills/<name>/SKILL.md` by WRITING the file
|
||||
directly with the write tool — this is the simplest reliable path. (bash
|
||||
is available and confined to the workspace if a helper script is truly
|
||||
needed, but a direct write is preferred.) Only create when the workflow is
|
||||
genuinely reusable — not for a one-off task.
|
||||
|
||||
CRITICAL — fix the SOURCE, do not just remember the symptom: when the root
|
||||
cause of a problem lives IN a skill file itself (its instructions, content,
|
||||
or configuration are wrong/outdated), the correct action is to EDIT that
|
||||
skill so the problem cannot recur. Recording the corrected fact in memory
|
||||
does NOT prevent recurrence — only fixing the skill does. Never log "skill X
|
||||
has wrong detail Y" as a memory note in place of editing skill X.
|
||||
|
||||
2. UNFINISHED TASK — a specific deliverable you promised but didn't produce,
|
||||
AND you already have everything needed to finish it. DO IT now with the
|
||||
available tools and produce the result (e.g. write the file you said you'd
|
||||
write). If key info is missing, or the task is merely waiting on the user's
|
||||
reply/decision, do NOTHING and stay [SILENT] — do not nag or ping the user.
|
||||
You only ever notify the user as a side effect of having actually done work.
|
||||
|
||||
3. MEMORY — RARE, last resort. Default to writing NOTHING here. The main
|
||||
assistant already writes memory during the chat, and a nightly pass plus
|
||||
context-overflow saves are dedicated safety nets — so memory is almost always
|
||||
already covered without you. Skip unless the main assistant clearly missed a
|
||||
durable fact that belongs in no skill AND would visibly change future replies.
|
||||
- MEMORY.md is the curated long-term index, auto-loaded into EVERY future
|
||||
conversation. Treat it as precious: edit it in place to CORRECT a wrong
|
||||
fact, or append a new durable preference/decision/lesson — but do so
|
||||
SPARINGLY (a lasting fact, not a passing detail; the nightly pass handles
|
||||
routine consolidation).
|
||||
- For a NEW fact that is important but not yet clearly lasting, append ONE
|
||||
short bullet to today's `memory/YYYY-MM-DD.md` instead. When unsure, the
|
||||
daily file is the safe place — but first ask whether this really belongs
|
||||
in a skill.
|
||||
- Keep it to ONE short bullet. Never write paragraphs, never re-summarize the
|
||||
conversation, never copy what the main assistant already recorded.
|
||||
- If it is already captured anywhere (check MEMORY.md AND the daily file
|
||||
first), do NOTHING.
|
||||
|
||||
4. KNOWLEDGE — only if the conversation produced durable, reusable reference
|
||||
knowledge on a topic (the kind worth looking up again) that the main
|
||||
assistant did NOT already save to `knowledge/`. Add or update the relevant
|
||||
file there. Like memory, this is the exception: skip routine Q&A, and if the
|
||||
topic is already covered in `knowledge/`, do NOTHING rather than duplicate.
|
||||
|
||||
# Do NOT capture (these poison future behavior)
|
||||
|
||||
- Environment failures: missing binaries, unset credentials, uninstalled
|
||||
packages, "command not found". The user can fix these; they are not durable
|
||||
rules.
|
||||
- Negative claims about tools or features ("tool X does not work"). These
|
||||
harden into refusals the agent cites against itself later.
|
||||
- One-off task narratives (e.g. summarizing today's content). Not a class of
|
||||
reusable work.
|
||||
- Transient errors that resolved on retry within the conversation.
|
||||
|
||||
# Execution constraints
|
||||
|
||||
- Before changing memory or a skill, READ the current content first and make a
|
||||
small INCREMENTAL edit. Never fabricate, never rewrite large sections.
|
||||
- AVOID DUPLICATES. Before writing memory, READ both MEMORY.md AND today's
|
||||
daily file `memory/YYYY-MM-DD.md`. If the fact/preference is already recorded
|
||||
in EITHER (even if worded differently), do NOT add it again. The main
|
||||
assistant likely already wrote it during the chat — only add what is
|
||||
genuinely new or a correction not yet reflected anywhere.
|
||||
- You may only edit files inside the workspace. Built-in skills shipped with
|
||||
the product live outside it and are write-protected; do not try to edit them.
|
||||
- Make at most the few edits the signals justify; do not go looking for work.
|
||||
|
||||
# Output
|
||||
|
||||
- Nothing worth evolving -> output exactly `[SILENT]` and nothing else.
|
||||
- Otherwise, after performing the edits, output a short user-facing summary in
|
||||
the SAME LANGUAGE the user speaks in the conversation. Write it for an ordinary user, in plain
|
||||
everyday words — NOT a developer report. No need to expose internal details
|
||||
(file names/paths, system mechanics, etc.). Tell the user, briefly:
|
||||
1) that you just did a self-learning pass,
|
||||
2) what you learned and what you changed in THIS pass ("remembered X" /
|
||||
"improved the <name> skill" / "finished <task>").
|
||||
Keep it to 1-3 lines. Generic shape (do not copy domain words):
|
||||
"I just did a self-learning pass.
|
||||
- Learned: <what you learned>
|
||||
- Changed: <remembered it / improved the <name> skill / finished <task>>
|
||||
Reply 'undo the last learning' if this is wrong."
|
||||
"""
|
||||
|
||||
|
||||
def build_review_user_message(transcript: str, protected_skills: list = None) -> str:
|
||||
"""Wrap the conversation transcript as the review agent's user message.
|
||||
|
||||
``protected_skills`` lists skill names that must never be edited (built-in
|
||||
skills shipped with the product). Surfaced so the agent avoids them.
|
||||
"""
|
||||
protected_note = ""
|
||||
if protected_skills:
|
||||
names = ", ".join(sorted(protected_skills))
|
||||
protected_note = (
|
||||
"\n\nPROTECTED skills (built-in — never edit these): "
|
||||
f"{names}\n"
|
||||
)
|
||||
return (
|
||||
"Here is the conversation transcript that just went idle. Review it per "
|
||||
"your instructions. Acting is the exception: the main value is fixing or "
|
||||
"creating a skill and finishing promised work. Memory and knowledge are "
|
||||
"rare last resorts — stay [SILENT] unless there is a clear, durable signal "
|
||||
"not already covered."
|
||||
f"{protected_note}\n"
|
||||
"<transcript>\n"
|
||||
f"{transcript}\n"
|
||||
"</transcript>"
|
||||
)
|
||||
55
agent/evolution/record.py
Normal file
55
agent/evolution/record.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Self-evolution record log.
|
||||
|
||||
Session-level evolutions are appended to their OWN per-day file under
|
||||
``memory/evolution/YYYY-MM-DD.md`` (separate from the nightly Deep Dream diary
|
||||
in ``memory/dreams/``). Each day's file accumulates one short section per
|
||||
evolution pass — tagged with a timestamp and a backup id for undo — so the
|
||||
memory UI can surface "what the agent learned/changed today" on one timeline
|
||||
without ever mixing into the dream diary or the main conversation memory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from common.log import logger
|
||||
|
||||
|
||||
def _evolution_dir(workspace_dir: Path, user_id: Optional[str] = None) -> Path:
|
||||
base = Path(workspace_dir) / "memory"
|
||||
if user_id:
|
||||
return base / "users" / user_id / "evolution"
|
||||
return base / "evolution"
|
||||
|
||||
|
||||
def append_session_evolution(
|
||||
workspace_dir: Path,
|
||||
summary: str,
|
||||
backup_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Append a session-evolution entry to today's evolution log."""
|
||||
if not summary or not summary.strip():
|
||||
return
|
||||
try:
|
||||
evo_dir = _evolution_dir(workspace_dir, user_id)
|
||||
evo_dir.mkdir(parents=True, exist_ok=True)
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
log_file = evo_dir / f"{today}.md"
|
||||
|
||||
ts = datetime.now().strftime("%H:%M")
|
||||
header = f"## {ts}"
|
||||
body = summary.strip()
|
||||
if backup_id:
|
||||
body += f"\n\n_backup_id: {backup_id}_"
|
||||
|
||||
# Create with a title if the file is new, otherwise append a section.
|
||||
if not log_file.exists():
|
||||
log_file.write_text(f"# Self-Evolution: {today}\n\n", encoding="utf-8")
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
f.write(f"\n{header}\n\n{body}\n")
|
||||
logger.info(f"[Evolution] Recorded session evolution to {log_file.name}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Failed to record session evolution: {e}")
|
||||
133
agent/evolution/trigger.py
Normal file
133
agent/evolution/trigger.py
Normal file
@@ -0,0 +1,133 @@
|
||||
"""Idle-based evolution trigger.
|
||||
|
||||
A single background thread periodically scans live agent sessions and runs an
|
||||
evolution pass for any session that is idle for >= idle_minutes AND has enough
|
||||
accumulated signal, where "enough signal" is EITHER:
|
||||
- >= min_turns user turns since the last evolution, OR
|
||||
- the live context has grown past _CONTEXT_RATIO of the agent's token budget
|
||||
(mirrors how OpenClacky / Claude Code consolidate under context pressure).
|
||||
|
||||
Turn counting is per user turn (not per message), measured from the last
|
||||
evolution (or session start). After a pass runs, the baseline resets so a long
|
||||
session can evolve multiple times without re-judging old content.
|
||||
|
||||
Per-session evolution state is stored on the agent instance via lightweight
|
||||
attributes set by AgentBridge.agent_reply (see _note_user_turn).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from common.log import logger
|
||||
|
||||
from agent.evolution.config import get_evolution_config
|
||||
from agent.evolution.executor import run_evolution_for_session
|
||||
|
||||
_SCAN_INTERVAL_SECONDS = 60
|
||||
|
||||
# Context-pressure trigger: evolve once the live context exceeds this fraction
|
||||
# of the agent's token budget, even if min_turns hasn't been reached. Kept as a
|
||||
# module constant (not user config) for now. Fallback budget matches
|
||||
# agent_initializer / config.py (agent_max_context_tokens default = 50000).
|
||||
_CONTEXT_RATIO = 0.8
|
||||
_FALLBACK_CONTEXT_BUDGET = 50000
|
||||
|
||||
|
||||
def _context_pressure_reached(agent) -> bool:
|
||||
"""True if the agent's live context exceeds _CONTEXT_RATIO of its budget.
|
||||
|
||||
Uses the agent's own (estimated) token accounting so behavior matches the
|
||||
existing context-trimming path. Best-effort: any error -> False.
|
||||
"""
|
||||
try:
|
||||
with agent.messages_lock:
|
||||
messages = list(agent.messages)
|
||||
if not messages:
|
||||
return False
|
||||
est = sum(agent._estimate_message_tokens(m) for m in messages)
|
||||
budget = getattr(agent, "max_context_tokens", None) or _FALLBACK_CONTEXT_BUDGET
|
||||
return est / budget > _CONTEXT_RATIO
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def note_user_turn(agent, channel_type: str = "", receiver: str = "") -> None:
|
||||
"""Record activity for a session's agent. Called once per real user turn.
|
||||
|
||||
Maintains, on the agent instance:
|
||||
_evo_last_active : epoch seconds of the last user turn
|
||||
_evo_turns : user turns since the last evolution
|
||||
_evo_channel_type : originating channel (for later notify)
|
||||
_evo_receiver : push target for notify
|
||||
"""
|
||||
try:
|
||||
agent._evo_last_active = time.time()
|
||||
agent._evo_turns = int(getattr(agent, "_evo_turns", 0)) + 1
|
||||
if channel_type:
|
||||
agent._evo_channel_type = channel_type
|
||||
if receiver:
|
||||
agent._evo_receiver = receiver
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def start_evolution_trigger(agent_bridge) -> None:
|
||||
"""Start the idle-scan thread once per process (idempotent)."""
|
||||
if getattr(agent_bridge, "_evolution_trigger_started", False):
|
||||
return
|
||||
agent_bridge._evolution_trigger_started = True
|
||||
|
||||
t = threading.Thread(
|
||||
target=_scan_loop, args=(agent_bridge,), daemon=True, name="evolution-trigger"
|
||||
)
|
||||
t.start()
|
||||
logger.info("[Evolution] Idle trigger started")
|
||||
|
||||
|
||||
def _scan_loop(agent_bridge) -> None:
|
||||
while True:
|
||||
try:
|
||||
time.sleep(_SCAN_INTERVAL_SECONDS)
|
||||
cfg = get_evolution_config()
|
||||
if not cfg.enabled:
|
||||
continue
|
||||
_scan_once(agent_bridge, cfg)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Scan loop error: {e}")
|
||||
time.sleep(_SCAN_INTERVAL_SECONDS)
|
||||
|
||||
|
||||
def _scan_once(agent_bridge, cfg) -> None:
|
||||
now = time.time()
|
||||
# Snapshot to avoid holding the dict while running long evolutions.
|
||||
sessions = list(getattr(agent_bridge, "agents", {}).items())
|
||||
for session_id, agent in sessions:
|
||||
try:
|
||||
last_active = getattr(agent, "_evo_last_active", 0)
|
||||
turns = int(getattr(agent, "_evo_turns", 0))
|
||||
# Enough signal = enough turns OR enough context pressure.
|
||||
enough_signal = turns >= cfg.min_turns or _context_pressure_reached(agent)
|
||||
if not enough_signal:
|
||||
continue
|
||||
idle = now - last_active if last_active > 0 else -1
|
||||
if last_active <= 0 or idle < cfg.idle_seconds:
|
||||
continue
|
||||
|
||||
channel_type = getattr(agent, "_evo_channel_type", "") or ""
|
||||
receiver = getattr(agent, "_evo_receiver", "") or ""
|
||||
|
||||
# Reset baseline BEFORE running so a long pass / new messages during
|
||||
# it don't double-trigger; turns accrue fresh from here.
|
||||
agent._evo_turns = 0
|
||||
|
||||
run_evolution_for_session(
|
||||
agent_bridge,
|
||||
session_id=session_id,
|
||||
channel_type=channel_type,
|
||||
receiver=receiver,
|
||||
idle_minutes=(now - last_active) / 60 if last_active > 0 else 0.0,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Evolution] Failed to evaluate session={session_id}: {e}")
|
||||
@@ -13,6 +13,7 @@ Storage path: ~/cow/sessions/conversations.db
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
@@ -109,6 +110,48 @@ def _extract_display_text(content: Any) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
# Internal markers written into the session for the agent's own bookkeeping
|
||||
# (scheduler injection / self-evolution undo). They must stay in the stored
|
||||
# content (the LLM reads them, e.g. to find a backup_id for undo) but should
|
||||
# never be shown verbatim to the user in the chat history UI.
|
||||
_SCHEDULED_DISPLAY_MARKERS = ("[SCHEDULED]", "Scheduled task")
|
||||
_EVOLUTION_DISPLAY_MARKER = "[EVOLUTION]"
|
||||
|
||||
|
||||
def _is_internal_user_marker(text: str) -> bool:
|
||||
"""True if a user-turn text is an internal injection marker (hide from UI)."""
|
||||
t = (text or "").lstrip()
|
||||
return any(t.startswith(m) for m in _SCHEDULED_DISPLAY_MARKERS)
|
||||
|
||||
|
||||
def _is_evolution_text(text: str) -> bool:
|
||||
"""True if assistant text is a self-evolution summary (before cleaning)."""
|
||||
return (text or "").lstrip().startswith(_EVOLUTION_DISPLAY_MARKER)
|
||||
|
||||
|
||||
def _clean_display_text(text: str) -> str:
|
||||
"""Strip internal markers from assistant text for user-facing display.
|
||||
|
||||
Removes a leading ``[EVOLUTION]`` tag and a trailing ``(backup_id: ...)``
|
||||
undo hint. The raw stored message is untouched, so undo + LLM context still
|
||||
work; only the rendered chat bubble is cleaned.
|
||||
"""
|
||||
if not text:
|
||||
return text
|
||||
cleaned = text
|
||||
stripped = cleaned.lstrip()
|
||||
if stripped.startswith(_EVOLUTION_DISPLAY_MARKER):
|
||||
cleaned = stripped[len(_EVOLUTION_DISPLAY_MARKER):].lstrip()
|
||||
# Drop a trailing backup_id undo hint line, e.g.
|
||||
# "(backup_id: 20260607-...; to undo, restore this backup)"
|
||||
cleaned = re.sub(
|
||||
r"\n*\(backup_id:[^\)]*\)\s*$",
|
||||
"",
|
||||
cleaned,
|
||||
).rstrip()
|
||||
return cleaned
|
||||
|
||||
|
||||
def _extract_tool_calls(content: Any) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Extract tool_use blocks from an assistant message content.
|
||||
@@ -210,7 +253,10 @@ def _group_into_display_turns(
|
||||
if user_row:
|
||||
content, created_at, _u_extras = user_row
|
||||
text = _extract_display_text(content)
|
||||
if text:
|
||||
# Hide internal injection markers (scheduler / self-evolution) so the
|
||||
# user never sees a synthetic "[SCHEDULED] self-evolution" bubble;
|
||||
# the assistant reply that follows is still rendered.
|
||||
if text and not _is_internal_user_marker(text):
|
||||
turns.append({"role": "user", "content": text, "created_at": created_at})
|
||||
|
||||
# Build an ordered list of steps preserving the original sequence:
|
||||
@@ -265,6 +311,18 @@ def _group_into_display_turns(
|
||||
step["result"] = tr.get("result", "")
|
||||
step["is_error"] = tr.get("is_error", False)
|
||||
|
||||
# Detect a self-evolution bubble BEFORE cleaning the marker away, so the
|
||||
# UI can flag it even though the visible text stays clean.
|
||||
is_evolution = _is_evolution_text(final_text)
|
||||
|
||||
# Clean internal markers from the user-facing assistant text. Applies to
|
||||
# both the final content and the mirrored content step so the rendered
|
||||
# bubble shows clean text while the stored message keeps the markers.
|
||||
final_text = _clean_display_text(final_text)
|
||||
for step in steps:
|
||||
if step.get("type") == "content":
|
||||
step["content"] = _clean_display_text(step.get("content", ""))
|
||||
|
||||
if steps or final_text:
|
||||
turn = {
|
||||
"role": "assistant",
|
||||
@@ -272,6 +330,8 @@ def _group_into_display_turns(
|
||||
"steps": steps,
|
||||
"created_at": final_ts or (user_row[1] if user_row else 0),
|
||||
}
|
||||
if is_evolution:
|
||||
turn["kind"] = "evolution"
|
||||
if merged_extras:
|
||||
turn["extras"] = merged_extras
|
||||
turns.append(turn)
|
||||
@@ -291,7 +351,7 @@ class ConversationStore:
|
||||
|
||||
def __init__(self, db_path: Path):
|
||||
self._db_path = db_path
|
||||
self._lock = threading.Lock()
|
||||
self._lock = threading.RLock() # Use RLock to allow reentrant locking
|
||||
self._init_db()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -509,6 +569,65 @@ class ConversationStore:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_latest_pair_seqs(self, session_id: str) -> Dict[str, Optional[int]]:
|
||||
"""Return the seq numbers of the latest visible user message and the
|
||||
latest assistant message in a session.
|
||||
|
||||
A "visible" user message is one whose content is real user text
|
||||
(not just a tool_result block), so tool-execution turns do not
|
||||
shadow the actual user query.
|
||||
|
||||
Returns:
|
||||
Dict with keys ``user_seq`` and ``bot_seq``; either may be None
|
||||
when no matching message exists.
|
||||
"""
|
||||
result: Dict[str, Optional[int]] = {"user_seq": None, "bot_seq": None}
|
||||
with self._lock:
|
||||
conn = self._connect()
|
||||
try:
|
||||
# Latest assistant message (cheap: single row by seq DESC).
|
||||
row = conn.execute(
|
||||
"SELECT seq FROM messages "
|
||||
"WHERE session_id = ? AND role = 'assistant' "
|
||||
"ORDER BY seq DESC LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
if row:
|
||||
result["bot_seq"] = int(row[0])
|
||||
|
||||
# Latest visible user message: scan recent user rows and
|
||||
# skip pure tool_result entries.
|
||||
rows = conn.execute(
|
||||
"SELECT seq, content FROM messages "
|
||||
"WHERE session_id = ? AND role = 'user' "
|
||||
"ORDER BY seq DESC LIMIT 20",
|
||||
(session_id,),
|
||||
).fetchall()
|
||||
for seq, content_raw in rows:
|
||||
try:
|
||||
content = json.loads(content_raw)
|
||||
except Exception:
|
||||
result["user_seq"] = int(seq)
|
||||
break
|
||||
if isinstance(content, list):
|
||||
has_text = any(
|
||||
isinstance(b, dict) and b.get("type") == "text"
|
||||
for b in content
|
||||
)
|
||||
has_tool_result = any(
|
||||
isinstance(b, dict) and b.get("type") == "tool_result"
|
||||
for b in content
|
||||
)
|
||||
if has_text and not has_tool_result:
|
||||
result["user_seq"] = int(seq)
|
||||
break
|
||||
else:
|
||||
result["user_seq"] = int(seq)
|
||||
break
|
||||
finally:
|
||||
conn.close()
|
||||
return result
|
||||
|
||||
def clear_session(self, session_id: str) -> None:
|
||||
"""Delete all messages and the session record for a given session_id."""
|
||||
with self._lock:
|
||||
@@ -524,6 +643,109 @@ class ConversationStore:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def delete_message_pair(self, session_id: str, user_seq: int, delete_user: bool = True, cascade: bool = False) -> int:
|
||||
"""Delete a user message and/or its corresponding assistant reply.
|
||||
|
||||
The assistant reply is identified as all messages between user_seq
|
||||
and the next visible user message (or end of session).
|
||||
|
||||
Args:
|
||||
session_id: Session identifier.
|
||||
user_seq: The seq number of the user message.
|
||||
delete_user: If True (default), delete the user message too.
|
||||
If False, only delete assistant reply (for regenerate scenarios).
|
||||
cascade: If True, also delete all subsequent turns after this one.
|
||||
Used by edit-message which removes this turn and everything after.
|
||||
|
||||
Returns:
|
||||
Number of message rows deleted.
|
||||
"""
|
||||
with self._lock:
|
||||
conn = self._connect()
|
||||
try:
|
||||
with conn:
|
||||
# Verify this is a user message
|
||||
row = conn.execute(
|
||||
"SELECT role FROM messages WHERE session_id = ? AND seq = ?",
|
||||
(session_id, user_seq),
|
||||
).fetchone()
|
||||
if not row or row[0] != "user":
|
||||
return 0
|
||||
|
||||
if cascade:
|
||||
# Delete from this message to end of session
|
||||
start_seq = user_seq if delete_user else user_seq + 1
|
||||
end_seq_row = conn.execute(
|
||||
"SELECT MAX(seq) FROM messages WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
end_seq = (end_seq_row[0] or user_seq) + 1
|
||||
else:
|
||||
# Find the next visible user message seq (exclude tool_result)
|
||||
# Use batched query to avoid loading too many rows at once
|
||||
next_user_seq = None
|
||||
batch_size = 100
|
||||
offset = 0
|
||||
while True:
|
||||
batch = conn.execute(
|
||||
"""
|
||||
SELECT seq, content FROM messages
|
||||
WHERE session_id = ? AND seq > ? AND role = 'user'
|
||||
ORDER BY seq ASC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
(session_id, user_seq, batch_size, offset),
|
||||
).fetchall()
|
||||
if not batch:
|
||||
break
|
||||
for seq, content in batch:
|
||||
try:
|
||||
content_obj = json.loads(content)
|
||||
except Exception:
|
||||
content_obj = content
|
||||
if _is_visible_user_message(content_obj):
|
||||
next_user_seq = seq
|
||||
break
|
||||
if next_user_seq is not None:
|
||||
break
|
||||
offset += batch_size
|
||||
|
||||
# Determine the end boundary for deletion
|
||||
if next_user_seq is not None:
|
||||
end_seq = next_user_seq
|
||||
else:
|
||||
end_seq_row = conn.execute(
|
||||
"SELECT MAX(seq) FROM messages WHERE session_id = ?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
end_seq = (end_seq_row[0] or user_seq) + 1
|
||||
|
||||
# Determine the start boundary for deletion
|
||||
start_seq = user_seq if delete_user else user_seq + 1
|
||||
|
||||
# Delete messages from start_seq to end_seq (exclusive)
|
||||
cur = conn.execute(
|
||||
"DELETE FROM messages WHERE session_id = ? AND seq >= ? AND seq < ?",
|
||||
(session_id, start_seq, end_seq),
|
||||
)
|
||||
deleted = cur.rowcount
|
||||
|
||||
# Update session msg_count
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET msg_count = (
|
||||
SELECT COUNT(*) FROM messages WHERE session_id = ?
|
||||
)
|
||||
WHERE session_id = ?
|
||||
""",
|
||||
(session_id, session_id),
|
||||
)
|
||||
|
||||
return deleted
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def prune_scheduled_messages(
|
||||
self,
|
||||
session_id: str,
|
||||
@@ -1053,3 +1275,4 @@ def get_conversation_store() -> ConversationStore:
|
||||
_store_instance = ConversationStore(db_path)
|
||||
logger.debug(f"[ConversationStore] Using shared DB at: {db_path}")
|
||||
return _store_instance
|
||||
|
||||
|
||||
@@ -34,13 +34,18 @@ class MemoryService:
|
||||
# ------------------------------------------------------------------
|
||||
def list_files(self, page: int = 1, page_size: int = 20, category: str = "memory") -> dict:
|
||||
"""
|
||||
List memory or dream files with metadata (without content).
|
||||
List memory, dream, or evolution files with metadata (without content).
|
||||
|
||||
Args:
|
||||
category: ``"memory"`` (default) — MEMORY.md + daily files;
|
||||
``"dream"`` — dream diary files from memory/dreams/
|
||||
``"dream"`` — dream diary files from memory/dreams/;
|
||||
``"evolution"`` — self-evolution logs from memory/evolution/
|
||||
merged with the nightly dream diaries, so
|
||||
one tab shows everything the agent learned.
|
||||
"""
|
||||
if category == "dream":
|
||||
if category == "evolution":
|
||||
files = self._list_evolution_files()
|
||||
elif category == "dream":
|
||||
files = self._list_dream_files()
|
||||
else:
|
||||
files = self._list_memory_files()
|
||||
@@ -93,6 +98,26 @@ class MemoryService:
|
||||
|
||||
return files
|
||||
|
||||
def _list_evolution_files(self) -> List[dict]:
|
||||
"""Self-evolution logs (memory/evolution/*.md) merged with the nightly
|
||||
dream diaries (memory/dreams/*.md), newest first.
|
||||
|
||||
Both are surfaced under the unified "Self-Evolution" tab. A file's
|
||||
``type`` records its origin so the reader can resolve the right dir.
|
||||
"""
|
||||
files: List[dict] = []
|
||||
for sub, ftype in (("evolution", "evolution"), ("dreams", "dream")):
|
||||
sub_dir = os.path.join(self.memory_dir, sub)
|
||||
if not os.path.isdir(sub_dir):
|
||||
continue
|
||||
for name in os.listdir(sub_dir):
|
||||
full = os.path.join(sub_dir, name)
|
||||
if os.path.isfile(full) and name.endswith(".md"):
|
||||
files.append(self._file_info(full, name, ftype))
|
||||
# Sort newest first by filename (date-named); ties favor evolution.
|
||||
files.sort(key=lambda f: (f["filename"], f["type"] != "evolution"), reverse=True)
|
||||
return files
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# content — read a single file
|
||||
# ------------------------------------------------------------------
|
||||
@@ -101,7 +126,7 @@ class MemoryService:
|
||||
Read the full content of a memory or dream file.
|
||||
|
||||
:param filename: File name, e.g. ``MEMORY.md``, ``2026-02-20.md``
|
||||
:param category: ``"memory"`` or ``"dream"``
|
||||
:param category: ``"memory"``, ``"dream"`` or ``"evolution"``
|
||||
:return: dict with ``filename`` and ``content``
|
||||
:raises FileNotFoundError: if the file does not exist
|
||||
"""
|
||||
@@ -125,7 +150,7 @@ class MemoryService:
|
||||
Dispatch a memory management action.
|
||||
|
||||
:param action: ``list`` or ``content``
|
||||
:param payload: action-specific payload (supports ``category``: ``"memory"`` | ``"dream"``)
|
||||
:param payload: action-specific payload (supports ``category``: ``"memory"`` | ``"dream"`` | ``"evolution"``)
|
||||
:return: protocol-compatible response dict
|
||||
"""
|
||||
payload = payload or {}
|
||||
@@ -166,6 +191,7 @@ class MemoryService:
|
||||
- ``MEMORY.md`` → ``{workspace_root}/MEMORY.md``
|
||||
- ``2026-02-20.md`` (memory) → ``{workspace_root}/memory/2026-02-20.md``
|
||||
- ``2026-02-20.md`` (dream) → ``{workspace_root}/memory/dreams/2026-02-20.md``
|
||||
- ``2026-02-20.md`` (evolution) → ``{workspace_root}/memory/evolution/2026-02-20.md``
|
||||
|
||||
Raises ValueError if the resolved path escapes the allowed directory.
|
||||
"""
|
||||
@@ -173,6 +199,8 @@ class MemoryService:
|
||||
base_dir = self.workspace_root
|
||||
elif category == "dream":
|
||||
base_dir = os.path.join(self.memory_dir, "dreams")
|
||||
elif category == "evolution":
|
||||
base_dir = os.path.join(self.memory_dir, "evolution")
|
||||
else:
|
||||
base_dir = self.memory_dir
|
||||
|
||||
|
||||
@@ -52,6 +52,11 @@ class Agent:
|
||||
self.workspace_dir = workspace_dir # Workspace directory
|
||||
self.enable_skills = enable_skills # Skills enabled flag
|
||||
self.runtime_info = runtime_info # Runtime info for dynamic time update
|
||||
# Optional extra instructions appended AFTER the rebuilt full system
|
||||
# prompt. Used by the self-evolution review agent to add its task brief
|
||||
# on top of the full context (tools, workspace, user preferences, time)
|
||||
# so it both follows the user's preferences and knows its evolution job.
|
||||
self.extra_system_suffix = None
|
||||
|
||||
# Initialize skill manager
|
||||
self.skill_manager = None
|
||||
@@ -120,15 +125,20 @@ class Agent:
|
||||
except Exception:
|
||||
lang = "zh"
|
||||
builder = PromptBuilder(workspace_dir=self.workspace_dir or "", language=lang)
|
||||
return builder.build(
|
||||
full = builder.build(
|
||||
tools=self.tools,
|
||||
context_files=context_files,
|
||||
skill_manager=self.skill_manager,
|
||||
memory_manager=self.memory_manager,
|
||||
runtime_info=self.runtime_info,
|
||||
)
|
||||
if self.extra_system_suffix:
|
||||
full = f"{full}\n\n{self.extra_system_suffix}"
|
||||
return full
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to rebuild system prompt, using cached version: {e}")
|
||||
if self.extra_system_suffix:
|
||||
return f"{self.system_prompt}\n\n{self.extra_system_suffix}"
|
||||
return self.system_prompt
|
||||
|
||||
def refresh_skills(self):
|
||||
|
||||
@@ -347,11 +347,14 @@ class AgentStreamExecutor:
|
||||
Returns:
|
||||
Final response text
|
||||
"""
|
||||
# Log user message with model info
|
||||
|
||||
# Log user message with model info. Truncate very long messages (e.g.
|
||||
# injected transcripts / large prompts) so logs stay readable.
|
||||
thinking_enabled = self._is_thinking_enabled()
|
||||
thinking_label = " | 💭 thinking" if thinking_enabled else ""
|
||||
logger.info(f"🤖 {self.model.model}{thinking_label} | 👤 {user_message}")
|
||||
_log_msg = user_message if len(user_message) <= 500 else (
|
||||
user_message[:500] + f" …(+{len(user_message) - 500} chars)"
|
||||
)
|
||||
logger.info(f"🤖 {self.model.model}{thinking_label} | 👤 {_log_msg}")
|
||||
|
||||
# Add user message (Claude format - use content blocks for consistency)
|
||||
self.messages.append({
|
||||
|
||||
@@ -14,6 +14,9 @@ from agent.tools.send.send import Send
|
||||
from agent.tools.memory.memory_search import MemorySearchTool
|
||||
from agent.tools.memory.memory_get import MemoryGetTool
|
||||
|
||||
# Import self-evolution tools
|
||||
from agent.tools.evolution_undo.evolution_undo import EvolutionUndoTool
|
||||
|
||||
# Import tools with optional dependencies
|
||||
def _import_optional_tools():
|
||||
"""Import tools that have optional dependencies"""
|
||||
@@ -135,6 +138,7 @@ __all__ = [
|
||||
'Send',
|
||||
'MemorySearchTool',
|
||||
'MemoryGetTool',
|
||||
'EvolutionUndoTool',
|
||||
'EnvConfig',
|
||||
'SchedulerTool',
|
||||
'WebSearch',
|
||||
|
||||
@@ -69,8 +69,8 @@ SAFETY:
|
||||
if not command:
|
||||
return ToolResult.fail("Error: command parameter is required")
|
||||
|
||||
# Security check: Prevent accessing sensitive config files
|
||||
if "~/.cow/.env" in command or "~/.cow" in command:
|
||||
# Security check: Prevent direct access to the credential file
|
||||
if re.search(r'\.cow[/\\]\.env', command):
|
||||
return ToolResult.fail(
|
||||
"Error: Access denied. API keys and credentials must be accessed through the env_config tool only."
|
||||
)
|
||||
|
||||
3
agent/tools/evolution_undo/__init__.py
Normal file
3
agent/tools/evolution_undo/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from agent.tools.evolution_undo.evolution_undo import EvolutionUndoTool
|
||||
|
||||
__all__ = ["EvolutionUndoTool"]
|
||||
58
agent/tools/evolution_undo/evolution_undo.py
Normal file
58
agent/tools/evolution_undo/evolution_undo.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Evolution undo tool.
|
||||
|
||||
Lets the main chat agent roll back a previous self-evolution when the user asks
|
||||
("undo the last learning"). The rollback itself is a deterministic FILE RESTORE
|
||||
from the snapshot taken before the evolution — the model only supplies the
|
||||
backup_id it reads from the [EVOLUTION] record in the conversation. No LLM-driven
|
||||
re-editing is involved, so a restore can never make things worse.
|
||||
"""
|
||||
|
||||
from agent.tools.base_tool import BaseTool, ToolResult
|
||||
|
||||
|
||||
class EvolutionUndoTool(BaseTool):
|
||||
"""Restore memory/skill files to the state before a self-evolution."""
|
||||
|
||||
name: str = "evolution_undo"
|
||||
description: str = (
|
||||
"Undo a previous self-evolution (self-learning) by restoring the "
|
||||
"memory/skill files to their state before that learning. Use this when "
|
||||
"the user asks to undo / revert / roll back the last self-learning. "
|
||||
"Find the backup_id in the most recent [EVOLUTION] record in the "
|
||||
"conversation and pass it here."
|
||||
)
|
||||
params: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"backup_id": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"The backup_id from the [EVOLUTION] record to restore "
|
||||
"(e.g. '20260607-155551-850')."
|
||||
),
|
||||
}
|
||||
},
|
||||
"required": ["backup_id"],
|
||||
}
|
||||
|
||||
def execute(self, args: dict):
|
||||
backup_id = (args.get("backup_id") or "").strip()
|
||||
if not backup_id:
|
||||
return ToolResult.fail("Error: backup_id is required")
|
||||
try:
|
||||
from agent.memory.config import get_default_memory_config
|
||||
from agent.evolution.backup import restore_backup
|
||||
|
||||
workspace_dir = get_default_memory_config().get_workspace()
|
||||
ok = restore_backup(workspace_dir, backup_id)
|
||||
if ok:
|
||||
return ToolResult.success(
|
||||
f"Restored memory/skills to the state before evolution "
|
||||
f"{backup_id}. The previous self-learning has been undone."
|
||||
)
|
||||
return ToolResult.fail(
|
||||
f"Could not find or restore backup {backup_id}. It may have "
|
||||
f"expired or already been rolled back."
|
||||
)
|
||||
except Exception as e:
|
||||
return ToolResult.fail(f"Error during undo: {e}")
|
||||
@@ -7,7 +7,7 @@ without any external MCP SDK dependency.
|
||||
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import queue
|
||||
import subprocess
|
||||
import threading
|
||||
import urllib.request
|
||||
@@ -34,6 +34,8 @@ class McpClient:
|
||||
self.config = config
|
||||
self.name: str = config.get("name", "unknown")
|
||||
raw_transport: str = config.get("type", "stdio")
|
||||
# Per-server timeout for tool calls (default 120s, suitable for data queries)
|
||||
self._timeout: int = int(config.get("timeout", 120))
|
||||
# Normalize streamable-http aliases to a single internal key
|
||||
self.transport: str = (
|
||||
"streamable-http"
|
||||
@@ -43,6 +45,7 @@ class McpClient:
|
||||
|
||||
# stdio state
|
||||
self._proc: Optional[subprocess.Popen] = None
|
||||
self._read_queue: queue.Queue = queue.Queue()
|
||||
|
||||
# SSE state
|
||||
self._sse_url: Optional[str] = None
|
||||
@@ -56,7 +59,13 @@ class McpClient:
|
||||
# Shared state
|
||||
self._next_id = 1
|
||||
self._id_lock = threading.Lock()
|
||||
# _call_lock serializes all requests on the single stdio pipe.
|
||||
# SSE and streamable-http use independent HTTP requests, so they
|
||||
# do not acquire this lock (see _send_request).
|
||||
self._call_lock = threading.Lock()
|
||||
# _http_lock protects _http_session_id initialization across
|
||||
# concurrent streamable-http requests.
|
||||
self._http_lock = threading.Lock()
|
||||
self._initialized = False
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -172,6 +181,9 @@ class McpClient:
|
||||
threading.Thread(
|
||||
target=self._drain_stderr, daemon=True, name=f"mcp-stderr-{self.name}"
|
||||
).start()
|
||||
threading.Thread(
|
||||
target=self._drain_stdout, daemon=True, name=f"mcp-stdout-{self.name}"
|
||||
).start()
|
||||
|
||||
return self._handshake()
|
||||
|
||||
@@ -179,14 +191,35 @@ class McpClient:
|
||||
for line in self._proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
logger.debug(f"[MCP:{self.name}] stderr: {line}")
|
||||
logger.warning(f"[MCP:{self.name}] stderr: {line}")
|
||||
|
||||
def _readline_with_timeout(self, timeout: int = 30) -> str:
|
||||
"""Read one line from stdio stdout with a hard timeout."""
|
||||
ready, _, _ = select.select([self._proc.stdout], [], [], timeout)
|
||||
if not ready:
|
||||
raise TimeoutError(f"[MCP:{self.name}] stdio read timed out after {timeout}s")
|
||||
return self._proc.stdout.readline()
|
||||
def _drain_stdout(self):
|
||||
"""Background thread: read lines from stdout and put them into the queue."""
|
||||
try:
|
||||
for line in self._proc.stdout:
|
||||
self._read_queue.put(line)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
self._read_queue.put("")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _readline_with_timeout(self, timeout: Optional[int] = None) -> str:
|
||||
"""Read one line from stdio stdout with a hard timeout (cross-platform).
|
||||
|
||||
Uses the per-server timeout from mcp.json config when no explicit
|
||||
timeout is provided.
|
||||
"""
|
||||
effective = timeout if timeout is not None else self._timeout
|
||||
try:
|
||||
line = self._read_queue.get(timeout=effective)
|
||||
except queue.Empty:
|
||||
raise TimeoutError(f"[MCP:{self.name}] stdio read timed out after {effective}s")
|
||||
if not line:
|
||||
raise IOError(f"[MCP:{self.name}] stdio process closed unexpectedly")
|
||||
return line
|
||||
|
||||
def _stdio_send(self, message: dict) -> dict:
|
||||
"""Send a JSON-RPC message over stdio and read the response."""
|
||||
@@ -194,6 +227,7 @@ class McpClient:
|
||||
self._proc.stdin.write(raw)
|
||||
self._proc.stdin.flush()
|
||||
|
||||
expected_id = message.get("id")
|
||||
while True:
|
||||
line = self._readline_with_timeout()
|
||||
if not line:
|
||||
@@ -208,6 +242,14 @@ class McpClient:
|
||||
if "id" not in data:
|
||||
logger.debug(f"[MCP:{self.name}] notification skipped: {data.get('method', '?')}")
|
||||
continue
|
||||
# Verify response id matches request id to avoid consuming a stale
|
||||
# response left over from a previously failed/timed-out request.
|
||||
if data.get("id") != expected_id:
|
||||
logger.warning(
|
||||
f"[MCP:{self.name}] Stale response id={data.get('id')} "
|
||||
f"(expected {expected_id}), skipping"
|
||||
)
|
||||
continue
|
||||
return data
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -302,8 +344,12 @@ class McpClient:
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/event-stream",
|
||||
}
|
||||
if self._http_session_id:
|
||||
headers["Mcp-Session-Id"] = self._http_session_id
|
||||
# Read session id under lock to avoid racing with the
|
||||
# initialization write below during concurrent requests.
|
||||
with self._http_lock:
|
||||
sid = self._http_session_id
|
||||
if sid:
|
||||
headers["Mcp-Session-Id"] = sid
|
||||
headers.update(self._http_headers)
|
||||
|
||||
req = urllib.request.Request(
|
||||
@@ -329,8 +375,13 @@ class McpClient:
|
||||
with resp:
|
||||
# Capture session id assigned by the server (if any)
|
||||
session_id = resp.headers.get("Mcp-Session-Id")
|
||||
# Double-checked lock: only the first response sets the
|
||||
# session id, preventing concurrent initializers from
|
||||
# overwriting each other.
|
||||
if session_id and not self._http_session_id:
|
||||
self._http_session_id = session_id
|
||||
with self._http_lock:
|
||||
if not self._http_session_id:
|
||||
self._http_session_id = session_id
|
||||
|
||||
status = resp.status if hasattr(resp, "status") else resp.getcode()
|
||||
|
||||
@@ -409,15 +460,18 @@ class McpClient:
|
||||
|
||||
message = self._build_request(method, params)
|
||||
|
||||
with self._call_lock:
|
||||
if self.transport == "stdio":
|
||||
# stdio transport uses a single pipe and must be serialized.
|
||||
# SSE and streamable-http use independent HTTP requests and
|
||||
# can safely run concurrently across sessions.
|
||||
if self.transport == "stdio":
|
||||
with self._call_lock:
|
||||
return self._stdio_send(message)
|
||||
elif self.transport == "sse":
|
||||
return self._sse_send(message)
|
||||
elif self.transport == "streamable-http":
|
||||
return self._streamable_http_send(message)
|
||||
else:
|
||||
raise ValueError(f"[MCP:{self.name}] Unsupported transport: {self.transport}")
|
||||
elif self.transport == "sse":
|
||||
return self._sse_send(message)
|
||||
elif self.transport == "streamable-http":
|
||||
return self._streamable_http_send(message)
|
||||
else:
|
||||
raise ValueError(f"[MCP:{self.name}] Unsupported transport: {self.transport}")
|
||||
|
||||
def _send_notification(self, method: str, params: dict):
|
||||
"""Fire-and-forget notification (no response expected)."""
|
||||
|
||||
@@ -51,7 +51,7 @@ _MAIN_MODEL_PROVIDER_NAME = "MainModel"
|
||||
_DISCOVERABLE_MODELS = [
|
||||
("moonshot_api_key", const.MOONSHOT, const.KIMI_K2_6, "Moonshot"),
|
||||
("ark_api_key", const.DOUBAO, const.DOUBAO_SEED_2_PRO, "Doubao"),
|
||||
("dashscope_api_key", const.QWEN_DASHSCOPE, const.QWEN36_PLUS, "DashScope"),
|
||||
("dashscope_api_key", const.QWEN_DASHSCOPE, const.QWEN37_PLUS, "DashScope"),
|
||||
("claude_api_key", const.CLAUDEAPI, const.CLAUDE_4_6_SONNET, "Claude"),
|
||||
("gemini_api_key", const.GEMINI, const.GEMINI_35_FLASH, "Gemini"),
|
||||
("qianfan_api_key", const.QIANFAN, const.ERNIE_45_TURBO_VL, "Qianfan"),
|
||||
@@ -161,7 +161,7 @@ class Vision(BaseTool):
|
||||
"Error: No model available for Vision.\n"
|
||||
"The main model does not support vision and no other API keys are configured.\n"
|
||||
"Options:\n"
|
||||
" 1. Switch to a multimodal model (e.g. ernie-4.5-turbo-vl, qwen3.6-plus, claude-sonnet-4-6, gemini-2.0-flash)\n"
|
||||
" 1. Switch to a multimodal model (e.g. ernie-4.5-turbo-vl, qwen3.7-plus, claude-sonnet-4-6, gemini-2.0-flash)\n"
|
||||
" 2. Configure OPENAI_API_KEY: env_config(action=\"set\", key=\"OPENAI_API_KEY\", value=\"your-key\")\n"
|
||||
" 3. Configure LINKAI_API_KEY: env_config(action=\"set\", key=\"LINKAI_API_KEY\", value=\"your-key\")"
|
||||
)
|
||||
|
||||
3
app.py
3
app.py
@@ -236,6 +236,9 @@ def _clear_singleton_cache(channel_name: str):
|
||||
const.DINGTALK: "channel.dingtalk.dingtalk_channel.DingTalkChanel",
|
||||
const.WECOM_BOT: "channel.wecom_bot.wecom_bot_channel.WecomBotChannel",
|
||||
const.QQ: "channel.qq.qq_channel.QQChannel",
|
||||
const.TELEGRAM: "channel.telegram.telegram_channel.TelegramChannel",
|
||||
const.SLACK: "channel.slack.slack_channel.SlackChannel",
|
||||
const.DISCORD: "channel.discord.discord_channel.DiscordChannel",
|
||||
const.WEIXIN: "channel.weixin.weixin_channel.WeixinChannel",
|
||||
"wx": "channel.weixin.weixin_channel.WeixinChannel",
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ class AgentLLMModel(LLMModel):
|
||||
("moonshot", const.MOONSHOT), ("kimi", const.MOONSHOT),
|
||||
("doubao", const.DOUBAO), ("deepseek", const.DEEPSEEK),
|
||||
("ernie", const.QIANFAN),
|
||||
("mimo-", const.MIMO),
|
||||
]
|
||||
|
||||
def __init__(self, bridge: Bridge, bot_type: str = "chat"):
|
||||
@@ -294,6 +295,14 @@ class AgentBridge:
|
||||
self.scheduler_initialized = True
|
||||
except Exception as e:
|
||||
logger.warning(f"[AgentBridge] Eager scheduler init failed: {e}")
|
||||
|
||||
# Start the self-evolution idle trigger (idempotent, daemon thread).
|
||||
try:
|
||||
from agent.evolution.trigger import start_evolution_trigger
|
||||
start_evolution_trigger(self)
|
||||
except Exception as e:
|
||||
logger.warning(f"[AgentBridge] Evolution trigger init failed: {e}")
|
||||
|
||||
def create_agent(self, system_prompt: str, tools: List = None, **kwargs) -> Agent:
|
||||
"""
|
||||
Create the super agent with COW integration
|
||||
@@ -382,7 +391,49 @@ class AgentBridge:
|
||||
"""Initialize agent for a specific session"""
|
||||
agent = self.initializer.initialize_agent(session_id=session_id)
|
||||
self.agents[session_id] = agent
|
||||
|
||||
|
||||
def sync_session_messages_from_store(self, session_id: str) -> int:
|
||||
"""Reload an agent's in-memory ``messages`` list from the persistent
|
||||
conversation store.
|
||||
|
||||
Used after an external mutation (e.g. user edits / deletes a message
|
||||
via the web console) so the agent's next turn sees the same history
|
||||
as the database. The operation is a no-op when the agent has not been
|
||||
instantiated yet for the session.
|
||||
|
||||
Returns:
|
||||
Number of messages now held in the agent's memory. Returns -1 if
|
||||
the agent does not exist or has no compatible ``messages`` attr.
|
||||
"""
|
||||
if not session_id or session_id not in self.agents:
|
||||
return -1
|
||||
agent = self.agents[session_id]
|
||||
if not (hasattr(agent, "messages") and hasattr(agent, "messages_lock")):
|
||||
return -1
|
||||
try:
|
||||
from agent.memory import get_conversation_store
|
||||
store = get_conversation_store()
|
||||
# No turn cap here: we want a faithful mirror of what the store
|
||||
# has for this session after deletion.
|
||||
remaining = store.load_messages(session_id, max_turns=10**6)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[AgentBridge] Failed to load messages for sync (session={session_id}): {e}"
|
||||
)
|
||||
return -1
|
||||
with agent.messages_lock:
|
||||
agent.messages.clear()
|
||||
for msg in remaining:
|
||||
agent.messages.append({
|
||||
"role": msg["role"],
|
||||
"content": msg["content"],
|
||||
})
|
||||
count = len(agent.messages)
|
||||
logger.info(
|
||||
f"[AgentBridge] Synced agent memory for session={session_id}, messages={count}"
|
||||
)
|
||||
return count
|
||||
|
||||
def agent_reply(self, query: str, context: Context = None,
|
||||
on_event=None, clear_history: bool = False) -> Reply:
|
||||
"""
|
||||
@@ -464,6 +515,15 @@ class AgentBridge:
|
||||
)
|
||||
self._trim_in_memory_to_turns(agent, scheduler_keep_turns)
|
||||
|
||||
# Eagerly persist the user message BEFORE running the agent so the
|
||||
# session and the user's bubble are immediately visible — even if
|
||||
# the user switches away or refreshes before the reply finishes.
|
||||
# The reply (assistant/tool messages) is appended once the run
|
||||
# completes; the final persist skips this already-stored user turn.
|
||||
pre_persisted = self._pre_persist_user_message(
|
||||
session_id, query, context, clear_history
|
||||
)
|
||||
|
||||
try:
|
||||
# Use agent's run_stream method with event handler
|
||||
response = agent.run_stream(
|
||||
@@ -490,7 +550,11 @@ class AgentBridge:
|
||||
# Persist new messages generated during this run
|
||||
if session_id:
|
||||
channel_type = (context.get("channel_type") or "") if context else ""
|
||||
new_messages = getattr(agent, '_last_run_new_messages', [])
|
||||
new_messages = list(getattr(agent, '_last_run_new_messages', []))
|
||||
# The leading user turn was already persisted eagerly above;
|
||||
# drop it here so it isn't stored twice.
|
||||
if pre_persisted and new_messages and new_messages[0].get("role") == "user":
|
||||
new_messages = new_messages[1:]
|
||||
if new_messages:
|
||||
self._persist_messages(session_id, list(new_messages), channel_type)
|
||||
else:
|
||||
@@ -504,6 +568,23 @@ class AgentBridge:
|
||||
except Exception as e:
|
||||
logger.warning(f"[AgentBridge] Failed to clear DB after recovery: {e}")
|
||||
|
||||
# Record this user turn for the self-evolution idle trigger. Skip
|
||||
# scheduler-injected / scheduled-task sessions so internal runs do
|
||||
# not count as user activity.
|
||||
if session_id and not session_id.startswith("scheduler_") and not (
|
||||
context and context.get("is_scheduled_task")
|
||||
):
|
||||
try:
|
||||
from agent.evolution.trigger import note_user_turn
|
||||
ch = (context.get("channel_type") or "") if context else ""
|
||||
rcv = (context.get("receiver") or "") if context else ""
|
||||
is_group = bool(context.get("isgroup")) if context else False
|
||||
# Only enable proactive push for single chats (group push is
|
||||
# noisy); group sessions still evolve, just without notify.
|
||||
note_user_turn(agent, channel_type=ch, receiver=(rcv if not is_group else ""))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Post-message hot-reload: detect edits to ~/cow/mcp.json and
|
||||
# sync any new/removed MCP tools into the live agent in the
|
||||
# background. Off the critical path so user latency is unaffected;
|
||||
@@ -689,6 +770,48 @@ class AgentBridge:
|
||||
except Exception as e:
|
||||
logger.warning(f"[AgentBridge] Failed to sync API keys: {e}")
|
||||
|
||||
def _pre_persist_user_message(
|
||||
self, session_id: str, query: str, context: Context, clear_history: bool
|
||||
) -> bool:
|
||||
"""Persist the user's message before the agent runs.
|
||||
|
||||
This makes a brand-new session (and the user's bubble) visible even if
|
||||
the reply hasn't finished — switching away or refreshing no longer
|
||||
loses the in-flight session. Returns True when the user turn was
|
||||
stored, so the caller can skip it in the post-run persist.
|
||||
|
||||
Best-effort: any failure is swallowed and reported as not-persisted.
|
||||
"""
|
||||
if not session_id or not query:
|
||||
return False
|
||||
# Only real user turns: skip scheduler-injected / scheduled-task runs.
|
||||
if session_id.startswith("scheduler_") or (
|
||||
context and context.get("is_scheduled_task")
|
||||
):
|
||||
return False
|
||||
try:
|
||||
from config import conf
|
||||
if not conf().get("conversation_persistence", True):
|
||||
return False
|
||||
from agent.memory import get_conversation_store
|
||||
store = get_conversation_store()
|
||||
# clear_history starts a fresh transcript: wipe the store first so
|
||||
# the eager user turn becomes seq 0, matching in-memory state.
|
||||
if clear_history:
|
||||
store.clear_session(session_id)
|
||||
channel_type = (context.get("channel_type") or "") if context else ""
|
||||
user_msg = {
|
||||
"role": "user",
|
||||
"content": [{"type": "text", "text": query}],
|
||||
}
|
||||
store.append_messages(session_id, [user_msg], channel_type=channel_type)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"[AgentBridge] Failed to pre-persist user message for session={session_id}: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
def _persist_messages(
|
||||
self, session_id: str, new_messages: list, channel_type: str = ""
|
||||
) -> None:
|
||||
|
||||
@@ -524,6 +524,14 @@ class AgentInitializer:
|
||||
logger.debug("[AgentInitializer] WebSearch skipped - no search provider configured")
|
||||
continue
|
||||
|
||||
# Skip evolution_undo when self-evolution is disabled: with no
|
||||
# evolution there is nothing to roll back, so the tool is dead weight.
|
||||
if tool_name == "evolution_undo":
|
||||
from agent.evolution.config import get_evolution_config
|
||||
if not get_evolution_config().enabled:
|
||||
logger.debug("[AgentInitializer] evolution_undo skipped - self-evolution disabled")
|
||||
continue
|
||||
|
||||
# Special handling for EnvConfig tool
|
||||
if tool_name == "env_config":
|
||||
from agent.tools import EnvConfig
|
||||
|
||||
@@ -620,6 +620,18 @@
|
||||
after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="flex items-center gap-1.5 text-sm font-medium text-slate-600 dark:text-slate-400">
|
||||
<span data-i18n="config_self_evolution">Self-Evolution</span>
|
||||
<span class="cfg-tip" data-tip-key="config_self_evolution_hint"><i class="fas fa-circle-question"></i></span>
|
||||
</label>
|
||||
<label class="relative inline-flex items-center cursor-pointer">
|
||||
<input id="cfg-self-evolution" type="checkbox" class="sr-only peer">
|
||||
<div class="w-9 h-5 bg-slate-200 dark:bg-slate-700 peer-checked:bg-primary-400 rounded-full
|
||||
after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white
|
||||
after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-full"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex items-center justify-end gap-3 pt-1">
|
||||
<span id="cfg-agent-status" class="text-xs text-primary-500 opacity-0 transition-opacity duration-300"></span>
|
||||
<button id="cfg-agent-save"
|
||||
@@ -760,7 +772,7 @@
|
||||
</button>
|
||||
<button id="memory-tab-dreams" onclick="switchMemoryTab('dreams')"
|
||||
class="memory-tab px-3 py-1.5 rounded-md text-xs font-medium cursor-pointer transition-colors duration-150">
|
||||
<i class="fas fa-moon mr-1.5"></i><span data-i18n="memory_tab_dreams">梦境日记</span>
|
||||
<i class="fas fa-seedling mr-1.5"></i><span data-i18n="memory_tab_dreams">自主进化</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1399,3 +1399,175 @@
|
||||
.agent-cancelled-tag {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
Code Block Enhancements
|
||||
===================================================================== */
|
||||
.code-block-wrapper {
|
||||
position: relative;
|
||||
margin: 1em 0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #f8f9fa;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.dark .code-block-wrapper {
|
||||
background: #1e293b;
|
||||
border-color: #334155;
|
||||
}
|
||||
|
||||
.code-block-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5em 1em;
|
||||
background: #e2e8f0;
|
||||
border-bottom: 1px solid #cbd5e1;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.dark .code-block-header {
|
||||
background: #0f172a;
|
||||
border-bottom-color: #334155;
|
||||
}
|
||||
|
||||
.code-block-lang {
|
||||
color: #64748b;
|
||||
font-weight: 500;
|
||||
text-transform: lowercase;
|
||||
}
|
||||
|
||||
.dark .code-block-lang {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.code-copy-btn {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #64748b;
|
||||
cursor: pointer;
|
||||
padding: 0.25em 0.5em;
|
||||
border-radius: 4px;
|
||||
transition: all 0.2s;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.code-copy-btn:hover {
|
||||
background: rgba(100, 116, 139, 0.1);
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.dark .code-copy-btn {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.dark .code-copy-btn:hover {
|
||||
background: rgba(148, 163, 184, 0.1);
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.code-block-wrapper pre {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
Drag and Drop Overlay
|
||||
===================================================================== */
|
||||
/* Anchor the absolutely-positioned overlay to the chat view. */
|
||||
#view-chat {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.drag-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(59, 130, 246, 0.1);
|
||||
backdrop-filter: blur(2px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.drag-overlay.active {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.drag-overlay.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.drag-overlay-content {
|
||||
background: white;
|
||||
border: 3px dashed #3b82f6;
|
||||
border-radius: 16px;
|
||||
padding: 3em 4em;
|
||||
text-align: center;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
|
||||
animation: bounce 1s ease infinite;
|
||||
}
|
||||
|
||||
.dark .drag-overlay-content {
|
||||
background: #1e293b;
|
||||
border-color: #60a5fa;
|
||||
}
|
||||
|
||||
.drag-overlay-content i {
|
||||
font-size: 4em;
|
||||
color: #3b82f6;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
|
||||
.dark .drag-overlay-content i {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.drag-overlay-content p {
|
||||
font-size: 1.5em;
|
||||
font-weight: 600;
|
||||
color: #1e293b;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.dark .drag-overlay-content p {
|
||||
color: #f1f5f9;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10px); }
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
Message Action Buttons
|
||||
===================================================================== */
|
||||
.edit-msg-btn,
|
||||
.delete-msg-btn,
|
||||
.regenerate-msg-btn {
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s, color 0.2s;
|
||||
}
|
||||
|
||||
.user-message-group:hover .edit-msg-btn,
|
||||
.user-message-group:hover .delete-msg-btn,
|
||||
.bot-message-group:hover .regenerate-msg-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.edit-msg-btn:hover,
|
||||
.regenerate-msg-btn:hover {
|
||||
color: #3b82f6 !important;
|
||||
}
|
||||
|
||||
.delete-msg-btn:hover {
|
||||
color: #ef4444 !important;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -251,6 +251,21 @@ class WebChannel(ChatChannel):
|
||||
"""生成唯一的请求ID"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def _fetch_latest_pair_seqs(self, session_id: str):
|
||||
"""Query the conversation store for the latest user/bot message seqs.
|
||||
|
||||
Returned as ``{"user_seq": int|None, "bot_seq": int|None}``; used to
|
||||
attach seq metadata onto the SSE ``done`` event so the frontend can
|
||||
wire edit / regenerate buttons for live-streamed bubbles without a
|
||||
page refresh.
|
||||
"""
|
||||
try:
|
||||
from agent.memory import get_conversation_store
|
||||
return get_conversation_store().get_latest_pair_seqs(session_id)
|
||||
except Exception as e:
|
||||
logger.debug(f"[WebChannel] _fetch_latest_pair_seqs failed: {e}")
|
||||
return {"user_seq": None, "bot_seq": None}
|
||||
|
||||
def send(self, reply: Reply, context: Context):
|
||||
try:
|
||||
if reply.type in self.NOT_SUPPORT_REPLYTYPE:
|
||||
@@ -291,11 +306,14 @@ class WebChannel(ChatChannel):
|
||||
if reply.type in (ReplyType.IMAGE_URL, ReplyType.FILE) and content.startswith("file://"):
|
||||
text_content = getattr(reply, 'text_content', '')
|
||||
if text_content:
|
||||
seqs = self._fetch_latest_pair_seqs(session_id)
|
||||
self.sse_queues[request_id].put({
|
||||
"type": "done",
|
||||
"content": text_content,
|
||||
"request_id": request_id,
|
||||
"timestamp": time.time()
|
||||
"timestamp": time.time(),
|
||||
"user_seq": seqs.get("user_seq"),
|
||||
"bot_seq": seqs.get("bot_seq"),
|
||||
})
|
||||
logger.debug(f"SSE skipped duplicate file for request {request_id}")
|
||||
return
|
||||
@@ -307,11 +325,14 @@ class WebChannel(ChatChannel):
|
||||
logger.debug(f"SSE skipped http media reply for request {request_id}")
|
||||
return
|
||||
|
||||
seqs = self._fetch_latest_pair_seqs(session_id)
|
||||
self.sse_queues[request_id].put({
|
||||
"type": "done",
|
||||
"content": content,
|
||||
"request_id": request_id,
|
||||
"timestamp": time.time()
|
||||
"timestamp": time.time(),
|
||||
"user_seq": seqs.get("user_seq"),
|
||||
"bot_seq": seqs.get("bot_seq"),
|
||||
})
|
||||
logger.debug(f"SSE done sent for request {request_id}")
|
||||
# Auto-trigger TTS once the bot finishes its text reply. The
|
||||
@@ -339,6 +360,13 @@ class WebChannel(ChatChannel):
|
||||
):
|
||||
logger.debug(f"Polling skipped duplicate file reply for session {session_id}")
|
||||
return
|
||||
# SSE-enabled requests already stream the text reply to the
|
||||
# client. Do NOT also enqueue it for polling: if the user
|
||||
# switched away mid-run, the queued copy would resurface as a
|
||||
# duplicate bubble when they return and poll the session.
|
||||
if reply.type == ReplyType.TEXT and context.get("on_event") is not None:
|
||||
logger.debug(f"Polling skipped SSE text reply for session {session_id}")
|
||||
return
|
||||
response_data = {
|
||||
"type": str(reply.type),
|
||||
"content": content,
|
||||
@@ -919,7 +947,12 @@ class WebChannel(ChatChannel):
|
||||
post_done = True
|
||||
post_deadline = time.time() + 2 # 2s post-attach tail
|
||||
finally:
|
||||
self.sse_queues.pop(request_id, None)
|
||||
# Only drop the queue once the reply is actually complete. If the
|
||||
# client disconnected early (e.g. switched sessions and will
|
||||
# re-attach with the same request_id), keep the queue so the new
|
||||
# connection can resume reading the remaining events.
|
||||
if post_done or time.time() >= deadline:
|
||||
self.sse_queues.pop(request_id, None)
|
||||
|
||||
def cancel_request(self):
|
||||
"""
|
||||
@@ -1025,22 +1058,44 @@ class WebChannel(ChatChannel):
|
||||
|
||||
self._cleanup_stale_voice_recordings()
|
||||
|
||||
# Print available channel types
|
||||
# Print available channel types (ordered by language: prioritize
|
||||
# locally-popular channels for the current UI language)
|
||||
logger.info(
|
||||
"[WebChannel] Available channels (edit `channel_type` in config.json to switch, separate multiple with commas):")
|
||||
logger.info("[WebChannel] 1. web - Web")
|
||||
logger.info("[WebChannel] 2. terminal - Terminal")
|
||||
logger.info("[WebChannel] 3. weixin - WeChat")
|
||||
logger.info("[WebChannel] 4. feishu - Feishu")
|
||||
logger.info("[WebChannel] 5. dingtalk - DingTalk")
|
||||
logger.info("[WebChannel] 6. wecom_bot - WeCom Bot")
|
||||
logger.info("[WebChannel] 7. wechatcom_app - WeCom App")
|
||||
logger.info("[WebChannel] 8. wechat_kf - WeChat Customer Service")
|
||||
logger.info("[WebChannel] 9. wechatmp - WeChat Official Account")
|
||||
logger.info("[WebChannel] 10. wechatmp_service - WeChat Official Account (Service)")
|
||||
logger.info("[WebChannel] 11. telegram - Telegram")
|
||||
logger.info("[WebChannel] 12. slack - Slack")
|
||||
logger.info("[WebChannel] 13. discord - Discord")
|
||||
zh_channels = [
|
||||
("web", "Web"),
|
||||
("terminal", "Terminal"),
|
||||
("weixin", "WeChat"),
|
||||
("feishu", "Feishu"),
|
||||
("dingtalk", "DingTalk"),
|
||||
("wecom_bot", "WeCom Bot"),
|
||||
("wechatcom_app", "WeCom App"),
|
||||
("wechat_kf", "WeChat Customer Service"),
|
||||
("wechatmp", "WeChat Official Account"),
|
||||
("wechatmp_service", "WeChat Official Account (Service)"),
|
||||
("telegram", "Telegram"),
|
||||
("slack", "Slack"),
|
||||
("discord", "Discord"),
|
||||
]
|
||||
en_channels = [
|
||||
("web", "Web"),
|
||||
("terminal", "Terminal"),
|
||||
("telegram", "Telegram"),
|
||||
("slack", "Slack"),
|
||||
("discord", "Discord"),
|
||||
("weixin", "WeChat"),
|
||||
("feishu", "Feishu"),
|
||||
("dingtalk", "DingTalk"),
|
||||
("wecom_bot", "WeCom Bot"),
|
||||
("wechatcom_app", "WeCom App"),
|
||||
("wechat_kf", "WeChat Customer Service"),
|
||||
("wechatmp", "WeChat Official Account"),
|
||||
("wechatmp_service", "WeChat Official Account (Service)"),
|
||||
]
|
||||
channels = en_channels if i18n.get_language() == "en" else zh_channels
|
||||
name_width = max(len(name) for name, _ in channels)
|
||||
for idx, (name, label) in enumerate(channels, 1):
|
||||
logger.info(f"[WebChannel] {idx:>2}. {name:<{name_width}} - {label}")
|
||||
logger.info("[WebChannel] ✅ Web console is running")
|
||||
logger.info(f"[WebChannel] 🌐 Local access: http://localhost:{port}")
|
||||
if is_public_bind:
|
||||
@@ -1096,6 +1151,7 @@ class WebChannel(ChatChannel):
|
||||
'/api/sessions/(.*)/clear_context', 'SessionClearContextHandler',
|
||||
'/api/sessions/(.*)', 'SessionDetailHandler',
|
||||
'/api/history', 'HistoryHandler',
|
||||
'/api/messages/delete', 'MessageDeleteHandler',
|
||||
'/api/logs', 'LogsHandler',
|
||||
'/api/version', 'VersionHandler',
|
||||
'/assets/(.*)', 'AssetsHandler',
|
||||
@@ -1404,12 +1460,12 @@ class ConfigHandler:
|
||||
|
||||
_RECOMMENDED_MODELS = [
|
||||
const.DEEPSEEK_V4_FLASH, const.DEEPSEEK_V4_PRO, const.DEEPSEEK_CHAT, const.DEEPSEEK_REASONER,
|
||||
const.MINIMAX_M2_7_HIGHSPEED, const.MINIMAX_M2_7, const.MINIMAX_M2_5, const.MINIMAX_M2_1, const.MINIMAX_M2_1_LIGHTNING,
|
||||
const.MINIMAX_M3, const.MINIMAX_M2_7_HIGHSPEED, const.MINIMAX_M2_7,
|
||||
const.CLAUDE_4_8_OPUS, const.CLAUDE_4_7_OPUS, const.CLAUDE_4_6_SONNET, const.CLAUDE_4_6_OPUS, const.CLAUDE_4_5_SONNET,
|
||||
const.GEMINI_35_FLASH, const.GEMINI_31_FLASH_LITE_PRE, const.GEMINI_31_PRO_PRE, const.GEMINI_3_FLASH_PRE,
|
||||
const.GPT_55, const.GPT_54, const.GPT_54_MINI, const.GPT_54_NANO, const.GPT_5, const.GPT_41, const.GPT_4o,
|
||||
const.GLM_5_1, const.GLM_5_TURBO, const.GLM_5, const.GLM_4_7,
|
||||
const.QWEN36_PLUS, const.QWEN37_MAX, const.QWEN35_PLUS, const.QWEN3_MAX,
|
||||
const.QWEN37_PLUS, const.QWEN37_MAX, const.QWEN36_PLUS,
|
||||
const.DOUBAO_SEED_2_PRO, const.DOUBAO_SEED_2_CODE,
|
||||
const.KIMI_K2_6, const.KIMI_K2_5, const.KIMI_K2,
|
||||
const.ERNIE_5_1, const.ERNIE_5, const.ERNIE_X1_1, const.ERNIE_45_TURBO_128K, const.ERNIE_45_TURBO_32K,
|
||||
@@ -1442,7 +1498,7 @@ class ConfigHandler:
|
||||
"api_base_key": None,
|
||||
"api_base_default": None,
|
||||
"api_base_placeholder": "",
|
||||
"models": [const.MINIMAX_M2_7, const.MINIMAX_M2_7_HIGHSPEED, const.MINIMAX_M2_5, const.MINIMAX_M2_1, const.MINIMAX_M2_1_LIGHTNING],
|
||||
"models": [const.MINIMAX_M3, const.MINIMAX_M2_7, const.MINIMAX_M2_7_HIGHSPEED],
|
||||
}),
|
||||
("claudeAPI", {
|
||||
"label": "Claude",
|
||||
@@ -1482,7 +1538,7 @@ class ConfigHandler:
|
||||
"api_base_key": None,
|
||||
"api_base_default": None,
|
||||
"api_base_placeholder": "",
|
||||
"models": [const.QWEN36_PLUS, const.QWEN37_MAX, const.QWEN35_PLUS, const.QWEN3_MAX],
|
||||
"models": [const.QWEN37_PLUS, const.QWEN37_MAX, const.QWEN36_PLUS],
|
||||
}),
|
||||
("doubao", {
|
||||
"label": {"zh": "豆包", "en": "Doubao"},
|
||||
@@ -1543,7 +1599,7 @@ class ConfigHandler:
|
||||
"zhipu_ai_api_key", "dashscope_api_key", "moonshot_api_key",
|
||||
"ark_api_key", "minimax_api_key", "linkai_api_key", "custom_api_key", "mimo_api_key",
|
||||
"agent_max_context_tokens", "agent_max_context_turns", "agent_max_steps",
|
||||
"enable_thinking", "web_password",
|
||||
"enable_thinking", "self_evolution_enabled", "web_password",
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@@ -1598,6 +1654,7 @@ class ConfigHandler:
|
||||
"agent_max_context_turns": local_config.get("agent_max_context_turns", 20),
|
||||
"agent_max_steps": local_config.get("agent_max_steps", 20),
|
||||
"enable_thinking": bool(local_config.get("enable_thinking", False)),
|
||||
"self_evolution_enabled": bool(local_config.get("self_evolution_enabled", False)),
|
||||
"api_bases": api_bases,
|
||||
"api_keys": api_keys_masked,
|
||||
"providers": providers,
|
||||
@@ -1623,7 +1680,7 @@ class ConfigHandler:
|
||||
continue
|
||||
if key in ("agent_max_context_tokens", "agent_max_context_turns", "agent_max_steps"):
|
||||
value = int(value)
|
||||
if key in ("use_linkai", "enable_thinking"):
|
||||
if key in ("use_linkai", "enable_thinking", "self_evolution_enabled"):
|
||||
value = bool(value)
|
||||
local_config[key] = value
|
||||
applied[key] = value
|
||||
@@ -1720,6 +1777,28 @@ class ModelsHandler:
|
||||
],
|
||||
}
|
||||
|
||||
# ASR engine catalog per provider. The first entry of each list is the
|
||||
# runtime default (mirrors DEFAULT_ASR_MODEL in voice/*). Users can still
|
||||
# pick "custom" in the UI to send any other model id.
|
||||
_ASR_PROVIDER_MODELS = {
|
||||
"openai": [
|
||||
{"value": "gpt-4o-mini-transcribe", "hint": "默认 · 速度快"},
|
||||
{"value": "gpt-4o-transcribe", "hint": "更高准确率"},
|
||||
{"value": "whisper-1", "hint": "经典 Whisper"},
|
||||
],
|
||||
"dashscope": [
|
||||
{"value": "qwen3-asr-flash", "hint": "覆盖普通话、方言与主流外语"},
|
||||
],
|
||||
"zhipu": [
|
||||
{"value": "glm-asr-2512", "hint": "智谱语音识别"},
|
||||
],
|
||||
# LinkAI gateway pins whisper-1 for ASR and ignores any other id,
|
||||
# so expose only that to avoid misleading the user.
|
||||
"linkai": [
|
||||
{"value": "whisper-1", "hint": "网关固定使用"},
|
||||
],
|
||||
}
|
||||
|
||||
# Per-provider voice timbres. Entries can be a bare code string
|
||||
# (label = code) or {value, hint?} when a friendly secondary label
|
||||
# helps recognition. We keep `value` as the raw API code so power
|
||||
@@ -1964,7 +2043,7 @@ class ModelsHandler:
|
||||
],
|
||||
"doubao": [const.DOUBAO_SEED_2_PRO],
|
||||
"moonshot": [const.KIMI_K2_6],
|
||||
"dashscope": [const.QWEN36_PLUS, const.QWEN35_PLUS, const.QWEN3_MAX],
|
||||
"dashscope": [const.QWEN37_PLUS, const.QWEN36_PLUS],
|
||||
"claudeAPI": [const.CLAUDE_4_8_OPUS, const.CLAUDE_4_7_OPUS, const.CLAUDE_4_6_SONNET, const.CLAUDE_4_6_OPUS],
|
||||
"gemini": [const.GEMINI_35_FLASH, const.GEMINI_31_FLASH_LITE_PRE, const.GEMINI_31_PRO_PRE, const.GEMINI_3_FLASH_PRE],
|
||||
"qianfan": [const.ERNIE_45_TURBO_VL],
|
||||
@@ -1985,7 +2064,7 @@ class ModelsHandler:
|
||||
"linkai": [
|
||||
const.GPT_41_MINI,
|
||||
const.GPT_54_MINI,
|
||||
const.QWEN36_PLUS,
|
||||
const.QWEN37_PLUS,
|
||||
const.DOUBAO_SEED_2_PRO,
|
||||
const.KIMI_K2_6,
|
||||
const.CLAUDE_4_6_SONNET,
|
||||
@@ -2102,7 +2181,7 @@ class ModelsHandler:
|
||||
_VISION_AUTO_ORDER = [
|
||||
("moonshot", "moonshot_api_key", const.KIMI_K2_6),
|
||||
("doubao", "ark_api_key", const.DOUBAO_SEED_2_PRO),
|
||||
("dashscope", "dashscope_api_key", const.QWEN36_PLUS),
|
||||
("dashscope", "dashscope_api_key", const.QWEN37_PLUS),
|
||||
("claudeAPI", "claude_api_key", const.CLAUDE_4_6_SONNET),
|
||||
("gemini", "gemini_api_key", const.GEMINI_35_FLASH),
|
||||
("qianfan", "qianfan_api_key", const.ERNIE_45_TURBO_VL),
|
||||
@@ -2240,8 +2319,9 @@ class ModelsHandler:
|
||||
"editable": True,
|
||||
"current_provider": explicit,
|
||||
"suggested_provider": suggested,
|
||||
"current_model": "",
|
||||
"current_model": (local_config.get("voice_to_text_model") or "") if explicit else "",
|
||||
"providers": cls._ASR_PROVIDERS,
|
||||
"provider_models": cls._ASR_PROVIDER_MODELS,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
@@ -2613,7 +2693,7 @@ class ModelsHandler:
|
||||
if capability == "vision":
|
||||
return self._set_vision(provider_id, model)
|
||||
if capability == "asr":
|
||||
return self._set_simple("voice_to_text", provider_id)
|
||||
return self._set_asr(provider_id, model)
|
||||
if capability == "tts":
|
||||
return self._set_tts(provider_id, model, (data.get("voice") or "").strip())
|
||||
if capability == "embedding":
|
||||
@@ -2773,6 +2853,30 @@ class ModelsHandler:
|
||||
self._refresh_voice_routing()
|
||||
return json.dumps({"status": "success", key: value})
|
||||
|
||||
def _set_asr(self, provider_id: str, model: str) -> str:
|
||||
local_config = conf()
|
||||
file_cfg = self._read_file_config()
|
||||
local_config["voice_to_text"] = provider_id
|
||||
file_cfg["voice_to_text"] = provider_id
|
||||
# Only overwrite the model when one is supplied. An empty model means
|
||||
# "keep whatever is configured" so switching provider from the console
|
||||
# never wipes a user's hand-set voice_to_text_model (runtime falls back
|
||||
# to the engine default via `or DEFAULT_ASR_MODEL` regardless).
|
||||
if model:
|
||||
local_config["voice_to_text_model"] = model
|
||||
file_cfg["voice_to_text_model"] = model
|
||||
self._write_file_config(file_cfg)
|
||||
logger.info(
|
||||
f"[ModelsHandler] asr updated: provider={provider_id!r} "
|
||||
f"model={model!r}"
|
||||
)
|
||||
self._refresh_voice_routing()
|
||||
return json.dumps({
|
||||
"status": "success",
|
||||
"provider": provider_id,
|
||||
"model": local_config.get("voice_to_text_model", ""),
|
||||
})
|
||||
|
||||
def _set_tts(self, provider_id: str, model: str, voice: str = "") -> str:
|
||||
local_config = conf()
|
||||
file_cfg = self._read_file_config()
|
||||
@@ -3873,6 +3977,40 @@ class HistoryHandler:
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
|
||||
class MessageDeleteHandler:
|
||||
def POST(self):
|
||||
_require_auth()
|
||||
web.header('Content-Type', 'application/json; charset=utf-8')
|
||||
web.header('Access-Control-Allow-Origin', '*')
|
||||
try:
|
||||
data = json.loads(web.data())
|
||||
session_id = data.get('session_id', '').strip()
|
||||
user_seq = data.get('user_seq')
|
||||
delete_user = data.get('delete_user', True)
|
||||
cascade = data.get('cascade', False)
|
||||
|
||||
if not session_id or user_seq is None:
|
||||
return json.dumps({"status": "error", "message": "session_id and user_seq required"})
|
||||
|
||||
# 1. Delete from database
|
||||
from agent.memory import get_conversation_store
|
||||
store = get_conversation_store()
|
||||
deleted = store.delete_message_pair(session_id, int(user_seq), delete_user=delete_user, cascade=cascade)
|
||||
|
||||
# 2. Sync agent's in-memory context so its next turn sees the
|
||||
# same history as the DB. Handled by the agent_bridge helper.
|
||||
try:
|
||||
from bridge import Bridge
|
||||
Bridge().get_agent_bridge().sync_session_messages_from_store(session_id)
|
||||
except Exception as sync_err:
|
||||
logger.warning(f"[WebChannel] Failed to sync agent memory: {sync_err}")
|
||||
|
||||
return json.dumps({"status": "success", "deleted": deleted}, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logger.error(f"[WebChannel] Message delete error: {e}")
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
|
||||
class LogsHandler:
|
||||
def GET(self):
|
||||
_require_auth()
|
||||
|
||||
@@ -19,9 +19,15 @@ def verify_server(data):
|
||||
nonce = data.nonce
|
||||
echostr = data.get("echostr", None)
|
||||
token = conf().get("wechatmp_token") # 请按照公众平台官网\基本配置中信息填写
|
||||
# Reject when token is empty: an empty token reduces signature verification
|
||||
# to a predictable hash over attacker-controlled values.
|
||||
if not token:
|
||||
raise web.Forbidden("wechatmp_token is not configured")
|
||||
check_signature(token, signature, timestamp, nonce)
|
||||
return echostr
|
||||
except InvalidSignatureException:
|
||||
raise web.Forbidden("Invalid signature")
|
||||
except web.Forbidden:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise web.Forbidden(str(e))
|
||||
|
||||
@@ -1 +1 @@
|
||||
2.0.9
|
||||
2.1.1
|
||||
|
||||
@@ -275,7 +275,7 @@ def update(ctx):
|
||||
def status():
|
||||
"""Show CowAgent running status."""
|
||||
from cli import __version__
|
||||
from cli.utils import load_config_json, get_cli_language
|
||||
from cli.utils import load_config_json, get_cli_language, get_project_root
|
||||
|
||||
# get_cli_language() calls ensure_sys_path(), which adds the project root
|
||||
# to sys.path. Import `common` only AFTER that, otherwise it fails with
|
||||
@@ -292,6 +292,11 @@ def status():
|
||||
|
||||
click.echo(_t(f" 版本: v{__version__}", f" Version: v{__version__}"))
|
||||
|
||||
# Project path bound to this `cow` CLI — disambiguates which checkout the
|
||||
# command actually controls when the user has multiple clones.
|
||||
project_root = get_project_root()
|
||||
click.echo(_t(f" 路径: {project_root}", f" Path: {project_root}"))
|
||||
|
||||
cfg = load_config_json()
|
||||
if cfg:
|
||||
channel = cfg.get("channel_type", "unknown")
|
||||
|
||||
@@ -34,7 +34,9 @@ chat_client: LinkAIClient
|
||||
|
||||
CHANNEL_ACTIONS = {"channel_create", "channel_update", "channel_delete"}
|
||||
|
||||
# channelType -> config key mapping for app credentials
|
||||
# channelType -> config key mapping for app credentials.
|
||||
# secret_key may be "" for single-token channels (e.g. telegram/discord).
|
||||
# For slack, appId carries bot_token and appSecret carries app_token.
|
||||
CREDENTIAL_MAP = {
|
||||
"feishu": ("feishu_app_id", "feishu_app_secret"),
|
||||
"dingtalk": ("dingtalk_client_id", "dingtalk_client_secret"),
|
||||
@@ -43,6 +45,9 @@ CREDENTIAL_MAP = {
|
||||
"wechatmp": ("wechatmp_app_id", "wechatmp_app_secret"),
|
||||
"wechatmp_service": ("wechatmp_app_id", "wechatmp_app_secret"),
|
||||
"wechatcom_app": ("wechatcomapp_agent_id", "wechatcomapp_secret"),
|
||||
"telegram": ("telegram_token", ""),
|
||||
"slack": ("slack_bot_token", "slack_app_token"),
|
||||
"discord": ("discord_token", ""),
|
||||
}
|
||||
|
||||
|
||||
@@ -357,7 +362,8 @@ class CloudClient(LinkAIClient):
|
||||
local_config[id_key] = app_id
|
||||
os.environ[id_key.upper()] = str(app_id)
|
||||
changed = True
|
||||
if app_secret is not None and local_config.get(secret_key) != app_secret:
|
||||
# secret_key may be empty for single-token channels (e.g. telegram/discord)
|
||||
if secret_key and app_secret is not None and local_config.get(secret_key) != app_secret:
|
||||
local_config[secret_key] = app_secret
|
||||
os.environ[secret_key.upper()] = str(app_secret)
|
||||
changed = True
|
||||
@@ -372,9 +378,10 @@ class CloudClient(LinkAIClient):
|
||||
return
|
||||
id_key, secret_key = cred
|
||||
local_config.pop(id_key, None)
|
||||
local_config.pop(secret_key, None)
|
||||
os.environ.pop(id_key.upper(), None)
|
||||
os.environ.pop(secret_key.upper(), None)
|
||||
if secret_key:
|
||||
local_config.pop(secret_key, None)
|
||||
os.environ.pop(secret_key.upper(), None)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# channel_type list helpers
|
||||
@@ -862,25 +869,16 @@ def _build_config():
|
||||
if plugin_config.get("Godcmd"):
|
||||
config["admin_password"] = plugin_config.get("Godcmd").get("password")
|
||||
|
||||
# Add channel-specific app credentials
|
||||
# Add channel-specific app credentials based on CREDENTIAL_MAP.
|
||||
# For multi-channel channel_type (comma-separated), the first matched type wins.
|
||||
current_channel_type = local_conf.get("channel_type", "")
|
||||
if current_channel_type == "feishu":
|
||||
config["app_id"] = local_conf.get("feishu_app_id")
|
||||
config["app_secret"] = local_conf.get("feishu_app_secret")
|
||||
elif current_channel_type == "dingtalk":
|
||||
config["app_id"] = local_conf.get("dingtalk_client_id")
|
||||
config["app_secret"] = local_conf.get("dingtalk_client_secret")
|
||||
elif current_channel_type in ("wechatmp", "wechatmp_service"):
|
||||
config["app_id"] = local_conf.get("wechatmp_app_id")
|
||||
config["app_secret"] = local_conf.get("wechatmp_app_secret")
|
||||
elif current_channel_type == "wecom_bot":
|
||||
config["app_id"] = local_conf.get("wecom_bot_id")
|
||||
config["app_secret"] = local_conf.get("wecom_bot_secret")
|
||||
elif current_channel_type == "qq":
|
||||
config["app_id"] = local_conf.get("qq_app_id")
|
||||
config["app_secret"] = local_conf.get("qq_app_secret")
|
||||
elif current_channel_type == "wechatcom_app":
|
||||
config["app_id"] = local_conf.get("wechatcomapp_agent_id")
|
||||
config["app_secret"] = local_conf.get("wechatcomapp_secret")
|
||||
for ch_type in CloudClient._parse_channel_types({"channel_type": current_channel_type}):
|
||||
cred = CREDENTIAL_MAP.get(ch_type)
|
||||
if not cred:
|
||||
continue
|
||||
id_key, secret_key = cred
|
||||
config["app_id"] = local_conf.get(id_key)
|
||||
config["app_secret"] = local_conf.get(secret_key) if secret_key else ""
|
||||
break
|
||||
|
||||
return config
|
||||
|
||||
@@ -108,17 +108,15 @@ QWEN_LONG = "qwen-long"
|
||||
QWEN3_MAX = "qwen3-max" # Qwen3 Max - Agent推荐模型
|
||||
QWEN35_PLUS = "qwen3.5-plus" # Qwen3.5 Plus - Omni model (MultiModalConversation)
|
||||
QWEN36_PLUS = "qwen3.6-plus" # Qwen3.6 Plus - Omni model (MultiModalConversation)
|
||||
QWEN37_PLUS = "qwen3.7-plus" # Qwen3.7 Plus - Omni model (MultiModalConversation)
|
||||
QWEN37_MAX = "qwen3.7-max" # Qwen3.7 Max - Agent推荐模型
|
||||
QWQ_PLUS = "qwq-plus"
|
||||
|
||||
# MiniMax
|
||||
MINIMAX_M2_7 = "MiniMax-M2.7" # MiniMax M2.7 - Latest
|
||||
MINIMAX_TEXT_01 = "MiniMax-Text-01" # MiniMax 多模态 (vision)
|
||||
MINIMAX_M3 = "MiniMax-M3" # MiniMax M3 - Latest (default)
|
||||
MINIMAX_M2_7 = "MiniMax-M2.7" # MiniMax M2.7
|
||||
MINIMAX_M2_7_HIGHSPEED = "MiniMax-M2.7-highspeed" # MiniMax M2.7 highspeed
|
||||
MINIMAX_M2_5 = "MiniMax-M2.5" # MiniMax M2.5
|
||||
MINIMAX_M2_1 = "MiniMax-M2.1" # MiniMax M2.1
|
||||
MINIMAX_M2_1_LIGHTNING = "MiniMax-M2.1-lightning" # MiniMax M2.1 极速版
|
||||
MINIMAX_M2 = "MiniMax-M2" # MiniMax M2
|
||||
MINIMAX_TEXT_01 = "MiniMax-Text-01" # MiniMax 多模态 (vision)
|
||||
MINIMAX_ABAB6_5 = "abab6.5-chat" # MiniMax abab6.5
|
||||
|
||||
# GLM (智谱AI)
|
||||
@@ -189,7 +187,7 @@ MODEL_LIST = [
|
||||
ERNIE_45_TURBO_VL, ERNIE_45_TURBO_VL_32K,
|
||||
|
||||
# MiniMax
|
||||
MiniMax, MINIMAX_M2_7, MINIMAX_M2_7_HIGHSPEED, MINIMAX_M2_5, MINIMAX_M2_1, MINIMAX_M2_1_LIGHTNING, MINIMAX_M2, MINIMAX_ABAB6_5,
|
||||
MiniMax, MINIMAX_M3, MINIMAX_M2_7, MINIMAX_M2_7_HIGHSPEED, MINIMAX_ABAB6_5,
|
||||
|
||||
# 小米 MiMo
|
||||
MIMO, MIMO_V2_5_PRO, MIMO_V2_5, MIMO_V2_PRO, MIMO_V2_OMNI, MIMO_V2_FLASH,
|
||||
@@ -218,7 +216,7 @@ MODEL_LIST = [
|
||||
GLM_4_0520, GLM_4_AIR, GLM_4_AIRX, GLM_4_7,
|
||||
|
||||
# Qwen (通义千问)
|
||||
QWEN37_MAX, QWEN36_PLUS, QWEN35_PLUS, QWEN3_MAX, QWEN_MAX, QWEN_PLUS, QWEN_TURBO, QWEN_LONG,
|
||||
QWEN37_PLUS, QWEN37_MAX, QWEN36_PLUS, QWEN35_PLUS, QWEN3_MAX, QWEN_MAX, QWEN_PLUS, QWEN_TURBO, QWEN_LONG,
|
||||
|
||||
# Doubao (豆包)
|
||||
DOUBAO, DOUBAO_SEED_2_CODE, DOUBAO_SEED_2_PRO, DOUBAO_SEED_2_LITE, DOUBAO_SEED_2_MINI,
|
||||
|
||||
@@ -124,6 +124,8 @@ def detect_language():
|
||||
3. Python locale module
|
||||
4. default English
|
||||
"""
|
||||
if os.environ.get("CLOUD_DEPLOYMENT_ID"):
|
||||
return ZH
|
||||
return (
|
||||
_detect_from_macos()
|
||||
or _detect_from_env()
|
||||
|
||||
@@ -40,5 +40,6 @@
|
||||
"agent_max_steps": 20,
|
||||
"enable_thinking": false,
|
||||
"reasoning_effort": "high",
|
||||
"knowledge": true
|
||||
"knowledge": true,
|
||||
"self_evolution_enabled": true
|
||||
}
|
||||
|
||||
@@ -251,6 +251,10 @@ available_setting = {
|
||||
"enable_thinking": False, # Enable deep-thinking mode for thinking-capable models
|
||||
"reasoning_effort": "high", # Reasoning depth under thinking mode: "high" or "max"
|
||||
"knowledge": True, # whether to enable the knowledge base feature
|
||||
# Self-evolution: review idle conversations to learn memory/skills. Flat keys.
|
||||
"self_evolution_enabled": False, # switch to enable/disable self-evolution
|
||||
"self_evolution_idle_minutes": 15, # idle time before a session is reviewed
|
||||
"self_evolution_min_turns": 8, # min user turns (or context pressure) to trigger
|
||||
"skill": {}, # Per-skill runtime config; nested keys flatten to SKILL_<NAME>_<KEY> env vars at startup
|
||||
"mcp_servers": [], # MCP server list; each entry supports type "stdio" (local process) or "sse" (remote URL)
|
||||
}
|
||||
|
||||
@@ -179,7 +179,8 @@
|
||||
"pages": [
|
||||
"memory/index",
|
||||
"memory/context",
|
||||
"memory/deep-dream"
|
||||
"memory/deep-dream",
|
||||
"memory/self-evolution"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -240,6 +241,7 @@
|
||||
"group": "Release Notes",
|
||||
"pages": [
|
||||
"releases/overview",
|
||||
"releases/v2.1.1",
|
||||
"releases/v2.1.0",
|
||||
"releases/v2.0.9",
|
||||
"releases/v2.0.8",
|
||||
@@ -393,7 +395,8 @@
|
||||
"pages": [
|
||||
"zh/memory/index",
|
||||
"zh/memory/context",
|
||||
"zh/memory/deep-dream"
|
||||
"zh/memory/deep-dream",
|
||||
"zh/memory/self-evolution"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -454,6 +457,7 @@
|
||||
"group": "发布记录",
|
||||
"pages": [
|
||||
"zh/releases/overview",
|
||||
"zh/releases/v2.1.1",
|
||||
"zh/releases/v2.1.0",
|
||||
"zh/releases/v2.0.9",
|
||||
"zh/releases/v2.0.8",
|
||||
@@ -607,7 +611,8 @@
|
||||
"pages": [
|
||||
"ja/memory/index",
|
||||
"ja/memory/context",
|
||||
"ja/memory/deep-dream"
|
||||
"ja/memory/deep-dream",
|
||||
"ja/memory/self-evolution"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -668,6 +673,7 @@
|
||||
"group": "リリースノート",
|
||||
"pages": [
|
||||
"ja/releases/overview",
|
||||
"ja/releases/v2.1.1",
|
||||
"ja/releases/v2.1.0",
|
||||
"ja/releases/v2.0.9",
|
||||
"ja/releases/v2.0.8",
|
||||
|
||||
@@ -5,7 +5,7 @@ description: One-click install and manage CowAgent with scripts
|
||||
|
||||
The project provides scripts for one-click install, configuration, startup, and management. Script-based deployment is recommended for quick setup.
|
||||
|
||||
Supports Linux, macOS, and Windows. Requires Python 3.7-3.12 (3.9 recommended).
|
||||
Supports Linux, macOS, and Windows. Requires Python 3.7-3.13 (3.9 recommended).
|
||||
|
||||
## Install Command
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ CowAgent's architecture consists of the following core modules:
|
||||
| **Plan** | Understands user intent, decomposes complex tasks into multi-step plans, and iteratively invokes tools until the goal is achieved |
|
||||
| **Memory** | Automatically persists important information as core memory and daily memory, with hybrid keyword and vector retrieval for cross-session context continuity |
|
||||
| **Knowledge** | Organizes structured knowledge by topic. The Agent autonomously distills valuable information into Markdown pages, maintaining indexes and cross-references to build a growing knowledge network |
|
||||
| **Evolution** | Reviews a conversation in an isolated environment after it goes idle, improving skills, following up on unfinished tasks, and backfilling memory and knowledge so the Agent keeps growing through everyday use |
|
||||
| **Tools** | Core capability for Agent to access OS resources. 10+ built-in tools including file read/write, terminal, browser, scheduler, memory search, web search, and more |
|
||||
| **Skills** | Loads and manages Skills. Supports one-click installation from Skill Hub, GitHub, and more, or custom skill creation through conversation |
|
||||
| **Models** | Model layer with unified access to OpenAI, Claude, Gemini, DeepSeek, MiniMax, GLM, Qwen, and other mainstream LLMs |
|
||||
@@ -84,4 +85,5 @@ Configure Agent mode parameters in `config.json`:
|
||||
| `agent_max_steps` | Max decision steps per task | `20` |
|
||||
| `enable_thinking` | Enable deep-thinking mode | `false` |
|
||||
| `knowledge` | Enable personal knowledge base | `true` |
|
||||
| `self_evolution_enabled` | Enable Self-Evolution (on by default for new installs) | `false` |
|
||||
| `cow_lang` | Language for the UI, command text and system prompts; `auto` to detect, or set `zh` / `en` | `auto` |
|
||||
|
||||
@@ -15,7 +15,13 @@ In subsequent long-term conversations, the Agent intelligently stores or retriev
|
||||
<img src="https://cdn.link-ai.tech/doc/20260203000455.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
See [Long-term Memory](/memory) and [Deep Dream](/memory/deep-dream) for details.
|
||||
Building on this, **Self-Evolution** lets the Agent keep growing through everyday use: after a conversation goes idle, it reviews it automatically to improve skills, follow up on unfinished tasks, and backfill memory and knowledge. It speaks up only when it actually made a change, and every change can be undone. Enabled by default for new installs.
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-demo.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
See [Long-term Memory](/memory), [Deep Dream](/memory/deep-dream), and [Self-Evolution](/memory/self-evolution) for details.
|
||||
|
||||
## 2. Personal Knowledge Base
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ CowAgent is lightweight, easy to deploy, and built to extend. Plug in any major
|
||||
<Card title="Personal Knowledge Base" icon="book" href="/knowledge/index">
|
||||
Auto-curates structured knowledge into a Markdown wiki, builds an evolving knowledge graph with visual browsing.
|
||||
</Card>
|
||||
<Card title="Self-Evolution" icon="seedling" href="/memory/self-evolution">
|
||||
Reviews conversations automatically to improve skills, follow up on unfinished tasks, and consolidate memory and knowledge, growing through everyday use.
|
||||
</Card>
|
||||
<Card title="Skills System" icon="puzzle-piece" href="/skills/index">
|
||||
A complete skill creation and execution engine. Install from Skill Hub or generate custom skills via natural-language conversation.
|
||||
</Card>
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
<p align="center"><img src="https://github.com/user-attachments/assets/eca9a9ec-8534-4615-9e0f-96c5ac1d10a3" alt="CowAgent" width="420" /></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/github/license/zhayujie/CowAgent" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square" alt="Stars"></a> <br/>
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent?cacheSeconds=3600" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square&cacheSeconds=3600" alt="Stars"></a>
|
||||
<a href="https://docs.cowagent.ai/ja"><img src="https://img.shields.io/badge/%E3%83%89%E3%82%AD%E3%83%A5%E3%83%A1%E3%83%B3%E3%83%88-cowagent.ai-blue?style=flat&logo=readthedocs&logoColor=white" alt="ドキュメント"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/25763" target="_blank"><img src="https://trendshift.io/api/badge/repositories/25763" alt="zhayujie%2FCowAgent | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
[<a href="../../README.md">English</a>] | [<a href="../zh/README.md">中文</a>] | [日本語]
|
||||
</p>
|
||||
|
||||
**CowAgent** は、自律的にタスクを計画し、コンピュータや外部リソースを操作し、Skill を作成・実行し、パーソナルナレッジベースと長期記憶でユーザーとともに成長するオープンソースのスーパー AI アシスタントです。エンドツーエンドの Agent Harness のリファレンス実装の一つでもあります。
|
||||
**CowAgent** は、自律的にタスクを計画し、コンピュータや外部リソースを操作し、Skill を作成・実行し、パーソナルナレッジベースと長期記憶を構築し、自己進化によってユーザーとともに成長するオープンソースのスーパー AI アシスタントです。エンドツーエンドの Agent Harness のリファレンス実装の一つでもあります。
|
||||
|
||||
CowAgent は軽量でデプロイしやすく、拡張性に優れています。主要な LLM プロバイダーをそのまま組み込み、Web や主要な IM プラットフォーム上で動作。個人 PC やサーバー上で 24 時間 365 日稼働できます。
|
||||
|
||||
@@ -28,6 +36,7 @@ CowAgent は軽量でデプロイしやすく、拡張性に優れています
|
||||
| [タスク計画](https://docs.cowagent.ai/ja/intro/architecture) | 複雑なタスクを分解し、目標達成までツールを繰り返し呼び出して段階的に実行 |
|
||||
| [長期記憶](https://docs.cowagent.ai/ja/memory/index) | 三層構造(コンテキスト → デイリー → コア)、Deep Dream による自動蒸留、キーワードとベクトルのハイブリッド検索 |
|
||||
| [ナレッジベース](https://docs.cowagent.ai/ja/knowledge/index) | 構造化された知識を Markdown Wiki として自動整理し、進化し続けるナレッジグラフを可視化ブラウジング |
|
||||
| [自己進化](https://docs.cowagent.ai/ja/memory/self-evolution) | 会話を自動でレビューして Skill を改善し、未完了のタスクを引き継ぎ、記憶と知識を補完。日々の利用を通じて成長 |
|
||||
| [Skill](https://docs.cowagent.ai/ja/skills/index) | [Skill Hub](https://skills.cowagent.ai/)、GitHub、ClawHub からワンクリックでインストール;対話によるカスタム Skill 作成にも対応 |
|
||||
| [ツール](https://docs.cowagent.ai/ja/tools/index) | ファイル I/O、ターミナル、ブラウザ、スケジューラ、記憶検索、Web 検索など 10+ の組み込みツール — MCP プロトコルに完全対応 |
|
||||
| [チャネル](https://docs.cowagent.ai/ja/channels/index) | 一つの Agent で Web、WeChat、Feishu、DingTalk、WeCom、QQ、公式アカウント、Telegram、Slack を同時にサポート |
|
||||
@@ -98,11 +107,11 @@ CowAgent は主要な LLM プロバイダーすべてに対応しています。
|
||||
| [OpenAI](https://docs.cowagent.ai/ja/models/openai) | gpt-5.5、o シリーズ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Gemini](https://docs.cowagent.ai/ja/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [DeepSeek](https://docs.cowagent.ai/ja/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [Qwen](https://docs.cowagent.ai/ja/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Qwen](https://docs.cowagent.ai/ja/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [GLM](https://docs.cowagent.ai/ja/models/glm) | glm-5.1、glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [Doubao](https://docs.cowagent.ai/ja/models/doubao) | doubao-seed-2.0 シリーズ | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](https://docs.cowagent.ai/ja/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [MiniMax](https://docs.cowagent.ai/ja/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](https://docs.cowagent.ai/ja/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [ERNIE](https://docs.cowagent.ai/ja/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
| [MiMo](https://docs.cowagent.ai/ja/models/mimo) | mimo-v2.5-pro / v2.5 | ✅ | ✅ | | | ✅ | |
|
||||
| [LinkAI](https://docs.cowagent.ai/ja/models/linkai) | 1 つの Key で 100+ モデルに接続 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
@@ -190,6 +199,8 @@ CowAgent は主要な LLM プロバイダーすべてに対応しています。
|
||||
|
||||
## 🏷 更新履歴
|
||||
|
||||
> **2026.06.09:** [v2.1.1](https://github.com/zhayujie/CowAgent/releases/tag/2.1.1) — 自己進化、Web コンソールの強化(メッセージ管理、マルチセッション並行)、クロスプラットフォーム対応の MCP 強化と並行呼び出し、新モデル(MiniMax-M3、qwen3.7-plus)、Python 3.13 対応。
|
||||
|
||||
> **2026.06.01:** [v2.1.0](https://github.com/zhayujie/CowAgent/releases/tag/2.1.0) — 国際化対応、新チャネル(Telegram、Discord、Slack、WeChat カスタマーサービス)、CLI インタラクション強化、ワンライナーインストールの最適化、MCP Streamable HTTP 対応、新モデル(claude-opus-4-8、MiMo)。
|
||||
|
||||
> **2026.05.22:** [v2.0.9](https://github.com/zhayujie/CowAgent/releases/tag/2.0.9) — モデル管理、MCP プロトコル対応、ブラウザセッション永続化、新モデル(gpt-5.5、gemini-3.5-flash、qwen3.7-max)、デプロイのセキュリティ強化。
|
||||
@@ -238,9 +249,9 @@ GitHub で [Issue を報告](https://github.com/zhayujie/CowAgent/issues) する
|
||||
|
||||
## 🛠️ 開発とコントリビューション
|
||||
|
||||
新しいチャネルの追加を歓迎します — [Feishu チャネル](https://github.com/zhayujie/CowAgent/blob/master/channel/feishu/feishu_channel.py) を参考にカスタムチャネルを実装できます。新しい Skill のコントリビューションも [Skill Hub](https://skills.cowagent.ai/submit) で受け付けています。
|
||||
あらゆる形のコントリビューションを歓迎します —— 新機能、バグ修正、パフォーマンス改善、ドキュメント、あるいは [Skill Hub](https://skills.cowagent.ai/submit) への Skill の共有など。まずは [CONTRIBUTING.md](/CONTRIBUTING.md) をご覧いただき、Issue で相談するか、直接 PR を送ってください。
|
||||
|
||||
⭐ Star でプロジェクトの更新をフォローしてください。PR や Issue の提出も歓迎します。
|
||||
⭐ Star でプロジェクトを応援し、Watch → Custom → Releases で新バージョンの通知を受け取れます。PR や Issue の提出も歓迎します。
|
||||
|
||||
## 🌟 コントリビューター
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ description: スクリプトによるCowAgentのワンクリックインスト
|
||||
|
||||
本プロジェクトでは、ワンクリックでのインストール、設定、起動、管理を行うスクリプトを提供しています。素早くセットアップするには、スクリプトによるデプロイを推奨します。
|
||||
|
||||
Linux、macOS、Windowsに対応しています。Python 3.7〜3.12が必要です(3.9を推奨)。
|
||||
Linux、macOS、Windowsに対応しています。Python 3.7〜3.13が必要です(3.9を推奨)。
|
||||
|
||||
## インストールコマンド
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ CowAgent のアーキテクチャは以下のコアモジュールで構成さ
|
||||
| **Plan** | ユーザーの意図を理解し、複雑なタスクをマルチステップの計画に分解、目標達成までツールを反復的に呼び出す |
|
||||
| **Memory** | 重要な情報をコアメモリとデイリーメモリとして自動永続化し、キーワードとベクトルのハイブリッド検索でセッション間の連続性を実現 |
|
||||
| **Knowledge** | トピック別に構造化された知識を整理。Agent が価値ある情報を Markdown ページとして自律的に整理し、インデックスと相互参照で成長するナレッジネットワークを構築 |
|
||||
| **Evolution** | 会話がアイドルになった後、隔離環境で自動レビューを実行。Skill を改善し、未完了のタスクを引き継ぎ、記憶と知識を補完して、日々の利用を通じて Agent を成長させる |
|
||||
| **Tools** | Agent が OS リソースにアクセスするための中核能力。ファイル読み書き、ターミナル、ブラウザ、スケジューラ、記憶検索、Web 検索など 10 以上の組み込みツール |
|
||||
| **Skills** | Skill の読み込み・管理。Skill Hub や GitHub からのワンクリックインストール、または会話を通じたカスタム Skill の作成をサポート |
|
||||
| **Models** | モデル層。OpenAI、Claude、Gemini、DeepSeek、MiniMax、GLM、Qwen など主要 LLM への統一アクセスを提供 |
|
||||
@@ -82,4 +83,5 @@ Agent のワークスペースはデフォルトで `~/cow` にあり、シス
|
||||
| `agent_max_context_turns` | 最大コンテキストターン数 | `30` |
|
||||
| `agent_max_steps` | タスクあたりの最大判断ステップ数 | `15` |
|
||||
| `knowledge` | パーソナルナレッジベースの有効化 | `true` |
|
||||
| `self_evolution_enabled` | 自己進化の有効化(新規インストールではデフォルト有効) | `false` |
|
||||
| `cow_lang` | UI・コマンド文言・システムプロンプトなどの言語。`auto` で自動検出、`zh` / `en` も指定可 | `auto` |
|
||||
|
||||
@@ -15,7 +15,13 @@ description: CowAgent の長期記憶、タスク計画、Skill システム、C
|
||||
<img src="https://cdn.link-ai.tech/doc/20260203000455.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
詳細は [長期記憶](/ja/memory) と [Deep Dream](/ja/memory/deep-dream) を参照してください。
|
||||
これに加えて、**自己進化(Self-Evolution)** により Agent は日々の利用を通じて成長し続けます。会話がアイドルになった後に自動でレビューを行い、Skill を改善し、未完了のタスクを引き継ぎ、記憶と知識を補完します。実際に変更があったときのみ簡潔に通知し、変更はいつでも取り消せます。新規インストールではデフォルトで有効です。
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-demo.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
詳細は [長期記憶](/ja/memory)、[Deep Dream](/ja/memory/deep-dream)、[自己進化](/ja/memory/self-evolution) を参照してください。
|
||||
|
||||
## 2. パーソナルナレッジベース
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ CowAgent は自ら思考しタスクを計画し、コンピュータや外部
|
||||
<Card title="ナレッジベース" icon="book" href="/ja/knowledge">
|
||||
構造化された知識を自動整理し、ナレッジグラフの可視化をサポート。相互参照により継続的に成長するナレッジネットワークを構築します。
|
||||
</Card>
|
||||
<Card title="自己進化" icon="seedling" href="/ja/memory/self-evolution">
|
||||
会話の終了後に自動でレビューし、Skill を改善し、未完了のタスクを引き継ぎ、記憶と知識を補完。日々の利用を通じて Agent が成長し続けます。
|
||||
</Card>
|
||||
<Card title="Skill システム" icon="puzzle-piece" href="/ja/skills/index">
|
||||
Skill の作成・実行エンジンを実装し、組み込み Skill を搭載。自然言語の会話を通じてカスタム Skill の開発もサポートしています。
|
||||
</Card>
|
||||
|
||||
78
docs/ja/memory/self-evolution.mdx
Normal file
78
docs/ja/memory/self-evolution.mdx
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: 自律進化
|
||||
description: Self-Evolution — 会話がアイドル状態になった後に振り返り、記憶を蓄積し、スキルを改善し、未完了のタスクに対応する
|
||||
---
|
||||
|
||||
## 機能概要
|
||||
|
||||
### はじめに
|
||||
|
||||
自律進化(Self-Evolution)は、Agent が単発のタスクをこなすだけでなく、あなたとのやり取りを通じて成長し続けられるようにする仕組みです。会話が一段落すると、Agent は静かに振り返りを行います。覚えておくべきことを長期記憶に保存し、スキルで見つかった問題を修正し、やり残したタスクを引き継いで進めます。使い込むほど、Agent はあなたの好みを理解し、同じ失敗を繰り返さなくなり、自分から物事を仕上げるようになります。これらはすべてバックグラウンドで静かに行われ、実際に何かを行ったときだけ簡潔に知らせます。
|
||||
|
||||
> 自律進化は[夢境蒸留](/ja/memory/deep-dream)と補完し合います。夢境蒸留が記憶そのものを整理するのに対し、自律進化はさらに一歩進んでスキルを改善し、未完了のタスクを前に進め、日々の利用を通じて Agent の能力を磨きます。
|
||||
|
||||
### 3 つの目標
|
||||
|
||||
自律進化は次の 3 つを軸に動きます:
|
||||
|
||||
| 目標 | 説明 |
|
||||
| --- | --- |
|
||||
| **記憶の蓄積** | 会話中の重要な好み、決定、事実を記憶に補い、メインの会話の取りこぼしを補完します |
|
||||
| **スキルの改善** | スキルの利用中に問題(設定の誤りや手順の欠落など)が見つかったら、メモを残すだけでなくスキルファイルを直接修正します。必要に応じて新しいスキルも作成します |
|
||||
| **未完了タスクへの対応** | 会話に残ったやるべきことを見つけ、可能なときにその場で完了させます |
|
||||
|
||||
振り返りが終わり、実際に変更を加えた場合は、Agent が「何を学び、どこを調整したか」を会話の中で一言で伝えるので、元に戻すかどうかを判断できます。
|
||||
|
||||
## 使い方
|
||||
|
||||
### トリガーのタイミング
|
||||
|
||||
自律進化は定時実行ではなく、**会話が自然に終わってアイドル状態になった後**にのみ起動するため、進行中のやり取りを妨げることはありません。次の 2 つの条件を同時に満たす必要があります:
|
||||
|
||||
- **会話がアイドル状態**:最後のやり取りから、設定したアイドル時間(デフォルトは 15 分)以上が経過している
|
||||
- **振り返るだけの内容がある**:前回の進化から十分なターン数が蓄積されている、またはコンテキストが容量の上限に近づいている
|
||||
|
||||
両方の条件を満たしたときにのみ振り返りが始まります。これにより、振り返る価値のある内容を確保しつつ、会話の途中で邪魔をしないようにしています。
|
||||
|
||||
### 関連設定
|
||||
|
||||
自律進化は Web コンソールの「設定 → Agent 設定」(「ディープシンキング」の下)にあるスイッチで切り替えられるほか、設定ファイルで調整することもできます:
|
||||
|
||||
| パラメータ | 説明 | デフォルト値 |
|
||||
| --- | --- | --- |
|
||||
| `self_evolution_enabled` | 自律進化を有効にするかどうか(新規インストールはデフォルトで有効) | `false` |
|
||||
| `self_evolution_idle_minutes` | 会話がアイドル状態になってからトリガーするまでの時間(分) | `15` |
|
||||
| `self_evolution_min_turns` | トリガーに必要な最小会話ターン数 | `8` |
|
||||
|
||||
<Tip>
|
||||
Web コンソールでは有効・無効のスイッチのみを提供しています。アイドル時間やターン数のしきい値を変更したい場合は、設定ファイルを編集してください。変更は即時に反映され、再起動は不要です。
|
||||
</Tip>
|
||||
|
||||
### 進化の記録
|
||||
|
||||
各振り返りは日付ごとに `memory/evolution/YYYY-MM-DD.md` に記録され、Web コンソールの「メモリ管理 → 自律進化」タブで確認できます。このタブには自律進化の記録と夢日記の両方がまとめられており、Agent の成長の軌跡を一箇所で振り返ることができます。
|
||||
|
||||
### 元に戻す方法
|
||||
|
||||
ある振り返りの変更に納得できない場合は、会話の中で Agent に「直前の変更を取り消して」と伝えるだけで、振り返り前のバックアップから該当ファイルを復元します。各振り返りはそれぞれ独立したバックアップを持つため、互いに干渉することはありません。
|
||||
|
||||
## 設計
|
||||
|
||||
自律進化はシステムの既存の機能を再利用しており、軽量に保たれています:
|
||||
|
||||
- **隔離実行**:各振り返りは独立した短命のタスクとして実行されます。メインの会話と同じモデルを使いますが、ツールは制限されています(コンテキストの読み取りと、記憶およびスキルファイルの編集のみ可能)。メインの会話のコンテキストを汚さず、その動作にも影響しません。
|
||||
- **バックアップによる取り消し**:振り返り前に該当ファイルのスナップショットを取り、取り消し時にそのスナップショットから復元するため、すべての変更が追跡可能で元に戻せます。
|
||||
- **変更検知**:振り返り後にファイルのスナップショットを比較して実際に変更があったかを確認し、それをもとに通知するかどうかを判断します。これにより「何もしなければ通知しない」ことを仕組みとして保証します。
|
||||
|
||||
### 抑制と安全性
|
||||
|
||||
自律進化は、必要なときに動き、それ以外のときは邪魔をしないように設計されています:
|
||||
|
||||
| 仕組み | 説明 |
|
||||
| --- | --- |
|
||||
| **何もしなければ通知しない** | 振り返りで実際の変更がなければ、静かなままで何も送りません |
|
||||
| **アイドル時のみトリガー** | 会話がアイドル状態になったときだけ実行し、進行中の会話を妨げません |
|
||||
| **変更を元に戻せる** | 振り返りごとに事前にバックアップを取るため、納得できない結果は取り消せます |
|
||||
| **組み込みスキルの保護** | 製品に付属する組み込みスキルは保護され、変更されません |
|
||||
| **ワークスペースに限定** | すべての読み書きはワークスペース内に限定され、他のシステムファイルには触れません |
|
||||
| **バックグラウンド実行** | 振り返りはバックグラウンドで実行され、通常の返信を妨げません |
|
||||
@@ -61,7 +61,7 @@ description: Coding Planモデルの設定
|
||||
```json
|
||||
{
|
||||
"bot_type": "openai",
|
||||
"model": "MiniMax-M2.5",
|
||||
"model": "MiniMax-M3",
|
||||
"open_ai_api_base": "https://api.minimaxi.com/v1",
|
||||
"open_ai_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
@@ -69,7 +69,7 @@ description: Coding Planモデルの設定
|
||||
|
||||
| パラメータ | 説明 |
|
||||
| --- | --- |
|
||||
| `model` | `MiniMax-M2.5`、`MiniMax-M2.5-highspeed`、`MiniMax-M2.1`、`MiniMax-M2` |
|
||||
| `model` | `MiniMax-M3`、`MiniMax-M2.7`、`MiniMax-M2.7-highspeed` |
|
||||
| `open_ai_api_base` | 中国: `https://api.minimaxi.com/v1`、グローバル: `https://api.minimax.io/v1` |
|
||||
| `open_ai_api_key` | Coding Plan専用キー(従量課金とは共有不可) |
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ description: CowAgent がサポートするモデルベンダーと機能マト
|
||||
CowAgent は国内外の主要ベンダーの大規模言語モデルをサポートしており、モデル接続の実装はプロジェクトの `models/` ディレクトリにあります。テキスト対話に加えて、一部のベンダーは画像理解、画像生成、音声認識、音声合成、ベクトルなどの機能も提供しており、Agent フローの中で必要に応じて呼び出すことができます。
|
||||
|
||||
<Note>
|
||||
Agent モードでは、効果とコストのバランスを考慮して以下のモデルの利用を推奨します:deepseek-v4-flash、MiniMax-M2.7、claude-sonnet-4-6、gemini-3.5-flash、glm-5.1、qwen3.6-plus、kimi-k2.6、ernie-5.1。
|
||||
Agent モードでは、効果とコストのバランスを考慮して以下のモデルの利用を推奨します:deepseek-v4-flash、MiniMax-M3、claude-sonnet-4-6、gemini-3.5-flash、glm-5.1、qwen3.7-plus、kimi-k2.6、ernie-5.1。
|
||||
|
||||
同時に [LinkAI](https://link-ai.tech) プラットフォームの API もサポートしており、1 つの Key で複数ベンダーを柔軟に切り替えられ、ナレッジベース、ワークフロー、プラグインなどの機能も付属しています。
|
||||
</Note>
|
||||
@@ -19,12 +19,12 @@ CowAgent は国内外の主要ベンダーの大規模言語モデルをサポ
|
||||
| ベンダー | 代表モデル | テキスト | 画像理解 | 画像生成 | 音声認識 | 音声合成 | ベクトル |
|
||||
| --- | --- | :-: | :-: | :-: | :-: | :-: | :-: |
|
||||
| [DeepSeek](/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [MiniMax](/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [Claude](/models/claude) | claude-opus-4-8 | ✅ | ✅ | | | | |
|
||||
| [Gemini](/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [OpenAI](/models/openai) | gpt-5.5、o シリーズ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Zhipu GLM](/models/glm) | glm-5.1、glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [Tongyi Qianwen](/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Tongyi Qianwen](/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Doubao](/models/doubao) | doubao-seed-2.0 シリーズ | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [Baidu Qianfan](/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
|
||||
@@ -40,7 +40,7 @@ description: LinkAI プラットフォーム経由でテキスト、ビジョン
|
||||
}
|
||||
```
|
||||
|
||||
選択可能なモデル:`gpt-4.1-mini`、`gpt-5.4-mini`、`qwen3.6-plus`、`doubao-seed-2-0-pro-260215`、`kimi-k2.6`、`claude-sonnet-4-6`、`gemini-3.1-flash-lite-preview` など。
|
||||
選択可能なモデル:`gpt-4.1-mini`、`gpt-5.4-mini`、`qwen3.7-plus`、`doubao-seed-2-0-pro-260215`、`kimi-k2.6`、`claude-sonnet-4-6`、`gemini-3.1-flash-lite-preview` など。
|
||||
|
||||
## 画像生成
|
||||
|
||||
|
||||
@@ -13,14 +13,14 @@ MiniMax はテキスト対話、画像理解、画像生成、音声合成をサ
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "MiniMax-M2.7",
|
||||
"model": "MiniMax-M3",
|
||||
"minimax_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| パラメータ | 説明 |
|
||||
| --- | --- |
|
||||
| `model` | `MiniMax-M2.7`、`MiniMax-M2.7-highspeed`、`MiniMax-M2.5`、`MiniMax-M2.1`、`MiniMax-M2.1-lightning`、`MiniMax-M2` などを指定可能 |
|
||||
| `model` | `MiniMax-M3`、`MiniMax-M2.7`、`MiniMax-M2.7-highspeed` などを指定可能 |
|
||||
| `minimax_api_key` | [MiniMax コンソール](https://platform.minimaxi.com/user-center/basic-information/interface-key) で作成 |
|
||||
|
||||
## 画像理解
|
||||
|
||||
@@ -13,19 +13,19 @@ Tongyi Qianwen(DashScope / Bailian)は国内で最も広範な機能をカ
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "qwen3.6-plus",
|
||||
"model": "qwen3.7-plus",
|
||||
"dashscope_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| パラメータ | 説明 |
|
||||
| --- | --- |
|
||||
| `model` | `qwen3.6-plus`、`qwen3.7-max`、`qwen3.5-plus`、`qwen3-max`、`qwen-max`、`qwen-plus`、`qwen-turbo`、`qwq-plus` などを指定可能 |
|
||||
| `model` | `qwen3.7-plus`、`qwen3.7-max`、`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`、`qwen-max`、`qwen-plus`、`qwen-turbo`、`qwq-plus` などを指定可能 |
|
||||
| `dashscope_api_key` | [Bailian コンソール](https://bailian.console.aliyun.com/?tab=model#/api-key) で作成。詳細は [公式ドキュメント](https://bailian.console.aliyun.com/?tab=api#/api) を参照 |
|
||||
|
||||
## 画像理解
|
||||
|
||||
`dashscope_api_key` を設定すると、Agent の Vision ツールは自動的に Qwen のビジョンモデルを呼び出して画像を認識します。`qwen3-max` / `qwen3.5-plus` / `qwen3.6-plus` などのモデルはそのままマルチモーダルです。メインモデルがテキスト専用(`qwen-turbo` など)の場合は、自動的に `qwen-vl-max` にフォールバックします。
|
||||
`dashscope_api_key` を設定すると、Agent の Vision ツールは自動的に Qwen のビジョンモデルを呼び出して画像を認識します。`qwen3.7-plus` / `qwen3.6-plus` / `qwen3.5-plus` / `qwen3-max` などのモデルはそのままマルチモーダルです。メインモデルがテキスト専用(`qwen-turbo` など)の場合は、自動的に `qwen-vl-max` にフォールバックします。
|
||||
|
||||
Vision モデルを手動で指定したい場合:
|
||||
|
||||
@@ -33,13 +33,13 @@ Vision モデルを手動で指定したい場合:
|
||||
{
|
||||
"tools": {
|
||||
"vision": {
|
||||
"model": "qwen3.6-plus"
|
||||
"model": "qwen3.7-plus"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
サポートするモデル:`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`。
|
||||
サポートするモデル:`qwen3.7-plus`、`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`。
|
||||
|
||||
## 画像生成
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ description: CowAgent バージョン更新履歴
|
||||
|
||||
| バージョン | 日付 | 説明 |
|
||||
| --- | --- | --- |
|
||||
| [2.1.1](/ja/releases/v2.1.1) | 2026.06.09 | 自己進化、Web コンソールの強化(メッセージ管理、マルチセッション並行)、クロスプラットフォーム対応の MCP 強化と並行呼び出し、新モデル追加(MiniMax-M3、qwen3.7-plus など)、各種改善 |
|
||||
| [2.1.0](/ja/releases/v2.1.0) | 2026.06.01 | 国際化対応、Telegram / Discord / Slack / WeChat カスタマーサービスチャネルの追加、CLI インタラクション強化(ストリーミング出力、コマンドあいまいマッチング、タスクキャンセル)、MCP Streamable HTTP、新モデル追加 |
|
||||
| [2.0.9](/ja/releases/v2.0.9) | 2026.05.22 | モデル管理機能の追加、MCP プロトコル対応、ブラウザログイン状態の永続化、新モデル追加(gpt-5.5、gemini-3.5-flash、qwen3.7-max など)、デプロイ・セキュリティ強化 |
|
||||
| [2.0.8](/ja/releases/v2.0.8) | 2026.05.06 | Feishu チャネル全面アップグレード(音声、ストリーミング出力と Markdown、QR コードによるワンクリック接続)、DeepSeek V4 と百度モデルの追加、スケジュールタスクツールの強化 |
|
||||
|
||||
61
docs/ja/releases/v2.1.1.mdx
Normal file
61
docs/ja/releases/v2.1.1.mdx
Normal file
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: v2.1.1
|
||||
description: CowAgent 2.1.1 - 自己進化、Web コンソールのメッセージ管理とマルチセッション並行、クロスプラットフォーム対応の MCP 強化、新モデルと改善
|
||||
---
|
||||
|
||||
🌐 [English](https://docs.cowagent.ai/releases/v2.1.1) | [中文](https://docs.cowagent.ai/zh/releases/v2.1.1)
|
||||
|
||||
## 🧬 自己進化
|
||||
|
||||
CowAgent に **自己進化(Self-Evolution)** が加わりました。Agent は単発のタスクをこなすだけでなく、日々の協働を通じて成長し続けます:
|
||||
|
||||
- **アイドル後の自動レビュー**:会話がアイドルになると、Agent はバックグラウンドでその会話をレビューし、使用中に表面化した Skill の問題を修正し、再利用可能な新しい Skill を作成し、未完了のタスクを引き継ぎ、重要な情報を記憶とナレッジベースに記録します
|
||||
- **静かに実行、必要なときだけ通知**:実際に変更があったときのみ調整内容を一言で伝え、変更がなければ何も通知しません
|
||||
- **安全で取り消し可能**:レビューのたびに事前にバックアップを取り、いつでも取り消せます。組み込み Skill は保護され、すべての読み書きはワークスペース内に限定されます
|
||||
|
||||
新規インストールではデフォルトで有効です。既存ユーザーは Web コンソールの **設定 → Agent 設定** からワンクリックで有効化できます。
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-demo.png" alt="自己進化の会話例" />
|
||||
|
||||
ドキュメント:[自己進化](https://docs.cowagent.ai/ja/memory/self-evolution)
|
||||
|
||||
## 💬 Web コンソールの強化
|
||||
|
||||
Web コンソールのチャット体験がさらに強化され、主要なチャット製品に近い操作感になりました:
|
||||
|
||||
- **メッセージ管理**:ユーザーと Bot のメッセージを編集・削除・再生成できます。コードブロックに言語ラベルとワンクリックコピーボタンを追加。Thanks [@core-power](https://github.com/core-power) (#2865)
|
||||
- **マルチセッション並行**:複数のセッションを同時に実行しても互いに干渉せず、セッションに戻るとライブストリーミングが自動的に再開されます
|
||||
- **細部の改善**:チャット画面のどこにでもファイルをドラッグ&ドロップ可能。アクティブなセッションを削除すると隣接セッションへ自動で切り替わります
|
||||
|
||||
## 🧩 クロスプラットフォーム対応の MCP 強化
|
||||
|
||||
- **Windows 互換性の修正**:Windows で `stdio` 通信が動作しない問題を修正し、サーバーのタイムアウトを `mcp.json` で設定できるようにしました
|
||||
- **並行呼び出し**:`sse` と `streamable-http` トランスポートがセッション間の並行呼び出しに対応し、複数ツールの応答が高速化されました
|
||||
|
||||
Thanks [@xliu123321](https://github.com/xliu123321) (#2859)
|
||||
|
||||
ドキュメント:[MCP ツール](https://docs.cowagent.ai/ja/tools/mcp)
|
||||
|
||||
## 🤖 新モデルと改善
|
||||
|
||||
- **MiniMax-M3**:追加してデフォルトモデルに設定(M2.7 シリーズはオプションとして継続)。Thanks [@octo-patch](https://github.com/octo-patch) (#2855)
|
||||
- **Qwen3.7-plus**:マルチモーダル対話に対応
|
||||
- **ASR モデルの選択**:Web コンソールで ASR(音声認識)モデルを選択して永続化できるようになりました。Thanks [@nightwhite](https://github.com/nightwhite) (#2857)
|
||||
- **インストールメニューの簡素化**:ワンライナーインストールスクリプトのモデルメニューを簡素化し、Xiaomi MiMo オプションを追加
|
||||
|
||||
ドキュメント:[モデル概要](https://docs.cowagent.ai/ja/models)
|
||||
|
||||
## 🛠 改善と修正
|
||||
|
||||
- **Python 3.13 対応**:Python 3.13 環境でのインストールと依存関係の互換性を修正
|
||||
- **国際化**:チャネル一覧を UI の言語順に表示。`auto` モードでの言語自動フォールバックを改善
|
||||
- **より確実なキャンセル**:ストリーミング応答を中断できない場合がある問題を修正
|
||||
- **CLI**:`cow status` に現在のプロジェクトパスを表示
|
||||
- **デプロイのセキュリティ強化**:認証ファイルのブロック範囲を `~/.cow/.env` に限定し、他のディレクトリに影響しないように修正(Thanks [@orbisai0security](https://github.com/orbisai0security) #2863)。WeChat 公式アカウントは `wechatmp_token` が空の場合に Webhook リクエストを拒否します
|
||||
- **グループタスクボードプラグイン**:グループタスクボードプラグインのソースを追加。Thanks [@Wyh-max-star](https://github.com/Wyh-max-star) (#2853)
|
||||
|
||||
## 📦 アップグレード
|
||||
|
||||
ソースコードでデプロイしている場合は `cow update` でワンクリックアップグレードするか、最新コードを取得して手動で再起動してください。詳細は [アップグレードガイド](https://docs.cowagent.ai/ja/guide/upgrade) を参照してください。
|
||||
|
||||
**リリース日**:2026.06.09 | [Full Changelog](https://github.com/zhayujie/CowAgent/compare/2.1.0...2.1.1)
|
||||
@@ -19,7 +19,7 @@ Vision ツールは多段階の自動選択 + 自動フォールバック戦略
|
||||
| プロバイダー | ビジョンモデル | 説明 |
|
||||
| --- | --- | --- |
|
||||
| OpenAI / 互換プロトコル | メインモデルを使用 | すべての OpenAI 互換マルチモーダルモデルに対応 |
|
||||
| 通義千問 (DashScope) | メインモデルを使用 | 例:qwen3.6-plus など |
|
||||
| 通義千問 (DashScope) | メインモデルを使用 | 例:qwen3.7-plus など |
|
||||
| Claude | メインモデルを使用 | Anthropic ネイティブ画像形式 |
|
||||
| Gemini | メインモデルを使用 | inlineData 形式 |
|
||||
| 豆包 (Doubao) | メインモデルを使用 | doubao-seed-2-0 シリーズがネイティブ対応 |
|
||||
|
||||
90
docs/memory/self-evolution.mdx
Normal file
90
docs/memory/self-evolution.mdx
Normal file
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Self-Evolution
|
||||
description: Self-Evolution — review a conversation after it goes idle to consolidate memory, improve skills, and follow up on unfinished tasks
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
### Introduction
|
||||
|
||||
Self-Evolution lets the Agent do more than finish one task at a time; it keeps improving as it works with you. After a conversation winds down, it quietly reviews what just happened: it saves anything worth remembering into long-term memory, fixes problems that surfaced in a skill, and picks up tasks that were left unfinished. Over time the Agent learns your preferences, repeats fewer mistakes, and gets better at wrapping things up on its own. All of this runs in the background, and it only tells you when it actually did something.
|
||||
|
||||
> Self-Evolution complements [Deep Dream](/memory/deep-dream). Deep Dream organizes memory itself, while Self-Evolution goes a step further to improve skills and push unfinished tasks forward, sharpening the Agent's abilities through everyday use.
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-demo.png" alt="Self-Evolution in a conversation" />
|
||||
</Frame>
|
||||
|
||||
### Three Goals
|
||||
|
||||
Self-Evolution focuses on three things:
|
||||
|
||||
| Goal | Description |
|
||||
| --- | --- |
|
||||
| **Consolidate memory** | Record important preferences, decisions, and facts from the conversation, filling in what the main chat may have missed |
|
||||
| **Improve skills** | ① When a skill shows a problem in use (such as a wrong setting or a missing step), fix the skill file directly; ② when a reusable workflow emerges, turn it into a new skill so it can be reused next time |
|
||||
| **Follow up on unfinished tasks** | Spot the to-dos left in a conversation and finish them when possible |
|
||||
|
||||
Once a review is done, if it actually changed something, the Agent tells you in a single line what it just learned and what it adjusted, so you can decide whether to roll it back.
|
||||
|
||||
## Usage
|
||||
|
||||
### When It Triggers
|
||||
|
||||
Self-Evolution does not run on a fixed schedule. It only kicks in **after a conversation naturally ends and goes idle**, so it never interrupts an ongoing exchange. Two conditions must both hold:
|
||||
|
||||
- **The conversation is idle**: more time has passed since the last interaction than the configured idle window (15 minutes by default)
|
||||
- **There is enough to review**: enough turns have accumulated since the last evolution, or the context is close to its capacity
|
||||
|
||||
Only when both are met does a review begin. This makes sure there is something worth reviewing while keeping it from bothering you mid-conversation.
|
||||
|
||||
### Configuration
|
||||
|
||||
You can toggle Self-Evolution in the Web console under **Settings → Agent Config** (below "Deep Thinking"), or adjust it in the config file:
|
||||
|
||||
| Parameter | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `self_evolution_enabled` | Whether Self-Evolution is enabled (on by default for new installs) | `false` |
|
||||
| `self_evolution_idle_minutes` | How long the conversation must be idle before it triggers (minutes) | `15` |
|
||||
| `self_evolution_min_turns` | Minimum conversation turns required to trigger | `8` |
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-config.png" alt="Enable Self-Evolution in the Web console" />
|
||||
</Frame>
|
||||
|
||||
<Tip>
|
||||
The Web console only exposes the on/off toggle. To change the idle window or the turn threshold, edit the config file. Changes take effect immediately, with no restart needed.
|
||||
</Tip>
|
||||
|
||||
### Evolution Records
|
||||
|
||||
Each review is recorded by date in `memory/evolution/YYYY-MM-DD.md`, viewable in the Web console under the **Memory → Self-Evolution** tab. That tab gathers both self-evolution records and dream diaries in one place, so you can look back on how the Agent has grown.
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-logs.png" alt="Self-Evolution records list" />
|
||||
</Frame>
|
||||
|
||||
### Rolling Back
|
||||
|
||||
If you disagree with a change from a review, just tell the Agent in chat to undo the last change. It restores the affected files from the backup taken before the review. Every review keeps its own backup, so they never interfere with each other.
|
||||
|
||||
## Design
|
||||
|
||||
Self-Evolution reuses what the system already has, which keeps it lightweight:
|
||||
|
||||
- **Isolated execution**: each review runs as a separate, short-lived task. It uses the same model as the main chat but with a restricted toolset (it can only read context and edit memory and skill files). It does not pollute the main chat's context or affect its performance.
|
||||
- **Backup-based undo**: the relevant files are snapshotted before a review and restored from that snapshot on undo, so every change is traceable and reversible.
|
||||
- **Change detection**: after a review, the system compares file snapshots to see whether anything actually changed, and uses that to decide whether to notify you. This is how it guarantees, at the engineering level, that no work means no message.
|
||||
|
||||
### Restraint and Safety
|
||||
|
||||
Self-Evolution is built to act when needed and stay out of the way otherwise:
|
||||
|
||||
| Mechanism | Description |
|
||||
| --- | --- |
|
||||
| **No work, no notification** | If a review produces no real change, it stays silent and sends nothing |
|
||||
| **Triggers only when idle** | It runs only after the conversation is idle, never interrupting an active one |
|
||||
| **Reversible changes** | A backup is taken before every review, so you can undo a result you do not like |
|
||||
| **Built-in skills protected** | The skills shipped with the product are protected and never modified |
|
||||
| **Workspace-scoped** | All reads and writes stay inside the workspace and never touch other system files |
|
||||
| **Runs in the background** | Reviews run in the background and do not block normal replies |
|
||||
@@ -61,7 +61,7 @@ Reference: [Quick Start](https://help.aliyun.com/zh/model-studio/coding-plan-qui
|
||||
```json
|
||||
{
|
||||
"bot_type": "openai",
|
||||
"model": "MiniMax-M2.5",
|
||||
"model": "MiniMax-M3",
|
||||
"open_ai_api_base": "https://api.minimaxi.com/v1",
|
||||
"open_ai_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
@@ -69,7 +69,7 @@ Reference: [Quick Start](https://help.aliyun.com/zh/model-studio/coding-plan-qui
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `model` | `MiniMax-M2.5`, `MiniMax-M2.5-highspeed`, `MiniMax-M2.1`, `MiniMax-M2` |
|
||||
| `model` | `MiniMax-M3`, `MiniMax-M2.7`, `MiniMax-M2.7-highspeed` |
|
||||
| `open_ai_api_base` | China: `https://api.minimaxi.com/v1`; Global: `https://api.minimax.io/v1` |
|
||||
| `open_ai_api_key` | Coding Plan specific key (not shared with pay-as-you-go) |
|
||||
|
||||
|
||||
@@ -12,12 +12,12 @@ A snapshot of each vendor's capabilities. "Text" refers to the main chat model;
|
||||
| Vendor | Representative Models | Text | Vision | Image Gen | STT | TTS | Embedding |
|
||||
| --- | --- | :-: | :-: | :-: | :-: | :-: | :-: |
|
||||
| [DeepSeek](/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [MiniMax](/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [Claude](/models/claude) | claude-opus-4-8 | ✅ | ✅ | | | | |
|
||||
| [Gemini](/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [OpenAI](/models/openai) | gpt-5.5, o-series | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [GLM](/models/glm) | glm-5.1, glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [Qwen](/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Qwen](/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [Doubao](/models/doubao) | doubao-seed-2.0 series | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [ERNIE](/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
|
||||
@@ -40,7 +40,7 @@ Once configured, the Agent's Vision tool automatically calls multimodal models v
|
||||
}
|
||||
```
|
||||
|
||||
Available models: `gpt-4.1-mini`, `gpt-5.4-mini`, `qwen3.6-plus`, `doubao-seed-2-0-pro-260215`, `kimi-k2.6`, `claude-sonnet-4-6`, `gemini-3.1-flash-lite-preview`, etc.
|
||||
Available models: `gpt-4.1-mini`, `gpt-5.4-mini`, `qwen3.7-plus`, `doubao-seed-2-0-pro-260215`, `kimi-k2.6`, `claude-sonnet-4-6`, `gemini-3.1-flash-lite-preview`, etc.
|
||||
|
||||
## Image Generation
|
||||
|
||||
|
||||
@@ -13,14 +13,14 @@ MiniMax supports text chat, image understanding, image generation, and text-to-s
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "MiniMax-M2.7",
|
||||
"model": "MiniMax-M3",
|
||||
"minimax_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `model` | Can be `MiniMax-M2.7`, `MiniMax-M2.7-highspeed`, `MiniMax-M2.5`, `MiniMax-M2.1`, `MiniMax-M2.1-lightning`, `MiniMax-M2`, etc. |
|
||||
| `model` | Can be `MiniMax-M3`, `MiniMax-M2.7`, `MiniMax-M2.7-highspeed`, etc. |
|
||||
| `minimax_api_key` | Create one in the [MiniMax Console](https://platform.minimaxi.com/user-center/basic-information/interface-key) |
|
||||
|
||||
## Image Understanding
|
||||
|
||||
@@ -13,19 +13,19 @@ Qwen (Alibaba DashScope / Bailian) is one of the most fully-featured vendors. Te
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "qwen3.6-plus",
|
||||
"model": "qwen3.7-plus",
|
||||
"dashscope_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `model` | Can be `qwen3.6-plus`, `qwen3.7-max`, `qwen3.5-plus`, `qwen3-max`, `qwen-max`, `qwen-plus`, `qwen-turbo`, `qwq-plus`, etc. |
|
||||
| `model` | Can be `qwen3.7-plus`, `qwen3.7-max`, `qwen3.6-plus`, `qwen3.5-plus`, `qwen3-max`, `qwen-max`, `qwen-plus`, `qwen-turbo`, `qwq-plus`, etc. |
|
||||
| `dashscope_api_key` | Create one in the [Bailian Console](https://bailian.console.aliyun.com/?tab=model#/api-key); see the [official docs](https://bailian.console.aliyun.com/?tab=api#/api) |
|
||||
|
||||
## Image Understanding
|
||||
|
||||
Once `dashscope_api_key` is configured, the Agent's Vision tool automatically calls Qwen's vision models to recognize images. Models like `qwen3-max` / `qwen3.5-plus` / `qwen3.6-plus` are already multimodal; if the main model is text-only (e.g. `qwen-turbo`), it automatically falls back to `qwen-vl-max`.
|
||||
Once `dashscope_api_key` is configured, the Agent's Vision tool automatically calls Qwen's vision models to recognize images. Models like `qwen3.7-plus` / `qwen3.6-plus` / `qwen3.5-plus` / `qwen3-max` are already multimodal; if the main model is text-only (e.g. `qwen-turbo`), it automatically falls back to `qwen-vl-max`.
|
||||
|
||||
To manually specify a Vision model:
|
||||
|
||||
@@ -33,13 +33,13 @@ To manually specify a Vision model:
|
||||
{
|
||||
"tools": {
|
||||
"vision": {
|
||||
"model": "qwen3.6-plus"
|
||||
"model": "qwen3.7-plus"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Supported models: `qwen3.6-plus`, `qwen3.5-plus`, `qwen3-max`.
|
||||
Supported models: `qwen3.7-plus`, `qwen3.6-plus`, `qwen3.5-plus`, `qwen3-max`.
|
||||
|
||||
## Image Generation
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ description: CowAgent version history
|
||||
|
||||
| Version | Date | Description |
|
||||
| --- | --- | --- |
|
||||
| [2.1.1](/releases/v2.1.1) | 2026.06.09 | Self-Evolution, Web Console message management and parallel sessions, cross-platform MCP enhancements with concurrent calls, new models (MiniMax-M3, qwen3.7-plus, etc.), various improvements |
|
||||
| [2.1.0](/releases/v2.1.0) | 2026.06.01 | Internationalization, new Telegram / Discord / Slack / WeChat Customer Service channels, CLI interaction upgrades (streaming output, fuzzy command matching, task cancellation), MCP Streamable HTTP, new models |
|
||||
| [2.0.9](/releases/v2.0.9) | 2026.05.22 | Model management console, MCP protocol support, browser persistent login, new models (gpt-5.5, gemini-3.5-flash, qwen3.7-max, etc.), deployment hardening |
|
||||
| [2.0.8](/releases/v2.0.8) | 2026.05.06 | Major Feishu channel upgrade (voice, streaming and Markdown, one-click QR-scan setup), DeepSeek V4 and Baidu models, scheduler tool enhancements |
|
||||
|
||||
63
docs/releases/v2.1.1.mdx
Normal file
63
docs/releases/v2.1.1.mdx
Normal file
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: v2.1.1
|
||||
description: CowAgent 2.1.1 - Self-Evolution, Web Console message management and parallel sessions, cross-platform MCP enhancements, new models and improvements
|
||||
---
|
||||
|
||||
🌐 [English](https://docs.cowagent.ai/releases/v2.1.1) | [中文](https://docs.cowagent.ai/zh/releases/v2.1.1)
|
||||
|
||||
## 🧬 Self-Evolution
|
||||
|
||||
CowAgent introduces **Self-Evolution**, letting the agent go beyond completing a single task and keep improving through everyday collaboration with you:
|
||||
|
||||
- **Automatic review after idle**: Once a conversation goes idle, the agent reviews it in the background to fix problems a skill exposed in use, create reusable new skills, follow up on unfinished tasks, and record important information into memory and the knowledge base
|
||||
- **Silent by default, notify on demand**: It reports what it changed only when it actually made a change, and stays silent otherwise
|
||||
- **Safe and reversible**: Every review is backed up beforehand and can be undone at any time. Built-in skills are protected, and all reads and writes stay within the workspace
|
||||
|
||||
Enabled by default for new installs. Existing users can turn it on with a single click in the Web Console under **Settings → Agent Config**.
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/en/web-console-evolution-demo.png" alt="Self-Evolution conversation example" />
|
||||
|
||||
Documentation: [Self-Evolution](https://docs.cowagent.ai/memory/self-evolution)
|
||||
|
||||
## 💬 Web Console Upgrades
|
||||
|
||||
The Web Console chat experience gets several enhancements:
|
||||
|
||||
- **Message management**: Edit, delete, and regenerate both user and bot messages; code blocks now include language labels and a one-click copy button
|
||||
- **Parallel sessions**: Run multiple sessions at the same time without interference, with live streaming automatically resumed when you switch back to a session
|
||||
- **Refinements**: Drag and drop files anywhere in the chat view; automatically switch to a sibling session after deleting the active one
|
||||
|
||||
Thanks [@core-power](https://github.com/core-power) (#2865)
|
||||
|
||||
## 🧩 Cross-platform MCP Enhancements
|
||||
|
||||
- **Windows compatibility fix**: Fixed `stdio` communication failing on Windows, and made the server timeout configurable via `mcp.json`
|
||||
- **Concurrent calls**: The `sse` and `streamable-http` transports now support concurrent calls across sessions for faster multi-tool responses
|
||||
|
||||
Thanks [@xliu123321](https://github.com/xliu123321) (#2859)
|
||||
|
||||
Documentation: [MCP Tools](https://docs.cowagent.ai/tools/mcp)
|
||||
|
||||
## 🤖 New Models & Improvements
|
||||
|
||||
- **MiniMax-M3**: Added and set as the default model, with the M2.7 series kept as an option. Thanks [@octo-patch](https://github.com/octo-patch) (#2855)
|
||||
- **Qwen3.7-plus**: Added support for multi-modal conversations
|
||||
- **Selectable ASR model**: The Web Console can now select and persist the ASR (speech recognition) model. Thanks [@nightwhite](https://github.com/nightwhite) (#2857)
|
||||
- **Simplified install menu**: The one-line install script streamlines the model menu and adds the Xiaomi MiMo option
|
||||
|
||||
Documentation: [Models Overview](https://docs.cowagent.ai/models)
|
||||
|
||||
## 🛠 Improvements & Fixes
|
||||
|
||||
- **Python 3.13 support**: Fixed installation and dependency compatibility on Python 3.13
|
||||
- **Internationalization**: The channel list is now ordered by the interface language; refined the automatic language fallback under `auto` mode
|
||||
- **More reliable cancellation**: Fixed cases where a streaming reply could not be interrupted
|
||||
- **CLI**: `cow status` now shows the current project path
|
||||
- **Hardened deployment security**: The credential-file block is narrowed to `~/.cow/.env` so other directories are no longer affected (Thanks [@orbisai0security](https://github.com/orbisai0security) #2863); the WeChat Official Account now rejects webhook requests when `wechatmp_token` is empty
|
||||
- **Group task board plugin**: Added the group task board plugin source. Thanks [@Wyh-max-star](https://github.com/Wyh-max-star) (#2853)
|
||||
|
||||
## 📦 Upgrade
|
||||
|
||||
Source-code deployments can run `cow update` for a one-click upgrade, or pull the latest code and restart manually. See the [Upgrade Guide](https://docs.cowagent.ai/guide/upgrade) for details.
|
||||
|
||||
**Release Date**: 2026.06.09 | [Full Changelog](https://github.com/zhayujie/CowAgent/compare/2.1.0...2.1.1)
|
||||
@@ -19,7 +19,7 @@ If the current provider fails, the tool automatically tries the next one until i
|
||||
| Provider | Vision Model | Notes |
|
||||
| --- | --- | --- |
|
||||
| OpenAI / Compatible | Main model | All OpenAI-protocol-compatible multimodal models |
|
||||
| Qwen (DashScope) | Main model | e.g. qwen3.6-plus, etc. |
|
||||
| Qwen (DashScope) | Main model | e.g. qwen3.7-plus, etc. |
|
||||
| Claude | Main model | Anthropic native image format |
|
||||
| Gemini | Main model | inlineData format |
|
||||
| Doubao | Main model | doubao-seed-2-0 series natively supported |
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
<p align="center"><img src= "https://github.com/user-attachments/assets/eca9a9ec-8534-4615-9e0f-96c5ac1d10a3" alt="CowAgent" width="420" /></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/github/license/zhayujie/CowAgent" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square" alt="Stars"></a> <br/>
|
||||
<a href="https://github.com/zhayujie/CowAgent/releases/latest"><img src="https://img.shields.io/github/v/release/zhayujie/CowAgent?cacheSeconds=3600" alt="Latest release"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT"></a>
|
||||
<a href="https://github.com/zhayujie/CowAgent"><img src="https://img.shields.io/github/stars/zhayujie/CowAgent?style=flat-square&cacheSeconds=3600" alt="Stars"></a>
|
||||
<a href="https://docs.cowagent.ai/zh"><img src="https://img.shields.io/badge/%E6%96%87%E6%A1%A3-cowagent.ai-blue?style=flat&logo=readthedocs&logoColor=white" alt="文档"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://trendshift.io/repositories/25763" target="_blank"><img src="https://trendshift.io/api/badge/repositories/25763" alt="zhayujie%2FCowAgent | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
[<a href="../../README.md">English</a>] | [中文] | [<a href="../ja/README.md">日本語</a>]
|
||||
</p>
|
||||
|
||||
**CowAgent** 是一个开源的超级 AI 助理,能够主动思考和规划任务、操作计算机和外部资源、创造和执行 Skills、构建知识库与长期记忆,与你一同成长,是 Agent Harness 工程的最佳实践之一。
|
||||
**CowAgent** 是一个开源的超级 AI 助理,能够主动思考和规划任务、操作计算机和外部资源、创造和执行 Skills、构建知识库与长期记忆、通过自主进化与你一同成长,是 Agent Harness 工程的最佳实践之一。
|
||||
|
||||
CowAgent 轻量、易部署、可扩展,自由接入主流大模型,覆盖微信、飞书、钉钉、企微、QQ、Telegram、Slack、网页等多渠道,7×24 运行于个人电脑或服务器中。
|
||||
|
||||
@@ -28,6 +36,7 @@ CowAgent 轻量、易部署、可扩展,自由接入主流大模型,覆盖
|
||||
| [任务规划](https://docs.cowagent.ai/zh/intro/architecture) | 理解复杂任务并自主分解执行,循环调用工具直到完成目标 |
|
||||
| [长期记忆](https://docs.cowagent.ai/zh/memory) | 三层记忆架构(上下文 → 天级 → 核心),梦境蒸馏自动整理,支持关键词与向量混合检索 |
|
||||
| [知识库](https://docs.cowagent.ai/zh/knowledge) | 自动整理结构化知识为 Markdown Wiki,构建持续增长的知识图谱,可视化浏览 |
|
||||
| [自主进化](https://docs.cowagent.ai/zh/memory/self-evolution) | 自动复盘对话,优化技能、处理未完成事项、沉淀记忆与知识,在使用中持续成长 |
|
||||
| [技能](https://docs.cowagent.ai/zh/skills) | 从 [Skill Hub](https://skills.cowagent.ai/)、GitHub、ClawHub 等一键安装;也可通过对话创造自定义技能 |
|
||||
| [工具](https://docs.cowagent.ai/zh/tools) | 内置文件读写、终端、浏览器、定时任务、记忆检索、联网搜索等 10+ 工具,支持 MCP 协议 |
|
||||
| [通道](https://docs.cowagent.ai/zh/channels) | 一个 Agent 同时接入 Web、微信、飞书、钉钉、企微、QQ、公众号、Telegram、Slack 等多个渠道 |
|
||||
@@ -95,12 +104,12 @@ CowAgent 支持国内外主流厂商的大语言模型。**文本对话、图像
|
||||
| 厂商 | 代表模型 | 文本 | 图像理解 | 图像生成 | 语音识别 | 语音合成 | 向量 |
|
||||
| --- | --- | :-: | :-: | :-: | :-: | :-: | :-: |
|
||||
| [DeepSeek](https://docs.cowagent.ai/zh/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [MiniMax](https://docs.cowagent.ai/zh/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](https://docs.cowagent.ai/zh/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [Claude](https://docs.cowagent.ai/zh/models/claude) | claude-opus-4-8 | ✅ | ✅ | | | | |
|
||||
| [Gemini](https://docs.cowagent.ai/zh/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [OpenAI](https://docs.cowagent.ai/zh/models/openai) | gpt-5.5、o 系列 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [智谱 GLM](https://docs.cowagent.ai/zh/models/glm) | glm-5.1、glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [通义千问](https://docs.cowagent.ai/zh/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [通义千问](https://docs.cowagent.ai/zh/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [豆包 Doubao](https://docs.cowagent.ai/zh/models/doubao) | doubao-seed-2.0 系列 | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](https://docs.cowagent.ai/zh/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [百度ERNIE](https://docs.cowagent.ai/zh/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
@@ -191,6 +200,8 @@ CowAgent 支持国内外主流厂商的大语言模型。**文本对话、图像
|
||||
|
||||
## 🏷 更新日志
|
||||
|
||||
> **2026.06.09:** [v2.1.1](https://github.com/zhayujie/CowAgent/releases/tag/2.1.1) — 自进化能力、Web 控制台升级(消息管理、多会话并行)、新模型接入(MiniMax-M3、qwen3.7-plus)、Python 3.13 支持
|
||||
|
||||
> **2026.06.01:** [v2.1.0](https://github.com/zhayujie/CowAgent/releases/tag/2.1.0) — 国际化支持、新增通道(Telegram、Discord、Slack、微信客服)、命令行交互升级、一键安装脚本优化、MCP Streamable HTTP 支持、新模型接入(claude-opus-4-8、MiMo)
|
||||
|
||||
> **2026.05.22:** [v2.0.9](https://github.com/zhayujie/CowAgent/releases/tag/2.0.9) — 模型管理、MCP 协议支持、浏览器登录态持久化、新模型接入(gpt-5.5、gemini-3.5-flash、qwen3.7-max)、部署安全加固
|
||||
@@ -250,9 +261,9 @@ CowAgent 支持国内外主流厂商的大语言模型。**文本对话、图像
|
||||
|
||||
## 🛠️ 开发与贡献
|
||||
|
||||
欢迎接入更多应用通道,参考 [飞书通道实现](https://github.com/zhayujie/CowAgent/blob/master/channel/feishu/feishu_channel.py) 新增自定义通道;同时欢迎贡献新技能,向 [Skill Hub](https://skills.cowagent.ai/submit) 提交。
|
||||
欢迎各种形式的贡献:新功能、Bug 修复、性能优化、文档完善,或向 [Skill Hub](https://skills.cowagent.ai/submit) 分享你的技能。请先阅读 [CONTRIBUTING.md](/CONTRIBUTING.md) 了解如何开始,然后提交 Issue 讨论或直接发起 PR。
|
||||
|
||||
通过 ⭐ Star 关注项目更新,欢迎提交 PR、Issue 进行反馈。
|
||||
欢迎 ⭐ Star 支持项目,并通过 Watch → Custom → Releases 订阅新版本通知。也欢迎提交 PR、Issue 进行反馈。
|
||||
|
||||
## 🌟 贡献者
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ description: 查看状态、管理配置和上下文等常用命令
|
||||
Process: PID 12345 | Running 2h 15m
|
||||
Version: 2.0.4
|
||||
Channel: web
|
||||
Model: MiniMax-M2.5
|
||||
Model: MiniMax-M3
|
||||
Mode: agent
|
||||
|
||||
Session: 12 messages | 8 skills loaded
|
||||
|
||||
@@ -75,7 +75,7 @@ cow status
|
||||
Status: ● Running (PID: 12345)
|
||||
Version: 2.0.4
|
||||
Channel: web
|
||||
Model: MiniMax-M2.5
|
||||
Model: MiniMax-M3
|
||||
Mode: agent
|
||||
```
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ description: 使用脚本一键安装和管理 CowAgent
|
||||
|
||||
项目提供了一键安装、配置、启动、管理程序的脚本,推荐使用脚本快速运行。
|
||||
|
||||
支持 Linux、macOS、Windows 操作系统,需安装 Python 3.7 ~ 3.12(推荐 3.9)。
|
||||
支持 Linux、macOS、Windows 操作系统,需安装 Python 3.7 ~ 3.13(推荐 3.9)。
|
||||
|
||||
## 安装命令
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ CowAgent 的整体架构由以下核心模块组成:
|
||||
| **Plan** | 理解用户意图,将复杂任务分解为多步骤计划,循环调用工具直到完成目标 |
|
||||
| **Memory** | 自动将重要信息持久化为核心记忆和日级记忆,支持关键词和向量混合检索,跨会话保持上下文连续性 |
|
||||
| **Knowledge** | 以主题维度组织结构化知识,Agent 自主整理有价值信息为 Markdown 页面,维护索引和交叉引用,构建持续增长的知识网络 |
|
||||
| **Evolution** | 对话空闲后在隔离环境中自动复盘,优化技能、处理未完成事项、补全记忆与知识,让 Agent 在使用中持续成长 |
|
||||
| **Tools** | Agent 访问操作系统资源的核心能力,内置文件读写、终端执行、浏览器操作、定时调度、记忆检索、联网搜索等 10+ 种工具 |
|
||||
| **Skills** | 加载和管理 Skills,支持从 Skill Hub、GitHub 等一键安装,或通过对话创建自定义技能 |
|
||||
| **Models** | 模型层,统一接入 OpenAI、Claude、Gemini、DeepSeek、MiniMax、GLM、Qwen 等国内外主流大语言模型 |
|
||||
@@ -84,4 +85,5 @@ Agent 的工作空间默认位于 `~/cow` 目录,用于存储系统提示词
|
||||
| `agent_max_steps` | 单次任务最大决策步数 | `20` |
|
||||
| `enable_thinking` | 是否启用深度思考模式 | `false` |
|
||||
| `knowledge` | 是否启用个人知识库 | `true` |
|
||||
| `self_evolution_enabled` | 是否启用自主进化 | `false` |
|
||||
| `cow_lang` | 界面、命令文案、系统提示词等的语言,`auto` 自动检测,可设为 `zh` / `en` | `auto` |
|
||||
|
||||
@@ -15,7 +15,13 @@ description: CowAgent 长期记忆、个人知识库、任务规划、技能系
|
||||
<img src="https://cdn.link-ai.tech/doc/20260203000455.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
详细说明请参考 [长期记忆](/zh/memory) 和 [梦境蒸馏](/zh/memory/deep-dream)。
|
||||
在此基础上,**自主进化(Self-Evolution)** 让 Agent 在使用中持续成长:对话空闲后自动复盘,优化技能、处理遗留任务、补全记忆与知识,仅在确有改动时简短告知,且每次改动可随时撤销。
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/web-console-evolution-demo-zh.png" width="800" />
|
||||
</Frame>
|
||||
|
||||
详细说明请参考 [长期记忆](/zh/memory)、[梦境蒸馏](/zh/memory/deep-dream) 和 [自主进化](/zh/memory/self-evolution)。
|
||||
|
||||
## 2. 个人知识库
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ CowAgent 支持灵活切换多种模型,能处理文本、语音、图片、
|
||||
<Card title="个人知识库" icon="book" href="/zh/knowledge">
|
||||
自动整理结构化知识,支持知识图谱可视化,通过交叉引用构建持续增长的知识网络。
|
||||
</Card>
|
||||
<Card title="自主进化" icon="seedling" href="/zh/memory/self-evolution">
|
||||
对话结束后自动复盘,优化技能、处理遗留任务、沉淀记忆与知识,让 Agent 在使用中持续成长。
|
||||
</Card>
|
||||
<Card title="技能系统" icon="puzzle-piece" href="/zh/skills/index">
|
||||
实现了Skills创建和运行的引擎,内置多种技能,并支持通过自然语言对话完成自定义Skills开发。
|
||||
</Card>
|
||||
|
||||
91
docs/zh/memory/self-evolution.mdx
Normal file
91
docs/zh/memory/self-evolution.mdx
Normal file
@@ -0,0 +1,91 @@
|
||||
---
|
||||
title: 自主进化
|
||||
description: Self-Evolution:自动复盘,沉淀记忆、优化技能、处理未完成事项
|
||||
---
|
||||
|
||||
## 功能介绍
|
||||
|
||||
### 简介
|
||||
|
||||
自主进化(Self-Evolution)让 Agent 不止于"完成单次任务",而是能在与你的相处中持续成长。在每段对话告一段落后,它会自动"回头复盘"一次:把使用中暴露的问题修进技能、把没做完的事情接着推进,并把值得记住的沉淀进记忆与知识库。久而久之,Agent 会越来越懂你的偏好、越来越少重复犯错、越来越主动地把事情收尾,而这一切都在后台静默完成,当真正做了事情时才会主动地告诉你。
|
||||
|
||||
> 它与[梦境蒸馏](/zh/memory/deep-dream)互补:梦境蒸馏负责整理记忆本身,自主进化则在记忆之外,进一步优化技能、推进未完成的任务,让 Agent 的能力随使用不断打磨。
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/web-console-evolution-demo-zh.png" alt="自主进化对话示例" />
|
||||
</Frame>
|
||||
|
||||
### 几个目标
|
||||
|
||||
自主进化围绕以下几件事工作,并以「优化技能、处理未完成事项」为主,「沉淀记忆、知识」作为主对话的查缺补漏:
|
||||
|
||||
| 目标 | 说明 |
|
||||
| --- | --- |
|
||||
| **优化技能** | ① 技能在使用中暴露问题(如配置错误、步骤缺失)时,直接修正技能文件;② 出现一套可复用的流程时,主动固化为新技能,下次直接调用 |
|
||||
| **处理未完成事项** | 识别对话中遗留的待办,在能完成时直接完成 |
|
||||
| **沉淀记忆** | 把对话中重要的偏好、决策、事实补记到记忆中,作为主对话的查缺补漏 |
|
||||
| **沉淀知识** | 把对话中产生的、值得日后查阅的可复用知识补充进知识库(主对话遗漏时) |
|
||||
|
||||
复盘完成后,如果确实做了改动,Agent 会在对话中用一句话告诉你"刚刚自主学习了什么、调整了哪里",方便你判断是否需要回滚。
|
||||
|
||||
## 如何使用
|
||||
|
||||
### 触发时机
|
||||
|
||||
自主进化不是定时执行,而是在**一段对话自然结束、进入空闲后**才触发,避免打断正在进行的交流。需要同时满足:
|
||||
|
||||
- **对话已空闲** — 距离最后一次互动超过设定的空闲时长(默认 15 分钟)
|
||||
- **对话有足够内容** — 自上次进化以来累积了足够轮次(默认 8 轮),或上下文已接近容量上限
|
||||
|
||||
只有两个条件都满足,才会启动一次复盘。这样既保证有足够的内容值得复盘,又不会在你还在对话时打扰你。
|
||||
|
||||
### 相关配置
|
||||
|
||||
自主进化可在 Web 控制台「配置 → Agent 配置」中通过开关启停(位于"深度思考"下方),也可在配置文件中调整:
|
||||
|
||||
| 参数 | 说明 | 默认值 |
|
||||
| --- | --- | --- |
|
||||
| `self_evolution_enabled` | 是否启用自主进化 | `false` |
|
||||
| `self_evolution_idle_minutes` | 对话空闲多久后触发(分钟) | `15` |
|
||||
| `self_evolution_min_turns` | 触发所需的最少对话轮次 | `8` |
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/web-console-evolution-config-zh.png" alt="在 Web 控制台开启自主进化" />
|
||||
</Frame>
|
||||
|
||||
<Tip>
|
||||
Web 控制台只提供启用开关,若需调整空闲时长或轮次阈值,请编辑配置文件。修改后即时生效,无需重启。
|
||||
</Tip>
|
||||
|
||||
### 进化记录
|
||||
|
||||
每次进化的过程和结果会按日期记录在 `memory/evolution/YYYY-MM-DD.md` 中,可在 Web 控制台的「记忆管理 → 自主进化」tab 中查看。该 tab 同时汇总了自主进化记录与梦境日记,方便统一回顾 Agent 的成长轨迹。
|
||||
|
||||
<Frame>
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/web-console-evolution-logs-zh.png" alt="自主进化记录列表" />
|
||||
</Frame>
|
||||
|
||||
### 如何回滚
|
||||
|
||||
如果你不认同某次进化的改动,直接在对话中告诉 Agent "把刚才的改动撤销"即可,它会根据进化前的备份还原相关文件。每次进化的改动都有独立备份,互不影响。
|
||||
|
||||
## 实现设计
|
||||
|
||||
自主进化复用了系统已有的能力,保持轻量:
|
||||
|
||||
- **隔离执行**:每次复盘都启动一个独立的、临时的复盘任务,使用与主对话相同的模型,但拥有受限的工具集(只能读上下文、改记忆与技能文件)。它不会污染主对话的上下文,也不会影响主对话的性能。
|
||||
- **基于备份的撤销**:进化前对相关文件做快照备份,撤销时按备份还原,因此每一次改动都可追溯、可逆。
|
||||
- **改动检测**:复盘结束后通过对比文件快照判断是否真的有改动,以此决定要不要通知你,从工程上保证"没做事就不打扰"。
|
||||
|
||||
### 克制与安全
|
||||
|
||||
自主进化的设计原则是"必要时执行,减少打扰":
|
||||
|
||||
| 机制 | 说明 |
|
||||
| --- | --- |
|
||||
| **没做事不通知** | 如果复盘后没有任何实际改动,全程静默,不产生任何通知 |
|
||||
| **空闲才触发** | 仅在对话空闲后运行,绝不打断正在进行的对话 |
|
||||
| **改动可回滚** | 每次进化前自动备份,若对结果不满意,可一键撤销本次改动 |
|
||||
| **保护内置技能** | 项目自带的内置技能受保护,进化过程不会改动 |
|
||||
| **限定工作空间** | 所有读写都限定在工作空间内,不会触碰系统其他文件 |
|
||||
| **后台异步** | 复盘在后台进行,不阻塞正常对话回复 |
|
||||
@@ -61,7 +61,7 @@ description: Coding Plan 模式模型配置
|
||||
```json
|
||||
{
|
||||
"bot_type": "openai",
|
||||
"model": "MiniMax-M2.5",
|
||||
"model": "MiniMax-M3",
|
||||
"open_ai_api_base": "https://api.minimaxi.com/v1",
|
||||
"open_ai_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
@@ -69,7 +69,7 @@ description: Coding Plan 模式模型配置
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `model` | `MiniMax-M2.5`、`MiniMax-M2.5-highspeed`、`MiniMax-M2.1`、`MiniMax-M2` |
|
||||
| `model` | `MiniMax-M3`、`MiniMax-M2.7`、`MiniMax-M2.7-highspeed` |
|
||||
| `open_ai_api_base` | 国内:`https://api.minimaxi.com/v1`;海外:`https://api.minimax.io/v1` |
|
||||
| `open_ai_api_key` | Coding Plan 专用 Key(与按量计费接口不通用) |
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@ CowAgent 支持国内外主流厂商的大语言模型,模型接口实现在
|
||||
| 厂商 | 代表模型 | 文本 | 图像理解 | 图像生成 | 语音识别 | 语音合成 | 向量 |
|
||||
| --- | --- | :-: | :-: | :-: | :-: | :-: | :-: |
|
||||
| [DeepSeek](/zh/models/deepseek) | deepseek-v4-flash / pro | ✅ | | | | | |
|
||||
| [MiniMax](/zh/models/minimax) | MiniMax-M2.7 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [MiniMax](/zh/models/minimax) | MiniMax-M3 | ✅ | ✅ | ✅ | | ✅ | |
|
||||
| [Claude](/zh/models/claude) | claude-opus-4-8 | ✅ | ✅ | | | | |
|
||||
| [Gemini](/zh/models/gemini) | gemini-3.5-flash | ✅ | ✅ | ✅ | | | |
|
||||
| [OpenAI](/zh/models/openai) | gpt-5.5、o 系列 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [智谱 GLM](/zh/models/glm) | glm-5.1、glm-5v-turbo | ✅ | ✅ | | ✅ | | ✅ |
|
||||
| [通义千问](/zh/models/qwen) | qwen3.7-max | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [通义千问](/zh/models/qwen) | qwen3.7-plus | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| [豆包 Doubao](/zh/models/doubao) | doubao-seed-2.0 系列 | ✅ | ✅ | ✅ | | | ✅ |
|
||||
| [Kimi](/zh/models/kimi) | kimi-k2.6 | ✅ | ✅ | | | | |
|
||||
| [百度千帆](/zh/models/qianfan) | ernie-5.1 | ✅ | ✅ | | | | |
|
||||
|
||||
@@ -40,7 +40,7 @@ description: 通过 LinkAI 平台统一接入文本、视觉、图像、语音
|
||||
}
|
||||
```
|
||||
|
||||
可选模型:`gpt-4.1-mini`、`gpt-5.4-mini`、`qwen3.6-plus`、`doubao-seed-2-0-pro-260215`、`kimi-k2.6`、`claude-sonnet-4-6`、`gemini-3.1-flash-lite-preview` 等。
|
||||
可选模型:`gpt-4.1-mini`、`gpt-5.4-mini`、`qwen3.7-plus`、`doubao-seed-2-0-pro-260215`、`kimi-k2.6`、`claude-sonnet-4-6`、`gemini-3.1-flash-lite-preview` 等。
|
||||
|
||||
## 图像生成
|
||||
|
||||
|
||||
@@ -13,14 +13,14 @@ MiniMax 支持文本对话、图像理解、图像生成与语音合成,一份
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "MiniMax-M2.7",
|
||||
"model": "MiniMax-M3",
|
||||
"minimax_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `model` | 可填 `MiniMax-M2.7`、`MiniMax-M2.7-highspeed`、`MiniMax-M2.5`、`MiniMax-M2.1`、`MiniMax-M2.1-lightning`、`MiniMax-M2` 等 |
|
||||
| `model` | 可填 `MiniMax-M3`、`MiniMax-M2.7`、`MiniMax-M2.7-highspeed` 等 |
|
||||
| `minimax_api_key` | 在 [MiniMax 控制台](https://platform.minimaxi.com/user-center/basic-information/interface-key) 创建 |
|
||||
|
||||
## 图像理解
|
||||
|
||||
@@ -13,19 +13,19 @@ description: 通义千问模型配置(文本 / 图像理解 / 图像生成 /
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "qwen3.6-plus",
|
||||
"model": "qwen3.7-plus",
|
||||
"dashscope_api_key": "YOUR_API_KEY"
|
||||
}
|
||||
```
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `model` | 可填 `qwen3.6-plus`、`qwen3.7-max`、`qwen3.5-plus`、`qwen3-max`、`qwen-max`、`qwen-plus`、`qwen-turbo`、`qwq-plus` 等 |
|
||||
| `model` | 可填 `qwen3.7-plus`、`qwen3.7-max`、`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`、`qwen-max`、`qwen-plus`、`qwen-turbo`、`qwq-plus` 等 |
|
||||
| `dashscope_api_key` | 在 [百炼控制台](https://bailian.console.aliyun.com/?tab=model#/api-key) 创建,参考 [官方文档](https://bailian.console.aliyun.com/?tab=api#/api) |
|
||||
|
||||
## 图像理解
|
||||
|
||||
配置 `dashscope_api_key` 后 Agent 的 Vision 工具会自动调用千问的视觉模型识别图像。`qwen3-max` / `qwen3.5-plus` / `qwen3.6-plus` 等模型本身就是多模态;若主模型是纯文本(如 `qwen-turbo`),会自动回落到 `qwen-vl-max`。
|
||||
配置 `dashscope_api_key` 后 Agent 的 Vision 工具会自动调用千问的视觉模型识别图像。`qwen3.7-plus` / `qwen3.6-plus` / `qwen3.5-plus` / `qwen3-max` 等模型本身就是多模态;若主模型是纯文本(如 `qwen-turbo`),会自动回落到 `qwen-vl-max`。
|
||||
|
||||
如需手动指定 Vision 模型:
|
||||
|
||||
@@ -33,13 +33,13 @@ description: 通义千问模型配置(文本 / 图像理解 / 图像生成 /
|
||||
{
|
||||
"tools": {
|
||||
"vision": {
|
||||
"model": "qwen3.6-plus"
|
||||
"model": "qwen3.7-plus"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
支持模型:`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`。
|
||||
支持模型:`qwen3.7-plus`、`qwen3.6-plus`、`qwen3.5-plus`、`qwen3-max`。
|
||||
|
||||
## 图像生成
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ description: CowAgent 版本更新历史
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| [2.1.1](/zh/releases/v2.1.1) | 2026.06.09 | 自主进化能力、Web 控制台消息管理升级、新模型接入(MiniMax-M3、qwen3.7-plus 等)、其他多项优化和修复 |
|
||||
| [2.1.0](/zh/releases/v2.1.0) | 2026.06.01 | 国际化支持、新增 Telegram / Discord / Slack / 微信客服通道、命令行交互升级(流式输出、命令模糊匹配、任务取消)、MCP Streamable HTTP、新模型接入 |
|
||||
| [2.0.9](/zh/releases/v2.0.9) | 2026.05.22 | 新增模型管理、MCP 协议支持、浏览器登录态持久化、新模型接入(gpt-5.5、gemini-3.5-flash、qwen3.7-max 等)、部署安全加固 |
|
||||
| [2.0.8](/zh/releases/v2.0.8) | 2026.05.06 | 飞书渠道全面升级(语音、流式输出和Markdown、扫码一键接入)、DeepSeek V4和百度模型新增、定时任务工具增强 |
|
||||
|
||||
63
docs/zh/releases/v2.1.1.mdx
Normal file
63
docs/zh/releases/v2.1.1.mdx
Normal file
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: v2.1.1
|
||||
description: CowAgent 2.1.1:自主进化能力、Web 控制台消息管理与多会话并行、MCP 跨平台增强、多模型接入与优化
|
||||
---
|
||||
|
||||
🌐 [English](https://docs.cowagent.ai/releases/v2.1.1) | [中文](https://docs.cowagent.ai/zh/releases/v2.1.1)
|
||||
|
||||
## 🧬 自主进化能力
|
||||
|
||||
CowAgent 新增 **自主进化(Self-Evolution)** 能力,让 Agent 不止于完成单次任务,而是在与你的日常协作中持续成长:
|
||||
|
||||
- **空闲后自动复盘**:对话空闲后自动复盘,修正技能在使用中暴露的问题、创建可复用的新技能,处理遗留的未完成事项,并将重要信息补充进记忆与知识库
|
||||
- **静默执行、按需提醒**:仅在实际有改动时主动告知本次调整内容,无变更时全程静默
|
||||
- **安全可回退**:每次复盘前自动备份,可随时撤销本次改动;内置技能受保护,所有读写均限定在工作空间内
|
||||
|
||||
新安装用户默认开启,已有用户可在 Web 控制台 **设置 → Agent 配置** 中一键开启。
|
||||
|
||||
<img src="https://cdn.jsdelivr.net/gh/zhayujie/cowagent-assets@main/screenshots/zh/web-console-evolution-demo-zh.png" alt="自主进化对话示例" />
|
||||
|
||||
相关文档:[自主进化](https://docs.cowagent.ai/zh/memory/self-evolution)
|
||||
|
||||
## 💬 Web 控制台升级
|
||||
|
||||
Web 控制台的聊天体验进一步增强:
|
||||
|
||||
- **消息管理**:用户与机器人的消息均支持编辑、删除、重新生成;代码块新增语言标签和一键复制按钮
|
||||
- **多会话并行**:支持多个会话同时进行、互不干扰,切回会话时自动恢复实时流式输出
|
||||
- **细节优化**:支持将文件拖拽到整个聊天区域;删除当前会话后自动切换到相邻会话
|
||||
|
||||
Thanks @core-power (#2865)
|
||||
|
||||
## 🧩 MCP 跨平台增强
|
||||
|
||||
- **Windows 兼容修复**:修复 MCP 在 Windows 下 `stdio` 通信不可用的问题,并支持通过 `mcp.json` 配置服务超时时间
|
||||
- **并发调用支持**:`sse` 与 `streamable-http` 传输支持跨会话并发调用,多工具响应更快
|
||||
|
||||
Thanks @xliu123321 (#2859)
|
||||
|
||||
相关文档:[MCP 工具](https://docs.cowagent.ai/zh/tools/mcp)
|
||||
|
||||
## 🤖 模型新增与优化
|
||||
|
||||
- **MiniMax-M3**:新增并设为默认模型,保留 M2.7 系列作为可选项。Thanks @octo-patch (#2855)
|
||||
- **通义千问 qwen3.7-plus**:支持多模态对话
|
||||
- **语音识别模型可选**:Web 控制台支持选择 ASR(语音识别)模型并持久化保存。Thanks @nightwhite (#2857)
|
||||
- **安装菜单简化**:一键安装脚本精简模型选择菜单,新增小米 MiMo 选项
|
||||
|
||||
相关文档:[模型概览](https://docs.cowagent.ai/zh/models)
|
||||
|
||||
## 🛠 体验优化与修复
|
||||
|
||||
- **Python 3.13 支持**:修复在 Python 3.13 环境下的安装与依赖兼容问题
|
||||
- **国际化体验**:通道列表按界面语言排序展示;优化 `auto` 模式下的语言自动回退逻辑
|
||||
- **任务取消更可靠**:修复部分场景下流式回复无法中断的问题
|
||||
- **CLI 增强**:`cow status` 新增显示当前项目路径
|
||||
- **部署安全加固**:凭证文件拦截范围收敛至 `~/.cow/.env`,不再误拦其他目录(Thanks @orbisai0security #2863);微信公众号在 `wechatmp_token` 为空时拒绝 Webhook 请求
|
||||
- **群任务看板插件**:新增群聊任务看板插件源。Thanks @Wyh-max-star (#2853)
|
||||
|
||||
## 📦 升级方式
|
||||
|
||||
源码部署可执行 `cow update` 一键升级,或手动拉取代码后重启。详见 [更新升级文档](https://docs.cowagent.ai/zh/guide/upgrade)。
|
||||
|
||||
**发布日期**:2026.06.09 | [Full Changelog](https://github.com/zhayujie/CowAgent/compare/2.1.0...2.1.1)
|
||||
@@ -19,7 +19,7 @@ Vision 工具采用多级自动选择 + 自动兜底策略,无需手动配置
|
||||
| 厂商 | 视觉模型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| OpenAI / 兼容协议 | 使用主模型 | 支持所有 OpenAI 协议兼容的多模态模型 |
|
||||
| 通义千问 (DashScope) | 使用主模型 | 例如 qwen3.6-plus 等 |
|
||||
| 通义千问 (DashScope) | 使用主模型 | 例如 qwen3.7-plus 等 |
|
||||
| Claude | 使用主模型 | Anthropic 原生图像格式 |
|
||||
| Gemini | 使用主模型 | inlineData 格式 |
|
||||
| 豆包 (Doubao) | 使用主模型 | doubao-seed-2-0 系列原生支持 |
|
||||
|
||||
@@ -28,15 +28,15 @@ dashscope_models = {
|
||||
|
||||
# Model name prefixes that require MultiModalConversation API instead of Generation API.
|
||||
# Qwen3.5+ series are omni models that only support MultiModalConversation.
|
||||
MULTIMODAL_MODEL_PREFIXES = ("qwen3.5-", "qwen3.6-")
|
||||
MULTIMODAL_MODEL_PREFIXES = ("qwen3.5-", "qwen3.6-", "qwen3.7-plus")
|
||||
|
||||
|
||||
# Qwen对话模型API
|
||||
class DashscopeBot(Bot):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.sessions = SessionManager(DashscopeSession, model=conf().get("model") or "qwen3.6-plus")
|
||||
self.model_name = conf().get("model") or "qwen3.6-plus"
|
||||
self.sessions = SessionManager(DashscopeSession, model=conf().get("model") or "qwen3.7-plus")
|
||||
self.model_name = conf().get("model") or "qwen3.7-plus"
|
||||
self.client = dashscope.Generation
|
||||
api_key = conf().get("dashscope_api_key")
|
||||
if api_key:
|
||||
|
||||
@@ -133,7 +133,7 @@ class LinkAIBot(Bot, OpenAICompatibleBot):
|
||||
if file_id:
|
||||
body["file_id"] = file_id
|
||||
logger.info(f"[LINKAI] query={query}, app_code={app_code}, model={body.get('model')}, file_id={file_id}")
|
||||
headers = {"Authorization": "Bearer " + linkai_api_key}
|
||||
headers = {"Authorization": "Bearer " + linkai_api_key, "X-Title": "CowAgent"}
|
||||
|
||||
# do http request
|
||||
base_url = conf().get("linkai_api_base", "https://api.link-ai.tech")
|
||||
@@ -272,7 +272,7 @@ class LinkAIBot(Bot, OpenAICompatibleBot):
|
||||
}
|
||||
if self.args.get("max_tokens"):
|
||||
body["max_tokens"] = self.args.get("max_tokens")
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key"), "X-Title": "CowAgent"}
|
||||
|
||||
# do http request
|
||||
base_url = conf().get("linkai_api_base", "https://api.link-ai.tech")
|
||||
@@ -565,7 +565,7 @@ def _linkai_call_with_tools(self, messages, tools=None, stream=False, **kwargs):
|
||||
body["thinking"] = thinking
|
||||
|
||||
# Prepare headers
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key"), "X-Title": "CowAgent"}
|
||||
base_url = conf().get("linkai_api_base", "https://api.link-ai.tech")
|
||||
|
||||
if stream:
|
||||
|
||||
@@ -22,7 +22,7 @@ class MinimaxBot(Bot):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.args = {
|
||||
"model": conf().get("model") or "MiniMax-M2.7",
|
||||
"model": conf().get("model") or "MiniMax-M3",
|
||||
"temperature": conf().get("temperature", 0.3),
|
||||
"top_p": conf().get("top_p", 0.95),
|
||||
}
|
||||
|
||||
@@ -26,12 +26,12 @@ class Keyword(Plugin):
|
||||
config_path = os.path.join(curdir, "config.json")
|
||||
conf = None
|
||||
if not os.path.exists(config_path):
|
||||
logger.debug(f"[keyword]不存在配置文件{config_path}")
|
||||
logger.debug(f"[keyword] config file not found: {config_path}")
|
||||
conf = {"keyword": {}}
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
json.dump(conf, f, indent=4)
|
||||
else:
|
||||
logger.debug(f"[keyword]加载配置文件{config_path}")
|
||||
logger.debug(f"[keyword] loading config file: {config_path}")
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
conf = json.load(f)
|
||||
# 加载关键词
|
||||
|
||||
@@ -24,6 +24,10 @@
|
||||
"url": "https://github.com/dividduang/blackroom.git",
|
||||
"desc": "小黑屋插件,被拉进小黑屋的人将不能使用@bot的功能的插件"
|
||||
},
|
||||
"group_task_board": {
|
||||
"url": "https://github.com/Wyh-max-star/cowagent-plugin-group-task-board.git",
|
||||
"desc": "群聊任务看板插件,支持从群聊消息中创建、查看和管理任务"
|
||||
},
|
||||
"midjourney": {
|
||||
"url": "https://github.com/baojingyu/midjourney.git",
|
||||
"desc": "利用midjourney实现ai绘图的的插件"
|
||||
|
||||
@@ -3,8 +3,6 @@ aiohttp>=3.8.6,<3.10
|
||||
requests>=2.28.2
|
||||
chardet>=5.1.0
|
||||
Pillow
|
||||
web.py
|
||||
legacy-cgi; python_version >= "3.13"
|
||||
python-dotenv>=1.0.0
|
||||
PyYAML>=6.0
|
||||
croniter>=2.0.0
|
||||
@@ -32,4 +30,9 @@ python-telegram-bot
|
||||
# slack bot
|
||||
slack_bolt
|
||||
# discord bot
|
||||
discord.py
|
||||
discord.py
|
||||
|
||||
# web.py: PyPI 0.62 fails to build on Python 3.13+ (cgi module removed), use GitHub fix instead
|
||||
web.py; python_version < "3.13"
|
||||
web.py @ git+https://github.com/webpy/webpy.git ; python_version >= "3.13"
|
||||
legacy-cgi; python_version >= "3.13"
|
||||
|
||||
71
run.sh
71
run.sh
@@ -359,39 +359,37 @@ detect_python_command() {
|
||||
FOUND_NEWER_VERSION=""
|
||||
|
||||
# Try to find Python command in order of preference
|
||||
for cmd in python3 python python3.12 python3.11 python3.10 python3.9 python3.8 python3.7; do
|
||||
for cmd in python3 python python3.13 python3.12 python3.11 python3.10 python3.9 python3.8 python3.7; do
|
||||
if command -v $cmd &> /dev/null; then
|
||||
# Check Python version
|
||||
major_version=$($cmd -c 'import sys; print(sys.version_info[0])' 2>/dev/null)
|
||||
minor_version=$($cmd -c 'import sys; print(sys.version_info[1])' 2>/dev/null)
|
||||
|
||||
if [[ "$major_version" == "3" ]]; then
|
||||
# Check if version is in supported range (3.7 - 3.12)
|
||||
if (( minor_version >= 7 && minor_version <= 12 )); then
|
||||
# Supported range is 3.7+. On 3.13+ web.py is installed from a
|
||||
# pinned GitHub commit (see requirements.txt), which needs git.
|
||||
if (( minor_version >= 7 )); then
|
||||
PYTHON_CMD=$cmd
|
||||
PYTHON_VERSION="${major_version}.${minor_version}"
|
||||
break
|
||||
elif (( minor_version >= 13 )); then
|
||||
# Found Python 3.13+, but not compatible
|
||||
if [ -z "$FOUND_NEWER_VERSION" ]; then
|
||||
FOUND_NEWER_VERSION="${major_version}.${minor_version}"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$PYTHON_CMD" ]; then
|
||||
echo -e "${YELLOW}Tried: python3, python, python3.12, python3.11, python3.10, python3.9, python3.8, python3.7${NC}"
|
||||
if [ -n "$FOUND_NEWER_VERSION" ]; then
|
||||
echo -e "${RED}❌ Found Python $FOUND_NEWER_VERSION, but this project requires Python 3.7-3.12${NC}"
|
||||
echo -e "${YELLOW}Python 3.13+ has compatibility issues with some dependencies (web.py, cgi module removed)${NC}"
|
||||
echo -e "${YELLOW}Please install Python 3.7-3.12 (recommend Python 3.12)${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ No suitable Python found. Please install Python 3.7-3.12${NC}"
|
||||
fi
|
||||
echo -e "${YELLOW}Tried: python3, python, python3.13, python3.12, python3.11, python3.10, python3.9, python3.8, python3.7${NC}"
|
||||
echo -e "${RED}❌ No suitable Python found. Please install Python 3.7 or newer${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# On 3.13+, web.py is pulled from GitHub via pip, which requires git.
|
||||
if [[ "$major_version" == "3" ]] && (( minor_version >= 13 )); then
|
||||
if ! command -v git &> /dev/null; then
|
||||
echo -e "${YELLOW}⚠️ Python $PYTHON_VERSION detected. Installing web.py from GitHub requires git, which was not found.${NC}"
|
||||
echo -e "${YELLOW} Please install git, or use Python 3.12 where web.py installs directly from PyPI.${NC}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Export for global use
|
||||
export PYTHON_CMD
|
||||
@@ -596,17 +594,18 @@ select_model() {
|
||||
echo ""
|
||||
local title sel
|
||||
title="$(t "选择 AI 模型" "Select AI Model")"
|
||||
# The 11th option is "skip" -> configure later in the web console.
|
||||
# The 12th option is "skip" -> configure later in the web console.
|
||||
select_menu sel "$title" \
|
||||
"DeepSeek (deepseek-v4-flash, deepseek-v4-pro, etc.)" \
|
||||
"Claude (claude-opus-4-8, claude-opus-4-7, claude-sonnet-4-6, etc.)" \
|
||||
"Gemini (gemini-3.1-flash-lite-preview, gemini-3.1-pro-preview, etc.)" \
|
||||
"OpenAI GPT (gpt-5.4, gpt-5.2, gpt-4.1, etc.)" \
|
||||
"MiniMax (MiniMax-M2.7, MiniMax-M2.5, etc.)" \
|
||||
"Zhipu AI (glm-5.1, glm-5-turbo, glm-5, etc.)" \
|
||||
"Qwen (qwen3.6-plus, qwen3.5-plus, qwen3-max, qwq-plus, etc.)" \
|
||||
"Doubao (doubao-seed-2-0-code-preview-260215, etc.)" \
|
||||
"Kimi (kimi-k2.6, kimi-k2.5, kimi-k2, etc.)" \
|
||||
"Claude (claude-opus-4-8, claude-opus-4-7, etc.)" \
|
||||
"Gemini (gemini-3.5-flash, gemini-3.1-pro-preview, etc.)" \
|
||||
"OpenAI (gpt-5.5, etc.)" \
|
||||
"MiniMax (MiniMax-M3, etc.)" \
|
||||
"GLM (glm-5.1, etc.)" \
|
||||
"Qwen (qwen3.7-plus, qwen3.7-max, etc.)" \
|
||||
"Doubao (doubao-seed-2.0, etc.)" \
|
||||
"Kimi (kimi-k2.6, etc.)" \
|
||||
"MiMo (mimo-v2.5-pro, etc.)" \
|
||||
"LinkAI ($(t "一个 Key 接入所有模型" "access all models via one API"))" \
|
||||
"$(t "⏭ 跳过(稍后在 Web 控制台配置)" "⏭ Skip (configure later in the web console)")"
|
||||
model_choice="$sel"
|
||||
@@ -632,19 +631,20 @@ configure_model() {
|
||||
1) read_model_config "DeepSeek" "deepseek-v4-flash" "DEEPSEEK_KEY" ;;
|
||||
2) read_model_config "Claude" "claude-opus-4-8" "CLAUDE_KEY" ;;
|
||||
3) read_model_config "Gemini" "gemini-3.1-pro-preview" "GEMINI_KEY" ;;
|
||||
4) read_model_config "OpenAI GPT" "gpt-5.4" "OPENAI_KEY" ;;
|
||||
5) read_model_config "MiniMax" "MiniMax-M2.7" "MINIMAX_KEY" ;;
|
||||
6) read_model_config "Zhipu AI" "glm-5.1" "ZHIPU_KEY" ;;
|
||||
7) read_model_config "Qwen (DashScope)" "qwen3.6-plus" "DASHSCOPE_KEY" ;;
|
||||
4) read_model_config "OpenAI" "gpt-5.5" "OPENAI_KEY" ;;
|
||||
5) read_model_config "MiniMax" "MiniMax-M3" "MINIMAX_KEY" ;;
|
||||
6) read_model_config "GLM" "glm-5.1" "ZHIPU_KEY" ;;
|
||||
7) read_model_config "Qwen (DashScope)" "qwen3.7-plus" "DASHSCOPE_KEY" ;;
|
||||
8) read_model_config "Doubao (Volcengine Ark)" "doubao-seed-2-0-code-preview-260215" "ARK_KEY" ;;
|
||||
9) read_model_config "Kimi (Moonshot)" "kimi-k2.6" "MOONSHOT_KEY" ;;
|
||||
10)
|
||||
10) read_model_config "MiMo" "mimo-v2.5-pro" "MIMO_KEY" ;;
|
||||
11)
|
||||
# Show where to obtain a LinkAI key (zh users -> console page).
|
||||
echo -e "${CYAN}$(t "获取 LinkAI Key" "Get your LinkAI Key"): https://link-ai.tech/console/interface${NC}"
|
||||
read_model_config "LinkAI" "deepseek-v4-flash" "LINKAI_KEY"
|
||||
USE_LINKAI="true"
|
||||
;;
|
||||
11)
|
||||
12)
|
||||
# Skip: leave model unset, will be configured in web console
|
||||
MODEL_SKIPPED="true"
|
||||
MODEL_NAME=""
|
||||
@@ -657,8 +657,8 @@ configure_model() {
|
||||
channel_label() {
|
||||
case "$1" in
|
||||
web) t "Web 网页控制台(推荐,开箱即用)" "Web Console (recommended, ready to use)" ;;
|
||||
weixin) t "微信" "WeChat (Weixin)" ;;
|
||||
feishu) t "飞书" "Feishu / Lark" ;;
|
||||
weixin) t "微信" "Wechat" ;;
|
||||
feishu) t "飞书" "Feishu" ;;
|
||||
dingtalk) t "钉钉" "DingTalk" ;;
|
||||
wecom_bot) t "企微智能机器人" "WeCom Bot" ;;
|
||||
qq) printf '%s' "QQ" ;;
|
||||
@@ -823,6 +823,7 @@ create_config_file() {
|
||||
ARK_KEY="${ARK_KEY:-}" \
|
||||
DASHSCOPE_KEY="${DASHSCOPE_KEY:-}" \
|
||||
MINIMAX_KEY="${MINIMAX_KEY:-}" \
|
||||
MIMO_KEY="${MIMO_KEY:-}" \
|
||||
DEEPSEEK_KEY="${DEEPSEEK_KEY:-}" \
|
||||
DEEPSEEK_BASE="${DEEPSEEK_BASE:-https://api.deepseek.com/v1}" \
|
||||
USE_LINKAI="${USE_LINKAI:-false}" \
|
||||
@@ -865,6 +866,7 @@ base = {
|
||||
'ark_api_key': e('ARK_KEY', ''),
|
||||
'dashscope_api_key': e('DASHSCOPE_KEY', ''),
|
||||
'minimax_api_key': e('MINIMAX_KEY', ''),
|
||||
'mimo_api_key': e('MIMO_KEY', ''),
|
||||
'deepseek_api_key': e('DEEPSEEK_KEY', ''),
|
||||
'deepseek_api_base': e('DEEPSEEK_BASE'),
|
||||
'voice_to_text': 'openai',
|
||||
@@ -879,6 +881,9 @@ base = {
|
||||
'agent_max_context_tokens': 40000,
|
||||
'agent_max_context_turns': 30,
|
||||
'agent_max_steps': 15,
|
||||
# New installs opt into self-evolution; existing users (no key) keep the
|
||||
# code default (off) so an upgrade never silently changes their behavior.
|
||||
'self_evolution_enabled': True,
|
||||
}
|
||||
channel_map = {
|
||||
'feishu': {'feishu_app_id': 'FEISHU_APP_ID', 'feishu_app_secret': 'FEISHU_APP_SECRET'},
|
||||
|
||||
@@ -201,7 +201,7 @@ function Find-Python {
|
||||
$ver = & $bin.Source -c "import sys; v=sys.version_info; print(f'{v.major}.{v.minor}')" 2>$null
|
||||
$parts = $ver -split '\.'
|
||||
$major = [int]$parts[0]; $minor = [int]$parts[1]
|
||||
if ($major -eq 3 -and $minor -ge 9 -and $minor -le 13) {
|
||||
if ($major -eq 3 -and $minor -ge 7 -and $minor -le 13) {
|
||||
return $bin.Source
|
||||
}
|
||||
} catch {}
|
||||
@@ -212,7 +212,7 @@ function Find-Python {
|
||||
$PythonCmd = Find-Python
|
||||
function Assert-Python {
|
||||
if (-not $PythonCmd) {
|
||||
Write-Err (T "未找到 Python 3.9-3.13,请从 https://www.python.org/downloads/ 安装" "Python 3.9-3.13 not found. Please install from https://www.python.org/downloads/")
|
||||
Write-Err (T "未找到 Python 3.7-3.13,请从 https://www.python.org/downloads/ 安装" "Python 3.7-3.13 not found. Please install from https://www.python.org/downloads/")
|
||||
Read-Host (T "按回车退出" "Press Enter to exit")
|
||||
exit 1
|
||||
}
|
||||
@@ -367,13 +367,14 @@ $ModelChoices = @{
|
||||
1 = @{ Provider = "DeepSeek"; Default = "deepseek-v4-flash"; Field = "deepseek_api_key" }
|
||||
2 = @{ Provider = "Claude"; Default = "claude-opus-4-8"; Field = "claude_api_key"; BaseField = "claude_api_base" }
|
||||
3 = @{ Provider = "Gemini"; Default = "gemini-3.1-pro-preview"; Field = "gemini_api_key"; BaseField = "gemini_api_base" }
|
||||
4 = @{ Provider = "OpenAI GPT"; Default = "gpt-5.4"; Field = "open_ai_api_key"; BaseField = "open_ai_api_base" }
|
||||
5 = @{ Provider = "MiniMax"; Default = "MiniMax-M2.7"; Field = "minimax_api_key" }
|
||||
6 = @{ Provider = "Zhipu AI"; Default = "glm-5.1"; Field = "zhipu_ai_api_key" }
|
||||
7 = @{ Provider = "Qwen (DashScope)"; Default = "qwen3.6-plus"; Field = "dashscope_api_key" }
|
||||
4 = @{ Provider = "OpenAI"; Default = "gpt-5.5"; Field = "open_ai_api_key"; BaseField = "open_ai_api_base" }
|
||||
5 = @{ Provider = "MiniMax"; Default = "MiniMax-M3"; Field = "minimax_api_key" }
|
||||
6 = @{ Provider = "GLM"; Default = "glm-5.1"; Field = "zhipu_ai_api_key" }
|
||||
7 = @{ Provider = "Qwen (DashScope)"; Default = "qwen3.7-plus"; Field = "dashscope_api_key" }
|
||||
8 = @{ Provider = "Doubao (Volcengine Ark)"; Default = "doubao-seed-2-0-code-preview-260215"; Field = "ark_api_key" }
|
||||
9 = @{ Provider = "Kimi (Moonshot)"; Default = "kimi-k2.6"; Field = "moonshot_api_key" }
|
||||
10 = @{ Provider = "LinkAI"; Default = "deepseek-v4-flash"; Field = "linkai_api_key"; Linkai = $true }
|
||||
10 = @{ Provider = "MiMo"; Default = "mimo-v2.5-pro"; Field = "mimo_api_key" }
|
||||
11 = @{ Provider = "LinkAI"; Default = "deepseek-v4-flash"; Field = "linkai_api_key"; Linkai = $true }
|
||||
}
|
||||
|
||||
function Select-Model {
|
||||
@@ -381,14 +382,15 @@ function Select-Model {
|
||||
$title = T "选择 AI 模型" "Select AI Model"
|
||||
$options = @(
|
||||
"DeepSeek (deepseek-v4-flash, deepseek-v4-pro, etc.)",
|
||||
"Claude (claude-opus-4-8, claude-opus-4-7, claude-sonnet-4-6, etc.)",
|
||||
"Gemini (gemini-3.1-flash-lite-preview, gemini-3.1-pro-preview, etc.)",
|
||||
"OpenAI GPT (gpt-5.4, gpt-5.2, gpt-4.1, etc.)",
|
||||
"MiniMax (MiniMax-M2.7, MiniMax-M2.5, etc.)",
|
||||
"Zhipu AI (glm-5.1, glm-5-turbo, glm-5, etc.)",
|
||||
"Qwen (qwen3.6-plus, qwen3.5-plus, qwen3-max, qwq-plus, etc.)",
|
||||
"Doubao (doubao-seed-2-0-code-preview-260215, etc.)",
|
||||
"Kimi (kimi-k2.6, kimi-k2.5, kimi-k2, etc.)",
|
||||
"Claude (claude-opus-4-8, claude-opus-4-7, etc.)",
|
||||
"Gemini (gemini-3.5-flash, gemini-3.1-pro-preview, etc.)",
|
||||
"OpenAI (gpt-5.5, etc.)",
|
||||
"MiniMax (MiniMax-M3, etc.)",
|
||||
"GLM (glm-5.1, etc.)",
|
||||
"Qwen (qwen3.7-plus, qwen3.7-max, etc.)",
|
||||
"Doubao (doubao-seed-2.0, etc.)",
|
||||
"Kimi (kimi-k2.6, etc.)",
|
||||
"MiMo (mimo-v2.5-pro, etc.)",
|
||||
("LinkAI (" + (T "一个 Key 接入所有模型" "access all models via one API") + ")"),
|
||||
(T "⏭ 跳过(稍后在 Web 控制台配置)" "⏭ Skip (configure later in the web console)")
|
||||
)
|
||||
@@ -406,7 +408,7 @@ function Configure-Model {
|
||||
$script:ApiBaseField = ""
|
||||
$script:UseLinkai = $false
|
||||
|
||||
if ($script:ModelChoice -eq 11) {
|
||||
if ($script:ModelChoice -eq 12) {
|
||||
# Skip: leave model unset, will be configured in the web console.
|
||||
Write-Warn (T "已跳过模型配置,稍后可在 Web 控制台填写" "Model configuration skipped, you can set it later in the web console")
|
||||
return
|
||||
@@ -432,8 +434,8 @@ function Get-ChannelLabel {
|
||||
param([string]$Key)
|
||||
switch ($Key) {
|
||||
"web" { return (T "Web 网页控制台(推荐,开箱即用)" "Web Console (recommended, ready to use)") }
|
||||
"weixin" { return (T "微信 Weixin" "WeChat (Weixin)") }
|
||||
"feishu" { return (T "飞书 Feishu" "Feishu / Lark") }
|
||||
"weixin" { return (T "微信 Weixin" "Wechat") }
|
||||
"feishu" { return (T "飞书 Feishu" "Feishu") }
|
||||
"dingtalk" { return (T "钉钉 DingTalk" "DingTalk") }
|
||||
"wecom_bot" { return (T "企微智能机器人 WeCom Bot" "WeCom Bot") }
|
||||
"qq" { return "QQ" }
|
||||
@@ -563,6 +565,7 @@ function New-ConfigFile {
|
||||
ark_api_key = ""
|
||||
dashscope_api_key = ""
|
||||
minimax_api_key = ""
|
||||
mimo_api_key = ""
|
||||
deepseek_api_key = ""
|
||||
deepseek_api_base = "https://api.deepseek.com/v1"
|
||||
voice_to_text = "openai"
|
||||
|
||||
63
tests/test_dashscope_provider.py
Normal file
63
tests/test_dashscope_provider.py
Normal file
@@ -0,0 +1,63 @@
|
||||
# encoding:utf-8
|
||||
"""Unit tests for Qwen DashScope qwen3.7-plus provider updates."""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
|
||||
class TestDashscopeConst(unittest.TestCase):
|
||||
def test_qwen37_plus_constant_defined(self):
|
||||
from common import const
|
||||
self.assertEqual(const.QWEN37_PLUS, "qwen3.7-plus")
|
||||
|
||||
def test_qwen37_plus_in_model_list(self):
|
||||
from common import const
|
||||
self.assertIn("qwen3.7-plus", const.MODEL_LIST)
|
||||
|
||||
def test_qwen37_plus_before_qwen37_max_in_model_list(self):
|
||||
from common import const
|
||||
qwen_models = [m for m in const.MODEL_LIST if str(m).startswith("qwen")]
|
||||
self.assertGreater(
|
||||
len(qwen_models),
|
||||
1,
|
||||
)
|
||||
self.assertEqual(qwen_models[0], "qwen3.7-plus")
|
||||
|
||||
|
||||
class TestDashscopeBotDefaultModel(unittest.TestCase):
|
||||
def test_default_model_is_qwen37_plus(self):
|
||||
mock_conf = MagicMock()
|
||||
mock_conf.get = MagicMock(side_effect=lambda key, default=None: default)
|
||||
|
||||
with patch("models.dashscope.dashscope_bot.conf", return_value=mock_conf):
|
||||
with patch("models.dashscope.dashscope_bot.SessionManager"):
|
||||
from models.dashscope.dashscope_bot import DashscopeBot
|
||||
bot = DashscopeBot.__new__(DashscopeBot)
|
||||
bot.sessions = MagicMock()
|
||||
bot.model_name = mock_conf.get("model") or "qwen3.7-plus"
|
||||
self.assertEqual(bot.model_name, "qwen3.7-plus")
|
||||
|
||||
def test_default_model_string_in_source(self):
|
||||
bot_path = os.path.join(
|
||||
os.path.dirname(__file__), "..", "models", "dashscope", "dashscope_bot.py"
|
||||
)
|
||||
with open(bot_path, encoding="utf-8") as f:
|
||||
source = f.read()
|
||||
self.assertIn('"qwen3.7-plus"', source)
|
||||
|
||||
|
||||
class TestDashscopeMultimodalRouting(unittest.TestCase):
|
||||
def test_qwen37_plus_uses_multimodal_api(self):
|
||||
from models.dashscope.dashscope_bot import DashscopeBot
|
||||
self.assertTrue(DashscopeBot._is_multimodal_model("qwen3.7-plus"))
|
||||
|
||||
def test_qwen37_max_uses_generation_api(self):
|
||||
from models.dashscope.dashscope_bot import DashscopeBot
|
||||
self.assertFalse(DashscopeBot._is_multimodal_model("qwen3.7-max"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
856
tests/test_evolution.py
Normal file
856
tests/test_evolution.py
Normal file
@@ -0,0 +1,856 @@
|
||||
"""Self-evolution test harness.
|
||||
|
||||
Simulates multiple realistic conversations and checks the evolution pass behaves
|
||||
correctly: stays silent when it should, evolves (memory/skill) when it should,
|
||||
backs up before editing, notifies the user, and supports undo.
|
||||
|
||||
Two modes:
|
||||
- stub (default): the review agent's reasoning is replaced by a scripted
|
||||
output per scenario. Fast, deterministic, validates the WIRING (backup,
|
||||
record, inject, notify, undo, protection). No model calls.
|
||||
- real: the review agent runs the configured model for real. Validates the
|
||||
QUALITY of the judgement (does it correctly decide to act / stay silent).
|
||||
|
||||
Run:
|
||||
python tests/test_evolution.py # stub mode
|
||||
python tests/test_evolution.py --real # real model mode
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fakes
|
||||
# ---------------------------------------------------------------------------
|
||||
class FakeChannel:
|
||||
"""Captures channel.send calls instead of sending."""
|
||||
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def send(self, reply, context):
|
||||
self.sent.append({"content": getattr(reply, "content", str(reply)), "receiver": context.get("receiver")})
|
||||
|
||||
|
||||
class FakeModel:
|
||||
pass
|
||||
|
||||
|
||||
class FakeAgent:
|
||||
"""Minimal stand-in for a chat Agent."""
|
||||
|
||||
def __init__(self, messages, tools=None):
|
||||
import threading
|
||||
self.messages = messages
|
||||
self.messages_lock = threading.Lock()
|
||||
self.tools = tools or []
|
||||
self.model = FakeModel()
|
||||
self.skill_manager = None
|
||||
self.memory_manager = None
|
||||
|
||||
|
||||
class FakeReviewAgent:
|
||||
"""Review agent whose run_stream returns a scripted result (stub mode)."""
|
||||
|
||||
def __init__(self, scripted_output, workspace, on_edit=None):
|
||||
self._out = scripted_output
|
||||
self._workspace = workspace
|
||||
self._on_edit = on_edit
|
||||
self.model = None
|
||||
|
||||
def run_stream(self, user_message, clear_history=False, **kwargs):
|
||||
# Simulate the side effects a real review agent would perform.
|
||||
if self._on_edit:
|
||||
self._on_edit(self._workspace)
|
||||
return self._out
|
||||
|
||||
|
||||
class FakeAgentBridge:
|
||||
"""Stand-in for AgentBridge wiring used by the executor."""
|
||||
|
||||
def __init__(self, agent, scripted_output, on_edit=None):
|
||||
self.agents = {"session_test": agent}
|
||||
self.default_agent = agent
|
||||
self._scripted = scripted_output
|
||||
self._on_edit = on_edit
|
||||
self.injected = []
|
||||
|
||||
def create_agent(self, **kwargs):
|
||||
from agent.memory.config import get_default_memory_config
|
||||
ws = get_default_memory_config().get_workspace()
|
||||
return FakeReviewAgent(self._scripted, ws, on_edit=self._on_edit)
|
||||
|
||||
def remember_scheduled_output(self, session_id, content, channel_type="", task_description=""):
|
||||
self.injected.append(content)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test scaffolding
|
||||
# ---------------------------------------------------------------------------
|
||||
def _setup_workspace():
|
||||
"""Create a realistic temp workspace: seeded memory + real editable skills.
|
||||
|
||||
Mirrors a real CowAgent workspace closely enough that the model has genuine
|
||||
content to read, reason about, and edit during a real evolution pass.
|
||||
"""
|
||||
ws = Path(tempfile.mkdtemp(prefix="evo_test_"))
|
||||
(ws / "MEMORY.md").write_text(
|
||||
"# Long-term Memory\n\n"
|
||||
"## User\n"
|
||||
"- Name: 大锤 (David)\n"
|
||||
"- Lives in Shenzhen, works as a backend engineer\n"
|
||||
"- Company: a fintech startup, team of 8\n\n"
|
||||
"## Preferences\n"
|
||||
"- Likes detailed technical explanations\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(ws / "memory").mkdir()
|
||||
(ws / "output").mkdir()
|
||||
skills = ws / "skills"
|
||||
|
||||
# Editable skill 1: weekly report generator (has a structural gap: no risk).
|
||||
(skills / "weekly-report").mkdir(parents=True)
|
||||
(skills / "weekly-report" / "SKILL.md").write_text(
|
||||
"# Weekly Report\n\n"
|
||||
"Generate a weekly work report from the user's notes.\n\n"
|
||||
"## Steps\n"
|
||||
"1. Collect this week's completed items.\n"
|
||||
"2. Summarize key progress in 3-5 bullets.\n"
|
||||
"3. List next week's plan.\n\n"
|
||||
"## Output format\n"
|
||||
"Markdown with sections: 本周进展 / 下周计划\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# Editable skill 2: expense tracker (has a wrong currency-format step).
|
||||
(skills / "expense-tracker").mkdir(parents=True)
|
||||
(skills / "expense-tracker" / "SKILL.md").write_text(
|
||||
"# Expense Tracker\n\n"
|
||||
"Record an expense into output/expenses.md.\n\n"
|
||||
"## Steps\n"
|
||||
"1. Parse amount and category from the user message.\n"
|
||||
"2. Append a row to output/expenses.md.\n"
|
||||
"3. Format the amount with a `$` prefix.\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# Editable skill 3: an API caller whose SKILL.md hardcodes a WRONG endpoint
|
||||
# host. The conversation discovers the correct host at runtime; the right
|
||||
# fix is to edit this file's source, not just log the corrected fact.
|
||||
(skills / "data-fetch").mkdir(parents=True)
|
||||
(skills / "data-fetch" / "SKILL.md").write_text(
|
||||
"# Data Fetch\n\n"
|
||||
"Fetch records from the data service.\n\n"
|
||||
"## Steps\n"
|
||||
"1. Build the request payload from the user's query.\n"
|
||||
"2. POST it to `https://api.example-wrong.com/v1/fetch`.\n"
|
||||
"3. Parse and return the `data` field.\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# Protected built-in skill: must never be edited by evolution.
|
||||
(skills / "image-generation").mkdir(parents=True)
|
||||
(skills / "image-generation" / "SKILL.md").write_text(
|
||||
"# Image Generation (built-in)\nDo not modify.\n", encoding="utf-8"
|
||||
)
|
||||
return ws
|
||||
|
||||
|
||||
def _point_config_at(ws):
|
||||
"""Force the global memory config to use the temp workspace."""
|
||||
from agent.memory.config import MemoryConfig, set_global_memory_config
|
||||
set_global_memory_config(MemoryConfig(workspace_root=str(ws)))
|
||||
|
||||
|
||||
def _make_messages(turns):
|
||||
msgs = []
|
||||
for u, a in turns:
|
||||
msgs.append({"role": "user", "content": u})
|
||||
msgs.append({"role": "assistant", "content": a})
|
||||
return msgs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Scenarios
|
||||
# ---------------------------------------------------------------------------
|
||||
def scenario_silent():
|
||||
"""Pure small talk -> should stay SILENT (no change, no notify)."""
|
||||
return {
|
||||
"name": "闲聊 (should stay SILENT)",
|
||||
"goal": "none",
|
||||
"turns": [
|
||||
("在吗", "在的,有什么可以帮你?"),
|
||||
("今天周五了,终于要放假了", "是呀,周末好好休息一下。"),
|
||||
("哈哈是的,那没事了", "好的,随时找我。"),
|
||||
],
|
||||
"scripted": "[SILENT]",
|
||||
"on_edit": None,
|
||||
"expect_evolved": False,
|
||||
}
|
||||
|
||||
|
||||
def scenario_silent_qa():
|
||||
"""A normal knowledge Q&A -> nothing durable, should stay SILENT."""
|
||||
return {
|
||||
"name": "普通问答 (should stay SILENT)",
|
||||
"goal": "none",
|
||||
"turns": [
|
||||
("Python 里 list 和 tuple 有什么区别?",
|
||||
"主要区别:list 可变、用 [];tuple 不可变、用 ()。tuple 更省内存、可作字典键。"),
|
||||
("那什么时候该用 tuple?", "当数据不应被修改、或要做字典键/集合元素时用 tuple。"),
|
||||
("懂了,谢谢", "不客气。"),
|
||||
],
|
||||
"scripted": "[SILENT]",
|
||||
"on_edit": None,
|
||||
"expect_evolved": False,
|
||||
}
|
||||
|
||||
|
||||
def scenario_silent_transient():
|
||||
"""User shares transient, non-durable info -> should stay SILENT."""
|
||||
return {
|
||||
"name": "临时信息 (should stay SILENT)",
|
||||
"goal": "none",
|
||||
"turns": [
|
||||
("帮我看下今天天气适合跑步吗,深圳", "深圳今天多云 26°C,傍晚湿度高,清晨或晚上跑步比较合适。"),
|
||||
("那我晚上去吧", "好的,记得补水。"),
|
||||
("行", "👍"),
|
||||
],
|
||||
"scripted": "[SILENT]",
|
||||
"on_edit": None,
|
||||
"expect_evolved": False,
|
||||
}
|
||||
|
||||
|
||||
def scenario_silent_advice():
|
||||
"""User asks for one-off advice, no reusable workflow -> should stay SILENT."""
|
||||
return {
|
||||
"name": "一次性建议 (should stay SILENT)",
|
||||
"goal": "none",
|
||||
"turns": [
|
||||
("给我起三个适合咖啡馆的名字", "可以考虑:① 拾光咖啡 ② 角落 Corner ③ 慢半拍。"),
|
||||
("第二个不错", "嗯,「角落 Corner」简洁好记。"),
|
||||
("就用这个了", "好的,祝开业顺利。"),
|
||||
],
|
||||
"scripted": "[SILENT]",
|
||||
"on_edit": None,
|
||||
"expect_evolved": False,
|
||||
}
|
||||
|
||||
|
||||
def scenario_memory_preference():
|
||||
"""User states a durable working preference -> update MEMORY.md."""
|
||||
def edit(ws):
|
||||
from datetime import datetime
|
||||
p = ws / "memory" / (datetime.now().strftime("%Y-%m-%d") + ".md")
|
||||
p.write_text((p.read_text() if p.exists() else "") + "- Prefers concise replies; avoid long explanations\n", encoding="utf-8")
|
||||
|
||||
return {
|
||||
"name": "记忆-偏好 (should note in daily memory)",
|
||||
"goal": "memory",
|
||||
"turns": [
|
||||
("你能帮我解释下什么是数据库事务吗", "当然可以。数据库事务(Transaction)是一组要么全部成功、要么全部失败的操作单元,它有四个核心特性 ACID:原子性、一致性、隔离性、持久性……(接着是 5 段详细展开)"),
|
||||
("打住打住,太长了", "抱歉,我说得太细了。"),
|
||||
("对,你以后回答我都简短一点,抓重点就行,别长篇大论", "好的,明白了。"),
|
||||
("嗯这样挺好", "👌"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:你希望回答简短、抓重点\n"
|
||||
"- 调整:更新了长期记忆 MEMORY.md\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_memory_contains": "concise",
|
||||
}
|
||||
|
||||
|
||||
def scenario_memory_correction():
|
||||
"""User corrects a wrong fact the agent stated -> fix MEMORY.md."""
|
||||
def edit(ws):
|
||||
from datetime import datetime
|
||||
p = ws / "memory" / (datetime.now().strftime("%Y-%m-%d") + ".md")
|
||||
p.write_text((p.read_text() if p.exists() else "") + "- Correction: team size is now 15 (was recorded as 8)\n", encoding="utf-8")
|
||||
|
||||
return {
|
||||
"name": "记忆-纠正事实 (should note correction in daily)",
|
||||
"goal": "memory",
|
||||
"turns": [
|
||||
("我们团队最近又招了几个人", "记得你们是 8 人的小团队,扩张了挺好的。"),
|
||||
("不对,我们现在是 15 个人了,上次你就记错了", "抱歉记错了,你们现在是 15 人团队。"),
|
||||
("嗯对,记住啊", "好的,记住了。"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:团队规模已是 15 人(之前记成 8 人)\n"
|
||||
"- 调整:修正了长期记忆 MEMORY.md\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_memory_contains": "15",
|
||||
}
|
||||
|
||||
|
||||
def scenario_skill_gap():
|
||||
"""Using weekly-report reveals a missing section -> patch the skill."""
|
||||
def edit(ws):
|
||||
p = ws / "skills" / "weekly-report" / "SKILL.md"
|
||||
p.write_text(p.read_text() + "4. List risk items / blockers.\n", encoding="utf-8")
|
||||
|
||||
return {
|
||||
"name": "技能-缺陷 (should patch weekly-report skill)",
|
||||
"goal": "skill",
|
||||
"turns": [
|
||||
("用周报技能帮我生成这周的周报,素材:完成了支付网关重构、修复了3个线上bug、对接了风控接口",
|
||||
"好的,我用 weekly-report 技能生成:\n\n## 本周进展\n- 完成支付网关重构\n- 修复 3 个线上 bug\n- 对接风控接口\n\n## 下周计划\n- 联调风控接口"),
|
||||
("不错,但是每次周报都漏了风险项,我们 leader 每次都要问这个", "确实,风险项很重要。"),
|
||||
("对,你能不能让这个周报技能以后都带上风险项这一节", "可以的,我把它固化进技能。"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:周报需要固定包含「风险项」一节\n"
|
||||
"- 调整:给 weekly-report 技能补充了风险项步骤\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_skill_contains": ("weekly-report", "risk"),
|
||||
}
|
||||
|
||||
|
||||
def scenario_skill_error():
|
||||
"""A skill step is wrong (currency format) -> correct the skill."""
|
||||
def edit(ws):
|
||||
p = ws / "skills" / "expense-tracker" / "SKILL.md"
|
||||
p.write_text(p.read_text().replace("`$` prefix", "`¥` prefix (RMB)"), encoding="utf-8")
|
||||
|
||||
return {
|
||||
"name": "技能-报错纠正 (should fix expense-tracker skill)",
|
||||
"goal": "skill",
|
||||
"turns": [
|
||||
("用记账技能记一笔:午饭 35", "好的,已记录:午饭 $35(已写入 output/expenses.md)"),
|
||||
("怎么是美元?我们都是人民币啊", "抱歉,格式用错了,应该是 ¥35。"),
|
||||
("对,以后这个记账技能都用人民币符号", "明白,我修正技能里的货币格式。"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:记账应使用人民币符号 ¥ 而非 $\n"
|
||||
"- 调整:修正了 expense-tracker 技能的货币格式步骤\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_skill_contains": ("expense-tracker", "¥"),
|
||||
}
|
||||
|
||||
|
||||
def scenario_skill_wrong_config():
|
||||
"""A skill's SKILL.md hardcodes a wrong endpoint; the chat works around it
|
||||
at runtime. Correct evolution = FIX the skill source, not log a memory note.
|
||||
"""
|
||||
def edit(ws):
|
||||
p = ws / "skills" / "data-fetch" / "SKILL.md"
|
||||
p.write_text(
|
||||
p.read_text().replace("api.example-wrong.com", "api.example-correct.com"),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return {
|
||||
"name": "技能-配置错误 (should fix skill source, not log memory)",
|
||||
"goal": "skill",
|
||||
"turns": [
|
||||
("用 data-fetch 技能拉一下最新数据",
|
||||
"好的,我按技能里的步骤 POST 到 https://api.example-wrong.com/v1/fetch …… 报错了,连接失败。"),
|
||||
("哦那个地址不对,正确的是 api.example-correct.com,你用这个调",
|
||||
"好的,换成 https://api.example-correct.com/v1/fetch ,成功拿到数据了 ✅"),
|
||||
("嗯对,就是这个地址", "明白了,这个才是正确的服务地址。"),
|
||||
],
|
||||
# The model must decide on its own to edit the skill; we still provide a
|
||||
# scripted output for stub mode wiring.
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:data-fetch 的正确服务地址是 api.example-correct.com\n"
|
||||
"- 调整:修正了 data-fetch 技能里写错的接口地址\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_skill_contains": ("data-fetch", "api.example-correct.com"),
|
||||
}
|
||||
|
||||
|
||||
def scenario_skill_create():
|
||||
"""A reusable, repeatable workflow emerges that no skill covers, and the
|
||||
user explicitly asks to make it permanent -> CREATE a new skill.
|
||||
"""
|
||||
return {
|
||||
"name": "技能-新增 (should create a new skill)",
|
||||
"goal": "skill",
|
||||
"turns": [
|
||||
("每周一帮我把客户反馈整理成晨会简报:先按「严重/一般/建议」给反馈分类,再统计每类数量,最后写一段 3 句话的总结,发我",
|
||||
"好的,本周客户反馈晨会简报:\n\n## 严重 (2)\n- 支付失败\n- 数据丢失\n## 一般 (3)\n- 加载慢…\n## 建议 (1)\n- 增加暗色模式\n\n总结:本周以稳定性问题为主,建议优先排查支付与数据链路,其余可排期跟进。"),
|
||||
("很好,就是这个格式。上周我也是这么让你弄的", "嗯,分类+计数+三句总结这套流程挺顺手。"),
|
||||
("对,这个我每周一都要用,你能不能把这套流程固化下来,以后我直接说『生成客户反馈晨会简报』你就照这个来",
|
||||
"可以,我把这套「客户反馈晨会简报」流程固化成一个可复用的技能。"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:你每周一都要按「分类+计数+三句总结」生成客户反馈晨会简报\n"
|
||||
"- 调整:新建了「客户反馈晨会简报」技能,固化这套流程\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": _create_briefing_skill,
|
||||
"expect_evolved": True,
|
||||
"expect_new_skill": True,
|
||||
}
|
||||
|
||||
|
||||
def scenario_skill_create_implicit():
|
||||
"""A complex, clearly-structured multi-step workflow is executed once. The
|
||||
user NEVER says "I do this weekly" or "make this a skill" — the agent must
|
||||
判断 on its own that this is a reusable procedure worth capturing.
|
||||
|
||||
This is the realistic, harder case: no explicit instruction to create a
|
||||
skill, only an obviously repeatable workflow.
|
||||
"""
|
||||
return {
|
||||
"name": "技能-隐式新增 (complex workflow, user never asks to save)",
|
||||
"goal": "skill",
|
||||
"turns": [
|
||||
("帮我做一份竞品调研:对比一下 Notion、飞书文档、语雀这三个产品",
|
||||
"好的,我按一套固定方法来做竞品调研:\n1. 先确定对比维度:定价、协作能力、模板生态、API 开放度、本地化;\n2. 逐个产品按维度收集信息;\n3. 做成对比表;\n4. 给出结论和选型建议。\n\n(随后产出了完整的五维度对比表 + 结论)"),
|
||||
("不错。再帮我用同样的方法调研一下 Slack、企业微信、钉钉",
|
||||
"好的,沿用刚才那套方法(定价/协作/模板/API/本地化 五维度 → 收集 → 对比表 → 结论):\n\n(产出了第二份五维度对比表 + 选型建议)"),
|
||||
("可以,结论挺清楚的", "嗯,这套五维度对比的方法做下来结构很清楚。"),
|
||||
],
|
||||
# In real mode the model decides on its own. The scripted side effect
|
||||
# only wires stub mode; it emulates capturing the procedure as a skill.
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 学到:你做竞品调研有一套固定方法(五维度对比 → 收集 → 对比表 → 结论)\n"
|
||||
"- 调整:把这套竞品调研流程固化成了一个可复用技能\n"
|
||||
"如果不对,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": _create_competitor_skill,
|
||||
"expect_evolved": True,
|
||||
"expect_new_skill": True,
|
||||
}
|
||||
|
||||
|
||||
def _create_competitor_skill(ws):
|
||||
"""Stub side effect: emulate capturing the competitor-research procedure."""
|
||||
d = ws / "skills" / "competitor-research"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "SKILL.md").write_text(
|
||||
"# Competitor Research\n\n"
|
||||
"Compare a set of products with a fixed methodology.\n\n"
|
||||
"## Steps\n"
|
||||
"1. Fix the comparison dimensions (pricing, collaboration, templates, API, localization).\n"
|
||||
"2. Collect info per product across each dimension.\n"
|
||||
"3. Build a comparison table.\n"
|
||||
"4. Give a conclusion and recommendation.\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def scenario_skill_no_create():
|
||||
"""A one-off, novel task with no sign of recurrence -> must NOT create a
|
||||
skill (and ideally stay silent). Guards against over-eager skill creation.
|
||||
"""
|
||||
return {
|
||||
"name": "技能-不应新增 (one-off task, must NOT create skill)",
|
||||
"goal": "none",
|
||||
"turns": [
|
||||
("帮我把这段话翻译成英文:今晚的庆功宴改到 8 点", "翻译:The celebration dinner tonight is moved to 8 PM."),
|
||||
("谢谢", "不客气。"),
|
||||
("嗯没事了", "好的,随时找我。"),
|
||||
],
|
||||
"scripted": "[SILENT]",
|
||||
"on_edit": None,
|
||||
"expect_evolved": False,
|
||||
"expect_no_new_skill": True,
|
||||
}
|
||||
|
||||
|
||||
def _create_briefing_skill(ws):
|
||||
"""Stub side effect: emulate creating a new skill under workspace skills/."""
|
||||
d = ws / "skills" / "customer-feedback-briefing"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "SKILL.md").write_text(
|
||||
"# Customer Feedback Briefing\n\n"
|
||||
"Turn raw customer feedback into a standup briefing.\n\n"
|
||||
"## Steps\n"
|
||||
"1. Classify each item as 严重/一般/建议.\n"
|
||||
"2. Count items per category.\n"
|
||||
"3. Write a 3-sentence summary.\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def scenario_unfinished_task():
|
||||
"""A promised deliverable was not produced -> finish it now via tools."""
|
||||
def edit(ws):
|
||||
p = ws / "output" / "team-roster.md"
|
||||
p.write_text("# Team Roster (backend)\n- 张伟\n- 李娜\n- 王强\n- 大锤\n", encoding="utf-8")
|
||||
|
||||
return {
|
||||
"name": "未完成任务 (should finish & write output file)",
|
||||
"goal": "task",
|
||||
"turns": [
|
||||
("帮我把后端团队花名册整理成一个文件保存下,成员有:张伟、李娜、王强,还有我自己(大锤)",
|
||||
"好的,后端 4 个人:张伟、李娜、王强、大锤。我整理成文件保存到 output/team-roster.md。"),
|
||||
("好的麻烦了,我先去开个会", "没问题,我现在就处理。"),
|
||||
("(用户离开,会话中断,文件尚未写入)", "(助手未及写入文件,对话中断)"),
|
||||
],
|
||||
"scripted": (
|
||||
"我刚做了一次自我学习。\n"
|
||||
"- 发现:之前答应整理团队花名册但没完成\n"
|
||||
"- 已完成:把后端成员名单写入 output/team-roster.md\n"
|
||||
"如果不需要,回复「撤销上次学习」即可。"
|
||||
),
|
||||
"on_edit": edit,
|
||||
"expect_evolved": True,
|
||||
"expect_output_file": "team-roster.md",
|
||||
}
|
||||
|
||||
|
||||
SCENARIOS = [
|
||||
scenario_silent,
|
||||
scenario_silent_qa,
|
||||
scenario_silent_transient,
|
||||
scenario_silent_advice,
|
||||
scenario_memory_preference,
|
||||
scenario_memory_correction,
|
||||
scenario_skill_gap,
|
||||
scenario_skill_error,
|
||||
scenario_skill_wrong_config,
|
||||
scenario_skill_create,
|
||||
scenario_skill_create_implicit,
|
||||
scenario_skill_no_create,
|
||||
scenario_unfinished_task,
|
||||
]
|
||||
|
||||
# Skill directories present in a fresh workspace; anything beyond these that
|
||||
# appears after a pass is a newly-created skill.
|
||||
_SEED_SKILLS = {"weekly-report", "expense-tracker", "data-fetch", "image-generation"}
|
||||
|
||||
|
||||
def _new_skill_dirs(ws: Path) -> set:
|
||||
"""Skill directories created beyond the seeded set."""
|
||||
skills_dir = ws / "skills"
|
||||
if not skills_dir.exists():
|
||||
return set()
|
||||
return {p.name for p in skills_dir.iterdir() if p.is_dir()} - _SEED_SKILLS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runner (stub mode)
|
||||
# ---------------------------------------------------------------------------
|
||||
def run_stub():
|
||||
from agent.evolution.executor import run_evolution_for_session
|
||||
from agent.evolution import backup as backup_mod
|
||||
from config import conf
|
||||
# Evolution is disabled by default now; enable for the test.
|
||||
conf()["self_evolution_enabled"] = True
|
||||
|
||||
passed, failed = 0, 0
|
||||
for make in SCENARIOS:
|
||||
sc = make()
|
||||
ws = _setup_workspace()
|
||||
try:
|
||||
_point_config_at(ws)
|
||||
# Patch channel push to capture instead of send.
|
||||
channel = FakeChannel()
|
||||
import agent.evolution.executor as ex
|
||||
orig_notify = ex._notify_user
|
||||
ex._notify_user = lambda ct, rcv, summary: channel.send(
|
||||
type("R", (), {"content": summary})(),
|
||||
{"receiver": rcv},
|
||||
)
|
||||
|
||||
agent = FakeAgent(_make_messages(sc["turns"]))
|
||||
bridge = FakeAgentBridge(agent, sc["scripted"], on_edit=sc["on_edit"])
|
||||
|
||||
evolved = run_evolution_for_session(
|
||||
bridge, "session_test", channel_type="telegram", receiver="user_42"
|
||||
)
|
||||
|
||||
ok = True
|
||||
errs = []
|
||||
|
||||
if evolved != sc["expect_evolved"]:
|
||||
ok = False
|
||||
errs.append(f"evolved={evolved}, expected {sc['expect_evolved']}")
|
||||
|
||||
if sc["expect_evolved"]:
|
||||
# memory / skill content checks
|
||||
if "expect_memory_contains" in sc:
|
||||
# Evolution now writes to the dated daily file, not MEMORY.md.
|
||||
from datetime import datetime
|
||||
daily = ws / "memory" / (datetime.now().strftime("%Y-%m-%d") + ".md")
|
||||
mem = daily.read_text() if daily.exists() else ""
|
||||
if sc["expect_memory_contains"] not in mem:
|
||||
ok = False
|
||||
errs.append("daily memory missing expected content")
|
||||
if "expect_skill_contains" in sc:
|
||||
sk, txt = sc["expect_skill_contains"]
|
||||
content = (ws / "skills" / sk / "SKILL.md").read_text()
|
||||
if txt not in content:
|
||||
ok = False
|
||||
errs.append("skill missing expected content")
|
||||
if sc.get("expect_new_skill") and not _new_skill_dirs(ws):
|
||||
ok = False
|
||||
errs.append("expected a new skill to be created")
|
||||
# notify happened
|
||||
if not channel.sent:
|
||||
ok = False
|
||||
errs.append("no notification sent")
|
||||
# injection happened (undo support)
|
||||
if not bridge.injected or "[EVOLUTION]" not in bridge.injected[0]:
|
||||
ok = False
|
||||
errs.append("no [EVOLUTION] record injected")
|
||||
# protected skill untouched
|
||||
prot = (ws / "skills" / "image-generation" / "SKILL.md").read_text()
|
||||
if prot != "# Image Generation (built-in)\nDo not modify.\n":
|
||||
ok = False
|
||||
errs.append("PROTECTED skill was modified!")
|
||||
# backup exists (undo possible)
|
||||
backups = list((ws / "memory" / ".evolution_backups").glob("*"))
|
||||
if not backups:
|
||||
ok = False
|
||||
errs.append("no backup created")
|
||||
else:
|
||||
# SILENT: nothing should have changed / been sent
|
||||
if channel.sent:
|
||||
ok = False
|
||||
errs.append("notification sent on SILENT")
|
||||
if bridge.injected:
|
||||
ok = False
|
||||
errs.append("injected record on SILENT")
|
||||
if sc.get("expect_no_new_skill") and _new_skill_dirs(ws):
|
||||
ok = False
|
||||
errs.append(f"unexpected new skill created: {_new_skill_dirs(ws)}")
|
||||
|
||||
ex._notify_user = orig_notify
|
||||
|
||||
if ok:
|
||||
passed += 1
|
||||
print(f" PASS {sc['name']}")
|
||||
else:
|
||||
failed += 1
|
||||
print(f" FAIL {sc['name']}: {'; '.join(errs)}")
|
||||
finally:
|
||||
shutil.rmtree(ws, ignore_errors=True)
|
||||
|
||||
# Undo verification (uses the memory scenario's backup path).
|
||||
print("\n-- undo tool --")
|
||||
_verify_undo()
|
||||
|
||||
print(f"\nStub results: {passed} passed, {failed} failed")
|
||||
return failed == 0
|
||||
|
||||
|
||||
def _verify_undo():
|
||||
from agent.evolution.backup import create_backup, restore_backup
|
||||
ws = _setup_workspace()
|
||||
try:
|
||||
_point_config_at(ws)
|
||||
mem = ws / "MEMORY.md"
|
||||
bid = create_backup(ws, [mem])
|
||||
mem.write_text("CORRUPTED", encoding="utf-8")
|
||||
from agent.tools.evolution_undo import EvolutionUndoTool
|
||||
r = EvolutionUndoTool().execute({"backup_id": bid})
|
||||
restored = mem.read_text()
|
||||
if r.status == "success" and "大锤" in restored:
|
||||
print(" PASS undo restores pre-evolution state")
|
||||
else:
|
||||
print(f" FAIL undo: status={r.status}, content={restored[:40]}")
|
||||
finally:
|
||||
shutil.rmtree(ws, ignore_errors=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runner (real mode) — minimal: just prints the model's decision per scenario.
|
||||
# ---------------------------------------------------------------------------
|
||||
def _snapshot_ws(ws: Path) -> dict:
|
||||
"""Map every text file under the workspace -> content (skip backups dir)."""
|
||||
snap = {}
|
||||
for p in ws.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
rel = str(p.relative_to(ws))
|
||||
if rel.startswith("memory/.evolution_backups"):
|
||||
continue
|
||||
try:
|
||||
snap[rel] = p.read_text(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
return snap
|
||||
|
||||
|
||||
def _print_diff(before: dict, after: dict) -> bool:
|
||||
"""Print added/changed files. Returns True if anything changed."""
|
||||
changed = False
|
||||
keys = sorted(set(before) | set(after))
|
||||
for rel in keys:
|
||||
old = before.get(rel)
|
||||
new = after.get(rel)
|
||||
if old == new:
|
||||
continue
|
||||
changed = True
|
||||
tag = "NEW FILE" if old is None else "CHANGED"
|
||||
print(f" ~ {rel} [{tag}]")
|
||||
old_lines = set((old or "").splitlines())
|
||||
for line in (new or "").splitlines():
|
||||
if line not in old_lines:
|
||||
print(f" + {line}")
|
||||
return changed
|
||||
|
||||
|
||||
def run_real():
|
||||
"""Run real model evolution on each scenario and print the actual output.
|
||||
|
||||
Uses config.json's configured model via a real AgentBridge, so you see
|
||||
exactly what the model decides and writes for each conversation.
|
||||
"""
|
||||
from bridge.bridge import Bridge
|
||||
from agent.memory.config import (
|
||||
MemoryConfig,
|
||||
set_global_memory_config,
|
||||
get_default_memory_config,
|
||||
)
|
||||
from config import conf, load_config
|
||||
|
||||
# Load config.json so real API keys are available to the bots.
|
||||
load_config()
|
||||
|
||||
# Default the test to deepseek-v4-flash (fast, low cost) unless overridden.
|
||||
override_model = os.environ.get("EVO_TEST_MODEL", "deepseek-v4-flash")
|
||||
conf()["model"] = override_model
|
||||
conf()["bot_type"] = os.environ.get("EVO_TEST_BOT_TYPE", "deepseek")
|
||||
# Force-enable evolution for the test regardless of config.json default.
|
||||
conf()["self_evolution_enabled"] = True
|
||||
print(f"[test] model: {override_model} (bot_type={conf().get('bot_type')}, "
|
||||
f"key={'set' if conf().get('deepseek_api_key') else 'MISSING'})")
|
||||
|
||||
from agent.memory.manager import MemoryManager
|
||||
import agent.evolution.executor as ex
|
||||
|
||||
bridge = Bridge()
|
||||
agent_bridge = bridge.get_agent_bridge()
|
||||
|
||||
# Capture the user-facing reply instead of pushing it to a channel.
|
||||
captured = {"reply": None}
|
||||
orig_notify = ex._notify_user
|
||||
ex._notify_user = lambda ct, rcv, summary: captured.__setitem__("reply", summary)
|
||||
|
||||
results = [] # (name, goal, evolved, changed, reply_ok)
|
||||
|
||||
only = os.environ.get("EVO_TEST_ONLY") # substring filter on goal/name
|
||||
try:
|
||||
for make in SCENARIOS:
|
||||
sc = make()
|
||||
if only and only not in sc["goal"] and only not in sc["name"]:
|
||||
continue
|
||||
ws = _setup_workspace()
|
||||
captured["reply"] = None
|
||||
try:
|
||||
mem_cfg = MemoryConfig(workspace_root=str(ws))
|
||||
set_global_memory_config(mem_cfg)
|
||||
|
||||
sid = "session_evo_real"
|
||||
# Fully isolated agent: tool cwd + memory_manager -> temp ws.
|
||||
iso_mem = MemoryManager(mem_cfg)
|
||||
agent = agent_bridge.create_agent(
|
||||
system_prompt="You are a helpful assistant.",
|
||||
tools=None,
|
||||
workspace_dir=str(ws),
|
||||
memory_manager=iso_mem,
|
||||
enable_skills=False,
|
||||
)
|
||||
# Notify path needs a channel+receiver to fire; give dummies.
|
||||
agent_bridge.agents[sid] = agent
|
||||
with agent.messages_lock:
|
||||
agent.messages.clear()
|
||||
agent.messages.extend(_make_messages(sc["turns"]))
|
||||
|
||||
before = _snapshot_ws(ws)
|
||||
|
||||
print("\n" + "=" * 72)
|
||||
print(f"场景: {sc['name']} [目标: {sc['goal']}]")
|
||||
print("-" * 72)
|
||||
print("【会话输入】")
|
||||
for u, a in sc["turns"]:
|
||||
print(f" 用户: {u}")
|
||||
print(f" 助手: {a}")
|
||||
|
||||
from agent.evolution.executor import run_evolution_for_session
|
||||
evolved = run_evolution_for_session(
|
||||
agent_bridge, sid, channel_type="telegram", receiver="tester"
|
||||
)
|
||||
|
||||
after = _snapshot_ws(ws)
|
||||
print("\n【进化结果】 evolved =", evolved)
|
||||
changed = False
|
||||
if evolved:
|
||||
changed = _print_diff(before, after)
|
||||
if not changed:
|
||||
print(" (无文件变更)")
|
||||
else:
|
||||
print(" (静默,未做任何改动)")
|
||||
|
||||
new_skills = _new_skill_dirs(ws)
|
||||
if new_skills:
|
||||
print(f" 新建技能: {', '.join(sorted(new_skills))}")
|
||||
# Surface mismatches against the scenario's skill expectation.
|
||||
if sc.get("expect_new_skill") and not new_skills:
|
||||
print(" ⚠ 预期新建技能,但未创建")
|
||||
if sc.get("expect_no_new_skill") and new_skills:
|
||||
print(" ⚠ 不应新建技能,但创建了")
|
||||
|
||||
print("\n【给用户的回复】")
|
||||
if captured["reply"]:
|
||||
for line in captured["reply"].splitlines():
|
||||
print(f" {line}")
|
||||
else:
|
||||
print(" (无推送)")
|
||||
|
||||
reply_ok = bool(captured["reply"]) == bool(evolved)
|
||||
results.append((sc["name"], sc["goal"], evolved, changed, reply_ok))
|
||||
agent_bridge.agents.pop(sid, None)
|
||||
finally:
|
||||
shutil.rmtree(ws, ignore_errors=True)
|
||||
finally:
|
||||
ex._notify_user = orig_notify
|
||||
|
||||
# Summary table.
|
||||
print("\n" + "=" * 72)
|
||||
print("汇总 (deepseek-v4-flash 真实运行)")
|
||||
print("-" * 72)
|
||||
for name, goal, evolved, changed, reply_ok in results:
|
||||
exp = "静默" if goal == "none" else "应进化"
|
||||
got = "进化" if evolved else "静默"
|
||||
mark = "✓" if (goal == "none") != evolved else "✗"
|
||||
print(f" {mark} {name:42s} 预期={exp} 实际={got}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "--debug" in sys.argv:
|
||||
import logging
|
||||
from common.log import logger as _cow_logger
|
||||
_cow_logger.setLevel(logging.DEBUG)
|
||||
for _h in _cow_logger.handlers:
|
||||
_h.setLevel(logging.DEBUG)
|
||||
if "--real" in sys.argv:
|
||||
run_real()
|
||||
else:
|
||||
ok = run_stub()
|
||||
sys.exit(0 if ok else 1)
|
||||
24
tests/test_invariant_bash.py
Normal file
24
tests/test_invariant_bash.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import pytest
|
||||
from agent.tools.bash.bash import Bash
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
"cat ~/.cow/.env",
|
||||
"cat .cow/.env",
|
||||
"less ~/.cow/.env",
|
||||
"cat /home/user/.cow/.env",
|
||||
])
|
||||
def test_credential_file_access_is_blocked(command):
|
||||
result = Bash().execute({"command": command})
|
||||
assert result.status == "error", f"Expected blocked result for: {command}"
|
||||
assert "Access denied" in str(result.result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("command", [
|
||||
"ls ~/.cow/skills",
|
||||
"ls ~/.cow/",
|
||||
"echo hello",
|
||||
])
|
||||
def test_legitimate_cow_directory_access_is_not_blocked(command):
|
||||
result = Bash().execute({"command": command})
|
||||
assert "Access denied" not in str(result.result)
|
||||
@@ -1,7 +1,7 @@
|
||||
# encoding:utf-8
|
||||
"""
|
||||
Unit tests for MiniMax provider additions:
|
||||
- MiniMax-M2.7-highspeed constant in const.py
|
||||
- MiniMax-M3 / M2.7 / M2.7-highspeed constants in const.py
|
||||
- Default model update in MinimaxBot
|
||||
- MinimaxVoice TTS provider
|
||||
"""
|
||||
@@ -16,7 +16,12 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
|
||||
class TestMinimaxConst(unittest.TestCase):
|
||||
"""Test that MiniMax-M2.7-highspeed is properly registered in const.py."""
|
||||
"""Test that MiniMax M3 / M2.7 constants are properly registered in const.py."""
|
||||
|
||||
def test_m3_constant_defined(self):
|
||||
from common import const
|
||||
self.assertTrue(hasattr(const, "MINIMAX_M3"))
|
||||
self.assertEqual(const.MINIMAX_M3, "MiniMax-M3")
|
||||
|
||||
def test_m2_7_highspeed_constant_defined(self):
|
||||
from common import const
|
||||
@@ -27,6 +32,10 @@ class TestMinimaxConst(unittest.TestCase):
|
||||
from common import const
|
||||
self.assertEqual(const.MINIMAX_M2_7, "MiniMax-M2.7")
|
||||
|
||||
def test_m3_in_model_list(self):
|
||||
from common import const
|
||||
self.assertIn("MiniMax-M3", const.MODEL_LIST)
|
||||
|
||||
def test_m2_7_highspeed_in_model_list(self):
|
||||
from common import const
|
||||
self.assertIn("MiniMax-M2.7-highspeed", const.MODEL_LIST)
|
||||
@@ -41,9 +50,9 @@ class TestMinimaxConst(unittest.TestCase):
|
||||
|
||||
|
||||
class TestMinimaxBotDefaultModel(unittest.TestCase):
|
||||
"""Test that MinimaxBot defaults to MiniMax-M2.7."""
|
||||
"""Test that MinimaxBot defaults to MiniMax-M3."""
|
||||
|
||||
def test_default_model_is_m2_7(self):
|
||||
def test_default_model_is_m3(self):
|
||||
# Patch conf() to return empty config
|
||||
mock_conf = MagicMock()
|
||||
mock_conf.get = MagicMock(side_effect=lambda key, default=None: default)
|
||||
@@ -57,18 +66,18 @@ class TestMinimaxBotDefaultModel(unittest.TestCase):
|
||||
with patch("models.minimax.minimax_bot.conf", return_value=mock_conf):
|
||||
bot = minimax_bot.MinimaxBot.__new__(minimax_bot.MinimaxBot)
|
||||
bot.args = {
|
||||
"model": mock_conf.get("model") or "MiniMax-M2.7",
|
||||
"model": mock_conf.get("model") or "MiniMax-M3",
|
||||
}
|
||||
self.assertEqual(bot.args["model"], "MiniMax-M2.7")
|
||||
self.assertEqual(bot.args["model"], "MiniMax-M3")
|
||||
|
||||
def test_default_model_string(self):
|
||||
"""Verify the fallback string literal in minimax_bot.py is MiniMax-M2.7."""
|
||||
"""Verify the fallback string literal in minimax_bot.py is MiniMax-M3."""
|
||||
import ast
|
||||
bot_path = os.path.join(os.path.dirname(__file__), "..", "models", "minimax", "minimax_bot.py")
|
||||
with open(bot_path) as f:
|
||||
source = f.read()
|
||||
# Verify MiniMax-M2.7 is in the source (not M2.1)
|
||||
self.assertIn("MiniMax-M2.7", source)
|
||||
# Verify MiniMax-M3 is in the source (not the older default)
|
||||
self.assertIn("MiniMax-M3", source)
|
||||
self.assertNotIn('"MiniMax-M2.1"', source)
|
||||
|
||||
|
||||
|
||||
99
tests/test_models_handler.py
Normal file
99
tests/test_models_handler.py
Normal file
@@ -0,0 +1,99 @@
|
||||
# encoding:utf-8
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
if "web" not in sys.modules:
|
||||
web_stub = types.ModuleType("web")
|
||||
web_stub.HTTPError = type("HTTPError", (Exception,), {})
|
||||
web_stub.cookies = lambda: {}
|
||||
web_stub.header = lambda *args, **kwargs: None
|
||||
web_stub.data = lambda: b"{}"
|
||||
web_stub.input = lambda **kwargs: types.SimpleNamespace(**kwargs)
|
||||
web_stub.setcookie = lambda *args, **kwargs: None
|
||||
web_stub.seeother = lambda *args, **kwargs: Exception("seeother")
|
||||
web_stub.notfound = lambda *args, **kwargs: Exception("notfound")
|
||||
web_stub.badrequest = lambda *args, **kwargs: Exception("badrequest")
|
||||
web_stub.application = lambda *args, **kwargs: types.SimpleNamespace(wsgifunc=lambda: None)
|
||||
web_stub.httpserver = types.SimpleNamespace(
|
||||
LogMiddleware=type("LogMiddleware", (), {"log": lambda *args, **kwargs: None}),
|
||||
StaticMiddleware=lambda app: app,
|
||||
WSGIServer=lambda *args, **kwargs: types.SimpleNamespace(serve_forever=lambda: None),
|
||||
)
|
||||
sys.modules["web"] = web_stub
|
||||
|
||||
|
||||
class TestModelsHandler(unittest.TestCase):
|
||||
def test_set_asr_capability_persists_provider_and_model(self):
|
||||
from channel.web.web_channel import ModelsHandler
|
||||
|
||||
local_config = {}
|
||||
file_config = {}
|
||||
handler = ModelsHandler()
|
||||
|
||||
with patch("channel.web.web_channel.conf", return_value=local_config):
|
||||
with patch.object(ModelsHandler, "_read_file_config", return_value=file_config):
|
||||
with patch.object(ModelsHandler, "_write_file_config") as write_file:
|
||||
with patch.object(ModelsHandler, "_refresh_voice_routing") as refresh_voice:
|
||||
result = json.loads(handler._handle_set_capability({
|
||||
"capability": "asr",
|
||||
"provider_id": "dashscope",
|
||||
"model": "qwen3-asr-flash",
|
||||
}))
|
||||
|
||||
self.assertEqual(result["status"], "success")
|
||||
self.assertEqual(local_config["voice_to_text"], "dashscope")
|
||||
self.assertEqual(local_config["voice_to_text_model"], "qwen3-asr-flash")
|
||||
self.assertEqual(file_config["voice_to_text"], "dashscope")
|
||||
self.assertEqual(file_config["voice_to_text_model"], "qwen3-asr-flash")
|
||||
write_file.assert_called_once_with(file_config)
|
||||
refresh_voice.assert_called_once()
|
||||
|
||||
def test_set_asr_empty_model_keeps_existing(self):
|
||||
# Switching provider with an empty model must not wipe a user's
|
||||
# hand-configured voice_to_text_model.
|
||||
from channel.web.web_channel import ModelsHandler
|
||||
|
||||
local_config = {"voice_to_text_model": "qwen3-asr-flash"}
|
||||
file_config = {"voice_to_text_model": "qwen3-asr-flash"}
|
||||
handler = ModelsHandler()
|
||||
|
||||
with patch("channel.web.web_channel.conf", return_value=local_config):
|
||||
with patch.object(ModelsHandler, "_read_file_config", return_value=file_config):
|
||||
with patch.object(ModelsHandler, "_write_file_config"):
|
||||
with patch.object(ModelsHandler, "_refresh_voice_routing"):
|
||||
result = json.loads(handler._handle_set_capability({
|
||||
"capability": "asr",
|
||||
"provider_id": "zhipu",
|
||||
"model": "",
|
||||
}))
|
||||
|
||||
self.assertEqual(result["status"], "success")
|
||||
self.assertEqual(local_config["voice_to_text"], "zhipu")
|
||||
# Existing model preserved, not overwritten with "".
|
||||
self.assertEqual(local_config["voice_to_text_model"], "qwen3-asr-flash")
|
||||
self.assertEqual(file_config["voice_to_text_model"], "qwen3-asr-flash")
|
||||
self.assertEqual(result["model"], "qwen3-asr-flash")
|
||||
|
||||
def test_asr_capability_exposes_provider_models(self):
|
||||
from channel.web.web_channel import ModelsHandler
|
||||
|
||||
cap = ModelsHandler._asr_capability({
|
||||
"voice_to_text": "dashscope",
|
||||
"voice_to_text_model": "qwen3-asr-flash",
|
||||
})
|
||||
|
||||
self.assertTrue(cap["editable"])
|
||||
self.assertEqual(cap["current_provider"], "dashscope")
|
||||
self.assertEqual(cap["current_model"], "qwen3-asr-flash")
|
||||
self.assertIn("provider_models", cap)
|
||||
self.assertIn("dashscope", cap["provider_models"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user