JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: 基于关键词的跨channel/session 历史检索
Haowei_Du643be344a0ab
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.pyindex 1569358566..edc84c85d4 100644--- a/jiuwenclaw/agentserver/prompt_builder.py+++ b/jiuwenclaw/agentserver/prompt_builder.py@@ -538,6 +538,23 @@ Available skills:"""+def _cross_session_history_fallback_prompt(language: str) -> str:+ """跨会话 history.json 检索说明:放在 memory 段之后,不作为记忆体系正文。"""+ if language == "zh":+ return """## **历史信息检索**:+在回答任何关于历史事件、日期、人物、过去对话的问题时,+如果记忆中没有相关信息或不足以回答,则需要使用跨会话检索聊天原文。+阅读 skill **`cross-channel-history-retrieval`** 的 `SKILL.md`,+不要用猜测代替检索结果。+"""+ return """## **Historical information retrieval**:+For questions about past events, dates, people, or earlier conversations,+if memory lacks relevant information or is insufficient, retrieve verbatim chat across sessions.+Read skill **`cross-channel-history-retrieval`** `SKILL.md`+Do not substitute guessing for retrieved facts.+"""++def _context_prompt(language: str) -> str:if language == "zh":return """## 隐藏消息@@ -893,6 +910,7 @@ def build_system_prompt(title = "## 记忆内容:" if language == "zh" else "## Memory content:"system_prompt += f"{title}\n\n{memory_block.strip()}\n"+ system_prompt += _cross_session_history_fallback_prompt(language) + '\n'system_prompt += """\n---\n\n"""if mode == "plan":system_prompt += _todo_prompt(language) + '\n'diff --git a/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/SKILL.md b/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/SKILL.mdnew file mode 100644index 0000000000..7da900e8df--- /dev/null+++ b/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/SKILL.md@@ -0,0 +1,67 @@+---+name: cross-channel-history-retrieval+description: 跨会话检索聊天原文(记忆不足时再用)+在回答任何关于历史事件、日期、人物、过去对话的问题时,如果记忆中没有相关信息或不足以回答,则需要使用跨会话检索聊天原文。用 mcp_exec_command 执行 scripts/search_history.py,读 ~/.jiuwenclaw/agent/sessions/*/history.json。支持 channel、session_id、关键词、时间窗。如果搜索结果不足,尝试用不同的关键词再次搜索。+allowed_tools: [mcp_exec_command]+---++# 跨频道历史检索++用于从 `~/.jiuwenclaw/agent/sessions/<session_id>/history.json` 中检索历史消息,并把命中结果整理为可直接粘贴进当前上下文的文本块。++## 何时使用++- 用户提到“其他频道/会话”的聊天内容,或在 **A 频道问自己在 B 频道(如网页)说过什么**+- **「今天/刚才我问了什么」「关于某某我提过什么问题」** 且当前会话里看不到原文+- 用户给出关键词,要求回溯某时间段对话+- 用户要求把检索结果“带到当前上下文里”++## 执行方式++必须使用 `mcp_exec_command` 执行脚本,不要只口头总结。++```bash+python ~/.jiuwenclaw/agent/skills/cross-channel-history-retrieval/scripts/search_history.py --channel feishu --query "报销 审批" --start "2026-03-26 09:00" --end "2026-03-26 18:00" --limit 30+```++(Windows:**`--channel` / `--query` / 时间参数等与 Unix 相同**;默认 `mcp_exec_command` 走 **cmd**,**cmd 不会展开 `~`**,不要用 `~/.jiuwenclaw`,应写 `python %USERPROFILE%\.jiuwenclaw\agent\skills\cross-channel-history-retrieval\scripts\search_history.py` 再接同样参数。若整条命令在 PowerShell 里执行,`~` 一般会展开,也可用 `$env:USERPROFILE\...`。)++## 参数说明++- `--channel`:按频道过滤(如 `feishu` / `dingtalk` / `web`)。如果用户在语言里没有指明 channel,则不要传 `--channel`,脚本会扫描所有会话。+- `--session-id`:只检索指定会话(优先级高于 `--channel`)+- `--query`:空格分词关键词(例如 `"合同 审批"`)+- `--keyword`:可重复传入多个精确关键词+- `--start`、`--end`:显式时间范围,格式支持+ - `YYYY-MM-DD`+ - `YYYY-MM-DD HH:MM`+ - `YYYY-MM-DD HH:MM:SS`+ - ISO8601(如 `2026-03-26T10:30:00+08:00`)+- `--at`:某个时间点,配合 `--window-minutes` 形成检索窗+- `--window-minutes`:窗口大小(默认 120 分钟)+- `--timezone`:默认 `Asia/Shanghai`+- `--limit`:返回命中上限(默认 20)+- `--max-sessions`:最多扫描会话数量(默认 200)+- `--auto-expand`:无命中时自动扩大时间窗重试(默认开启)++## 时间策略++1. 若用户明确给了开始/结束时间,优先使用。+2. 若仅给“某时刻”,使用 `--at + --window-minutes`。+3. 若用户没给时间,使用默认窗口(最近 24 小时)。+4. 若初次无结果且 `--auto-expand` 开启,自动扩展为最近 72 小时再试一次。++## 输出与上下文注入++脚本**第一行**固定输出 `SKILL=cross-channel-history-retrieval`,便于在 `mcp_exec_command` 回显或日志里 `grep` 确认本 skill 的脚本已执行。++脚本会输出两个区块:++- `HISTORY_SEARCH_SUMMARY`:统计信息与最终时间窗+- `HISTORY_CONTEXT_BLOCK`:可直接放入当前对话上下文的命中消息片段++拿到脚本输出后,你应当:++1. 在回复中简要说明检索范围和命中情况。+2. 把 `HISTORY_CONTEXT_BLOCK` 中的内容原样(或轻度裁剪)贴到当前回复里,作为上下文依据。+3. 若无命中,明确说明已检索的时间窗、频道/会话和关键词,并询问是否放宽条件。diff --git a/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/scripts/search_history.py b/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/scripts/search_history.pynew file mode 100644index 0000000000..323b886984--- /dev/null+++ b/jiuwenclaw/resources/agent/skills/cross-channel-history-retrieval/scripts/search_history.py@@ -0,0 +1,403 @@+from __future__ import annotations++import argparse+import json+import locale+import logging+import re+import sys+import warnings+from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any++try:+ from zoneinfo import ZoneInfo+except ImportError: # pragma: no cover+ ZoneInfo = None # type: ignore[assignment]++# 固定首行标记:在 mcp_exec_command 回显或日志里 grep `SKILL=cross-channel-history-retrieval` 即可确认本脚本被运行。+_SKILL_ID = "cross-channel-history-retrieval"++_REPORT_LOG = logging.getLogger("jiuwenclaw.skill.cross_channel_history_retrieval")+++def _configure_report_logging() -> None:+ """仅输出纯文本行(与原先 print 一致),默认写到 stderr,供 mcp_exec_command 一并捕获。"""+ if _REPORT_LOG.handlers:+ return+ _REPORT_LOG.setLevel(logging.INFO)+ handler = logging.StreamHandler()+ handler.setFormatter(logging.Formatter("%(message)s"))+ _REPORT_LOG.addHandler(handler)+ _REPORT_LOG.propagate = False+++def _report_line(s: str = "") -> None:+ _REPORT_LOG.info("%s", s)+++def _align_stdio_for_pipe_capture() -> None:+ """非 TTY(如 mcp_exec_command 管道捕获)时,按系统首选编码写出 stdout/stderr。++ 与 agentserver `mcp_exec_command` 的 `locale.getpreferredencoding(False)` 解码一致,+ 避免子进程默认 UTF-8 与父进程按 GBK/CP936 解码产生乱码。交互终端不改动,以免干扰本机 UTF-8 控制台。+ """+ if sys.stdout.isatty():+ return+ enc = locale.getpreferredencoding(False) or "utf-8"+ for stream in (sys.stdout, sys.stderr):+ reconf = getattr(stream, "reconfigure", None)+ if reconf is None:+ continue+ try:+ reconf(encoding=enc, errors="replace")+ except Exception:+ warnings.warn(+ f"Failed to reconfigure stream to {enc!r}; output encoding may mismatch the parent process.",+ UserWarning,+ stacklevel=1,+ )+++@dataclass+class Hit:+ session_id: str+ role: str+ channel_id: str+ timestamp: float+ content: str+ request_id: str+++def _default_sessions_root() -> Path:+ home = Path.home()+ return home / ".jiuwenclaw" / "agent" / "sessions"+++def _to_float_ts(v: Any, tz: timezone) -> float | None:+ if v is None:+ return None++ if isinstance(v, (int, float)):+ f = float(v)+ if f > 1e12:+ return f / 1000.0+ return f++ s = str(v).strip()+ if not s:+ return None++ if re.fullmatch(r"\d{13,}", s):+ return float(s) / 1000.0+ if re.fullmatch(r"\d{10,12}", s):+ return float(s)++ try:+ dt = datetime.fromisoformat(s.replace("Z", "+00:00"))+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=tz)+ return dt.timestamp()+ except Exception:+ return None+++def _parse_user_dt(s: str, tz: timezone) -> datetime:+ s = s.strip()+ fmts = [+ "%Y-%m-%d %H:%M:%S",+ "%Y-%m-%d %H:%M",+ "%Y-%m-%d",+ ]+ for fmt in fmts:+ try:+ dt = datetime.strptime(s, fmt)+ return dt.replace(tzinfo=tz)+ except ValueError:+ continue+ try:+ dt = datetime.fromisoformat(s.replace("Z", "+00:00"))+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=tz)+ return dt+ except Exception as exc:+ raise ValueError(f"无法解析时间: {s}") from exc+++def _read_history_file(path: Path) -> list[dict[str, Any]]:+ try:+ raw = path.read_text(encoding="utf-8")+ except Exception:+ return []+ try:+ data = json.loads(raw)+ except Exception:+ return []+ if not isinstance(data, list):+ return []+ out: list[dict[str, Any]] = []+ for item in data:+ if isinstance(item, dict):+ out.append(item)+ return out+++def _build_keywords(args: argparse.Namespace) -> list[str]:+ kws: list[str] = []+ for k in args.keyword or []:+ kk = str(k).strip()+ if kk:+ kws.append(kk)+ q = str(args.query or "").strip()+ if q:+ kws.extend([p for p in q.split() if p.strip()])+ seen: set[str] = set()+ uniq: list[str] = []+ for k in kws:+ lk = k.lower()+ if lk in seen:+ continue+ seen.add(lk)+ uniq.append(k)+ return uniq+++def _match_keywords(text: str, keywords: list[str]) -> bool:+ if not keywords:+ return True+ lt = text.lower()+ return all(k.lower() in lt for k in keywords)+++def _iter_session_dirs(sessions_root: Path, max_sessions: int) -> list[Path]:+ if not sessions_root.exists():+ return []+ dirs = [p for p in sessions_root.iterdir() if p.is_dir()]+ dirs.sort(key=lambda p: p.stat().st_mtime, reverse=True)+ return dirs[: max(1, int(max_sessions))]+++def _session_match(session_id: str, channel: str | None, exact_session_id: str | None) -> bool:+ if exact_session_id:+ return session_id == exact_session_id+ if channel:+ return session_id.startswith(f"{channel}_") or session_id == channel+ return True+++def _search_once(+ *,+ sessions_root: Path,+ channel: str | None,+ session_id: str | None,+ start_ts: float,+ end_ts: float,+ keywords: list[str],+ limit: int,+ max_sessions: int,+ tz: timezone,+) -> tuple[list[Hit], int, int]:+ hits: list[Hit] = []+ scanned_sessions = 0+ scanned_records = 0++ for d in _iter_session_dirs(sessions_root, max_sessions=max_sessions):+ sid = d.name+ if not _session_match(sid, channel=channel, exact_session_id=session_id):+ continue++ scanned_sessions += 1+ f = d / "history.json"+ if not f.exists():+ continue+ items = _read_history_file(f)+ for it in items:+ scanned_records += 1+ ts = _to_float_ts(it.get("timestamp"), tz=tz)+ if ts is None or ts < start_ts or ts > end_ts:+ continue+ content = str(it.get("content") or "")+ if not content.strip():+ continue+ if not _match_keywords(content, keywords):+ continue+ hits.append(+ Hit(+ session_id=sid,+ role=str(it.get("role") or "unknown"),+ channel_id=str(it.get("channel_id") or ""),+ timestamp=ts,+ content=content.strip(),+ request_id=str(it.get("request_id") or ""),+ )+ )++ hits.sort(key=lambda h: h.timestamp, reverse=True)+ return hits[:limit], scanned_sessions, scanned_records+++def _fmt_iso(ts: float, tz: timezone) -> str:+ return datetime.fromtimestamp(ts, tz=tz).isoformat()+++def _emit_search_report(+ *,+ hits: list[Hit],+ scanned_sessions: int,+ scanned_records: int,+ start_ts: float,+ end_ts: float,+ keywords: list[str],+ channel: str | None,+ session_id: str | None,+ timezone_name: str,+ auto_expanded: bool,+ tz: timezone,+) -> None:+ _report_line(f"SKILL={_SKILL_ID}")+ _report_line("HISTORY_SEARCH_SUMMARY_BEGIN")+ _report_line(f"timezone={timezone_name}")+ _report_line(f"start={_fmt_iso(start_ts, tz)}")+ _report_line(f"end={_fmt_iso(end_ts, tz)}")+ _report_line(f"channel={channel or '-'}")+ _report_line(f"session_id={session_id or '-'}")+ _report_line(f"keywords={','.join(keywords) if keywords else '-'}")+ _report_line(f"scanned_sessions={scanned_sessions}")+ _report_line(f"scanned_records={scanned_records}")+ _report_line(f"hit_count={len(hits)}")+ _report_line(f"auto_expanded={str(auto_expanded).lower()}")+ _report_line("HISTORY_SEARCH_SUMMARY_END")+ _report_line()++ _report_line("HISTORY_CONTEXT_BLOCK_BEGIN")+ if not hits:+ _report_line("未命中任何历史记录。")+ else:+ for idx, h in enumerate(hits, start=1):+ _report_line(+ f"[{idx}] time={_fmt_iso(h.timestamp, tz)} session={h.session_id} "+ f"role={h.role} channel={h.channel_id or '-'} request_id={h.request_id or '-'}"+ )+ _report_line(h.content)+ _report_line("---")+ _report_line("HISTORY_CONTEXT_BLOCK_END")+++def main() -> int:+ _align_stdio_for_pipe_capture()+ _configure_report_logging()+ parser = argparse.ArgumentParser(description="Search session history.json by channel/session/time/keywords.")+ parser.add_argument(+ "--sessions-root",+ type=str,+ default="",+ help="Path to sessions root. Default: ~/.jiuwenclaw/agent/sessions",+ )+ parser.add_argument("--channel", type=str, default="", help="Filter by channel prefix in session_id, e.g. feishu")+ parser.add_argument("--session-id", type=str, default="", help="Exact session_id")+ parser.add_argument("--query", type=str, default="", help="Space-separated keywords, all must match")+ parser.add_argument("--keyword", action="append", default=[], help="Exact keyword, can be passed multiple times")+ parser.add_argument("--start", type=str, default="", help="Start time")+ parser.add_argument("--end", type=str, default="", help="End time")+ parser.add_argument("--at", type=str, default="", help="Center time")+ parser.add_argument(+ "--window-minutes",+ type=int,+ default=120,+ help="Time window minutes for --at or default search",+ )+ parser.add_argument("--timezone", type=str, default="Asia/Shanghai", help="Timezone name")+ parser.add_argument("--limit", type=int, default=20, help="Max hits to emit in the report")+ parser.add_argument("--max-sessions", type=int, default=200, help="Max session folders to scan")+ parser.add_argument("--auto-expand", action="store_true", default=True, help="Auto expand to 72h if no hits")+ parser.add_argument("--no-auto-expand", dest="auto_expand", action="store_false", help="Disable auto expansion")+ args = parser.parse_args()++ if ZoneInfo is not None:+ tz = ZoneInfo(args.timezone)+ else:+ tz = timezone(timedelta(hours=8))++ now = datetime.now(tz=tz)+ window_minutes = max(1, int(args.window_minutes))++ start_ts: float+ end_ts: float+ if args.start or args.end:+ start_dt = _parse_user_dt(args.start, tz) if args.start else (now - timedelta(hours=24))+ end_dt = _parse_user_dt(args.end, tz) if args.end else now+ start_ts = start_dt.timestamp()+ end_ts = end_dt.timestamp()+ elif args.at:+ center = _parse_user_dt(args.at, tz)+ half = timedelta(minutes=window_minutes / 2)+ start_ts = (center - half).timestamp()+ end_ts = (center + half).timestamp()+ else:+ start_ts = (now - timedelta(hours=24)).timestamp()+ end_ts = now.timestamp()++ if start_ts > end_ts:+ start_ts, end_ts = end_ts, start_ts++ sessions_root = (+ Path(args.sessions_root).expanduser()+ if str(args.sessions_root).strip()+ else _default_sessions_root()+ )+ channel = str(args.channel or "").strip() or None+ session_id = str(args.session_id or "").strip() or None+ keywords = _build_keywords(args)+ limit = max(1, int(args.limit))+ max_sessions = max(1, int(args.max_sessions))++ hits, scanned_sessions, scanned_records = _search_once(+ sessions_root=sessions_root,+ channel=channel,+ session_id=session_id,+ start_ts=start_ts,+ end_ts=end_ts,+ keywords=keywords,+ limit=limit,+ max_sessions=max_sessions,+ tz=tz,+ )++ auto_expanded = False+ if not hits and args.auto_expand:+ if not args.start and not args.end:+ auto_expanded = True+ start_ts = (now - timedelta(hours=72)).timestamp()+ end_ts = now.timestamp()+ hits, scanned_sessions, scanned_records = _search_once(+ sessions_root=sessions_root,+ channel=channel,+ session_id=session_id,+ start_ts=start_ts,+ end_ts=end_ts,+ keywords=keywords,+ limit=limit,+ max_sessions=max_sessions,+ tz=tz,+ )++ _emit_search_report(+ hits=hits,+ scanned_sessions=scanned_sessions,+ scanned_records=scanned_records,+ start_ts=start_ts,+ end_ts=end_ts,+ keywords=keywords,+ channel=channel,+ session_id=session_id,+ timezone_name=args.timezone,+ auto_expanded=auto_expanded,+ tz=tz,+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())