Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(bot):Add eval function(support locomo, skillsbench), open add-resource tool, add feishu progress notification capability (#506)
yeshion23333a75f1ac22033
diff --git a/bot/eval/locomo/run_eval.py b/bot/eval/locomo/run_eval.pyindex 65e61cb87..a5f580a6e 100644--- a/bot/eval/locomo/run_eval.py+++ b/bot/eval/locomo/run_eval.py@@ -53,29 +53,12 @@ def run_vikingbot_chat(question: str) -> tuple[str, dict, float]:output = result.stdout.strip()# 解析返回的json结果,处理换行、多余前缀等特殊情况try:- # 先去掉[Pasted前缀- output = output.replace("[Pasted", "").strip()- # 提取第一个{到最后一个}之间的有效JSON内容,清除换行和多余空白- start_idx = output.find("{")- end_idx = output.rfind("}")- if start_idx != -1 and end_idx != -1:- json_str = (- output[start_idx : end_idx + 1].replace("\n", " ").replace("\r", "").strip()- )- # 处理text内容中未转义的双引号- json_str = re.sub(- r'"text": "(.*?)"(?=, "token_usage")',- lambda m: '"text": "%s"' % m.group(1).replace('"', '\\"'),- json_str,- )- resp_json = json.loads(json_str)- response = resp_json.get("text", "")- token_usage = resp_json.get(- "token_usage", {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}- )- time_cost = resp_json.get("time_cost", time_cost)- else:- raise ValueError("No valid JSON structure found in output")+ resp_json = json.loads(output, strict=False)+ response = resp_json.get("text", "")+ token_usage = resp_json.get(+ "token_usage", {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}+ )+ time_cost = resp_json.get("time_cost", time_cost)except (json.JSONDecodeError, ValueError) as e:response = f"[PARSE ERROR] {output}"token_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}@@ -111,8 +94,8 @@ def main():parser.add_argument("input",nargs="?",- default="./locomo10.json",- help="Path to locomo10.json file, default: ./locomo10.json",+ default="./test_data/locomo10.json",+ help="Path to locomo10.json file, default: ./test_data/locomo10.json",)parser.add_argument("--output",diff --git a/bot/eval/locomo/stat_judge_result.py b/bot/eval/locomo/stat_judge_result.pynew file mode 100644index 000000000..1c4ece6f2--- /dev/null+++ b/bot/eval/locomo/stat_judge_result.py@@ -0,0 +1,88 @@+import argparse+import csv+import json+import os+++def main():+ parser = argparse.ArgumentParser(description="Statistics for judge result csv")+ parser.add_argument(+ "--input",+ default="./result/judge_result.csv",+ help="Path to judge result csv file, default: ./result/judge_result.csv",+ )+ args = parser.parse_args()++ if not os.path.exists(args.input):+ print(f"Error: File not found: {args.input}")+ exit(1)++ correct = 0+ wrong = 0+ total_time = 0.0+ total_prompt_tokens = 0+ total_completion_tokens = 0+ total_tokens = 0+ valid_rows = 0++ with open(args.input, "r", encoding="utf-8", newline="") as f:+ reader = csv.DictReader(f)+ for row in reader:+ valid_rows += 1+ # 统计结果+ result = row.get("result", "").strip().upper()+ if result == "CORRECT":+ correct += 1+ elif result == "WRONG":+ wrong += 1++ # 统计耗时+ time_cost = row.get("time_cost", "")+ if time_cost:+ try:+ total_time += float(time_cost)+ except (ValueError, TypeError):+ pass++ # 统计token+ token_usage = row.get("token_usage", "")+ if token_usage and token_usage.strip():+ try:+ token_data = json.loads(token_usage)+ total_prompt_tokens += token_data.get("prompt_tokens", 0)+ total_completion_tokens += token_data.get("completion_tokens", 0)+ total_tokens += token_data.get("total_tokens", 0)+ except json.JSONDecodeError:+ pass++ total_graded = correct + wrong+ accuracy = correct / total_graded if total_graded > 0 else 0.0+ avg_time = total_time / valid_rows if valid_rows > 0 else 0.0++ output_lines = [+ "=== Judge Result Statistics ===",+ f"Total rows: {valid_rows}",+ f"Graded rows: {total_graded}",+ f"Correct: {correct}",+ f"Wrong: {wrong}",+ f"Accuracy: {accuracy:.2%}",+ f"\nAverage time cost: {avg_time:.2f}s",+ f"\nToken usage:",+ f" Total prompt tokens: {total_prompt_tokens}",+ f" Total completion tokens: {total_completion_tokens}",+ f" Total tokens: {total_tokens}",+ ]++ # 打印到控制台+ for line in output_lines:+ print(line)++ # 写入summary.txt+ summary_path = os.path.join(os.path.dirname(args.input), "summary.txt")+ with open(summary_path, "w", encoding="utf-8") as f:+ f.write("\n".join(output_lines) + "\n")+ print(f"\nSummary saved to {summary_path}")+++if __name__ == "__main__":+ main()diff --git a/bot/eval/skillsbench/skill_bench_eval.py b/bot/eval/skillsbench/skill_bench_eval.pynew file mode 100644index 000000000..19cb04b02--- /dev/null+++ b/bot/eval/skillsbench/skill_bench_eval.py@@ -0,0 +1,935 @@+"""+SkillsBench OpenClaw Evaluator.++Evaluates OpenClaw's ability to use skills by running tasks from SkillsBench.++Usage:+ # Prepare benchmark data (clone and filter tasks)+ uv run skill_bench_eval.py prepare++ # List available tasks+ uv run skill_bench_eval.py list++ # Run all tasks+ uv run skill_bench_eval.py run --token YOUR_TOKEN++ # Run specific task+ uv run skill_bench_eval.py run --task 3d-scan-calc --token YOUR_TOKEN+"""++import argparse+import csv+import json+import os+import re+import shutil+import stat+import subprocess+import sys+import time+import traceback+from pathlib import Path++SKILLSBENCH_REPO = "https://github.com/benchflow-ai/skillsbench.git"++EXCLUDED_TASKS = {+ "gh-repo-analytics",+ "mhc-layer-impl",+ "pedestrian-traffic-counting",+ "pg-essay-to-audiobook",+ "scheduling-email-assistant",+ "speaker-diarization-subtitles",+ "multilingual-video-dubbing",+ "trend-anomaly-causal-inference",+ "video-filler-word-remover",+ "video-tutorial-indexer",+}++PROJECT_ROOT = Path(__file__).parent.resolve()+BENCH_DATA_DIR = PROJECT_ROOT / "bench_data"+TASKS_DIR = BENCH_DATA_DIR / "tasks"+OPENCLAW_WORKSPACE = Path.home() / ".openclaw" / "workspace"+OPENCLAW_SKILLS_DIR = OPENCLAW_WORKSPACE / "skills"+WORK_DIR = OPENCLAW_WORKSPACE / "bench_work"+OUTPUT_DIR = PROJECT_ROOT / "bench_output"+++def safe_rmtree(path: Path) -> bool:+ if not path.exists():+ return True+ try:++ def _onerror(func, p, exc_info):+ try:+ if os.path.isdir(p):+ os.chmod(p, stat.S_IRWXU)+ else:+ os.chmod(p, stat.S_IRUSR | stat.S_IWUSR)+ except Exception:+ pass+ try:+ func(p)+ except Exception:+ pass++ shutil.rmtree(path, onerror=_onerror)+ return True+ except Exception:+ return False+++def get_available_tasks() -> list[Path]:+ """Get list of available task directories."""+ if not TASKS_DIR.exists():+ return []+ return sorted([d for d in TASKS_DIR.iterdir() if d.is_dir() and d.name not in EXCLUDED_TASKS])+++def run_prepare(args: argparse.Namespace) -> None:+ """Prepare benchmark data by cloning SkillsBench and filtering tasks."""+ print("=== Preparing SkillsBench data ===", file=sys.stderr)++ if BENCH_DATA_DIR.exists():+ if args.force:+ print(f" Removing existing {BENCH_DATA_DIR} (--force)...", file=sys.stderr)+ shutil.rmtree(BENCH_DATA_DIR)+ else:+ print(+ f" {BENCH_DATA_DIR} already exists. Use --force to re-download.", file=sys.stderr+ )+ tasks_dir = BENCH_DATA_DIR / "tasks"+ if tasks_dir.exists():+ excluded_count = 0+ for task_name in EXCLUDED_TASKS:+ task_path = tasks_dir / task_name+ if task_path.exists():+ shutil.rmtree(task_path)+ print(f" [exclude] removed {task_name}", file=sys.stderr)+ excluded_count += 1++ remaining = [d.name for d in tasks_dir.iterdir() if d.is_dir()]+ print(+ f"\n {len(remaining)} tasks available, {excluded_count} excluded.",+ file=sys.stderr,+ )+ print(f" Tasks: {', '.join(sorted(remaining))}", file=sys.stderr)+ return++ temp_dir = PROJECT_ROOT / f"temp_skillsbench_{int(time.time())}"++ print(f" Cloning {SKILLSBENCH_REPO}...", file=sys.stderr)+ print(f" (this may take a moment...)", file=sys.stderr)++ process = subprocess.Popen(+ ["git", "clone", "--progress", SKILLSBENCH_REPO, str(temp_dir)],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )++ while True:+ if process.stderr is None:+ break+ line = process.stderr.readline()+ if not line and process.poll() is not None:+ break+ if line:+ line = line.strip()+ if line:+ print(f" [git] {line}", file=sys.stderr)++ if process.returncode != 0:+ print(f" [error] git clone failed with code {process.returncode}", file=sys.stderr)+ if temp_dir.exists():+ shutil.rmtree(temp_dir)+ sys.exit(1)++ print(f" Extracting tasks directory...", file=sys.stderr)++ src_tasks = temp_dir / "tasks"+ if not src_tasks.exists():+ print(f" [error] tasks directory not found in cloned repo", file=sys.stderr)+ shutil.rmtree(temp_dir)+ sys.exit(1)++ BENCH_DATA_DIR.mkdir(parents=True, exist_ok=True)+ shutil.copytree(src_tasks, TASKS_DIR)++ print(f" Cleaning up temp files...", file=sys.stderr)+ shutil.rmtree(temp_dir)++ excluded_count = 0+ for task_name in EXCLUDED_TASKS:+ task_path = TASKS_DIR / task_name+ if task_path.exists():+ shutil.rmtree(task_path)+ print(f" [exclude] removed {task_name}", file=sys.stderr)+ excluded_count += 1++ remaining = [d.name for d in TASKS_DIR.iterdir() if d.is_dir()]+ print(+ f"\n Done! {len(remaining)} tasks available, {excluded_count} excluded.", file=sys.stderr+ )+ print(f" Tasks: {', '.join(sorted(remaining))}", file=sys.stderr)+++def run_list(args: argparse.Namespace) -> None:+ """List available tasks."""+ tasks = get_available_tasks()++ if not tasks:+ print("No tasks found. Run 'prepare' first.", file=sys.stderr)+ return++ print(f"=== Available Tasks ({len(tasks)}) ===", file=sys.stderr)+ for i, task_dir in enumerate(tasks, 1):+ instruction_file = task_dir / "instruction.md"+ has_instruction = instruction_file.exists()+ skills_dir = task_dir / "environment" / "skills"+ has_skills = skills_dir.exists()+ status = (+ f"instruction={'Y' if has_instruction else 'N'} skills={'Y' if has_skills else 'N'}"+ )+ print(f" {i:3d}. {task_dir.name} [{status}]", file=sys.stderr)+++def run_verification(task_dir: Path, work_dir: Path, storage_workspace: Path) -> dict:+ """Run task verification tests. Returns verification result."""+ task_name = task_dir.name+ tests_dir = task_dir / "tests"++ result = {+ "verified": False,+ "passed": False,+ "test_output": None,+ "error": None,+ "test_score": None,+ }++ if not tests_dir.exists():+ result["error"] = "no tests directory"+ result["verified"] = True+ result["passed"] = True+ print(f" [verify] no tests directory, skipping verification", file=sys.stderr)+ return result++ test_sh = tests_dir / "test.sh"+ # Collect all test_*.py files+ test_py_files = sorted(list(tests_dir.rglob("test_*.py")))+ test_py_files = [f for f in test_py_files if "__pycache__" not in str(f)]++ if not test_sh.exists() and not test_py_files:+ result["error"] = "no test files found"+ result["verified"] = True+ result["passed"] = True+ print(f" [verify] no test files, skipping verification", file=sys.stderr)+ return result++ print(f" [verify] running tests...", file=sys.stderr)++ logs_dir = work_dir / "logs" / "verifier"+ logs_dir.mkdir(parents=True, exist_ok=True)++ if tests_dir.exists():+ for item in tests_dir.rglob("*"):+ if not item.is_file():+ continue+ if item.suffix == ".sh":+ continue+ if item.suffix == ".py" and item.name == "test_outputs.py":+ continue+ rel = item.relative_to(tests_dir)+ dest = work_dir / rel+ dest.parent.mkdir(parents=True, exist_ok=True)+ if not dest.exists():+ shutil.copy2(item, dest)++ work_dir_relative = work_dir.relative_to(storage_workspace)+ work_dir_str = str(work_dir_relative)+ tests_dir_relative = str(task_dir / "tests")++ if test_py_files:+ try:+ local_test_files = []+ expected_paths = set()+ all_test_files = []++ # 收集所有测试文件内容和路径+ for test_py in test_py_files:+ with open(test_py, "r", encoding="utf-8") as f:+ test_content = f.read()+ all_test_files.append((test_py, test_content))+ # 累积所有路径+ expected_paths.update(re.findall(r"""['"](/root/[^'"]+)['"]""", test_content))+ expected_paths.update(re.findall(r"""['"](/app/[^'"]+)['"]""", test_content))++ # 处理所有需要复制的路径+ for full_path in sorted(expected_paths):+ if full_path.endswith("/"):+ continue+ try:+ if full_path.startswith("/root/"):+ rel = Path(full_path).relative_to("/root")+ else:+ rel = Path(full_path).relative_to("/app")+ except ValueError:+ continue+ src = storage_workspace / rel+ dest = work_dir / rel+ if dest.exists():+ continue+ if src.exists() and src.is_file():+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.move(str(src), str(dest))++ def replace_abs_token(text: str, src: str, dst: str) -> str:+ pattern = re.compile(+ rf"(^|(?<=[\s'\"`(])){re.escape(src)}(?=($|[\s'\"`)\]]))",+ re.MULTILINE,+ )+ return pattern.sub(lambda m: f"{m.group(1)}{dst}", text)++ def replace_abs_prefix(text: str, src: str, dst: str) -> str:+ pattern = re.compile(+ rf"(^|(?<=[\s'\"`(])){re.escape(src)}",+ re.MULTILINE,+ )+ return pattern.sub(lambda m: f"{m.group(1)}{dst}", text)++ def rewrite_test_text(text: str) -> str:+ abs_token_map = {+ "/root": "",+ "/app": "",+ "/workspace": "./workspace",+ "/output": "./output",+ "/data": "./data",+ "/logs": "./logs",+ "/tests": f"{tests_dir_relative}",+ }+ for src, dst in abs_token_map.items():+ text = replace_abs_token(text, src, dst)++ abs_prefix_map = {+ "/root/": "",+ "/app/": "",+ "/workspace/": "./workspace/",+ "/output/": "./output/",+ "/data/": "./data/",+ "/logs/": "./logs/",+ "/tests/": f"{tests_dir_relative}/",+ }+ for src, dst in abs_prefix_map.items():+ text = replace_abs_prefix(text, src, dst)++ text = text.replace(+ 'sys.path.insert(0, "/tests/src")',+ f'sys.path.insert(0, "{tests_dir_relative}/src")',+ )+ text = text.replace(+ "sys.path.insert(0, '/tests/src')",+ f"sys.path.insert(0, '{tests_dir_relative}/src')",+ )+ text = text.replace(+ 'sys.path.insert(0, "/root/workspace")', f'sys.path.insert(0, "{work_dir_str}")'+ )+ text = text.replace(+ "sys.path.insert(0, '/root/workspace')", f"sys.path.insert(0, '{work_dir_str}')"+ )+ text = text.replace(+ 'sys.path.insert(0, "/root")', f'sys.path.insert(0, "{work_dir_str}")'+ )+ text = text.replace(+ "sys.path.insert(0, '/root')", f"sys.path.insert(0, '{work_dir_str}')"+ )+ text = text.replace("cwd='/root'", f"cwd='{work_dir_str}'")+ text = text.replace('cwd="/root"', f'cwd="{work_dir_str}"')+ return text++ if tests_dir.exists():+ for helper_py in tests_dir.rglob("*.py"):+ if helper_py.name == "test_outputs.py":+ continue+ rel = helper_py.relative_to(tests_dir)+ dest = work_dir / rel+ dest.parent.mkdir(parents=True, exist_ok=True)+ if not dest.exists():+ shutil.copy2(helper_py, dest)+ try:+ helper_text = dest.read_text(encoding="utf-8")+ rewritten = rewrite_test_text(helper_text)+ if rewritten != helper_text:+ dest.write_text(rewritten, encoding="utf-8")+ except Exception:+ pass++ # 处理每个测试文件+ for test_py, test_content in all_test_files:+ rewritten_content = rewrite_test_text(test_content)+ local_test_py = work_dir / test_py.name+ with open(local_test_py, "w", encoding="utf-8") as f:+ f.write(rewritten_content)+ local_test_files.append(str(local_test_py))++ env = os.environ.copy()+ env["PYTHONPATH"] = str(work_dir)++ test_cmd = [+ "python",+ "-m",+ "pytest",+ *local_test_files,+ "-v",+ "--tb=short",+ "-W",+ "ignore::pytest.PytestCollectionWarning",+ f"--junitxml={logs_dir}/junit.xml",+ ]++ print(f" [verify] running: pytest test_outputs.py", file=sys.stderr)++ proc_result = subprocess.run(+ test_cmd,+ capture_output=True,+ text=True,+ cwd=str(work_dir),+ env=env,+ timeout=300,+ )++ result["test_output"] = str(proc_result.stdout or "") + str(proc_result.stderr or "")+ result["verified"] = True+ result["passed"] = proc_result.returncode == 0++ summary_text = result["test_output"] or ""+ collected_match = re.search(r"collected\s+(\d+)\s+items", summary_text)+ passed_count = len(re.findall(r"\bPASSED\s+\[", summary_text))+ failed_count = len(re.findall(r"\bFAILED\s+\[", summary_text))+ skipped_count = len(re.findall(r"\bSKIPPED\s+\[", summary_text))+ total_count = int(collected_match.group(1)) if collected_match else None+ if total_count is None and (passed_count or failed_count or skipped_count):+ total_count = passed_count + failed_count + skipped_count+ if total_count:+ score = passed_count / total_count+ result["test_score"] = round(score, 2)++ if result["passed"]:+ print(f" [verify] PASSED", file=sys.stderr)+ else:+ print(f" [verify] FAILED", file=sys.stderr)+ if proc_result.stdout:+ print(f" [verify stdout] {proc_result.stdout[:500]}", file=sys.stderr)+ if proc_result.stderr:+ print(f" [verify stderr] {proc_result.stderr[:500]}", file=sys.stderr)++ except subprocess.TimeoutExpired:+ result["error"] = "test timeout"+ result["verified"] = True+ result["passed"] = False+ print(f" [verify] TIMEOUT", file=sys.stderr)+ except Exception as e:+ result["error"] = str(e)+ result["verified"] = True+ result["passed"] = False+ print(f" [verify] ERROR: {e}", file=sys.stderr)+ else:+ result["verified"] = True+ result["passed"] = True+ print(f" [verify] no pytest file, skipping", file=sys.stderr)++ return result+++def run_task(+ task_dir: Path,+ output_base: Path,+ ov_config_path: Path,+ verify_only: bool = False,+) -> dict:+ """Run a single task. Returns result dict."""+ task_name = task_dir.name+ print(f"\n=== Task: {task_name} ===", file=sys.stderr)++ task_output_dir = output_base / task_name+ if not verify_only and task_output_dir.exists():+ shutil.rmtree(task_output_dir)+ task_output_dir.mkdir(parents=True, exist_ok=True)++ response = ""+ usage = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}++ # Load existing result if in verify-only mode+ task_output_dir = output_base / task_name+ existing_result_path = task_output_dir / "result.json"+ if verify_only and existing_result_path.exists():+ try:+ with open(existing_result_path, "r", encoding="utf-8") as f:+ result = json.load(f)+ # Keep original values, only update verification+ result["verification"] = None+ result["end_time"] = time.time()+ except Exception:+ # Fallback to new result if existing is invalid+ result = {+ "task": task_name,+ "status": "pending",+ "response": None,+ "usage": {},+ "error": None,+ "verification": None,+ "start_time": time.time(),+ "end_time": None,+ }+ else:+ result = {+ "task": task_name,+ "status": "pending",+ "response": None,+ "usage": {},+ "error": None,+ "verification": None,+ "start_time": time.time(),+ "end_time": None,+ }++ instruction_file = task_dir / "instruction.md"+ if not instruction_file.exists():+ result["status"] = "error"+ result["error"] = "instruction.md not found"+ print(f" [error] instruction.md not found", file=sys.stderr)+ return result++ task_skills_dir = task_dir / "environment" / "skills"+ session_name = f"cli__chat__{task_name}"++ work_dir = None++ try:+ # Read ov.conf to get storage.workspace path+ with open(ov_config_path, "r", encoding="utf-8") as f:+ ov_config = json.load(f)+ storage_workspace = Path(ov_config["storage"]["workspace"])++ # Copy skills to target directory+ target_session_dir = storage_workspace / "bot" / session_name+ target_skills_dir = target_session_dir / "skills"+ if not verify_only:+ if target_session_dir.exists():+ safe_rmtree(target_session_dir)+ target_session_dir.mkdir(parents=True, exist_ok=True)+ work_dir = target_session_dir+ if task_skills_dir.exists():+ shutil.copytree(task_skills_dir, target_skills_dir, dirs_exist_ok=True)+ print(f" [skills] copied to {target_skills_dir}", file=sys.stderr)++ # Copy other environment files except Dockerfile+ env_dir = task_dir / "environment"+ if env_dir.exists():+ for item in env_dir.iterdir():+ if item.name == "skills" or item.name == "Dockerfile" or item.name == ".DS_Store":+ continue+ target_path = target_session_dir / item.name+ if item.is_dir():+ shutil.copytree(item, target_path, dirs_exist_ok=True)+ else:+ shutil.copy2(item, target_path)+ print(f" [env] copied {item.name} to {target_session_dir}", file=sys.stderr)++ # Rewrite instruction paths: remove /root/ prefix+ with open(instruction_file, "r", encoding="utf-8") as f:+ instruction = f.read()++ instruction = re.sub(r"(^|(?<=[\s\'\"`(]))/root/", r"\1/", instruction)++ # Write modified content to session directory, avoid modifying original file+ modified_instruction_path = target_session_dir / "instruction.md"+ with open(modified_instruction_path, "w", encoding="utf-8") as f:+ f.write(instruction)+ print(+ f" [updated] modified instruction saved to {modified_instruction_path}",+ file=sys.stderr,+ )++ if not verify_only:+ # Run vikingbot command+ print(f" [running] vikingbot chat...", file=sys.stderr)+ cmd = [+ "vikingbot",+ "chat",+ "-m",+ instruction,+ "-e",+ "-s",+ session_name,+ "-c",+ str(ov_config_path),+ ]+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=2400)+ if proc.returncode != 0:+ raise Exception(f"vikingbot failed: {proc.stderr}")+ # Parse JSON response+ try:+ raw_output = proc.stdout.strip()+ print(f" [output] vikingbot output: {raw_output}", file=sys.stderr)+ if not raw_output:+ raise Exception("vikingbot returned empty output")++ # First try standard JSON parse+ try:+ bot_result = json.loads(raw_output, strict=False)+ except json.JSONDecodeError:+ # Fallback: regex extraction for unescaped quotes in text field+ # Extract text content+ text_pattern = re.compile(r'"text"\s*:\s*"((?:\\.|[^"\\])*)"', re.DOTALL)+ text_match = text_pattern.search(raw_output)+ # Extract token usage+ token_pattern = re.compile(r'"token_usage"\s*:\s*({[^}]*})', re.DOTALL)+ token_match = token_pattern.search(raw_output)++ if not text_match:+ raise Exception("Failed to extract text from invalid JSON response")++ text = text_match.group(1).replace('\\"', '"')+ token_usage = {}+ if token_match:+ try:+ token_usage = json.loads(token_match.group(1), strict=False)+ except Exception:+ pass++ bot_result = {"text": text, "token_usage": token_usage}++ response = bot_result["text"]+ token_usage = bot_result.get("token_usage", {})+ usage = {+ "input_tokens": token_usage.get("prompt_tokens", 0),+ "output_tokens": token_usage.get("completion_tokens", 0),+ "total_tokens": token_usage.get("total_tokens", 0),+ }+ except Exception as e:+ raise Exception(+ f"Failed to parse vikingbot response: {str(e)}\nRaw output: {proc.stdout}"+ )++ result["status"] = "completed"+ result["response"] = response+ result["usage"] = usage++ if not verify_only:+ with open(task_output_dir / "response.txt", "w", encoding="utf-8") as f:+ f.write(response)+ print(+ f" [saved] response.txt -> {task_output_dir.name}/response.txt", file=sys.stderr+ )++ preview = response.replace("\n", " | ")[:100]+ print(+ f" [response] {preview}{'...' if len(response) > 100 else ''}", file=sys.stderr+ )+ print(+ f" [tokens] in={usage.get('input_tokens', 0)} out={usage.get('output_tokens', 0)}",+ file=sys.stderr,+ )+ else:+ # Verify only mode, set default values+ result["status"] = "completed"+ result["response"] = ""+ result["usage"] = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}++ if work_dir:+ verification_result = run_verification(task_dir, work_dir, storage_workspace)+ result["verification"] = verification_result++ with open(task_output_dir / "verification.txt", "w", encoding="utf-8") as f:+ f.write(verification_result.get("test_output", ""))+ print(+ f" [saved] verification.txt -> {task_output_dir.name}/verification.txt",+ file=sys.stderr,+ )++ except Exception as e:+ result["status"] = "error"+ result["error"] = str(e)+ traceback.print_exc(file=sys.stderr)+ print(f" [error] {e}", file=sys.stderr)+ finally:+ result["end_time"] = time.time()++ with open(task_output_dir / "result.json", "w", encoding="utf-8") as f:+ json.dump(result, f, indent=2, ensure_ascii=False)+ print(f" [saved] result.json -> {task_output_dir.name}/result.json", file=sys.stderr)++ return result+++def run_run(args: argparse.Namespace) -> None:+ """Run benchmark tasks."""+ tasks = get_available_tasks()++ if not tasks:+ print("No tasks found. Run 'prepare' first.", file=sys.stderr)+ sys.exit(1)++ if args.task and (args.count is not None or args.start is not None or args.end is not None):+ print("Error: --task cannot be combined with --count/--start/--end", file=sys.stderr)+ sys.exit(1)+ if args.count is not None and (args.start is not None or args.end is not None):+ print("Error: --count cannot be combined with --start/--end", file=sys.stderr)+ sys.exit(1)++ if args.task:+ task_dir = TASKS_DIR / args.task+ if not task_dir.exists():+ print(f"Task not found: {args.task}", file=sys.stderr)+ sys.exit(1)+ tasks = [task_dir]+ elif args.start is not None or args.end is not None:+ start = args.start or 1+ end = args.end or len(tasks)+ if start < 1 or end < 1 or start > end:+ print(f"Error: invalid range --start {start} --end {end}", file=sys.stderr)+ sys.exit(1)+ if start > len(tasks):+ print(f"Error: --start {start} exceeds available tasks ({len(tasks)})", file=sys.stderr)+ sys.exit(1)+ end = min(end, len(tasks))+ tasks = tasks[start - 1 : end]+ elif args.count:+ tasks = tasks[: args.count]++ output_base = PROJECT_ROOT / "result"+ output_base.mkdir(parents=True, exist_ok=True)+ WORK_DIR.mkdir(parents=True, exist_ok=True)++ # Skip tasks already present in result.csv+ completed_tasks = set()+ csv_file = output_base / "result.csv"+ if csv_file.exists():+ try:+ with open(csv_file, "r", encoding="utf-8", newline="") as f:+ reader = csv.DictReader(f)+ for row in reader:+ if "taskname" in row:+ completed_tasks.add(row["taskname"])+ except Exception as e:+ print(f" [warn] failed to read existing result.csv: {e}", file=sys.stderr)++ # Filter out already completed tasks (skip in verify-only mode)+ original_task_count = len(tasks)+ if not args.verify_only:+ tasks = [t for t in tasks if t.name not in completed_tasks]+ skipped_count = original_task_count - len(tasks)++ if skipped_count > 0:+ print(f" [info] skipped {skipped_count} already completed tasks", file=sys.stderr)+ if not tasks:+ print(" [info] no new tasks to run, exiting", file=sys.stderr)+ return++ total_usage = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}++ print(f"=== Running {len(tasks)} task(s) ===", file=sys.stderr)+ print(f" output: {output_base}", file=sys.stderr)++ summary_file = output_base / "summary.json"+ for task_dir in tasks:+ result = run_task(+ task_dir=task_dir,+ output_base=output_base,+ ov_config_path=Path(args.ov_config_path),+ verify_only=args.verify_only,+ )++ # Accumulate usage+ current_usage = result.get("usage") or {+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ }+ for k in total_usage:+ total_usage[k] += current_usage[k]++ # Update result.csv+ verification = result.get("verification") or {}+ current_score = (result.get("verification") or {}).get("test_score") or 0+ current_row = [+ task_dir.name,+ result["status"],+ current_usage["input_tokens"],+ current_usage["output_tokens"],+ current_usage["total_tokens"],+ result.get("error", ""),+ str(verification.get("verified", False)),+ str(verification.get("passed", False)),+ current_score,+ round(result["end_time"] - result["start_time"], 2),+ ]++ if not args.verify_only:+ # Normal mode: append new row+ csv_exists = csv_file.exists()+ with open(csv_file, "a", encoding="utf-8", newline="") as f:+ writer = csv.writer(f)+ if not csv_exists:+ # Write header+ writer.writerow(+ [+ "taskname",+ "status",+ "input_tokens",+ "output_tokens",+ "total_tokens",+ "error",+ "verified",+ "passed",+ "test_score",+ "cost_time",+ ]+ )+ writer.writerow(current_row)+ else:+ # Verify only mode: update existing row+ if csv_file.exists():+ rows = []+ with open(csv_file, "r", encoding="utf-8", newline="") as f:+ reader = csv.reader(f)+ header = next(reader)+ rows.append(header)+ for row in reader:+ if row and row[0] == task_dir.name:+ # Update only verification related columns (indices 6,7,8)+ row[6] = str(verification.get("verified", False))+ row[7] = str(verification.get("passed", False))+ row[8] = str(current_score)+ rows.append(row)+ # Write back all rows+ with open(csv_file, "w", encoding="utf-8", newline="") as f:+ writer = csv.writer(f)+ writer.writerows(rows)++ # Generate final summary from result.csv+ summary_file = output_base / "summary.json"+ final_summary = {+ "total_tasks": 0,+ "completed": 0,+ "passed": 0,+ "errors": 0,+ "total_usage": {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0},+ "tasks": [],+ "pass_rate": 0.0,+ "score": 0.0,+ }+ all_scores = []+ if csv_file.exists():+ try:+ with open(csv_file, "r", encoding="utf-8", newline="") as f:+ reader = csv.DictReader(f)+ for row in reader:+ final_summary["total_tasks"] += 1+ final_summary["tasks"].append(row["taskname"])+ if row["status"] == "completed":+ final_summary["completed"] += 1+ if row["status"] == "error":+ final_summary["errors"] += 1+ # Accumulate tokens+ final_summary["total_usage"]["input_tokens"] += int(row.get("input_tokens", 0))+ final_summary["total_usage"]["output_tokens"] += int(+ row.get("output_tokens", 0)+ )+ final_summary["total_usage"]["total_tokens"] += int(row.get("total_tokens", 0))+ # Count passed and collect scores+ if row.get("passed") == "True":+ final_summary["passed"] += 1+ if row.get("test_score"):+ all_scores.append(float(row["test_score"]))+ # Calculate pass rate and total score+ if final_summary["total_tasks"] > 0:+ final_summary["pass_rate"] = round(+ final_summary["passed"] / final_summary["total_tasks"], 2+ )+ if all_scores:+ final_summary["score"] = round(sum(all_scores), 2)+ # Save summary to file+ with open(summary_file, "w", encoding="utf-8") as f:+ json.dump(final_summary, f, indent=2, ensure_ascii=False)+ except Exception as e:+ print(f" [warn] failed to generate summary from result.csv: {e}", file=sys.stderr)++ print(f"\n=== Summary ===", file=sys.stderr)+ print(+ f" Completed: {final_summary['completed']}/{final_summary['total_tasks']}",+ file=sys.stderr,+ )+ print(f" Errors: {final_summary['errors']}", file=sys.stderr)+ print(+ f" Total tokens: in={final_summary['total_usage']['input_tokens']} out={final_summary['total_usage']['output_tokens']}",+ file=sys.stderr,+ )+ print(f" Results saved to: {output_base}", file=sys.stderr)+++def main():+ parser = argparse.ArgumentParser(+ description="SkillsBench OpenClaw Evaluator",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog=__doc__,+ )+ subparsers = parser.add_subparsers(dest="command", help="Command to run")++ prepare_parser = subparsers.add_parser("prepare", help="Prepare benchmark data")+ prepare_parser.add_argument(+ "--force",+ action="store_true",+ default=False,+ help="Force re-download even if data already exists",+ )++ run_parser = subparsers.add_parser("run", help="Run benchmark tasks")+ run_parser.add_argument(+ "--task",+ default=None,+ help="Run specific task only",+ )+ run_parser.add_argument(+ "--count",+ type=int,+ default=None,+ help="Run first N tasks only",+ )+ run_parser.add_argument(+ "--start",+ type=int,+ default=None,+ help="Run tasks starting from this index (1-based, same order as list)",+ )+ run_parser.add_argument(+ "--end",+ type=int,+ default=None,+ help="Run tasks ending at this index (inclusive, 1-based, same order as list)",+ )+ run_parser.add_argument(+ "--verify-only",+ action="store_true",+ default=False,+ help="Only run verification step for already executed tasks",+ )+ run_parser.add_argument(+ "--ov-config-path",+ default=str(Path.home() / ".openviking" / "ov.conf"),+ help="Path to OpenViking configuration file",+ )++ args = parser.parse_args()++ if args.command == "prepare":+ run_prepare(args)+ elif args.command == "list":+ run_list(args)+ elif args.command == "run":+ run_run(args)+ else:+ parser.print_help()+++if __name__ == "__main__":+ main()diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex 2523ff9e9..e25609ed0 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -376,102 +376,146 @@ class AgentLoop:# Handle system messages (subagent announces)# The chat_id contains the original "channel:chat_id" to route back tostart_time = time.time()- if msg.session_key.type == "system":- return await self._process_system_message(msg)-- preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content- logger.info(f"Processing message from {msg.session_key}:{msg.sender_id}: {preview}")-- # Get or create session- session_key = msg.session_key- # For CLI/direct sessions, skip heartbeat by default- skip_heartbeat = session_key.type == "cli"- session = self.sessions.get_or_create(session_key, skip_heartbeat=skip_heartbeat)-- # Handle slash commands- is_group_chat = msg.metadata.get("chat_type") == "group" if msg.metadata else False- if is_group_chat:- cmd = msg.content.replace(f"@{msg.sender_id}", "").strip().lower()- else:- cmd = msg.content.strip().lower()- if cmd == "/new":- # Clone session for async consolidation, then immediately clear original- session_clone = session.clone()- session.clear()- await self.sessions.save(session)- # Run consolidation in background- await self._safe_consolidate_memory(session_clone, archive_all=True)- return OutboundMessage(- session_key=msg.session_key, content="🐈 New session started. Memory consolidated."+ long_running_notified = False++ # 监控处理时长,每50秒发送处理中提示事件+ async def check_long_running():+ nonlocal long_running_notified+ tick_count = 0+ # 最多发送7次提示+ max_ticks = 7++ while not long_running_notified and tick_count < max_ticks:+ await asyncio.sleep(40)+ if long_running_notified:+ break+ if msg.metadata:+ message_id = msg.metadata.get("message_id")+ if message_id:+ try:+ # 发送处理中tick事件,对应channel会自行处理展示逻辑+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=msg.session_key,+ content="",+ metadata={+ "action": "processing_tick",+ "tick_count": tick_count,+ "message_id": message_id,+ },+ )+ )+ tick_count += 1+ except Exception as e:+ logger.debug(f"Failed to send processing tick: {e}")++ monitor_task = asyncio.create_task(check_long_running())++ try:+ if msg.session_key.type == "system":+ return await self._process_system_message(msg)++ preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content+ logger.info(f"Processing message from {msg.session_key}:{msg.sender_id}: {preview}")++ # Get or create session+ session_key = msg.session_key+ # For CLI/direct sessions, skip heartbeat by default+ skip_heartbeat = session_key.type == "cli"+ session = self.sessions.get_or_create(session_key, skip_heartbeat=skip_heartbeat)++ # Handle slash commands+ is_group_chat = msg.metadata.get("chat_type") == "group" if msg.metadata else False+ if is_group_chat:+ cmd = msg.content.replace(f"@{msg.sender_id}", "").strip().lower()+ else:+ cmd = msg.content.strip().lower()+ if cmd == "/new":+ # Clone session for async consolidation, then immediately clear original+ session_clone = session.clone()+ session.clear()+ await self.sessions.save(session)+ # Run consolidation in background+ await self._safe_consolidate_memory(session_clone, archive_all=True)+ return OutboundMessage(+ session_key=msg.session_key, content="🐈 New session started. Memory consolidated.", metadata=msg.metadata+ )+ if cmd == "/help":+ return OutboundMessage(+ session_key=msg.session_key,+ content="🐈 vikingbot commands:\n/new — Start a new conversation\n/help — Show available commands",+ metadata=msg.metadata+ )++ # Consolidate memory before processing if session is too large+ if len(session.messages) > self.memory_window:+ # Clone session for async consolidation, then immediately trim original+ session_clone = session.clone()+ keep_count = min(10, max(2, self.memory_window // 2))+ session.messages = session.messages[-keep_count:] if keep_count else []+ await self.sessions.save(session)+ # Run consolidation in background+ await self._safe_consolidate_memory(session_clone, archive_all=False)++ if self.sandbox_manager:+ message_workspace = self.sandbox_manager.get_workspace_path(session_key)+ else:+ message_workspace = self.workspace++ from vikingbot.agent.context import ContextBuilder++ message_context = ContextBuilder(+ message_workspace,+ sandbox_manager=self.sandbox_manager,+ sender_id=msg.sender_id,+ is_group_chat=is_group_chat,+ eval=self._eval,)- if cmd == "/help":- return OutboundMessage(++ # Build initial messages (use get_history for LLM-formatted messages)+ messages = await message_context.build_messages(+ history=session.get_history(),+ current_message=msg.content,+ media=msg.media if msg.media else None,session_key=msg.session_key,- content="🐈 vikingbot commands:\n/new — Start a new conversation\n/help — Show available commands",)+ # logger.info(f"New messages: {messages}")- # Consolidate memory before processing if session is too large- if len(session.messages) > self.memory_window:- # Clone session for async consolidation, then immediately trim original- session_clone = session.clone()- keep_count = min(10, max(2, self.memory_window // 2))- session.messages = session.messages[-keep_count:] if keep_count else []- await self.sessions.save(session)- # Run consolidation in background- await self._safe_consolidate_memory(session_clone, archive_all=False)-- if self.sandbox_manager:- message_workspace = self.sandbox_manager.get_workspace_path(session_key)- else:- message_workspace = self.workspace-- from vikingbot.agent.context import ContextBuilder-- message_context = ContextBuilder(- message_workspace,- sandbox_manager=self.sandbox_manager,- sender_id=msg.sender_id,- is_group_chat=is_group_chat,- eval=self._eval,- )-- # Build initial messages (use get_history for LLM-formatted messages)- messages = await message_context.build_messages(- history=session.get_history(),- current_message=msg.content,- media=msg.media if msg.media else None,- session_key=msg.session_key,- )- # logger.info(f"New messages: {messages}")-- # Run agent loop- final_content, tools_used = await self._run_agent_loop(- messages=messages,- session_key=session_key,- publish_events=True,- sender_id=msg.sender_id,- )+ # Run agent loop+ final_content, tools_used = await self._run_agent_loop(+ messages=messages,+ session_key=session_key,+ publish_events=True,+ sender_id=msg.sender_id,+ )- # Log response preview- preview = final_content[:300] + "..." if len(final_content) > 300 else final_content- logger.info(f"Response to {msg.session_key}: {preview}")+ # Log response preview+ preview = final_content[:300] + "..." if len(final_content) > 300 else final_content+ logger.info(f"Response to {msg.session_key}: {preview}")- # Save to session (include tool names so consolidation sees what happened)- session.add_message("user", msg.content, sender_id=msg.sender_id)- session.add_message(- "assistant", final_content, tools_used=tools_used if tools_used else None- )- await self.sessions.save(session)+ # Save to session (include tool names so consolidation sees what happened)+ session.add_message("user", msg.content, sender_id=msg.sender_id)+ session.add_message(+ "assistant", final_content, tools_used=tools_used if tools_used else None+ )+ await self.sessions.save(session)- time_cost = round(time.time() - start_time, 2)- return OutboundMessage(- session_key=msg.session_key,- content=final_content,- metadata=msg.metadata,- token_usage=self._token_usage,- time_cost=time_cost- or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts)- )+ time_cost = round(time.time() - start_time, 2)+ return OutboundMessage(+ session_key=msg.session_key,+ content=final_content,+ metadata=msg.metadata,+ token_usage=self._token_usage,+ time_cost=time_cost+ or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts)+ )+ finally:+ long_running_notified = True+ monitor_task.cancel()+ try:+ await monitor_task+ except asyncio.CancelledError:+ passasync def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None:"""diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex e00f5816f..f4909af7a 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -4,6 +4,8 @@ from openviking.async_client import loggerfrom vikingbot.config.loader import load_configfrom pathlib import Pathfrom typing import Any+from loguru import logger+import timefrom vikingbot.openviking_mount.ov_server import VikingClientfrom vikingbot.utils.helpers import ensure_dir@@ -49,12 +51,19 @@ class MemoryStore:async def get_viking_memory_context(self, current_message: str, workspace_id: str) -> str:client = await VikingClient.create(agent_id=workspace_id)admin_user_id = load_config().ov_server.admin_user_id+ start = time.time()result = await client.search_memory(current_message, user_id=admin_user_id, limit=3)+ cost = round(time.time() - start, 2)if not result:+ logger.info(f"[USER_MEMORY]: search failed. cost {cost}")return ""user_memory = self._parse_viking_memory(result["user_memory"])agent_memory = self._parse_viking_memory(result["agent_memory"])- return f"### user memories:\n{user_memory}\n### agent memories:\n{agent_memory}"+ logger.info(f"[USER_MEMORY]: search success. res: {user_memory[:100]}. cost {cost}")+ return (+ f"### user memories:\n{user_memory}\n"+ f"### agent memories:\n{agent_memory}"+ )async def get_viking_user_profile(self, workspace_id: str, user_id: str) -> str:client = await VikingClient.create(agent_id=workspace_id)diff --git a/bot/vikingbot/agent/tools/factory.py b/bot/vikingbot/agent/tools/factory.pyindex 8716a8aeb..fc57942a4 100644--- a/bot/vikingbot/agent/tools/factory.py+++ b/bot/vikingbot/agent/tools/factory.py@@ -14,6 +14,7 @@ from vikingbot.agent.tools.ov_file import (VikingGlobTool,VikingSearchUserMemoryTool,VikingMemoryCommitTool,+ VikingAddResourceTool,)from vikingbot.agent.tools.registry import ToolRegistryfrom vikingbot.agent.tools.shell import ExecTool@@ -92,6 +93,10 @@ def register_default_tools(registry.register(VikingGlobTool())registry.register(VikingSearchUserMemoryTool())registry.register(VikingMemoryCommitTool())+ if not config.read_only:+ registry.register(VikingAddResourceTool())++# Image generation toolif include_image_tool:diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex a086d92e5..167b3cf03 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -3,6 +3,8 @@from abc import ABCfrom pathlib import Pathfrom typing import Any, Optional++import httpxfrom loguru import loggerfrom vikingbot.agent.tools.base import Tool, ToolContext@@ -144,7 +146,7 @@ class VikingSearchTool(OVFileTool):self,tool_context: "ToolContext",query: str,- target_uri: Optional[str] = None,+ target_uri: Optional[str] = "",**kwargs: Any,) -> str:try:@@ -173,57 +175,51 @@ class VikingAddResourceTool(OVFileTool):@propertydef description(self) -> str:- return "Add a local file as a resource to OpenViking."+ return "Add a resource (url like pic, git code or local file path) to OpenViking.This is a asynchronous operation."@propertydef parameters(self) -> dict[str, Any]:return {"type": "object","properties": {- "local_path": {"type": "string", "description": "Path to the local file to add"},+ "path": {"type": "string", "description": "Url or local file path"},"description": {"type": "string", "description": "Description of the resource"},- "target_path": {- "type": "string",- "description": "Target path in Viking (e.g., /bot_test/dutao/docs/)",- "default": "",- },- "wait": {- "type": "boolean",- "description": "Whether to wait for processing to complete",- "default": False,- },},- "required": ["local_path", "description"],+ "required": ["path", "description"],}async def execute(self,tool_context: "ToolContext",- local_path: str,+ path: str,description: str,- target_path: str = "",- wait: bool = False,**kwargs: Any,) -> str:+ client = Nonetry:- path = Path(local_path).expanduser().resolve()- if not path.exists():- return f"Error: File not found: {local_path}"- if not path.is_file():- return f"Error: Not a file: {local_path}"+ if path and not path.startswith("http"):+ local_path = Path(path).expanduser().resolve()+ if not local_path.exists():+ return f"Error: File not found: {path}"+ if not local_path.is_file():+ return f"Error: Not a file: {path}"- client = await self._get_client(tool_context)- result = await client.add_resource(- str(path), description, target_path=target_path or None, wait=wait- )+ client = await VikingClient.create(tool_context.workspace_id)+ result = await client.add_resource(path, description)if result:- root_uri = result.get("root_uri", "unknown")+ root_uri = result.get("root_uri", "")return f"Successfully added resource: {root_uri}"else:return "Failed to add resource"+ except httpx.ReadTimeout:+ return f"Request timed out. The resource addition task may still be processing on the server side."except Exception as e:+ logger.warning(f"Error adding resource: {e}")return f"Error adding resource to Viking: {str(e)}"+ finally:+ if client:+ await client.close()class VikingGrepTool(OVFileTool):@@ -244,7 +240,7 @@ class VikingGrepTool(OVFileTool):"properties": {"uri": {"type": "string",- "description": "The whole Viking URI to search within (e.g., viking://resources/path/)",+ "description": "The whole Viking URI to search within (e.g., viking://resources/)",},"pattern": {"type": "string",diff --git a/bot/vikingbot/channels/base.py b/bot/vikingbot/channels/base.pyindex 98f12fd41..1cf2b3d00 100644--- a/bot/vikingbot/channels/base.py+++ b/bot/vikingbot/channels/base.py@@ -75,12 +75,43 @@ class BaseChannel(ABC):pass@abstractmethod- async def send(self, msg: OutboundMessage) -> None:+ async def send(self, msg: OutboundMessage) -> bool:"""Send a message through this channel.Args:msg: The message to send.++ Returns:+ True if the message was handled by base logic, False if needs subclass handling+ """+ # 处理添加表情的通用动作+ if msg.metadata and msg.metadata.get("action") == "add_reaction":+ message_id = msg.metadata.get("message_id")+ emoji = msg.metadata.get("emoji")+ if message_id and emoji:+ await self.send_processing_reaction(message_id, emoji)+ return True+ # 处理处理中tick事件+ if msg.metadata and msg.metadata.get("action") == "processing_tick":+ message_id = msg.metadata.get("message_id")+ tick_count = msg.metadata.get("tick_count", 0)+ if message_id:+ await self.handle_processing_tick(message_id, tick_count)+ return True+ return False++ async def handle_processing_tick(self, message_id: str, tick_count: int) -> None:+ """+ Handle processing tick event. Default empty implementation,+ channels can override to show custom processing indicators.+ """+ pass++ async def send_processing_reaction(self, message_id: str, emoji: str) -> None:+ """+ Send a processing reaction emoji to a message.+ Default empty implementation, channels can override if supported."""passdiff --git a/bot/vikingbot/channels/feishu.py b/bot/vikingbot/channels/feishu.pyindex 14bcfcad9..00c3a8969 100644--- a/bot/vikingbot/channels/feishu.py+++ b/bot/vikingbot/channels/feishu.py@@ -77,6 +77,16 @@ class FeishuChannel(BaseChannel):"""name = "feishu"+ # 飞书官方支持的处理中表情列表,按顺序发送+ PROCESSING_EMOJIS = [+ "StatusInFlight",+ "OneSecond",+ "Typing",+ "OnIt",+ "Coffee",+ "OnIt",+ "EatingFood",+ ]def __init__(self, config: FeishuChannelConfig, bus: MessageBus, **kwargs):super().__init__(config, bus, **kwargs)@@ -310,6 +320,20 @@ class FeishuChannel(BaseChannel):loop = asyncio.get_running_loop()await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)+ async def send_processing_reaction(self, message_id: str, emoji: str) -> None:+ """+ Send processing reaction emoji implementation for Feishu.+ """+ await self._add_reaction(message_id, emoji)++ async def handle_processing_tick(self, message_id: str, tick_count: int) -> None:+ """+ Handle processing tick event, send corresponding emoji reaction.+ """+ if 0 <= tick_count < len(self.PROCESSING_EMOJIS):+ emoji = self.PROCESSING_EMOJIS[tick_count]+ await self.send_processing_reaction(message_id, emoji)+# Regex to match markdown tables (header + separator + data rows)_TABLE_RE = re.compile(r"((?:^[ \t]*\|.+\|[ \t]*\n)(?:^[ \t]*\|[-:\s|]+\|[ \t]*\n)(?:^[ \t]*\|.+\|[ \t]*\n?)+)",@@ -466,6 +490,9 @@ class FeishuChannel(BaseChannel):async def send(self, msg: OutboundMessage) -> None:"""Send a message through Feishu."""+ # 先调用基类处理通用动作+ if await super().send(msg):+ returnif not self._client:logger.warning("Feishu client not initialized")@@ -476,6 +503,7 @@ class FeishuChannel(BaseChannel):returntry:+ # logger.info(f"Sending message {msg}")# Determine receive_id_type based on chat_id format# open_id starts with "ou_", chat_id starts with "oc_"reply_to = msg.metadata.get("reply_to")@@ -487,23 +515,7 @@ class FeishuChannel(BaseChannel):# Process images and get cleaned contentcleaned_content, images = await self._extract_and_upload_images(msg.content)- # Process @mentions: convert @ou_xxxx to Feishu mention format- # Pattern: @ou_xxxxxxx (user open_id)- import re-- mention_pattern = r"@(ou_[a-zA-Z0-9_-]+)"-- def replace_mention(match):- open_id = match.group(1)- return f'<at user_id="{open_id}">@{open_id}</at>'-- # Replace all mentions- content_with_mentions = re.sub(mention_pattern, replace_mention, cleaned_content)-- # Also support @all mention- content_with_mentions = content_with_mentions.replace(- "@all", '<at user_id="all">所有人</at>'- )+ content_with_mentions = cleaned_content# Check if we need to reply to a specific message# Get reply message ID from metadata (original incoming message ID)@@ -745,7 +757,7 @@ class FeishuChannel(BaseChannel):chat_mode = await self._get_chat_mode(chat_id)if chat_mode == "thread" and not message.root_id:message.root_id = message.message_id- if message.root_id:+ if chat_mode == "thread" and message.root_id:chat_id = f"{reply_to}#{message.root_id}"await self._handle_message(sender_id=sender_id,diff --git a/bot/vikingbot/channels/single_turn.py b/bot/vikingbot/channels/single_turn.pyindex 5c5dc3263..333ccc335 100644--- a/bot/vikingbot/channels/single_turn.py+++ b/bot/vikingbot/channels/single_turn.py@@ -72,7 +72,7 @@ class SingleTurnChannel(BaseChannel):# Wait for response with timeouttry:- await asyncio.wait_for(self._response_received.wait(), timeout=300.0)+ await asyncio.wait_for(self._response_received.wait(), timeout=3000.0)if self._last_response:from vikingbot.cli.commands import consolefrom rich.markdown import Markdowndiff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.pyindex 1611d5192..41db22108 100644--- a/bot/vikingbot/cli/commands.py+++ b/bot/vikingbot/cli/commands.py@@ -557,6 +557,9 @@ def chat(eval: bool = typer.Option(False, "--eval", "-e", help="Run evaluation mode, output JSON results"),+ config_path: str = typer.Option(+ None, "--config", "-c", help="Path to ov.conf, default .openviking/ov.conf"+ )):"""Interact with the agent directly."""if message is not None:@@ -568,8 +571,10 @@ def chat(else:logger.disable("vikingbot")+ path = Path(config_path).expanduser() if config_path is not None else None+bus = MessageBus()- config = ensure_config()+ config = ensure_config(path)_init_bot_data(config)session_manager = SessionManager(config.bot_data_path)diff --git a/bot/vikingbot/config/loader.py b/bot/vikingbot/config/loader.pyindex d32b74388..f1bad266b 100644--- a/bot/vikingbot/config/loader.py+++ b/bot/vikingbot/config/loader.py@@ -7,6 +7,7 @@ from typing import Anyfrom loguru import loggerfrom vikingbot.config.schema import Config+CONFIG_PATH = Nonedef get_config_path() -> Path:"""Get the path to ov.conf config file.@@ -38,9 +39,11 @@ def get_data_dir() -> Path:return get_data_path()-def ensure_config():+def ensure_config(config_path: Path | None = None) -> Config:"""Ensure ov.conf exists, create with default bot config if not."""- config_path = get_config_path()+ config_path = config_path or get_config_path()+ global CONFIG_PATH+ CONFIG_PATH = config_pathif not config_path.exists():logger.info("Config not found, creating default config...")@@ -53,11 +56,11 @@ def ensure_config():save_config(default_config, config_path)logger.info(f"[green]✓[/green] Created default config at {config_path}")- config = load_config(config_path)+ config = load_config()return config-def load_config(config_path: Path | None = None) -> Config:+def load_config() -> Config:"""Load configuration from ov.conf's bot field, and merge vlm config for model.@@ -67,7 +70,7 @@ def load_config(config_path: Path | None = None) -> Config:Returns:Loaded configuration object."""- path = config_path or get_config_path()+ path = CONFIG_PATH or get_config_path()if path.exists():try:diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 653f76f48..b4c30b566 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -39,6 +39,11 @@ class SandboxMode(str, Enum):PER_SESSION = "per-session"SHARED = "shared"+class AgentMemoryMode(str, Enum):+ """Agent memory mode enumeration."""+ PER_SESSION = "per-session"+ SHARED = "shared"+class BaseChannelConfig(BaseModel):"""Base channel configuration."""@@ -606,6 +611,7 @@ class Config(BaseSettings):)storage_workspace: str | None = None # From ov.conf root level storage.workspaceuse_local_memory: bool = False+ read_only: bool = False@propertydef channels_config(self) -> ChannelsConfig:diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.pyindex 26a14a692..8eed926b3 100644--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py@@ -4,7 +4,7 @@ from typing import Anyfrom loguru import loggerfrom vikingbot.config.loader import load_config-from vikingbot.config.schema import SessionKey+from vikingbot.config.schema import SessionKey, AgentMemoryModefrom ...session import Sessionfrom ..base import Hook, HookContext@@ -45,39 +45,36 @@ class OpenVikingCompactHook(Hook):return []return [msg for msg in messages if msg.get("sender_id") in allow_from]- def _get_channel_allow_from(self, session_key: SessionKey) -> list[str]:+ def _get_channel_allow_from(self, session_key: SessionKey):"""根据 session_id 获取对应频道的 allow_from 配置"""config = load_config()+ if not config.read_only:+ return True, []+ allow_from = [config.ov_server.admin_user_id]if not session_key or not config.channels:- return []-+ return False, allow_from# 查找对应类型的 channel config- for channel_config in config.channels:- if hasattr(channel_config, "type") and channel_config.type == session_key.channel_id:+ for channel_config in config.channels_config.get_all_channels():+ if channel_config and channel_config.type.value == session_key.type:if hasattr(channel_config, "allow_from"):- return channel_config.allow_from- return []+ allow_from.extend(channel_config.allow_from)+ return False, allow_fromasync def execute(self, context: HookContext, **kwargs) -> Any:vikingbot_session: Session = kwargs.get("session", {})session_id = context.session_key.safe_name()try:- # allow_from = self._get_channel_allow_from(session_id)- # filtered_messages = self._filter_messages_by_sender(- # vikingbot_session.messages, allow_from- # )+ is_shared, allow_from = self._get_channel_allow_from(context.session_key)filtered_messages = vikingbot_session.messages- if not filtered_messages:- logger.info(- f"No messages to commit openviking for session {session_id} (allow_from filter applied)"- )- return {"success": True, "message": "No messages matched allow_from filter"}+ if not is_shared:+ filtered_messages = self._filter_messages_by_sender(vikingbot_session.messages, allow_from)+ if not filtered_messages:+ logger.info(f"No messages to commit openviking for session {session_id} (allow_from filter applied)")+ return {"success": True, "message": "No messages matched allow_from filter"}client = await self._get_client(context.workspace_id)- result = await client.commit(- session_id, filtered_messages, load_config().ov_server.admin_user_id- )+ result = await client.commit(session_id, filtered_messages, load_config().ov_server.admin_user_id)return resultexcept Exception as e:logger.exception(f"Failed to add message to OpenViking: {e}")diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 287af820f..935ce1623 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -25,6 +25,8 @@ class VikingClient:self.admin_user_id = "default"self._apikey_manager = Noneelse:+ if agent_id and "#" in agent_id:+ agent_id = agent_id.split("#", 1)[0]self.client = ov.AsyncHTTPClient(url=openviking_config.server_url,api_key=openviking_config.root_api_key,@@ -98,10 +100,10 @@ class VikingClient:return await self.client.find(query)async def add_resource(- self, local_path: str, desc: str, target_path: Optional[str] = None, wait: bool = False+ self, local_path: str, desc: str) -> Optional[Dict[str, Any]]:"""添加资源到 Viking"""- result = await self.client.add_resource(path=local_path, reason=desc, wait=wait)+ result = await self.client.add_resource(path=local_path, reason=desc)return resultasync def list_resources(@@ -325,7 +327,7 @@ class VikingClient:async def grep(self, uri: str, pattern: str, case_insensitive: bool = False) -> Dict[str, Any]:"""通过模式(正则表达式)搜索内容"""- return await self.client.grep(uri, pattern, case_insensitive=case_insensitive)+ return await self.client.grep(uri, pattern, case_insensitive=case_insensitive, node_limit=10)async def glob(self, pattern: str, uri: Optional[str] = None) -> Dict[str, Any]:"""通过 glob 模式匹配文件"""@@ -441,12 +443,13 @@ async def main_test():# res = await client.search_memory("你好", "user_1")# res = await client.list_resources("viking://resources/")# res = await client.read_content("viking://user/memories/profile.md", level="read")- # res = await client.add_resource("/Users/bytedance/Documents/论文/吉比特年报.pdf", "吉比特年报")- res = await client.commit(- session_id="99999",- messages=[{"role": "user", "content": "你好"}],- user_id="1010101010",- )+ # res = await client.add_resource("https://github.com/volcengine/OpenViking", "ov代码")+ res = await client.grep("viking://resources/", "viking", True)+ # res = await client.commit(+ # session_id="99999",+ # messages=[{"role": "user", "content": "你好"}],+ # user_id="1010101010",+ # )# res = await client.commit("1234", [{"role": "user", "content": "帮我搜索 Python asyncio 教程"}# ,{"role": "assistant", "content": "我来帮你r搜索 Python asyncio 相关的教程。"}])print(res)@@ -468,5 +471,5 @@ async def account_test():if __name__ == "__main__":- # asyncio.run(main_test())- asyncio.run(account_test())+ asyncio.run(main_test())+ # asyncio.run(account_test())