Skip to content

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

压测脚本

meizi639a0dd1c0846
diff --git a/packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py b/packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py
new file mode 100644
index 0000000000..cf70194351
--- /dev/null
+++ b/packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py
@@ -0,0 +1,2090 @@
+#!/usr/bin/env python3
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""并发向 Gateway WebChannel 发送 chat.send,验证 Runtime 转发与 AgentServer 池的端到端压测。
+
+脚本:`enterprise_runtime_concurrent_test.py`(与 ``enterprise_runtime_service_config.py`` 同属
+Gateway Runtime 联调/压测工具,前者读库校验 ``service_config`` 槽位,本脚本经 WebSocket 发真实
+``chat.send`` 做并发端到端验证。)
+
+默认发起 30 路并发(``--concurrency 30``),均匀分布到 3 个 AgentServer(``--shards 3``),
+即每个 AgentServer 10 路;**同一分片内共用同一个 ``group_id``**
+(默认 ``loadtest_s0`` / ``loadtest_s1`` / ``loadtest_s2``),以便经 Gateway 路由
+均匀打到 3 个 AgentServer 实例上。
+
+可选 ``--shards2 N``:在同一 AgentServer(同一 ``group_id``)内,再按 ``user_id`` 打到
+N 个 Agent 实例(``user_id`` 形如 ``{prefix}_s{shard}_a{j}``,同桶多路共用同一 ``user_id``)。
+不要求 ``concurrency`` 与 ``shards`` / ``shards2`` 整除,余数路由由靠前的分片/实例多承接。
+``shards2=0``(默认)时每路独立 ``user_id``(``{prefix}_{idx:02d}``);``shards2=1`` 时同一
+AgentServer 内全部打到同一 Agent 实例;``shards2>=2`` 时在实例间轮询。``session_id`` / ``req_id`` 始终每路唯一。
+
+依赖:主仓库已安装 ``websockets``(``uv sync`` 或 ``pip install websockets``)。
+
+压测时可配合 ``mock_llm_server.py`` 替代真实 LLM(见设计文档 **§3.3 Mock LLM**)。
+
+典型用法(项目根目录)::
+
+ # 本地 provision 后的 Gateway Web 端口
+ uv run python packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py \\
+ --web-port 19234
+
+ # 远程 Gateway
+ uv run python packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py \\
+ --ws-url ws://10.0.0.1:19001/ws
+
+ # K8s 仅暴露 Web NodePort(5173 -> 30105)时,经 HTTP 端口的 /ws 代理连入
+ # jiuwenclaw-web:19000 为 ClusterIP,集群外不可直连,须走 NodePort + /ws
+ uv run python packages/jiuwenclaw-ee/claw_manager/scripts/enterprise_runtime_concurrent_test.py \\
+ --ws-url ws://<节点IP>:30105/ws
+
+ # 等价写法(--web-port 填 NodePort 外部端口,非 19000)
+ uv run python .../enterprise_runtime_concurrent_test.py \\
+ --host <节点IP> --web-port 30105
+
+ # 自定义总并发与 AgentServer 分片(60 路均匀打到 6 个 AgentServer,每个 10 路)
+ uv run python .../enterprise_runtime_concurrent_test.py \\
+ --web-port 19234 --concurrency 60 --shards 6
+
+ # 每个 AgentServer 内再均匀打到 2 个 Agent 实例(user_id 分桶)
+ uv run python .../enterprise_runtime_concurrent_test.py \\
+ --ws-url ws://host:30105/ws --concurrency 6 --shards 3 --shards2 2
+
+ # 按 bot_id 分片路由(固定 group_id,每 shard 不同 bot_id),配合 Gateway AGENT_BOT_ID_GROUP_NUM 联调
+ uv run python .../enterprise_runtime_concurrent_test.py \\
+ --ws-url ws://host:30105/ws --concurrency 9 --shards 3 --service-shard-key bot_id
+
+ # loadtest 四步流程(travel → skill → file → cron,配合 mock_llm_server --profile loadtest)
+ uv run python .../enterprise_runtime_concurrent_test.py \\
+ --ws-url ws://host:30105/ws --concurrency 3 --flow loadtest
+
+默认等待整轮 Agent 任务结束。``--flow loadtest``(默认)时,每路会话在同一 ``session_id`` 内
+**依次**发送 4 条用户消息(travel → skill → file 上传扩写 → cron),与 ``mock_llm_server.py``
+``--profile loadtest`` 场景顺序一致;``--flow single`` 时仍为单条 ``--content`` 消息。
+含文件交付的步骤须先收到 ``chat.file``(或 ``send_file_to_user`` 的 ``chat.tool_result``),
+再采纳 ``chat.processing_status idle`` / ``chat.usage_summary`` 等终态信号;定时任务步骤须等
+约 1 分钟后收到喝水提醒投递文案(``🥤 喝水时间到啦!…``),创建确认 alone 不算完成。
+``file`` 扩写步骤在收到 ``chat.file`` 后,会把交付文件下载到脚本目录下带时间戳的
+``download_YYYYMMDD_HHMMSS/``(同一次压测共用一个目录),本地文件名再追加请求编号
+(如 ``童趣的春天_扩写版_00.md``)以免并发覆盖。
+DeepAgent 在流式文本 iteration 结束时可能发出 **content 为空** 的 ``chat.final`` 标记,
+该帧仅表示当前 LLM 轮次结束,**不是**整轮任务完成,脚本会忽略并继续等待。
+权限放行(``auto-allow``)后,忽略紧随其后的假 idle / 子流 ``usage_summary``,
+直至新一轮 ``chat.delta`` 表明 Agent 已继续执行。
+每路真正完成时打印 ``[done]`` 行(含 idx / session_id / 耗时)。Agent 弹出权限/追问(``chat.ask_user_question``)
+时自动全部允许(权限类选「总是允许」)。长任务可通过 ``--final-timeout`` 调整上限。
+资源打满(100001/100002)时 Gateway 常提前 ``is_processing=false`` 且不一定下发
+``chat.error``;脚本会识别 payload 错误关键字,并将「未交付即 idle」记为失败,避免挂死。
+若仅需验证 Gateway 接受请求、不等 Agent 跑完,加 ``--accept-only``;禁用自动放行加 ``--no-auto-allow``。
+排查权限/追问 WS 事件时加 ``--ws-event-log``,会打印每路收到的 event 名(含 frame.event
+与 payload.event_type 对照,便于发现事件名不匹配)。
+
+Ctrl+C 退出时,脚本会对**已接受且未完成**的会话发送 ``chat.interrupt``(``intent=cancel``),
+与 ``web_enterprise`` 页面点击「取消」一致;仅关闭 WebSocket **不会**自动停止 AgentServer 上的任务。
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import logging
+import statistics
+import sys
+import time
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlunparse
+from urllib.request import Request, urlopen
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_BOT_ID = "bot_main"
+_SERVICE_SHARD_KEYS = frozenset({"group_id", "bot_id"})
+
+
+@dataclass(frozen=True)
+class RoutePlan:
+ """单路 chat.send 的 Gateway 路由参数(shard→AgentServer,shard2→Agent 实例)。"""
+
+ shard: int
+ shard2: int
+ group_id: str
+ bot_id: str
+ user_id: str
+
+
+_SCRIPT_DIR = Path(__file__).resolve().parent
+_DEFAULT_SPRING_ESSAY = _SCRIPT_DIR / "童趣的春天.md"
+_DOWNLOAD_DIR_PREFIX = _SCRIPT_DIR / "download"
+
+
+def _make_run_download_dir(*, when: time.struct_time | None = None) -> Path:
+ """生成本次压测专用下载目录:download_YYYYMMDD_HHMMSS。"""
+ stamp = time.strftime("%Y%m%d_%H%M%S", when or time.localtime())
+ return Path(f"{_DOWNLOAD_DIR_PREFIX}_{stamp}")
+
+
+@dataclass(frozen=True)
+class LoadTestStep:
+ """loadtest 单步用户请求(与 mock_llm_server loadtest 场景顺序一致)。"""
+
+ name: str
+ content: str
+ expect_file: bool = True
+ files: tuple[dict[str, str], ...] = ()
+ expect_delayed_text: bool = False
+ download_deliverable: bool = False
+
+
+_CRON_CREATION_MARKERS = ("喝水提醒已创建", "执行时间:")
+_CRON_DELIVERY_MARKERS = ("喝水时间到啦",)
+
+
+def build_default_loadtest_steps(essay_path: Path) -> tuple[LoadTestStep, ...]:
+ if not essay_path.is_file():
+ raise FileNotFoundError(f"loadtest 附件不存在: {essay_path}")
+ resolved = str(essay_path.resolve())
+ essay_name = essay_path.name
+ return (
+ LoadTestStep(
+ name="travel",
+ content=(
+ "帮我写一篇十万字的小说,主题是旅行的意义,写完后保存到txt发给我。"
+ "直接开始写,不要问我其他问题"
+ ),
+ expect_file=True,
+ ),
+ LoadTestStep(
+ name="skill",
+ content=(
+ "先使用skillnet安装这个旅游攻略技能"
+ "https://github.com/Asif2BD/openclaw.tours/tree/main,"
+ "然后再给我制作一个北京3日游的旅游攻略"
+ ),
+ expect_file=True,
+ ),
+ LoadTestStep(
+ name="file",
+ content="帮我把这个文件里的作文扩写到6000字,然后发回给我",
+ expect_file=True,
+ files=({"path": resolved, "name": essay_name},),
+ download_deliverable=True,
+ ),
+ LoadTestStep(
+ name="cron",
+ content="创建一个定时任务,1分钟后提醒我喝水",
+ expect_file=False,
+ expect_delayed_text=True,
+ ),
+ )
+
+
+_DEFAULT_CONTENT = (
+ "帮我写一篇十万字的小说,主题是旅行的意义,写完后保存到txt发给我。直接开始写,不要问我其他问题"
+)
+
+
+@dataclass
+class RequestResult:
+ index: int
+ shard: int
+ shard2: int
+ session_id: str
+ req_id: str
+ group_id: str
+ bot_id: str
+ user_id: str
+ ok: bool
+ accepted: bool
+ error: str = ""
+ accept_ms: float = 0.0
+ total_ms: float = 0.0
+ final_received: bool = False
+ steps_completed: int = 0
+ steps_total: int = 0
+ failed_step: str = ""
+
+
+@dataclass
+class LoadTestStats:
+ total: int
+ completed: int
+ failed: int
+ elapsed_s: float
+ accept_ms: list[float] = field(default_factory=list)
+ total_ms: list[float] = field(default_factory=list)
+
+ def summary(self) -> str:
+ lines = [
+ f"total={self.total} completed={self.completed} failed={self.failed} "
+ f"elapsed={self.elapsed_s:.2f}s",
+ ]
+ if self.accept_ms:
+ sorted_accept = sorted(self.accept_ms)
+ lines.append(
+ f"accept_ms: avg={statistics.mean(sorted_accept):.0f} "
+ f"min={min(sorted_accept):.0f} "
+ f"max={max(sorted_accept):.0f} "
+ f"p50={_percentile(sorted_accept, 0.5):.0f} "
+ f"p95={_percentile(sorted_accept, 0.95):.0f}"
+ )
+ if self.total_ms:
+ sorted_total = sorted(self.total_ms)
+ lines.append(
+ f"total_ms: avg={statistics.mean(sorted_total):.0f} "
+ f"min={min(sorted_total):.0f} "
+ f"max={max(sorted_total):.0f} "
+ f"p50={_percentile(sorted_total, 0.5):.0f} "
+ f"p95={_percentile(sorted_total, 0.95):.0f}"
+ )
+ return "\n".join(lines)
+
+
+@dataclass
+class ProgressTracker:
+ total: int
+ completed: int = 0
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+
+ async def mark_done(self) -> int:
+ async with self.lock:
+ self.completed += 1
+ return self.completed
+
+
+@dataclass
+class _ActiveSession:
+ index: int
+ session_id: str
+ ws: Any
+ accepted: bool = False
+ finished: bool = False
+ cancel_sent: bool = False
+
+ def can_begin_cancel(self) -> bool:
+ return self.accepted and not self.finished and not self.cancel_sent
+
+
+class ActiveSessionRegistry:
+ """跟踪进行中的 WS 会话;退出时对已接受的请求发送 chat.interrupt(cancel)。"""
+
+ def __init__(self) -> None:
+ self._sessions: dict[str, _ActiveSession] = {}
+ self._lock = asyncio.Lock()
+
+ async def add(self, session: _ActiveSession) -> None:
+ async with self._lock:
+ self._sessions[session.session_id] = session
+
+ async def remove(self, session_id: str) -> None:
+ async with self._lock:
+ self._sessions.pop(session_id, None)
+
+ async def mark_accepted(self, session_id: str) -> None:
+ async with self._lock:
+ session = self._sessions.get(session_id)
+ if session is not None:
+ session.accepted = True
+
+ async def mark_finished(self, session_id: str) -> None:
+ async with self._lock:
+ session = self._sessions.get(session_id)
+ if session is not None:
+ session.finished = True
+
+ async def try_begin_cancel(self, session_id: str) -> _ActiveSession | None:
+ async with self._lock:
+ session = self._sessions.get(session_id)
+ if session is None or not session.can_begin_cancel():
+ return None
+ session.cancel_sent = True
+ return session
+
+ async def cancel_all(self, *, wait_ack: float = 3.0) -> int:
+ async with self._lock:
+ sessions = list(self._sessions.values())
+ if not sessions:
+ return 0
+ results = await asyncio.gather(
+ *[
+ _send_chat_interrupt_cancel(
+ s.ws,
+ session_id=s.session_id,
+ index=s.index,
+ wait_ack=wait_ack,
+ registry=self,
+ )
+ for s in sessions
+ ],
+ return_exceptions=True,
+ )
+ return sum(1 for item in results if item is True)
+
+
+async def _send_chat_interrupt_cancel(
+ ws: Any,
+ *,
+ session_id: str,
+ index: int,
+ wait_ack: float = 3.0,
+ registry: ActiveSessionRegistry | None = None,
+) -> bool:
+ """与 web_enterprise 点击「取消」一致:chat.interrupt intent=cancel。"""
+ if registry is not None:
+ session = await registry.try_begin_cancel(session_id)
+ if session is None:
+ return False
+
+ req_id = f"req_cancel_{index:02d}_{uuid.uuid4().hex[:8]}"
+ frame = {
+ "type": "req",
+ "id": req_id,
+ "method": "chat.interrupt",
+ "params": {"session_id": session_id, "intent": "cancel"},
+ }
+ try:
+ await ws.send(json.dumps(frame, ensure_ascii=False))
+ logger.info("[cancel] idx=%d session_id=%s", index, session_id)
+ if wait_ack > 0:
+ deadline = time.perf_counter() + wait_ack
+ while time.perf_counter() < deadline:
+ try:
+ remaining = max(0.05, deadline - time.perf_counter())
+ msg = await _recv_json(ws, remaining)
+ except asyncio.TimeoutError:
+ break
+ if msg.get("type") == "res" and msg.get("id") == req_id:
+ return bool(msg.get("ok"))
+ return True
+ except Exception as err:
+ logger.warning(
+ "[cancel-failed] idx=%d session_id=%s err=%s",
+ index,
+ session_id,
+ err,
+ )
+ return False
+
+
+def _percentile(sorted_values: list[float], ratio: float) -> float:
+ if not sorted_values:
+ return 0.0
+ idx = int((len(sorted_values) - 1) * ratio)
+ return sorted_values[idx]
+
+
+def _configure_cli_logging() -> None:
+ class _TimestampFormatter(logging.Formatter):
+ def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:
+ from datetime import datetime
+
+ dt = datetime.fromtimestamp(record.created)
+ base = dt.strftime(datefmt or "%Y-%m-%d %H:%M:%S")
+ return f"{base}.{int(record.msecs):03d}"
+
+ root = logging.getLogger()
+ root.handlers.clear()
+ root.setLevel(logging.INFO)
+ fmt = _TimestampFormatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
+ out = logging.StreamHandler(sys.stdout)
+ out.setLevel(logging.INFO)
+ out.setFormatter(fmt)
+ err = logging.StreamHandler(sys.stderr)
+ err.setLevel(logging.ERROR)
+ err.setFormatter(fmt)
+ root.addHandler(out)
+ root.addHandler(err)
+
+
+def _load_web_port_from_provision(path: Path) -> int:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ data = raw.get("data", raw)
+ ports = data.get("ports") if isinstance(data, dict) else None
+ if not isinstance(ports, dict):
+ raise ValueError(f"无法在 {path} 中找到 data.ports")
+ web = ports.get("web")
+ if web is None:
+ raise ValueError(f"无法在 {path} 中找到 data.ports.web")
+ return int(web)
+
+
+def _resolve_ws_url(args: argparse.Namespace) -> str:
+ if args.ws_url:
+ url = str(args.ws_url).strip()
+ parsed = urlparse(url)
+ if parsed.scheme not in ("ws", "wss"):
+ raise ValueError(f"--ws-url 须为 ws:// 或 wss://,当前 scheme={parsed.scheme!r}")
+ if not parsed.netloc:
+ raise ValueError(f"--ws-url 无效(缺少 host): {url!r}")
+ return url
+ if args.provision_json is not None:
+ web_port = _load_web_port_from_provision(args.provision_json)
+ else:
+ web_port = int(args.web_port)
+ return f"ws://{args.host}:{web_port}{args.ws_path}"
+
+
+def _browser_origin_header(ws_url: str) -> dict[str, str]:
+ parsed = urlparse(ws_url)
+ host = parsed.hostname or "127.0.0.1"
+ http_scheme = "https" if parsed.scheme == "wss" else "http"
+ port = parsed.port
+ default_port = 443 if http_scheme == "https" else 80
+ if port is not None and port != default_port:
+ origin = f"{http_scheme}://{host}:{port}"
+ else:
+ origin = f"{http_scheme}://{host}"
+ return {"Origin": origin}
+
+
+def _with_identity_query(
+ ws_url: str,
+ *,
+ group_id: str,
+ bot_id: str,
+ user_id: str,
+) -> str:
+ """在握手 URL 上带上租户身份,与前端 runtimeScope query 一致。"""
+ parsed = urlparse(ws_url)
+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))
+ query.setdefault("group_id", group_id)
+ query.setdefault("bot_id", bot_id)
+ query.setdefault("user_id", user_id)
+ return urlunparse(parsed._replace(query=urlencode(query)))
+
+
+def _tenant_headers(
+ *,
+ group_id: str,
+ bot_id: str,
+ user_id: str,
+ extra: dict[str, str] | None = None,
+) -> dict[str, str]:
+ headers = dict(extra or {})
+ headers["X-Group-Id"] = group_id
+ headers["X-Bot-Id"] = bot_id
+ headers["X-User-Id"] = user_id
+ return headers
+
+
+def _http_origin_from_ws_url(ws_url: str) -> str:
+ """由 WebSocket URL 推导 HTTP Origin(用于相对 download_url)。"""
+ return _browser_origin_header(ws_url)["Origin"]
+
+
+def _absolute_download_url(ws_url: str, download_url: str) -> str:
+ url = str(download_url or "").strip()
+ if not url:
+ raise ValueError("download_url 为空")
+ if url.startswith("http://") or url.startswith("https://"):
+ return url
+ return urljoin(_http_origin_from_ws_url(ws_url) + "/", url.lstrip("/"))
+
+
+def _indexed_download_filename(name: str, index: int) -> str:
+ """并发下载时在文件名后追加请求编号,避免互相覆盖。"""
+ path = Path(str(name or "download.bin").strip() or "download.bin")
+ return f"{path.stem}_{index:02d}{path.suffix}"
+
+
+def _extract_downloadable_files(payload: dict[str, Any]) -> list[dict[str, str]]:
+ """从 chat.file / tool_result payload 提取带 download_url 的文件项。"""
+ raw = payload.get("files")
+ if not isinstance(raw, list):
+ return []
+ entries: list[dict[str, str]] = []
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ download_url = str(item.get("download_url") or "").strip()
+ if not download_url:
+ continue
+ name = str(item.get("name") or item.get("filename") or Path(download_url).name or "download.bin")
+ entries.append({"name": name, "download_url": download_url})
+ return entries
+
+
+def _http_download_to_path(url: str, dest: Path, *, timeout: float = 60.0) -> None:
+ req = Request(url, method="GET")
+ with urlopen(req, timeout=timeout) as resp: # noqa: S310 — loadtest 下载 Gateway 自身签发的 URL
+ data = resp.read()
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(data)
+
+
+async def _download_deliverable_files(
+ *,
+ ws_url: str,
+ files: list[dict[str, str]],
+ index: int,
+ download_dir: Path,
+) -> list[Path]:
+ """把 chat.file 交付物下载到 download_dir,文件名带请求编号。"""
+ if not files:
+ return []
+ download_dir.mkdir(parents=True, exist_ok=True)
+ saved: list[Path] = []
+ for item in files:
+ abs_url = _absolute_download_url(ws_url, item["download_url"])
+ local_name = _indexed_download_filename(item["name"], index)
+ dest = download_dir / local_name
+ await asyncio.to_thread(_http_download_to_path, abs_url, dest)
+ saved.append(dest)
+ logger.info(
+ "[download] idx=%d saved=%s bytes=%d url=%s",
+ index,
+ dest,
+ dest.stat().st_size,
+ abs_url,
+ )
+ return saved
+
+
+def _build_route_plan(
+ concurrency: int,
+ shards: int,
+ shards2: int,
+ group_prefix: str,
+ user_id_prefix: str,
+ *,
+ bot_id: str = _DEFAULT_BOT_ID,
+ service_shard_key: str = "group_id",
+) -> list[RoutePlan]:
+ """返回每路路由计划:按 shard 分 AgentServer,user_id 按 shard2 分 Agent 实例。
+
+ ``service_shard_key`` 控制默认 ``service_id`` 路由维度的分片方式(Gateway 默认
+ ``service_id = group_id + hash_bucket(bot_id)``):
+
+ - ``group_id``(默认):``group_id={prefix}_s{shard}``,``bot_id`` 固定;
+ - ``bot_id``:``group_id={prefix}`` 固定,``bot_id={bot_id}_s{shard}``(测 AGENT_BOT_ID_GROUP_NUM)。
+
+ 按全局序号轮询分配 shard / shard2,不要求 concurrency 与 shards、shards2 整除;
+ 不能均分时,序号靠前的分片/实例多承接余数路由。
+ """
+ if shards <= 0:
+ raise ValueError("--shards 须 > 0")
+ if shards2 < 0:
+ raise ValueError("--shards2 须 >= 0")
+ if concurrency <= 0:
+ raise ValueError("--concurrency 须 > 0")
+ if service_shard_key not in _SERVICE_SHARD_KEYS:
+ raise ValueError(f"--service-shard-key 须为 {sorted(_SERVICE_SHARD_KEYS)} 之一")
+
+ plans: list[RoutePlan] = []
+ shard_route_counts = [0] * shards
+ for global_idx in range(concurrency):
+ shard = global_idx % shards
+ if service_shard_key == "group_id":
+ route_group_id = f"{group_prefix}_s{shard}"
+ route_bot_id = bot_id
+ else:
+ route_group_id = group_prefix
+ route_bot_id = f"{bot_id}_s{shard}"
+ if shards2 == 0:
+ user_id = f"{user_id_prefix}_{global_idx:02d}"
+ plan_shard2 = 0
+ else:
+ shard2 = shard_route_counts[shard] % shards2
+ user_id = f"{user_id_prefix}_s{shard}_a{shard2}"
+ plan_shard2 = shard2
+ shard_route_counts[shard] += 1
+ plans.append(
+ RoutePlan(
+ shard=shard,
+ shard2=plan_shard2,
+ group_id=route_group_id,
+ bot_id=route_bot_id,
+ user_id=user_id,
+ )
+ )
+ return plans
+
+
+async def _recv_json(ws: Any, timeout: float) -> dict[str, Any]:
+ raw = await asyncio.wait_for(ws.recv(), timeout=timeout)
+ data = json.loads(raw)
+ if not isinstance(data, dict):
+ raise TypeError(f"非 JSON 对象: {raw!r}")
+ return data
+
+
+def _normalize_event_frame(frame: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:
+ """从 WS event 帧解析 event 名与 payload(兼容 payload 内嵌 event_type)。"""
+ if frame.get("type") != "event":
+ return None, {}
+ event = frame.get("event")
+ payload = frame.get("payload") or {}
+ if not isinstance(payload, dict):
+ payload = {}
+ if not event:
+ nested = payload.get("event_type") or payload.get("event")
+ if isinstance(nested, str):
+ event = nested
+ return (str(event) if event else None), payload
+
+
+def _final_content(payload: dict[str, Any]) -> str:
+ content = payload.get("content")
+ if content is None:
+ return ""
+ return str(content).strip()
+
+
+def _event_session_id(frame: dict[str, Any], payload: dict[str, Any]) -> str:
+ """从 WS event 帧提取 session_id(WebChannel 广播时靠它区分会话)。"""
+ for source in (payload, frame):
+ if not isinstance(source, dict):
+ continue
+ sid = source.get("session_id")
+ if isinstance(sid, str) and sid.strip():
+ return sid.strip()
+ return ""
+
+
+def _is_cron_creation_text(content: str) -> bool:
+ text = content.strip()
+ return bool(text) and any(marker in text for marker in _CRON_CREATION_MARKERS)
+
+
+def _is_cron_delivery_text(content: str) -> bool:
+ """到点投递文案;创建确认里也含提醒正文,须排除。"""
+ text = content.strip()
+ if not text or _is_cron_creation_text(text):
+ return False
+ return any(marker in text for marker in _CRON_DELIVERY_MARKERS)
+
+
+def _matches_cron_delivery(
+ *,
+ expect_delayed_text: bool,
+ content: str,
+ logged_cron_creation: bool,
+ step_text_buf: str,
+) -> bool:
+ """delayed-text 步:当前片段或累计缓冲是否已是到点投递文案。"""
+ if not expect_delayed_text:
+ return False
+ if _is_cron_delivery_text(content):
+ return True
+ return logged_cron_creation and _is_cron_delivery_text(step_text_buf)
+
+
+def _matches_cron_creation(
+ *,
+ expect_delayed_text: bool,
+ logged_cron_creation: bool,
+ content: str,
+ step_text_buf: str,
+) -> bool:
+ """delayed-text 步:尚未记过创建确认,且当前/缓冲命中创建文案。"""
+ if not expect_delayed_text or logged_cron_creation:
+ return False
+ return _is_cron_creation_text(content) or _is_cron_creation_text(step_text_buf)
+
+
+def _content_marks_step_done(
+ *,
+ expect_file: bool,
+ expect_delayed_text: bool,
+ content: str,
+) -> bool:
+ text = content.strip()
+ if not text or expect_file:
+ return False
+ if expect_delayed_text:
+ return _is_cron_delivery_text(text)
+ return True
+
+
+def _tool_name_from_payload(payload: dict[str, Any]) -> str:
+ """从 chat.tool_call / chat.tool_result payload 提取工具名。"""
+ for key in ("tool_name", "name"):
+ val = payload.get(key)
+ if val:
+ return str(val).strip()
+ tool_call = payload.get("tool_call")
+ if isinstance(tool_call, dict):
+ for key in ("name", "tool_name"):
+ val = tool_call.get(key)
+ if val:
+ return str(val).strip()
+ return ""
+
+
+def _is_send_file_tool_success(payload: dict[str, Any]) -> bool:
+ """send_file_to_user 成功时 Gateway 可能只有 tool_result、没有 chat.file。"""
+ tool_name = _tool_name_from_payload(payload)
+ blob = _payload_text_blob(payload)
+ if "send_file" not in tool_name.lower() and "send_file_to_user" not in blob:
+ return False
+ result = str(payload.get("result") or payload.get("raw_output") or blob)
+ if "成功发送" in result:
+ return True
+ files = payload.get("files")
+ return isinstance(files, list) and bool(files)
+
+
+def _is_intra_turn_chat_final(event: str | None, payload: dict[str, Any]) -> bool:
+ """DeepAgent 流式文本 iteration 结束时的空 chat.final,仅标记当前 LLM 轮次完成。"""
+ return event == "chat.final" and not _final_content(payload)
+
+
+def _is_invoke_terminal_event(event: str | None, payload: dict[str, Any]) -> bool:
+ """可能是整轮结束的 WS event(仍需结合 HITL 状态判断是否采纳)。"""
+ if event == "chat.usage_summary":
+ return True
+ if event == "chat.final" and not _is_intra_turn_chat_final(event, payload):
+ return True
+ return False
+
+
+def _loadtest_terminal_ready(
+ *,
+ expect_file: bool = True,
+ saw_deliverable_file: bool,
+ saw_step_text: bool = False,
+ saw_post_deliverable_text: bool = False,
+) -> bool:
+ """单步完成判定:有文件交付的步骤须 chat.file;cron 须收到到点喝水提醒文案。"""
+ if expect_file:
+ _ = saw_post_deliverable_text
+ return saw_deliverable_file
+ return saw_step_text or saw_post_deliverable_text
+
+
+def _should_complete_invoke(
+ *,
+ expect_file: bool = True,
+ accepted: bool,
+ saw_agent_output: bool,
+ hitl_paused: bool,
+ hitl_await_agent_resume: bool,
+ saw_deliverable_file: bool,
+ saw_step_text: bool = False,
+ saw_post_deliverable_text: bool = False,
+ event: str | None,
+ payload: dict[str, Any],
+) -> bool:
+ """usage_summary / chat.final 完成判定。"""
+ if not accepted or not saw_agent_output:
+ return False
+ if hitl_paused:
+ return False
+ terminal_ready = _loadtest_terminal_ready(
+ expect_file=expect_file,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ )
+ # 放行后若交付里程碑已达成,usage_summary 可直接收尾(skill_complete 后未必再有 delta)。
+ if hitl_await_agent_resume and not (
+ terminal_ready
+ and event in {"chat.usage_summary", "chat.final"}
+ ):
+ return False
+ if not terminal_ready:
+ return False
+ return _is_invoke_terminal_event(event, payload)
+
+
+def _is_processing_idle(payload: dict[str, Any]) -> bool:
+ """chat.processing_status 是否表示 Agent 已停止处理(与 web_enterprise 一致)。"""
+ if "is_processing" not in payload:
+ return False
+ return not bool(payload.get("is_processing"))
+
+
+def _should_complete_on_processing_idle(
+ *,
+ expect_file: bool = True,
+ accepted: bool,
+ saw_agent_output: bool,
+ hitl_paused: bool,
+ hitl_suppress_next_idle: bool,
+ hitl_await_agent_resume: bool,
+ saw_deliverable_file: bool,
+ saw_step_text: bool = False,
+ saw_post_deliverable_text: bool = False,
+ payload: dict[str, Any],
+) -> bool:
+ if not accepted or not saw_agent_output:
+ return False
+ if hitl_paused or hitl_suppress_next_idle:
+ return False
+ terminal_ready = _loadtest_terminal_ready(
+ expect_file=expect_file,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ )
+ if hitl_await_agent_resume and not terminal_ready:
+ return False
+ if not terminal_ready:
+ return False
+ return _is_processing_idle(payload)
+
+
+_RUNTIME_CAPACITY_ERROR_MARKERS = (
+ "资源已满",
+ "服务并发度超过上限",
+ "无足够并发",
+ "服务启动失败",
+ "100001",
+ "100002",
+)
+
+
+def _payload_text_blob(payload: dict[str, Any]) -> str:
+ """把 payload 关键为便于关键字扫描的文本。"""
+ parts: list[str] = []
+ for key in ("error", "message", "content", "detail", "reason", "code", "error_code"):
+ val = payload.get(key)
+ if val is not None and val != "":
+ parts.append(str(val))
+ try:
+ parts.append(json.dumps(payload, ensure_ascii=False))
+ except (TypeError, ValueError):
+ parts.append(str(payload))
+ return " ".join(parts)
+
+
+def _extract_runtime_failure(event: str | None, payload: dict[str, Any]) -> str | None:
+ """识别应立即失败的运行时错误(含资源打满 100001/100002)。
+
+ Gateway 在资源拒绝时经常只下发带 error 的 chunk / chat.error,或甚至只有
+ processing idle;脚本必须显式识别,不能干等到 --final-timeout。
+ """
+ if not isinstance(payload, dict):
+ return None
+
+ code = payload.get("code", payload.get("error_code"))
+ code_s = str(code).strip() if code is not None else ""
+ blob = _payload_text_blob(payload)
+ is_capacity = code_s in {"100001", "100002"} or any(
+ marker in blob for marker in _RUNTIME_CAPACITY_ERROR_MARKERS
+ )
+
+ if event == "chat.error" or payload.get("error") not in (None, ""):
+ err = payload.get("error") or payload.get("message") or blob
+ prefix = "capacity_error" if is_capacity else "runtime_error"
+ return f"{prefix}: {err}"
+
+ if is_capacity:
+ return f"capacity_error: {blob}"
+
+ return None
+
+
+def _should_fail_on_premature_idle(
+ *,
+ expect_file: bool = True,
+ expect_delayed_text: bool = False,
+ accepted: bool,
+ hitl_paused: bool,
+ hitl_suppress_next_idle: bool,
+ hitl_await_agent_resume: bool,
+ saw_deliverable_file: bool,
+ saw_step_text: bool = False,
+ saw_post_deliverable_text: bool = False,
+ payload: dict[str, Any],
+) -> bool:
+ """processing idle 已到,但交付未完成 → 视为失败(避免资源拒绝后挂死)。
+
+ - HITL 等待用户作答(paused 且尚未放行)时仍可能出现 idle,不能当失败。
+ - 紧随 auto-allow 的假 idle 由 suppress 分支吞掉,不进入本判断。
+ - 放行后仍 await resume、却一直未交付就收到 idle:Agent 流已死,应失败。
+ - cron 创建完成后须再等约 1 分钟投递,创建子流的 idle 不算失败。
+ """
+ if expect_delayed_text:
+ return False
+ if not accepted or hitl_suppress_next_idle:
+ return False
+ if hitl_paused and not hitl_await_agent_resume:
+ return False
+ if _loadtest_terminal_ready(
+ expect_file=expect_file,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ ):
+ return False
+ return _is_processing_idle(payload)
+
+
+_AGENT_ACTIVITY_EVENTS = frozenset({
+ "chat.delta",
+ "chat.tool_call",
+ "chat.tool_result",
+ "chat.tool_calls.delta",
+ "chat.tool_update",
+ "todo.updated",
+ "chat.file",
+ "chat.final",
+})
+
+# 权限放行后:chat.delta / chat.file 表示 Agent 已恢复;tool_result 表示工具环继续推进。
+_HITL_RESUME_CLEAR_EVENTS = frozenset({
+ "chat.delta",
+ "chat.file",
+ "chat.tool_result",
+})
+
+
+def _log_ws_event(
+ *,
+ index: int,
+ session_id: str,
+ frame: dict[str, Any],
+ resolved_event: str | None,
+ payload: dict[str, Any],
+) -> None:
+ """打印 WS event 帧,便于对照 frame.event 与 payload.event_type。"""
+ frame_event = frame.get("event")
+ nested_event_type = payload.get("event_type") if isinstance(payload, dict) else None
+ nested_event = payload.get("event") if isinstance(payload, dict) else None
+ request_id = frame.get("request_id")
+ source = payload.get("source") if isinstance(payload, dict) else None
+ parts = [
+ f"idx={index}",
+ f"session_id={session_id}",
+ f"resolved={resolved_event or '<none>'}",
+ f"frame.event={frame_event!r}",
+ ]
+ if nested_event_type is not None:
+ parts.append(f"payload.event_type={nested_event_type!r}")
+ if nested_event is not None and nested_event != nested_event_type:
+ parts.append(f"payload.event={nested_event!r}")
+ if request_id:
+ parts.append(f"request_id={request_id}")
+ if source:
+ parts.append(f"source={source!r}")
+ logger.info("[ws-event] %s", " ".join(parts))
+
+
+def _pick_allow_option(options: list[Any]) -> str:
+ """从选项列表中选取「允许」类答案,优先「总是允许」。"""
+ labels: list[str] = []
+ for opt in options:
+ if isinstance(opt, dict):
+ labels.append(str(opt.get("label") or "").strip())
+ elif isinstance(opt, str):
+ labels.append(opt.strip())
+ prefer = (
+ "总是允许",
+ "Always allow",
+ "Allow always",
+ "本次允许",
+ "Allow once",
+ "Allow",
+ "允许",
+ "接收",
+ "Create",
+ "Yes",
+ "是",
+ "确认",
+ )
+ deny = frozenset({"拒绝", "Reject", "Deny", "否", "No"})
+ for token in prefer:
+ for lab in labels:
+ if lab == token or token in lab:
+ return lab
+ for lab in labels:
+ if lab and lab not in deny:
+ return lab
+ return labels[0] if labels else "总是允许"
+
+
+def _build_allow_answers(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """为 ask_user_question / 权限审批构造「全部允许」答案列表。"""
+ questions = payload.get("questions")
+ if not isinstance(questions, list) or not questions:
+ return [{"selected_options": ["总是允许"]}]
+ answers: list[dict[str, Any]] = []
+ for question in questions:
+ if not isinstance(question, dict):
+ answers.append({"selected_options": ["总是允许"]})
+ continue
+ options = question.get("options")
+ option_list = options if isinstance(options, list) else []
+ answers.append({"selected_options": [_pick_allow_option(option_list)]})
+ return answers
+
+
+async def _send_auto_allow(
+ ws: Any,
+ *,
+ index: int,
+ session_id: str,
+ payload: dict[str, Any],
+ bot_id: str,
+ group_id: str,
+ user_id: str,
+ mode: str,
+ answered_ids: set[str],
+) -> bool:
+ """响应 Agent 权限/追问:默认选「总是允许」类选项。"""
+ interrupt_request_id = str(payload.get("request_id") or "").strip()
+ if not interrupt_request_id or interrupt_request_id in answered_ids:
+ return False
+ answered_ids.add(interrupt_request_id)
+
+ source = str(payload.get("source") or "").strip()
+ answers = _build_allow_answers(payload)
+ first_choice = ""
+ if answers and isinstance(answers[0], dict):
+ opts = answers[0].get("selected_options")
+ if isinstance(opts, list) and opts:
+ first_choice = str(opts[0])
+
+ if source == "permission_interrupt":
+ method = "chat.send"
+ params: dict[str, Any] = {
+ "session_id": session_id,
+ "query": "",
+ "content": "",
+ "request_id": interrupt_request_id,
+ "answers": answers,
+ "mode": mode,
+ "group_id": group_id,
+ "bot_id": bot_id,
+ "user_id": user_id,
+ }
+ else:
+ method = "chat.user_answer"
+ params = {
+ "session_id": session_id,
+ "request_id": interrupt_request_id,
+ "answers": answers,
+ }
+ if source:
+ params["source"] = source
+
+ approve_req_id = f"req_allow_{index:02d}_{uuid.uuid4().hex[:8]}"
+ await ws.send(
+ json.dumps(
+ {"type": "req", "id": approve_req_id, "method": method, "params": params},
+ ensure_ascii=False,
+ )
+ )
+ logger.info(
+ "[auto-allow] idx=%d session_id=%s interrupt_request_id=%s method=%s choice=%r",
+ index,
+ session_id,
+ interrupt_request_id,
+ method,
+ first_choice or "总是允许",
+ )
+ return True
+
+
+async def run_single_request(
+ *,
+ ws_url: str,
+ ws_headers: dict[str, str],
+ index: int,
+ shard: int,
+ shard2: int,
+ group_id: str,
+ bot_id: str,
+ user_id: str,
+ content: str,
+ mode: str,
+ accept_timeout: float,
+ accept_only: bool,
+ final_timeout: float,
+ cron_delivery_timeout: float,
+ auto_allow: bool,
+ ws_event_log: bool,
+ progress: ProgressTracker,
+ registry: ActiveSessionRegistry,
+ steps: tuple[LoadTestStep, ...] | None = None,
+ download_dir: Path | None = None,
+ session_id: str | None = None,
+) -> RequestResult:
+ import websockets
+
+ run_download_dir = download_dir or _make_run_download_dir()
+ session_id = session_id or f"sess_load_{index:02d}_{uuid.uuid4().hex[:8]}"
+ run_steps: tuple[LoadTestStep, ...] = steps or (
+ LoadTestStep(name="single", content=content, expect_file=True),
+ )
+ if accept_only:
+ run_steps = run_steps[:1]
+ req_id = f"req_load_{index:02d}_{uuid.uuid4().hex[:8]}"
+ result = RequestResult(
+ index=index,
+ shard=shard,
+ shard2=shard2,
+ session_id=session_id,
+ req_id=req_id,
+ group_id=group_id,
+ bot_id=bot_id,
+ user_id=user_id,
+ ok=False,
+ accepted=False,
+ steps_total=len(run_steps),
+ )
+ logger.info(
+ "[send] idx=%d shard=%d shard2=%d session_id=%s steps=%d group_id=%s bot_id=%s user_id=%s",
+ index,
+ shard,
+ shard2,
+ session_id,
+ len(run_steps),
+ group_id,
+ bot_id,
+ user_id,
+ )
+ t0 = time.perf_counter()
+ deadline = t0 + (accept_timeout if accept_only else final_timeout)
+
+ async def _log_terminal(*, success: bool, event: str, detail: str = "") -> None:
+ done_n = await progress.mark_done()
+ level = logger.info if success else logger.error
+ level(
+ "[%s] %d/%d idx=%d shard=%d shard2=%d total_ms=%.0f session_id=%s req_id=%s "
+ "group_id=%s user_id=%s steps=%d/%d%s",
+ event,
+ done_n,
+ progress.total,
+ index,
+ shard,
+ shard2,
+ result.total_ms,
+ session_id,
+ req_id,
+ group_id,
+ user_id,
+ result.steps_completed,
+ result.steps_total,
+ f" {detail}" if detail else "",
+ )
+
+ try:
+ connect_url = _with_identity_query(
+ ws_url, group_id=group_id, bot_id=bot_id, user_id=user_id
+ )
+ connect_headers = _tenant_headers(
+ group_id=group_id,
+ bot_id=bot_id,
+ user_id=user_id,
+ extra=ws_headers,
+ )
+ async with websockets.connect(
+ connect_url,
+ open_timeout=15,
+ additional_headers=connect_headers,
+ ) as ws:
+ await registry.add(_ActiveSession(index=index, session_id=session_id, ws=ws))
+ try:
+ answered_interrupt_ids: set[str] = set()
+
+ for step_idx, step in enumerate(run_steps):
+ expect_file = step.expect_file
+ expect_delayed_text = step.expect_delayed_text
+ req_id = f"req_load_{index:02d}_s{step_idx}_{uuid.uuid4().hex[:8]}"
+ result.req_id = req_id
+
+ params: dict[str, Any] = {
+ "session_id": session_id,
+ "content": step.content,
+ "query": step.content,
+ "mode": mode,
+ "group_id": group_id,
+ "bot_id": bot_id,
+ "user_id": user_id,
+ }
+ if step.files:
+ params["files"] = [dict(item) for item in step.files]
+
+ req = {
+ "type": "req",
+ "id": req_id,
+ "method": "chat.send",
+ "params": params,
+ }
+ logger.info(
+ "[send-step] idx=%d step=%d/%d name=%s session_id=%s req_id=%s files=%d",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ session_id,
+ req_id,
+ len(step.files),
+ )
+
+ accepted = False
+ hitl_paused = False
+ hitl_suppress_next_idle = False
+ hitl_await_agent_resume = False
+ saw_agent_output = False
+ saw_deliverable_file = False
+ saw_post_deliverable_text = False
+ saw_step_text = False
+ step_text_buf = ""
+ step_done = False
+ logged_cron_creation = False
+ downloaded_paths: list[Path] = []
+
+ async def _maybe_download_deliverable(
+ payload: dict[str, Any],
+ *,
+ _paths: list[Path],
+ _step=step,
+ ) -> bool:
+ """file 扩写步:下载 chat.file 交付物。成功返回 True;无需下载也返回 True。"""
+ if not _step.download_deliverable or _paths:
+ return True
+ entries = _extract_downloadable_files(payload)
+ if not entries:
+ return True
+ try:
+ paths = await _download_deliverable_files(
+ ws_url=ws_url,
+ files=entries,
+ index=index,
+ download_dir=run_download_dir,
+ )
+ _paths.extend(paths)
+ return True
+ except Exception as download_err:
+ result.error = f"download_failed@{_step.name}: {download_err}"
+ result.failed_step = _step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="fail",
+ detail=f"error={result.error}",
+ )
+ return False
+
+ async def _complete_current_step(
+ *,
+ reason: str,
+ saw_deliverable_file: bool,
+ saw_step_text: bool,
+ saw_post_deliverable_text: bool,
+ _paths: list[Path],
+ _step=step,
+ _step_idx=step_idx,
+ _run_download_dir=run_download_dir,
+ ) -> bool:
+ """标记当前步完成;若需下载但未落盘则失败。返回是否成功完成。"""
+ nonlocal step_done
+ if _step.download_deliverable and not _paths:
+ result.error = (
+ f"download_missing@{_step.name}: 已交付但未下载到本地 "
+ f"(期望目录={_run_download_dir})"
+ )
+ result.failed_step = _step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="fail",
+ detail=f"error={result.error}",
+ )
+ return False
+ step_done = True
+ result.steps_completed += 1
+ logger.info(
+ "[step-done] idx=%d step=%d/%d name=%s reason=%s file=%s text=%s post=%s "
+ "downloaded=%d",
+ index,
+ _step_idx + 1,
+ len(run_steps),
+ _step.name,
+ reason,
+ saw_deliverable_file,
+ saw_step_text,
+ saw_post_deliverable_text,
+ len(_paths),
+ )
+ return True
+
+ await ws.send(json.dumps(req, ensure_ascii=False))
+
+ while time.perf_counter() < deadline and not step_done:
+ remaining = max(0.1, deadline - time.perf_counter())
+ try:
+ frame = await _recv_json(ws, remaining)
+ except asyncio.TimeoutError:
+ break
+
+ ftype = frame.get("type")
+
+ if ftype == "res" and frame.get("id") == req_id:
+ ok = bool(frame.get("ok"))
+ payload = frame.get("payload") or {}
+ result.ok = ok
+ if not ok:
+ err = frame.get("error") or payload.get("error") or frame
+ result.error = json.dumps(err, ensure_ascii=False)
+ result.failed_step = step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="fail",
+ detail=f"step={step.name} error={result.error}",
+ )
+ return result
+ accepted = bool(payload.get("accepted", True))
+ result.accepted = accepted
+ if result.accept_ms <= 0:
+ result.accept_ms = (time.perf_counter() - t0) * 1000
+ if accepted:
+ await registry.mark_accepted(session_id)
+ if not accepted:
+ result.error = "chat.send 未被接受"
+ result.failed_step = step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="reject",
+ detail=f"step={step.name}",
+ )
+ return result
+ logger.info(
+ "[accepted] idx=%d step=%d/%d name=%s accept_ms=%.0f session_id=%s req_id=%s",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ result.accept_ms,
+ session_id,
+ req_id,
+ )
+ if accept_only:
+ result.ok = True
+ result.final_received = False
+ result.steps_completed = 1
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(success=True, event="done", detail=f"step={step.name}")
+ return result
+ continue
+
+ if ftype != "event":
+ continue
+
+ event, payload = _normalize_event_frame(frame)
+ event_sid = _event_session_id(frame, payload)
+ # WebChannel 向所有连接广播;并发压测必须忽略其他 session 的事件。
+ if event_sid and event_sid != session_id:
+ if ws_event_log:
+ logger.info(
+ "[ws-event] idx=%d session_id=%s skip foreign session_id=%s event=%s",
+ index,
+ session_id,
+ event_sid,
+ event,
+ )
+ continue
+ if ws_event_log:
+ _log_ws_event(
+ index=index,
+ session_id=session_id,
+ frame=frame,
+ resolved_event=event,
+ payload=payload,
+ )
+ failure = _extract_runtime_failure(event, payload)
+ if failure:
+ result.error = failure
+ result.failed_step = step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="fail",
+ detail=f"step={step.name} error={result.error}",
+ )
+ return result
+ if auto_allow and event == "chat.ask_user_question":
+ allowed = await _send_auto_allow(
+ ws,
+ index=index,
+ session_id=session_id,
+ payload=payload,
+ bot_id=bot_id,
+ group_id=group_id,
+ user_id=user_id,
+ mode=mode,
+ answered_ids=answered_interrupt_ids,
+ )
+ if allowed:
+ hitl_suppress_next_idle = True
+ hitl_await_agent_resume = True
+ hitl_paused = False
+ continue
+ if event == "chat.ask_user_question":
+ hitl_paused = True
+ continue
+ if event == "chat.invocation_paused":
+ hitl_paused = True
+ hitl_suppress_next_idle = True
+ hitl_await_agent_resume = True
+ continue
+ if event in _AGENT_ACTIVITY_EVENTS:
+ saw_agent_output = True
+ hitl_suppress_next_idle = False
+ if event in _HITL_RESUME_CLEAR_EVENTS:
+ hitl_await_agent_resume = False
+ if event == "chat.file":
+ hitl_paused = False
+ hitl_await_agent_resume = False
+ saw_deliverable_file = True
+ if not await _maybe_download_deliverable(
+ payload, _paths=downloaded_paths
+ ):
+ return result
+ elif event == "chat.tool_result" and _is_send_file_tool_success(payload):
+ hitl_paused = False
+ hitl_await_agent_resume = False
+ saw_deliverable_file = True
+ if not await _maybe_download_deliverable(
+ payload, _paths=downloaded_paths
+ ):
+ return result
+ elif event == "chat.delta":
+ content = _final_content(payload)
+ if expect_delayed_text and content:
+ step_text_buf += content
+ if expect_file and saw_deliverable_file:
+ saw_post_deliverable_text = True
+ elif _matches_cron_delivery(
+ expect_delayed_text=expect_delayed_text,
+ content=content,
+ logged_cron_creation=logged_cron_creation,
+ step_text_buf=step_text_buf,
+ ):
+ saw_step_text = True
+ logger.info(
+ "[cron-delivery] idx=%d step=%d/%d name=%s session_id=%s",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ session_id,
+ )
+ if not await _complete_current_step(
+ reason="cron_delivery",
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ _paths=downloaded_paths,
+ ):
+ return result
+ break
+ elif _matches_cron_creation(
+ expect_delayed_text=expect_delayed_text,
+ logged_cron_creation=logged_cron_creation,
+ content=content,
+ step_text_buf=step_text_buf,
+ ):
+ logged_cron_creation = True
+ step_text_buf = ""
+ if cron_delivery_timeout > 0:
+ deadline = min(
+ deadline,
+ time.perf_counter() + cron_delivery_timeout,
+ )
+ logger.info(
+ "[cron-wait] idx=%d step=%d/%d name=%s session_id=%s "
+ "creation confirmed, waiting for delivery "
+ "(timeout=%.0fs)...",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ session_id,
+ cron_delivery_timeout if cron_delivery_timeout > 0 else final_timeout,
+ )
+ elif _content_marks_step_done(
+ expect_file=expect_file,
+ expect_delayed_text=expect_delayed_text,
+ content=content,
+ ):
+ saw_step_text = True
+ elif (
+ event == "chat.final"
+ and not _is_intra_turn_chat_final(event, payload)
+ ):
+ content = _final_content(payload)
+ if expect_delayed_text and content:
+ step_text_buf += content
+ if expect_file and saw_deliverable_file:
+ saw_post_deliverable_text = True
+ elif _matches_cron_delivery(
+ expect_delayed_text=expect_delayed_text,
+ content=content,
+ logged_cron_creation=logged_cron_creation,
+ step_text_buf=step_text_buf,
+ ):
+ saw_step_text = True
+ logger.info(
+ "[cron-delivery] idx=%d step=%d/%d name=%s session_id=%s",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ session_id,
+ )
+ if not await _complete_current_step(
+ reason="cron_delivery",
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ _paths=downloaded_paths,
+ ):
+ return result
+ break
+ elif _matches_cron_creation(
+ expect_delayed_text=expect_delayed_text,
+ logged_cron_creation=logged_cron_creation,
+ content=content,
+ step_text_buf=step_text_buf,
+ ):
+ logged_cron_creation = True
+ step_text_buf = ""
+ if cron_delivery_timeout > 0:
+ deadline = min(
+ deadline,
+ time.perf_counter() + cron_delivery_timeout,
+ )
+ logger.info(
+ "[cron-wait] idx=%d step=%d/%d name=%s session_id=%s "
+ "creation confirmed, waiting for delivery "
+ "(timeout=%.0fs)...",
+ index,
+ step_idx + 1,
+ len(run_steps),
+ step.name,
+ session_id,
+ cron_delivery_timeout if cron_delivery_timeout > 0 else final_timeout,
+ )
+ elif _content_marks_step_done(
+ expect_file=expect_file,
+ expect_delayed_text=expect_delayed_text,
+ content=content,
+ ):
+ saw_step_text = True
+ if event == "chat.processing_status":
+ if payload.get("is_processing") is True:
+ hitl_paused = False
+ hitl_suppress_next_idle = False
+ hitl_await_agent_resume = False
+ elif _is_processing_idle(payload):
+ if hitl_suppress_next_idle:
+ hitl_suppress_next_idle = False
+ hitl_paused = False
+ continue
+ if _should_complete_on_processing_idle(
+ expect_file=expect_file,
+ accepted=accepted,
+ saw_agent_output=saw_agent_output,
+ hitl_paused=hitl_paused,
+ hitl_suppress_next_idle=False,
+ hitl_await_agent_resume=hitl_await_agent_resume,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ payload=payload,
+ ):
+ if not await _complete_current_step(
+ reason="processing_status_idle",
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ _paths=downloaded_paths,
+ ):
+ return result
+ break
+ if _should_fail_on_premature_idle(
+ expect_file=expect_file,
+ expect_delayed_text=expect_delayed_text,
+ accepted=accepted,
+ hitl_paused=hitl_paused,
+ hitl_suppress_next_idle=False,
+ hitl_await_agent_resume=hitl_await_agent_resume,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ payload=payload,
+ ):
+ result.error = (
+ f"premature_idle@{step.name}: Agent 已 is_processing=false,但未完成交付 "
+ f"(file={saw_deliverable_file} text={saw_step_text} "
+ f"post={saw_post_deliverable_text} "
+ f"agent_output={saw_agent_output} "
+ f"hitl_await={hitl_await_agent_resume} hitl_paused={hitl_paused});"
+ "常见于资源已满(100001)/无法预留 session(100002) 后流提前结束"
+ )
+ result.failed_step = step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=False,
+ event="fail",
+ detail=f"error={result.error}",
+ )
+ return result
+ continue
+ if _is_intra_turn_chat_final(event, payload):
+ if ws_event_log:
+ logger.info(
+ "[ws-event] idx=%d session_id=%s skip intra-turn chat.final "
+ "(empty content; waiting for terminal usage_summary / chat.final / idle)",
+ index,
+ session_id,
+ )
+ continue
+ if _should_complete_invoke(
+ expect_file=expect_file,
+ accepted=accepted,
+ saw_agent_output=saw_agent_output,
+ hitl_paused=hitl_paused,
+ hitl_await_agent_resume=hitl_await_agent_resume,
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ event=event,
+ payload=payload,
+ ):
+ if not await _complete_current_step(
+ reason=str(event),
+ saw_deliverable_file=saw_deliverable_file,
+ saw_step_text=saw_step_text,
+ saw_post_deliverable_text=saw_post_deliverable_text,
+ _paths=downloaded_paths,
+ ):
+ return result
+ break
+
+ if not step_done:
+ if not accepted:
+ result.error = f"超时@{step.name}:未收到 chat.send 确认"
+ elif (
+ expect_delayed_text
+ and logged_cron_creation
+ and not saw_step_text
+ ):
+ result.error = (
+ f"cron_delivery_timeout@{step.name}: 已创建但未收到投递"
+ )
+ else:
+ result.error = (
+ f"超时@{step.name}:已接受但未收到步骤完成信号 "
+ f"(expect_file={expect_file} expect_delayed_text={expect_delayed_text} "
+ f"file={saw_deliverable_file} "
+ f"text={saw_step_text} post={saw_post_deliverable_text} "
+ f"hitl_await={hitl_await_agent_resume} hitl_paused={hitl_paused})"
+ )
+ result.failed_step = step.name
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(success=False, event="timeout", detail=result.error)
+ return result
+
+ result.final_received = True
+ result.ok = True
+ result.accepted = True
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(
+ success=True,
+ event="done",
+ detail=f"all_steps={result.steps_completed}/{result.steps_total}",
+ )
+ return result
+ except asyncio.CancelledError:
+ if result.accepted and not result.final_received:
+ await _send_chat_interrupt_cancel(
+ ws,
+ session_id=session_id,
+ index=index,
+ registry=registry,
+ )
+ raise
+ finally:
+ await registry.mark_finished(session_id)
+ await registry.remove(session_id)
+ except Exception as err:
+ result.error = str(err)
+ result.total_ms = (time.perf_counter() - t0) * 1000
+ await _log_terminal(success=False, event="fail", detail=f"exception={result.error}")
+ return result
+
+
+async def _run_loadtest(args: argparse.Namespace) -> int:
+ ws_url = _resolve_ws_url(args)
+ ws_headers = _browser_origin_header(ws_url)
+ route_plan = _build_route_plan(
+ args.concurrency,
+ args.shards,
+ args.shards2,
+ args.group_prefix,
+ args.user_id_prefix,
+ bot_id=args.bot_id,
+ service_shard_key=args.service_shard_key,
+ )
+
+ loadtest_steps: tuple[LoadTestStep, ...] | None = None
+ if args.flow == "loadtest":
+ loadtest_steps = build_default_loadtest_steps(args.essay_file)
+ run_download_dir = _make_run_download_dir()
+ need_download = bool(
+ loadtest_steps and any(step.download_deliverable for step in loadtest_steps)
+ )
+
+ logger.info(
+ "[plan] ws=%s concurrency=%d shards=%d shards2=%d service_shard_key=%s flow=%s",
+ ws_url,
+ args.concurrency,
+ args.shards,
+ args.shards2,
+ args.service_shard_key,
+ args.flow,
+ )
+ if loadtest_steps:
+ logger.info(
+ "[plan] loadtest steps=%s essay_file=%s",
+ " -> ".join(step.name for step in loadtest_steps),
+ args.essay_file,
+ )
+ else:
+ logger.info("[plan] content=%r", args.content)
+ if need_download:
+ logger.info("[plan] download_dir=%s", run_download_dir)
+ logger.info(
+ "[plan] accept_only=%s auto_allow=%s ws_event_log=%s accept_timeout=%ss "
+ "final_timeout=%ss cron_delivery_timeout=%ss",
+ args.accept_only,
+ args.auto_allow,
+ args.ws_event_log,
+ args.accept_timeout,
+ args.final_timeout,
+ args.cron_delivery_timeout,
+ )
+ for shard in range(args.shards):
+ indices = [i for i, plan in enumerate(route_plan) if plan.shard == shard]
+ if not indices:
+ continue
+ group_id = route_plan[indices[0]].group_id
+ bot_id = route_plan[indices[0]].bot_id
+ logger.info(
+ "[plan] shard=%d group_id=%s bot_id=%s requests=%d (idx %d..%d)",
+ shard,
+ group_id,
+ bot_id,
+ len(indices),
+ indices[0],
+ indices[-1],
+ )
+ if args.shards2 > 0:
+ for shard2 in range(args.shards2):
+ sub = [i for i in indices if route_plan[i].shard2 == shard2]
+ if not sub:
+ continue
+ logger.info(
+ "[plan] shard=%d shard2=%d user_id=%s requests=%d (idx %d..%d)",
+ shard,
+ shard2,
+ route_plan[sub[0]].user_id,
+ len(sub),
+ sub[0],
+ sub[-1],
+ )
+
+ progress = ProgressTracker(total=args.concurrency)
+ registry = ActiveSessionRegistry()
+ t0 = time.perf_counter()
+ task_objs = [
+ asyncio.create_task(
+ run_single_request(
+ ws_url=ws_url,
+ ws_headers=ws_headers,
+ index=idx,
+ shard=plan.shard,
+ shard2=plan.shard2,
+ group_id=plan.group_id,
+ bot_id=plan.bot_id,
+ user_id=plan.user_id,
+ content=args.content,
+ mode=args.mode,
+ accept_timeout=args.accept_timeout,
+ accept_only=args.accept_only,
+ final_timeout=args.final_timeout,
+ cron_delivery_timeout=args.cron_delivery_timeout,
+ auto_allow=args.auto_allow,
+ ws_event_log=args.ws_event_log,
+ progress=progress,
+ registry=registry,
+ steps=loadtest_steps,
+ download_dir=run_download_dir if need_download else None,
+ )
+ )
+ for idx, plan in enumerate(route_plan)
+ ]
+ try:
+ raw_results = await asyncio.gather(*task_objs, return_exceptions=True)
+ except asyncio.CancelledError:
+ logger.info("[shutdown] 收到中断信号,正在 cancel 进行中的会话(chat.interrupt)...")
+ cancelled = await registry.cancel_all()
+ logger.info("[shutdown] 已向 %d 路会话发送 cancel", cancelled)
+ for task in task_objs:
+ task.cancel()
+ await asyncio.gather(*task_objs, return_exceptions=True)
+ raise
+ elapsed = time.perf_counter() - t0
+
+ results: list[RequestResult] = []
+ for idx, item in enumerate(raw_results):
+ if isinstance(item, Exception):
+ plan = route_plan[idx]
+ fail_result = RequestResult(
+ index=idx,
+ shard=plan.shard,
+ shard2=plan.shard2,
+ session_id="",
+ req_id="",
+ group_id=plan.group_id,
+ bot_id=plan.bot_id,
+ user_id=plan.user_id,
+ ok=False,
+ accepted=False,
+ error=str(item),
+ )
+ done_n = await progress.mark_done()
+ logger.error(
+ "[fail] %d/%d idx=%d shard=%d shard2=%d session_id= req_id= group_id=%s user_id=%s "
+ "exception=%s",
+ done_n,
+ progress.total,
+ idx,
+ plan.shard,
+ plan.shard2,
+ plan.group_id,
+ fail_result.user_id,
+ fail_result.error,
+ )
+ results.append(fail_result)
+ else:
+ results.append(item)
+
+ def _is_success(r: RequestResult) -> bool:
+ if args.accept_only:
+ return r.accepted and r.ok
+ return r.final_received and r.ok
+
+ completed = sum(1 for r in results if _is_success(r))
+ failed = args.concurrency - completed
+ stats = LoadTestStats(
+ total=args.concurrency,
+ completed=completed,
+ failed=failed,
+ elapsed_s=elapsed,
+ accept_ms=[r.accept_ms for r in results if r.accept_ms > 0],
+ total_ms=[r.total_ms for r in results if r.total_ms > 0],
+ )
+
+ logger.info("\n[requests] 各请求路由参数汇总(按 idx 排序):")
+ for r in sorted(results, key=lambda x: x.index):
+ status = "ok" if _is_success(r) else "fail"
+ logger.info(
+ "[requests] idx=%02d shard=%d shard2=%d status=%s final=%s steps=%d/%d failed_step=%s "
+ "total_ms=%.0f accept_ms=%.0f session_id=%s req_id=%s group_id=%s bot_id=%s user_id=%s",
+ r.index,
+ r.shard,
+ r.shard2,
+ status,
+ r.final_received,
+ r.steps_completed,
+ r.steps_total,
+ r.failed_step or "-",
+ r.total_ms,
+ r.accept_ms,
+ r.session_id,
+ r.req_id,
+ r.group_id,
+ r.bot_id,
+ r.user_id,
+ )
+
+ shard_counts: dict[int, list[RequestResult]] = {s: [] for s in range(args.shards)}
+ for r in results:
+ shard_counts[r.shard].append(r)
+ for shard in range(args.shards):
+ shard_ok = sum(1 for r in shard_counts[shard] if _is_success(r))
+ logger.info("[shard] shard=%d completed=%d/%d", shard, shard_ok, len(shard_counts[shard]))
+
+ if args.shards2 > 0:
+ agent_buckets: dict[tuple[int, int], list[RequestResult]] = {}
+ for r in results:
+ agent_buckets.setdefault((r.shard, r.shard2), []).append(r)
+ for (shard, shard2), bucket in sorted(agent_buckets.items()):
+ ok_n = sum(1 for r in bucket if _is_success(r))
+ logger.info(
+ "[shard2] shard=%d shard2=%d user_id=%s completed=%d/%d",
+ shard,
+ shard2,
+ bucket[0].user_id if bucket else "",
+ ok_n,
+ len(bucket),
+ )
+
+ logger.info("\n[result] %s", stats.summary())
+
+ return 0 if failed == 0 else 1
+
+
+def _parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser(
+ description="Gateway Runtime 并发 chat.send 压测(经 WebChannel /ws 验证 AgentServer 池)",
+ )
+ p.add_argument("--host", default="127.0.0.1", help="Gateway 主机,默认 127.0.0.1")
+ p.add_argument("--ws-path", default="/ws", help="WebSocket 路径,默认 /ws")
+ p.add_argument(
+ "--flow",
+ choices=("loadtest", "single"),
+ default="loadtest",
+ help=(
+ "loadtest(默认):每路会话依次发送 travel/skill/file/cron 四条消息,"
+ "与 mock_llm_server --profile loadtest 对齐;single:仅发送一条 --content"
+ ),
+ )
+ p.add_argument(
+ "--content",
+ default=_DEFAULT_CONTENT,
+ help="--flow single 时的用户消息正文(同时写入 content 与 query)",
+ )
+ p.add_argument(
+ "--essay-file",
+ type=Path,
+ default=_DEFAULT_SPRING_ESSAY,
+ help="loadtest 第 3 步上传的作文附件路径,默认 scripts/童趣的春天.md",
+ )
+ p.add_argument(
+ "--bot-id",
+ default=_DEFAULT_BOT_ID,
+ help=(
+ "企业策略 bot_id 基名;service-shard-key=bot_id 时为 {bot_id}_s{shard}"
+ ),
+ )
+ p.add_argument("--user-id-prefix", default="loadtest_user", help="user_id 前缀,实际为 {prefix}_{idx:02d}")
+ p.add_argument("--mode", default="agent.plan", help="运行模式,如 agent.plan")
+ p.add_argument(
+ "--concurrency",
+ "--total",
+ dest="concurrency",
+ type=int,
+ default=30,
+ metavar="N",
+ help="总并发请求数,默认 30(按 shards / shards2 轮询分发,不要求整除)",
+ )
+ p.add_argument(
+ "--shards",
+ "--agent-shards",
+ dest="shards",
+ type=int,
+ default=3,
+ metavar="K",
+ help="轮询分布到的 AgentServer 数量,默认 3",
+ )
+ p.add_argument(
+ "--shards2",
+ "--agent-instance-shards",
+ dest="shards2",
+ type=int,
+ default=0,
+ metavar="M",
+ help=(
+ "同一 AgentServer 内按 user_id 轮询分布到的 Agent 实例数,默认 0(每路独立 "
+ "{user_id_prefix}_{idx:02d});M>=1 时 user_id 为 {user_id_prefix}_s{shard}_a{j},"
+ "同桶多路共用;M=1 时同一 AgentServer 内全部打到同一 Agent 实例;"
+ "不要求整除,余数由序号靠前的实例多承接"
+ ),
+ )
+ p.add_argument(
+ "--group-prefix",
+ default="loadtest",
+ help="group_id 前缀;service-shard-key=group_id 时为 {prefix}_s{shard},=bot_id 时固定为 {prefix}",
+ )
+ p.add_argument(
+ "--service-shard-key",
+ choices=sorted(_SERVICE_SHARD_KEYS),
+ default="group_id",
+ help=(
+ "默认 service_id 路由分片维度:group_id(每 shard 不同 group_id,bot_id 固定,默认)或 "
+ "bot_id(group_id 固定,每 shard 不同 bot_id,用于 AGENT_BOT_ID_GROUP_NUM 联调)"
+ ),
+ )
+ p.add_argument(
+ "--accept-timeout",
+ type=float,
+ default=60.0,
+ help="等待 chat.send 被接受的最长时间(秒),默认 60",
+ )
+ p.add_argument(
+ "--accept-only",
+ action="store_true",
+ help="仅等待 chat.send 被接受,不等待任务完成(默认会等到 usage_summary / final / processing idle)",
+ )
+ p.add_argument(
+ "--no-auto-allow",
+ action="store_true",
+ help="禁用自动响应 Agent 权限/追问(默认自动选「总是允许」)",
+ )
+ p.add_argument(
+ "--ws-event-log",
+ action="store_true",
+ help="打印每路 WS event 名(frame.event / payload.event_type),排查权限事件是否到达",
+ )
+ p.add_argument(
+ "--final-timeout",
+ type=float,
+ default=7200.0,
+ help="等待任务完成的最长时间(秒),默认 7200",
+ )
+ p.add_argument(
+ "--cron-delivery-timeout",
+ type=float,
+ default=120.0,
+ help="cron 步创建确认后等待到点投递的最长时间(秒),默认 120",
+ )
+ src = p.add_mutually_exclusive_group(required=True)
+ src.add_argument("--web-port", type=int, help="Gateway WebChannel 端口")
+ src.add_argument("--provision-json", type=Path, help="provision-local 响应 JSON(读取 data.ports.web)")
+ src.add_argument("--ws-url", help="完整 WebSocket URL,如 ws://host:19001/ws")
+ args = p.parse_args()
+ args.auto_allow = not args.no_auto_allow
+ return args
+
+
+def main() -> int:
+ _configure_cli_logging()
+ try:
+ import websockets # noqa: F401
+ except ImportError:
+ logger.error(
+ "缺少 websockets,请在 jiuwenclaw 仓库根目录执行: uv sync 或 pip install websockets"
+ )
+ return 1
+
+ args = _parse_args()
+ try:
+ return asyncio.run(_run_loadtest(args))
+ except KeyboardInterrupt:
+ return 130
+ except ValueError as err:
+ logger.error("[invalid-args] %s", err)
+ return 2
+ except OSError as connect_err:
+ logger.error("[connect-failed] %s", connect_err)
+ logger.error(
+ "请确认 Gateway 已启动,且 --web-port / --provision-json / --ws-url 指向可访问的 WebChannel。"
+ )
+ return 1
+ except Exception as err:
+ logger.error("[failed] %s", err)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/jiuwenclaw-ee/claw_manager/scripts/mock_llm_server.py b/packages/jiuwenclaw-ee/claw_manager/scripts/mock_llm_server.py
new file mode 100644
index 0000000000..66653730a5
--- /dev/null
+++ b/packages/jiuwenclaw-ee/claw_manager/scripts/mock_llm_server.py
@@ -0,0 +1,3182 @@
+#!/usr/bin/env python3
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""OpenAI 兼容 Mock LLM HTTP 服务,供 Enterprise Runtime 压测与 E2E 联调使用。
+
+实现 ``POST /v1/chat/completions``(流式 SSE / 非流式 JSON)、``GET /health``、``GET /v1/models``,
+并提供压测场景常用选项(``--host``、请求统计、毫秒时间戳日志)。
+
+``--profile loadtest`` 时按用户输入关键词自动路由多场景 Mock 流程:
+
+- **travel**(默认):小说《旅行的意义》多工具 Agent 流程
+- **scheduled_task**:用户消息含「定时任务」等关键词
+- **cron_delivery**:定时任务到点触发,返回一句喝水提醒
+- **skill**:用户消息含「skill」「技能」等关键词
+- **file**:用户消息含「文件」关键词
+
+典型用法(项目根目录)::
+
+ # E2E / --flow single:固定 mock token(数量、间隔可配)
+ uv run python packages/jiuwenclaw-ee/claw_manager/scripts/mock_llm_server.py \\
+ --port 19999 --profile e2e --stream-token-count 5 --stream-token-interval 0.05
+ # 等价:MOCK_LLM_STREAM_TOKEN_COUNT=5 MOCK_LLM_STREAM_TOKEN_INTERVAL=0.05 \\
+ # python .../mock_llm_server.py --port 19999 --profile e2e
+
+ # 压测:模拟真实 Agent 多工具流程(todo / 长文 / write_file / read_file / send_file)
+ uv run python packages/jiuwenclaw-ee/claw_manager/scripts/mock_llm_server.py \\
+ --host 0.0.0.0 --port 19999 --profile loadtest --novel-chars 32000
+
+AgentServer / Gateway 侧模型配置示例(经 Runtime ``_agent_env_vars`` 或 model_template)::
+
+ API_BASE=http://127.0.0.1:19999/v1
+ API_KEY=mock-key
+ MODEL_PROVIDER=OpenAI
+ MODEL_NAME=mock-model
+ LLM_SSL_VERIFY=false
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import json
+import logging
+import os
+import re
+import secrets
+import signal
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_STREAM_TOKEN_COUNT = 20
+DEFAULT_STREAM_TOKEN_INTERVAL_S = 2.0
+LOADTEST_STREAM_TOKEN_COUNT = 5
+LOADTEST_STREAM_TOKEN_INTERVAL_S = 0.05
+LOADTEST_NOVEL_CHARS = 32_000
+LOADTEST_STREAM_CHUNK_CHARS = 256
+LOADTEST_CHAT_EXCERPT_CHARS = 6_000
+LOADTEST_WRITE_MAX_CHARS = 32_000
+
+_LOADTEST_NOVEL_MARKERS = ("旅行的意义", "人生的意义", "十万字", "txt")
+# 单独「小说」太宽,会误匹配 Agent 回写的 intro 文案;用下方 echo 检测兜底
+_TRAVEL_ASSISTANT_ECHO_MARKERS = (
+ "我看到你希望我专注于",
+ "让我重新规划,专注于创作",
+ "而不是立即尝试完成整部",
+)
+_TRAVEL_COMPLETION_ECHO_MARKERS = (
+ "完成!我已经为你创作了小说",
+ "开篇章节约6000字",
+ "如需继续创作后续章节",
+)
+_SKILL_ECHO_MARKERS = (
+ "全部完成!✅",
+ "任务完成总结",
+ "北京3日游攻略已生成",
+ "有什么需要调整或补充的,随时告诉我",
+)
+_FILE_ECHO_MARKERS = (
+ "已经把扩写好的作文发给你了",
+ "纯汉字约 5400 字",
+ "字数核对:纯汉字",
+)
+_CRON_ECHO_MARKERS = (
+ "喝水提醒已创建",
+ "到点后会通过 web 频道向你推送提醒",
+ "执行完成后自动删除",
+)
+# skill 场景除关键字外,常见用户表述
+_SKILL_INTENT_EXTRA = ("skillnet", "openclaw.tours", "旅游攻略技能", "北京3日游", "旅游攻略")
+_NOVEL_FILENAME = "旅行的意义_开篇完整版.txt"
+
+
+# ---------------------------------------------------------------------------
+# 多场景路由:根据用户输入关键词选择 Mock 对话流程(loadtest profile)
+# ---------------------------------------------------------------------------
+class MockScenario:
+ """Mock LLM 联调场景标识。"""
+
+ TRAVEL = "travel"
+ SCHEDULED_TASK = "scheduled_task"
+ CRON_DELIVERY = "cron_delivery"
+ SKILL = "skill"
+ FILE = "file"
+
+
+# loadtest 联调脚本的固定场景顺序(travel 完成后用户发 skill 时,Agent 可能尚未把新消息注入 LLM)
+_LOADTEST_SCENARIO_SEQUENCE = (
+ MockScenario.TRAVEL,
+ MockScenario.SKILL,
+ MockScenario.FILE,
+ MockScenario.SCHEDULED_TASK,
+)
+
+
+# 优先级:cron_delivery > scheduled_task > skill > file > travel(默认)
+_SCHEDULED_TASK_KEYWORDS = ("定时任务", "定时提醒")
+_SKILL_KEYWORDS = ("skill", "技能")
+# 不要用单独的「文件」——用户包装 prompt / 系统提示里几乎总会出现,会把小说场景串到扩写
+_FILE_KEYWORDS = ("童趣的春天", "扩写", "作文")
+
+# ---------------------------------------------------------------------------
+# 定时任务场景常量
+# ---------------------------------------------------------------------------
+_CRON_INTRO = ""
+_CRON_JOB_ARGS = {
+ "name": "喝水提醒",
+ "delay_seconds": 60,
+ "delete_after_run": True,
+ "timezone": "Asia/Shanghai",
+ "description": "🥤 喝水时间到啦!记得喝杯水,保持水分摄入~",
+ "targets": "web",
+ "enabled": True,
+}
+_CRON_DONE_MESSAGE = (
+ "✅ 喝水提醒已创建!\n\n"
+ "⏰ 执行时间:1 分钟后\n\n"
+ "📝 提醒内容:🥤 喝水时间到啦!记得喝杯水,保持水分摄入~\n\n"
+ "📡 投递频道:web\n\n"
+ "🔔 一次性任务,到点后会通过 web 频道向你推送提醒,执行完成后自动删除\n\n"
+ "如果之后想取消,跟我说一声就行~"
+)
+_CRON_WAKE_MARKERS = ("喝水时间到啦",)
+_CRON_DELIVERY_MESSAGE = "🥤 喝水时间到啦!记得喝杯水,保持水分摄入~"
+_CRON_CONTEXT_PATH_RE = re.compile(r"/context/cron_[a-z0-9_]+_context")
+# ---------------------------------------------------------------------------
+# 技能加载场景常量(openclaw-tour-planner / 北京3日游)
+# ---------------------------------------------------------------------------
+_SKILL_GITHUB_URL = "https://github.com/Asif2BD/openclaw.tours/tree/main"
+_SKILL_NAME = "openclaw-tour-planner"
+_SKILL_INSTALL_ARGS_SHORT = {
+ "identifier": "Asif2BD/openclaw.tours",
+ "source": "skillnet",
+}
+_SKILL_INSTALL_ARGS_FULL = {
+ "identifier": _SKILL_GITHUB_URL,
+ "source": "skillnet",
+}
+_SKILL_STEP_TASKS = [
+ "地理编码 — 通过 Nominatim API 获取北京坐标信息",
+ "天气预报 — 获取北京未来3天天气",
+ "旅游指南 — 收集 Wikivoyage 旅行指南",
+ "行程规划 — 构建北京3日游逐日行程",
+ "生成攻略文档 — 输出完整 Markdown 攻略",
+]
+# 运行时 todo_create 仍接受「分号分隔字符串」(旧格式);对象数组会导致创建结果为空。
+# 场景切换后 session 内仍有 travel 等待办,skill 需 force=true 才能覆盖创建新任务列表。
+_SKILL_TODO_TASKS = (
+ "安装旅游规划技能;"
+ "收集北京旅游信息;"
+ "生成北京3日游攻略;"
+ "交付攻略文档"
+)
+_SKILL_TODO_CONTENTS = (
+ "安装旅游规划技能",
+ "收集北京旅游信息",
+ "生成北京3日游攻略",
+ "交付攻略文档",
+)
+_SKILL_INTRO = (
+ "我来帮你完成这个任务。首先,我需要通过 skillnet 安装这个旅游攻略技能,"
+ "然后为你制作北京3日游攻略。\n\n让我先尝试安装这个技能:\n"
+)
+_SKILL_INSTALL_RETRY_INTRO = "让我用完整的 GitHub URL 再试一次:\n"
+_SKILL_AFTER_LOAD_INTRO = (
+ "SKILL.md 已加载完毕!这是一个旅游规划技能,使用免费 API"
+ "(Nominatim 地理编码、天气预报、Wikivoyage 旅行指南)来生成行程。\n\n"
+ "现在我先创建 skill_step 路线图,然后开始为你制作北京3日游攻略。\n"
+)
+_SKILL_AFTER_PLAN_INTRO = (
+ "现在开始执行!我将并行获取北京的地理坐标、天气预报和旅游指南信息。\n\n"
+ "[当前步骤: 地理编码 — 通过 Nominatim API 获取北京坐标信息]\n"
+)
+_SKILL_AFTER_SEARCH_INTRO = (
+ "我已经收集到了足够的北京旅游信息。现在让我标记前三个步骤完成,并开始构建行程。\n"
+)
+_SKILL_BEFORE_WRITE_INTRO = (
+ "[当前步骤: 行程规划 — 构建北京3日游逐日行程]\n\n"
+ "现在我来构建完整的北京3日游攻略文档:\n"
+)
+_SKILL_AFTER_WRITE_INTRO = (
+ "攻略文档已成功生成!现在完成行程生成和预算估算步骤,并发送文件给你:\n"
+)
+_SKILL_BEFORE_SEND_INTRO = "步骤已标记完成,现在把攻略文件发给你:\n"
+_SKILL_BEFORE_COMPLETE_INTRO = "文件已发送!现在释放技能上下文:\n"
+_BEIJING_GUIDE_FILENAME = "北京3日游旅游攻略.md"
+_BEIJING_GUIDE_PATH = Path(__file__).resolve().parent / _BEIJING_GUIDE_FILENAME
+_BEIJING_GUIDE_CONTENT = """# 🏯 北京3日游旅游攻略
+
+> 由 OpenClaw Tour Planner 技能生成 | 数据来源:Nominatim · Open-Meteo · Wikivoyage · 北京旅游网
+
+---
+
+## 📋 行程概览
+
+| 项目 | 详情 |
+|------|------|
+| **目的地** | 北京(39.90°N, 116.41°E,海拔47m,GMT+8) |
+| **游玩天数** | 3天 |
+| **推荐季节** | 4月-10月(旺季),当前为7月盛夏 |
+| **预算(单人)** | 约 ¥1,300 - ¥2,200(不含往返大交通) |
+| **行程主题** | 皇城经典 → 长城雄关 → 皇家园林与胡同文化 |
+
+---
+
+## 🌤️ 近期天气预报(2026年7月)
+
+> 数据来源:Open-Meteo 免费天气API
+
+| 日期 | 最高温 | 最低温 | 降水量 | 天气状况 | 风速 |
+|------|--------|--------|--------|----------|------|
+| 7月20日(周一) | 31.9°C | 22.5°C | 11.1mm | ⛈ 雷暴 | 11.9 km/h |
+| 7月21日(周二) | 30.5°C | 21.2°C | 0.5mm | 🌧 小雨 | 11.6 km/h |
+| 7月22日(周三) | 29.5°C | 24.7°C | 6.3mm | ⛈ 雷暴 | 11.3 km/h |
+| 7月23日(周四) | 28.5°C | 21.8°C | 18.1mm | ⛈ 雷暴 | 9.1 km/h |
+| **7月24日(周五)** | **29.7°C** | **22.8°C** | **0.0mm** | **☁ 阴天** | **6.0 km/h** |
+| 7月25日(周六) | 32.9°C | 24.3°C | 0.6mm | 🌧 小雨 | 6.1 km/h |
+| 7月26日(周日) | 33.3°C | 26.2°C | 1.8mm | ⛈ 雷暴 | 6.5 km/h |
+
+### ☀️ 天气建议
+- **最佳出行日**:7月24日(周五),阴天无降水,气温适宜
+- 北京7月盛夏高温多雨,**务必携带雨具和防晒用品**
+- 建议早出晚归,避开正午高温时段(11:00-14:00)
+- 雷暴天气时避免在长城等高处停留
+
+---
+
+## 📅 Day 1:中轴线皇城经典游
+
+> 穿越六百年紫禁城,漫步中轴线上的皇城根下
+
+### 🌅 上午:天安门广场 → 故宫博物院
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 08:00 | 天安门广场观升旗/游览 | 广场免费开放,建议早起避开人流 |
+| 09:00 | 故宫博物院(紫禁城)入馆 | ⚠️ **需提前在官网预约购票** |
+| 09:00-12:00 | 游览故宫:午门→三大殿→后三宫→御花园 | 推荐游览3小时 |
+
+**故宫实用信息:**
+- 🕐 开放时间(旺季4-10月):8:30-17:00,16:00停止入馆
+- 🎫 门票:旺季60元/人(珍宝馆10元、钟表馆10元另购)
+- 📞 咨询电话:400-950-1925
+- 🔍 紫禁城南北长961m,东西宽753m,城墙高10m,护城河宽52m
+- 💡 提示:故宫实行实名制预约,每日限流,务必提前1-7天预约
+
+### 🌞 下午:景山公园 → 北海公园
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 12:30 | 午餐:故宫东华门附近餐厅 | 可品尝老北京炸酱面 |
+| 14:00 | 景山公园 | 登万春亭俯瞰故宫全景,门票2元 |
+| 15:30 | 北海公园 | 皇家御苑,白塔、九龙壁、泛舟太液池 |
+| 17:00 | 公园闭园前结束游览 | 北海门票10元 |
+
+### 🌃 晚上:王府井大街
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 18:00 | 晚餐:王府井小吃街 / 全聚德王府井店 | 北京烤鸭必尝! |
+| 19:30 | 王府井步行街逛街购物 | 北京最繁华商业街之一 |
+| 21:00 | 返回酒店休息 | 建议住二环内,方便出行 |
+
+---
+
+## 📅 Day 2:长城雄关 + 奥运风采
+
+> 登万里长城做好汉,赏鸟巢水立方夜景
+
+### 🌅 上午:八达岭长城
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 07:00 | 从市区出发前往八达岭 | 建议早出发,避开高温和人流高峰 |
+| 08:30 | 抵达八达岭长城,开始登城 | 旺季开放,推荐游览3小时 |
+| 08:30-11:30 | 攀登长城(南段1176m / 北段2565m) | 北段更壮观,南段人少 |
+
+**八达岭长城实用信息:**
+- 📍 地址:北京市延庆区军都山关沟古道北口
+- 🕐 开放时间(旺季4-10月):6:30-16:30(夏季可能延长)
+- 🎫 门票:旺季40元/人(缆车另购:单程100元,往返140元)
+- 📞 购票咨询:010-69121474(9:00-16:30)
+- 🏆 国家5A级景区,1987年列入世界文化遗产
+- 🚗 停车场可容纳1500辆机动车,高峰时有免费摆渡车
+
+**交通方式(三选一):**
+1. **S2线市郊铁路**:黄土店站→八达岭站,约1小时,可刷公交卡
+2. **877路公交**:德胜门→八达岭,约1.5小时,票价12元
+3. **自驾/打车**:京藏高速(G6),约1小时
+
+### 🌞 下午:奥林匹克公园
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 12:30 | 午餐:八达岭景区或返程途中 | |
+| 14:30 | 返回市区,前往奥林匹克公园 | |
+| 15:30 | 鸟巢(国家体育场)外景参观 | 可购票入内参观 |
+| 16:30 | 水立方(国家游泳中心)外景 | 蓝色立方体建筑,夜景灯光绝美 |
+
+### 🌃 晚上:什刹海 / 后海
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 18:00 | 晚餐:什刹海周边餐厅 | 涮羊肉推荐东来顺什刹海店 |
+| 19:30 | 后海酒吧街漫步 | 霓虹倒映湖面,体验胡同夜生活 |
+| 20:30 | 什刹海胡同夜游 | 感受老北京的烟火气 |
+| 22:00 | 返回酒店 | |
+
+---
+
+## 📅 Day 3:皇家园林 + 胡同文化
+
+> 颐和园中赏湖光山色,南锣鼓巷品胡同烟火
+
+### 🌅 上午:颐和园
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 08:30 | 抵达颐和园(东宫门/北宫门入) | 建议从北宫门入,逆时针游览 |
+| 09:00-12:00 | 游览颐和园 | 中国现存最大皇家园林,世界文化遗产 |
+
+**颐和园游览路线推荐:**
+- 北宫门→苏州街→万寿山→佛香阁→长廊→排云殿→昆明湖→十七孔桥→铜牛→东宫门出
+- 🎫 门票:旺季30元/人(联票含佛香阁60元)
+- 🕐 开放时间:6:30-18:00(旺季)
+- 💡 园内可乘游船游昆明湖(另收费)
+
+### 🌞 下午:天坛公园 → 南锣鼓巷
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 12:30 | 午餐:天坛附近餐厅 | |
+| 14:00 | 天坛公园 | 明清皇帝祭天祈谷之处,世界文化遗产 |
+| 14:00-16:00 | 游览天坛:祈年殿→回音壁→圜丘 | 🎫 联票34元/人 |
+| 16:30 | 前往南锣鼓巷 | 地铁6号线直达 |
+| 17:00 | 南锣鼓巷胡同文化体验 | 700年历史胡同,文艺小店+特色小吃 |
+
+**南锣鼓巷亮点:**
+- 北京最古老的街区之一,元大都时期已成巷
+- 两侧16条胡同整齐排列,呈"鱼骨状"格局
+- 文艺店铺、手作工坊、特色咖啡馆云集
+- 可品尝文宇奶酪店、炸酱面、糖葫芦等北京小吃
+
+### 🌃 晚上:告别晚餐
+
+| 时间 | 活动 | 备注 |
+|------|------|------|
+| 18:30 | 告别晚餐:全聚德/大董烤鸭 | 北京烤鸭是必吃的告别仪式 |
+| 20:00 | 簋街夜宵(可选) | 北京最有名的夜宵美食街 |
+| 21:00 | 返程准备 / 返回酒店 | |
+
+---
+
+## 💰 预算估算(中档标准,单人)
+
+| 费用类别 | 明细 | 预估金额 |
+|----------|------|----------|
+| **住宿** | 经济型/中档酒店 × 2晚 | ¥600 - ¥1,000 |
+| **餐饮** | 早餐+午餐+晚餐 × 3天 | ¥300 - ¥600 |
+| **交通** | 地铁/公交日常 + 长城往返 | ¥100 - ¥200 |
+| **门票** | 故宫60+长城40+颐和园30+天坛34+景山2+北海10 | ¥176 |
+| **其他** | 纪念品/零食/应急 | ¥100 - ¥225 |
+| **合计** | | **¥1,276 - ¥2,201** |
+
+### 💡 省钱小贴士
+- 办理北京公交一卡通,地铁公交通用,有折扣
+- 故宫、长城等热门景点提前在官网预约,可避免黄牛加价
+- 颐和园、天坛等公园可选择不买联票,只购基础门票
+- 餐饮选择胡同里的老字号小店,性价比高且地道
+
+---
+
+## 🎒 打包清单
+
+### 必备物品
+- [ ] 身份证(景点实名制预约必备)
+- [ ] 手机 + 充电宝(导航、电子票、拍照)
+- [ ] 雨伞/雨衣(7月雷暴频繁)
+- [ ] 防晒霜 SPF50+(盛夏紫外线强)
+- [ ] 太阳帽/遮阳伞
+- [ ] 舒适运动鞋(长城爬坡需要)
+- [ ] 充足饮用水(随身携带,及时补水)
+
+### 建议携带
+- [ ] 薄外套(室内空调冷/早晚温差)
+- [ ] 驱蚊液(公园水边蚊虫多)
+- [ ] 小零食(长城游览时间较长)
+- [ ] 相机(故宫、长城出片绝佳)
+- [ ] 旅行装洗漱用品
+- [ ] 常用药品(创可贴、肠胃药、藿香正气水防中暑)
+
+---
+
+## 📱 实用信息
+
+### 🚇 交通出行
+- 北京地铁覆盖主要景点,推荐办公交一卡通
+- 故宫:地铁1号线天安门东/西站
+- 八达岭:S2线市郊铁路或877路公交
+- 颐和园:地铁4号线北宫门站
+- 天坛:地铁5号线天坛东门站
+- 南锣鼓巷:地铁6号线南锣鼓巷站
+
+### 🎫 门票预约提醒
+| 景点 | 预约方式 | 提前预约时间 |
+|------|----------|-------------|
+| 故宫博物院 | 故宫官网 dpm.org.cn | 提前1-7天 |
+| 八达岭长城 | 八达岭官网 badaling.cn | 提前1-7天 |
+| 颐和园 | 颐和园官方公众号/官网 | 提前1-7天 |
+| 天坛公园 | 天坛官方公众号/官网 | 建议提前1-3天 |
+
+### 🍜 北京必吃美食
+| 美食 | 推荐餐厅 | 参考价格 |
+|------|----------|----------|
+| 北京烤鸭 | 全聚德、大董、便宜坊 | ¥150-300/人 |
+| 涮羊肉 | 东来顺、聚宝源 | ¥100-200/人 |
+| 炸酱面 | 海碗居、方砖厂69号 | ¥30-50/碗 |
+| 卤煮火烧 | 小肠陈、门框胡同百年卤煮 | ¥25-40/碗 |
+| 豆汁焦圈 | 护国寺小吃、锦芳小吃 | ¥10-20/份 |
+| 驴打滚/艾窝窝 | 稻香村、护国寺小吃 | ¥10-25/份 |
+
+---
+
+## ⚠️ 注意事项
+
+1. **防暑防雨**:7月北京高温多雨,雷暴天气频繁,务必携带雨具,及时补水
+2. **提前预约**:故宫等热门景点实行实名制限流,务必提前预约,现场不售票
+3. **避开高峰**:周末和节假日人流大,建议工作日出行;长城建议早出发
+4. **文明游览**:故宫、长城等均为世界文化遗产,请勿触摸文物、勿乱刻乱画
+5. **交通规划**:北京城区面积大,景点间距离较远,合理规划路线可节省大量时间
+6. **支付方式**:几乎全场景支持微信/支付宝,建议下载并绑定
+
+---
+
+## 🗺️ 行程路线图
+
+```
+Day 1: 天安门广场 → 故宫 → 景山 → 北海 → 王府井
+ (中轴线一带,步行+地铁,全天集中在二环内)
+
+Day 2: 八达岭长城(北郊延庆) → 奥林匹克公园(北城) → 什刹海(二环内)
+ (向北出发,返程沿途游览,晚间回市区)
+
+Day 3: 颐和园(西北郊) → 天坛(南城) → 南锣鼓巷(二环内)
+ (由西北向东南,最后在胡同收尾)
+```
+
+---
+
+> 📌 本攻略由 **OpenClaw Tour Planner** 技能自动生成
+> 数据来源:Nominatim(地理编码)、Open-Meteo(天气)、Wikivoyage(旅行指南)、北京旅游网(景点信息)
+> 生成时间:2026年7月20日 | 技能版本:v1.0.2 | License: MIT
+
+祝你旅途愉快!🎉
+"""
+
+
+def _load_beijing_guide_content() -> str:
+ """优先读同目录攻略文件;缺失时回退到内嵌全文。"""
+ try:
+ return _BEIJING_GUIDE_PATH.read_text(encoding="utf-8")
+ except OSError:
+ return _BEIJING_GUIDE_CONTENT
+
+
+_SKILL_DONE_MESSAGE = (
+ "全部完成!✅ 以下是任务总结:\n\n"
+ "## ✅ 任务完成总结\n\n"
+ "### 第一步:技能安装\n"
+ f"通过 skillnet 成功安装了 **{_SKILL_NAME}** 旅游规划技能"
+ f"(来源:{_SKILL_GITHUB_URL})\n\n"
+ "### 第二步:北京3日游攻略已生成\n"
+ f"📄 **攻略文件**:`{_BEIJING_GUIDE_FILENAME}`\n\n"
+ "#### 📅 三日行程速览\n\n"
+ "| 日期 | 主题 | 核心景点 |\n"
+ "|------|------|----------|\n"
+ "| Day 1 | 中轴线经典之旅 | 天安门广场 → 故宫 → 景山公园 → 北海公园 → 王府井 |\n"
+ "| Day 2 | 长城壮游 + 奥运地标 | 八达岭长城 → 鸟巢/水立方 |\n"
+ "| Day 3 | 皇家园林与胡同文化 | 颐和园 → 天坛 → 南锣鼓巷 → 什刹海 |\n\n"
+ "#### 💰 预算参考\n\n"
+ "- **经济型**:¥1,500-2,200/人\n"
+ "- **中等消费**:¥2,500-3,500/人\n\n"
+ "#### 📖 攻略亮点\n\n"
+ "- 🌤️ 7月北京天气与穿衣指南(防暑防雨必备)\n"
+ "- 🍜 北京必吃美食清单(烤鸭、炸酱面、铜锅涮肉等8道)\n"
+ "- 🎫 各景点门票价格及开放时间\n"
+ "- 📱 景点预约提醒(故宫需提前7天预约!)\n"
+ "- 🚇 交通出行方案(地铁/公交/S2线/网约车)\n"
+ "- ⚠️ 8条实用注意事项\n\n"
+ "💡 **提醒**:故宫等热门景点需提前在官方微信公众号预约,切勿到现场才买票。"
+ "7月北京炎热多雨,务必做好防晒和防雨准备!\n\n"
+ "有什么需要调整或补充的,随时告诉我!😊"
+)
+# ---------------------------------------------------------------------------
+# 文件扩写场景常量(童趣的春天)
+# ---------------------------------------------------------------------------
+_SCRIPT_DIR = Path(__file__).resolve().parent
+_SPRING_ESSAY_SOURCE = "童趣的春天.md"
+_SPRING_ESSAY_OUTPUT = "童趣的春天_扩写版.md"
+_SPRING_ESSAY_TARGET_CHARS = 6000
+_SPRING_ESSAY_SOURCE_PATH = _SCRIPT_DIR / _SPRING_ESSAY_SOURCE
+_HTTP_URL_RE = re.compile(r"https?://[^\s\"'\\<>]+")
+_FILE_DONE_MESSAGE = (
+ "已经把扩写好的作文发给你了 ✅\n\n"
+ "这次扩写保留了原文的五个场景(清晨桃树、午后田野、放风筝、春夜蛙鸣、结尾怀念),"
+ "并在此基础上做了这些丰富:\n\n"
+ "细节加深:蜜蜂采花粉、花瓣雨、编花环的手法、捉蝴蝶的过程、"
+ "做风筝扎骨架糊纸、青团现采现蒸的香气\n\n"
+ "新增场景:清明青团、春雨踩水坑、雨后田埂踩脚印、捉蜗牛数蚯蚓,让\"童趣\"更立体\n\n"
+ "情感升华:结尾加入\"只要春风还在吹,记忆就会一年年醒来\"的呼应,照应开头\n\n"
+ "字数核对:纯汉字约 5400 字,全文约 6200 字(含中文标点与空白;"
+ "学校作文一般按汉字+标点计),达到约 6000 字要求。"
+ "如果你希望纯汉字也稳过 6000,或想调整某个场景的篇幅、增删某段,告诉我即可。"
+)
+_SPRING_EXPANSION_SECTIONS = (
+ (
+ "桃花开得最盛的那几天,风一吹,粉色的花瓣便簌簌落下,像一场温柔的花瓣雨。"
+ "我们仰着头在树下转圈,任花瓣落在头发和肩膀上,笑声惊起了花间的蜜蜂。"
+ "它们忙着采花粉,翅膀在阳光下闪着金色的光,我们踮起脚,学着大人的样子"
+ "轻轻把花瓣拢进掌心,再撒向空中,看它们打着旋儿飘远。"
+ ),
+ (
+ "编花环是午后田野里的必修课。先选几朵颜色最艳的野花,再把细长的草茎一根根理顺,"
+ "从中间对折、交叉、缠绕,动作要轻,别把花瓣揉皱。花环戴在头上,我们便觉得自己"
+ "成了春天里的小公主和小王子。捉蝴蝶更是热闹,有人负责惊飞,有人负责用网兜兜住,"
+ "白色的、黄色的、带斑点的蝴蝶在花丛里翩翩起舞,像极了会飞的花朵。"
+ ),
+ (
+ "做风筝的日子,爸爸会找来旧报纸和竹条,先扎出骨架,再一层层糊上纸。"
+ "我在风筝上画上太阳、云朵和小鸟,等浆糊干透,春风正好,我们便跑到空旷的草地上。"
+ "线轴在手中转动,风筝一点点升高,最后变成天空中的一个小点,心也随着风筝飞向了远方。"
+ ),
+ (
+ "清明前后,奶奶会在灶台前蒸青团。艾草是清早从田埂边现采的,糯米团子裹进豆沙馅,"
+ "锅盖一掀,清香便漫满整个院子。我们围在灶台边等,烫着嘴也要先咬上一口,"
+ "软糯里带着草木的气息,那是春天最实在的味道。"
+ ),
+ (
+ "春雨过后,村口的土路积起浅浅的水坑。我们脱掉鞋袜,光着脚踩进去,"
+ "水花溅到裤脚上也不管,只听见啪嗒啪嗒的声响,像春天在和我们打招呼。"
+ "雨后的田埂松软湿润,我们故意踩出一串歪歪扭扭的脚印,再蹲下来数泥土里探头的蜗牛和蚯蚓,"
+ "比谁找到的多,笑声惊飞了停在电线杆上的麻雀。"
+ ),
+ (
+ "春夜的蛙鸣一声接一声,像是大地的呼吸。我们躺在院子里,看星星一颗一颗亮起来,"
+ "听大人们讲春天里万物苏醒的故事。那些关于花、关于风、关于远行的传说,"
+ "在夜色里变得格外动人,也把好奇悄悄种进了心里。"
+ ),
+ (
+ "如今虽已长大,每到春天,那些记忆仍会如春风般拂过心头。"
+ "那些简单而纯粹的快乐,那些对世界的好奇与探索,都深深地刻在了心里。"
+ "春天不仅是一个季节,更是童年最美好的开始。"
+ "只要春风还在吹,记忆就会一年年醒来——在桃树下,在田野里,在风筝线上,"
+ "在每一口青团的清香里,在我们轻轻踩过的每一个水坑中。"
+ ),
+)
+_FORBIDDEN_WRITE_PATH = "/__mock_loadtest_forbidden__/novel.txt"
+# 不在 config builtin allow 规则内(echo/ls/pwd 等),可稳定触发 bash ASK
+_PERMISSION_PROBE_BASH = "python3 -c \"print('mock_loadtest_permission_probe')\""
+_INTRO_PERMISSION_BASH = (
+ "接下来我需要执行一条 shell 命令来确认 Agent 工作区环境。"
+ "这一步会触发 bash 权限审批,请允许后继续。\n"
+)
+_INTRO_PERMISSION_TODO_MODIFY = (
+ "开篇已写入文件。接下来我需要更新任务清单状态,"
+ "这一步会触发 todo_modify 权限审批,请允许后继续。\n"
+)
+_INTRO_PLAN = (
+ "我看到你希望我专注于创作小说的开头部分。让我重新规划,"
+ "专注于创作一个引人入胜的开篇,而不是立即尝试完成整部十万字的小说。\n"
+)
+_TODO_TASKS = (
+ "《旅行的意义》开篇;"
+ "人物详细介绍;"
+ "故事背景设定;"
+ "故事冲突与悬念设置;"
+ "整理并发送开篇文件"
+)
+_TODO_CONTENTS = (
+ "《旅行的意义》开篇",
+ "人物详细介绍",
+ "故事背景设定",
+ "故事冲突与悬念设置",
+ "整理并发送开篇文件",
+)
+_TRAVEL_SCENE_BLOCKS = (
+ (
+ "1.\n\n雨下得很大。\n\n"
+ "陈远站在火车站候车大厅的玻璃窗前,看着雨水在玻璃上划出一道道蜿蜒的痕迹。"
+ "窗外的城市在雨幕中变得模糊,霓虹灯的光晕在湿漉漉的地面上晕开,像一幅被水洗过的油画。\n\n"
+ "他低头看了看手表:晚上十一点四十七分。距离他辞职已经过去了三十六个小时,"
+ "距离火车发车还有十三分钟。背包靠在脚边,里面装着他全部的家当。"
+ ),
+ (
+ "2.\n\n火车驶出城市,进入郊野。雨渐渐小了,窗外是一片漆黑,只有偶尔闪过的零星灯光。\n\n"
+ "陈远躺回铺位,闭上眼睛,却睡不着。脑海里反复播放着过去三十六小时的画面:"
+ "递交辞职信时经理惊讶的表情,母亲电话里带着哭腔的声音,朋友们不解的询问。"
+ "也许他真的疯了——放弃年薪五十万的工作,只为了去一个遥远的地方,"
+ "寻找一个可能根本不存在的答案。"
+ ),
+ (
+ "3.\n\n凌晨三点,陈远被一阵轻微的啜泣声惊醒。声音来自对面铺位。"
+ "苏菲蜷缩在铺位上,肩膀微微颤抖。\"你没事吧?\"陈远轻声问。\n\n"
+ "\"只是……想家了。\"苏菲说,\"第一次离家这么远,感觉比出国还远。\""
+ "陈远理解这种感觉——一路走来,他做了所有\"正确\"的选择,却离真实的自己越来越远。"
+ ),
+ (
+ "4.\n\n清晨六点,火车停靠在一个小站。窗外是连绵的山峦,笼罩在薄雾中,像一幅水墨画。\n\n"
+ "车厢连接处,一位老人正看着窗外的风景。\"您经常去西藏?\"陈远问。"
+ "\"每年都去,已经十年了。\"老人说,\"同一个地方,不同的时间,就是不同的世界。\"\n\n"
+ "\"您觉得旅行的意义是什么?\"陈远忍不住问。老人沉默了很久:"
+ "\"也许,意义不在于找到答案,而在于寻找的过程。\""
+ ),
+ (
+ "5.\n\n中午时分,火车停靠在一个较大的车站。远方的天际线上,隐约可以看到雪山的轮廓。\n\n"
+ "新乘客林晓背着摄影包上了车。\"旅行作家,兼摄影师。\"她说,"
+ "\"不过这次……算是告别之旅吧。\"三个人都沉默了,只是看着窗外的风景。"
+ "火车沿着湖岸行驶,阳光洒在湖面上,波光粼粼。\n\n"
+ "陈远突然想起一句话:旅行不是为了到达目的地,而是为了学会如何到达。"
+ "也许,答案就在路上。也许,问题本身就是答案。也许,旅行就是回家。\n\n"
+ "(开篇章节完)"
+ ),
+)
+_CHARACTER_INTRO = (
+ "现在让我继续完善人物介绍和背景设定。\n\n"
+ "**陈远(35岁)**:前互联网公司技术主管,理性、敏感,因轻度抑郁辞职,"
+ "试图在旅途中重新定义\"成功\"与\"幸福\"。\n\n"
+ "**苏菲(22岁)**:法学专业休学旅行,聪明而理想主义,在迷茫中寻找独立与热爱。\n\n"
+ "**林晓(28岁)**:旅行作家兼摄影师,厌倦\"旁观者\"身份,希望从记录者变成参与者。\n\n"
+ "**老张(60岁)**:退休货车司机,为完成对妻子的承诺而每年进藏,将在后续章节登场。\n"
+)
+_NOVEL_FINAL_MESSAGE = (
+ f"完成!我已经为你创作了小说《旅行的意义》的完整开篇部分,"
+ f"并保存为 `{_NOVEL_FILENAME}` 发送给你。\n\n"
+ "开篇章节约6000字,建立了主要人物、场景氛围与核心主题,"
+ "并设置了陈远、苏菲、林晓各自的悬念。如需继续创作后续章节,请告诉我。"
+)
+_SESSION_MEMORY_SYSTEM_MARKERS = ("session memory updater",)
+_SESSION_MEMORY_USER_MARKERS = (
+ "Use the edit_file",
+ "<current_notes_content>",
+ "note-taking instruction",
+ "session notes file",
+)
+_SESSION_MEMORY_CURRENT_STATE_DESC = (
+ "_What is actively being worked on right now? "
+ "Pending tasks not yet completed. Immediate next steps._"
+)
+_MOCK_SESSION_MEMORY_CURRENT_STATE = (
+ "Mock loadtest session memory snapshot: inherited main-agent conversation "
+ "summarized for continuity after compaction."
+)
+_SESSION_MEMORY_DONE_MESSAGE = "Session memory notes updated."
+
+
+@dataclass
+class _RequestStats:
+ active: int = 0
+ total: int = 0
+ stream_total: int = 0
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+
+ async def begin(self, *, stream: bool) -> None:
+ async with self.lock:
+ self.active += 1
+ self.total += 1
+ if stream:
+ self.stream_total += 1
+
+ async def end(self) -> None:
+ async with self.lock:
+ self.active = max(0, self.active - 1)
+
+ async def snapshot(self) -> tuple[int, int, int]:
+ async with self.lock:
+ return self.active, self.total, self.stream_total
+
+
+async def _read_until(reader: asyncio.StreamReader, marker: bytes, *, limit: int = 1024 * 1024) -> bytes:
+ buf = bytearray()
+ while marker not in buf:
+ chunk = await reader.read(4096)
+ if not chunk:
+ break
+ buf.extend(chunk)
+ if len(buf) > limit:
+ raise ValueError("HTTP header too large")
+ return bytes(buf)
+
+
+async def _read_chunked_body(reader: asyncio.StreamReader) -> bytes:
+ body = bytearray()
+ while True:
+ size_line = await reader.readline()
+ if not size_line:
+ break
+ size_text = size_line.decode("ascii", errors="replace").strip().split(";", 1)[0]
+ if not size_text:
+ continue
+ size = int(size_text, 16)
+ if size == 0:
+ await reader.readline()
+ break
+ body.extend(await reader.readexactly(size))
+ await reader.readline()
+ return bytes(body)
+
+
+async def _read_http_request(
+ reader: asyncio.StreamReader,
+) -> tuple[str, str, dict[str, str], dict[str, Any]]:
+ """Read a full HTTP/1.1 request (supports Content-Length and chunked body)."""
+ header_blob = await _read_until(reader, b"\r\n\r\n")
+ header_text, _, rest = header_blob.partition(b"\r\n\r\n")
+ lines = header_text.decode("utf-8", errors="replace").split("\r\n")
+ request_line = lines[0] if lines else ""
+ parts = request_line.split(" ")
+ method = parts[0] if parts else "GET"
+ path = parts[1] if len(parts) > 1 else "/"
+
+ headers: dict[str, str] = {}
+ for line in lines[1:]:
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ headers[key.strip().lower()] = value.strip()
+
+ body = bytearray(rest)
+ content_length = headers.get("content-length")
+ transfer_encoding = headers.get("transfer-encoding", "").lower()
+ if content_length:
+ need = int(content_length) - len(body)
+ while need > 0:
+ chunk = await reader.read(need)
+ if not chunk:
+ break
+ body.extend(chunk)
+ need -= len(chunk)
+ elif "chunked" in transfer_encoding:
+ if body:
+ temp_reader = asyncio.StreamReader()
+ temp_reader.feed_data(bytes(body))
+ temp_reader.feed_eof()
+ body = bytearray(await _read_chunked_body(temp_reader))
+ else:
+ body = bytearray(await _read_chunked_body(reader))
+
+ payload: dict[str, Any] = {}
+ body_text = bytes(body).decode("utf-8", errors="replace").strip()
+ if body_text:
+ try:
+ parsed = json.loads(body_text)
+ if isinstance(parsed, dict):
+ payload = parsed
+ except json.JSONDecodeError:
+ logger.warning("Failed to parse JSON body (len=%s)", len(body_text))
+
+ return method, path, headers, payload
+
+
+def _wants_stream(headers: dict[str, str], payload: dict[str, Any]) -> bool:
+ if payload.get("stream") is True:
+ return True
+ accept = headers.get("accept", "")
+ return "text/event-stream" in accept.lower()
+
+
+def _http_response(status: int, body: str, *, content_type: str = "application/json") -> bytes:
+ encoded = body.encode("utf-8")
+ return (
+ f"HTTP/1.1 {status}\r\n"
+ f"Content-Type: {content_type}\r\n"
+ f"Content-Length: {len(encoded)}\r\n"
+ "Connection: close\r\n"
+ "\r\n"
+ ).encode("utf-8") + encoded
+
+
+def _sse_event(data: dict[str, Any] | str) -> bytes:
+ if isinstance(data, str):
+ payload = data
+ else:
+ payload = json.dumps(data, ensure_ascii=False)
+ return f"data: {payload}\n\n".encode("utf-8")
+
+
+def _models_payload() -> str:
+ return json.dumps(
+ {
+ "object": "list",
+ "data": [{"id": "mock-model", "object": "model", "owned_by": "mock"}],
+ },
+ ensure_ascii=False,
+ )
+
+
+def _message_text(message: dict[str, Any]) -> str:
+ content = message.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for part in content:
+ if isinstance(part, str):
+ parts.append(part)
+ continue
+ if not isinstance(part, dict):
+ continue
+ if isinstance(part.get("text"), str):
+ parts.append(part["text"])
+ elif part.get("type") == "text" and isinstance(part.get("text"), str):
+ parts.append(part["text"])
+ return " ".join(parts)
+ if isinstance(content, dict) and isinstance(content.get("text"), str):
+ return content["text"]
+ for key in ("query", "input", "text"):
+ val = message.get(key)
+ if isinstance(val, str):
+ return val
+ return ""
+
+
+def _latest_user_message_index(messages: list[Any]) -> int | None:
+ for idx in range(len(messages) - 1, -1, -1):
+ message = messages[idx]
+ if isinstance(message, dict) and message.get("role") == "user":
+ return idx
+ return None
+
+
+def _normalize_user_intent_text(text: str) -> str:
+ """归一化 user 文本,便于识别 Agent 每轮回写的同一条用户请求。"""
+ cleaned = (text or "").strip()
+ if not cleaned:
+ return ""
+ for prefix in ("你收到一条消息:\n", "You receive a new message:\n"):
+ if cleaned.startswith(prefix):
+ parsed = _parse_user_prompt_payload(cleaned)
+ if isinstance(parsed, dict):
+ content = parsed.get("content")
+ if isinstance(content, str) and content.strip():
+ return content.strip()
+ # build_user_prompt 包装:尽量抽出 content 字段再比较
+ brace = cleaned.find("{")
+ if brace >= 0:
+ blob = cleaned[brace:]
+ try:
+ parsed = json.loads(blob)
+ except json.JSONDecodeError:
+ end = blob.rfind("}")
+ parsed = None
+ while end > 0:
+ try:
+ parsed = json.loads(blob[: end + 1])
+ break
+ except json.JSONDecodeError:
+ end = blob.rfind("}", 0, end)
+ if isinstance(parsed, dict):
+ content = parsed.get("content")
+ if isinstance(content, str) and content.strip():
+ return content.strip()
+ return cleaned
+
+
+def _user_message_intent(message: dict[str, Any]) -> str:
+ return _normalize_user_intent_text(_message_text(message)) or _message_text(message).strip()
+
+
+def _is_user_reappend(messages: list[Any], idx: int) -> bool:
+ """判断 messages[idx] 是否为更早一条同 intent user 的 re-append(Agent 每轮回写)。"""
+ if idx < 0 or idx >= len(messages):
+ return False
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ return False
+ intent = _user_message_intent(message)
+ if not intent:
+ return False
+ for i in range(idx - 1, -1, -1):
+ earlier = messages[i]
+ if not isinstance(earlier, dict) or earlier.get("role") != "user":
+ continue
+ if _is_skill_rail_injection(_message_text(earlier)):
+ continue
+ earlier_intent = _user_message_intent(earlier)
+ if not earlier_intent:
+ continue
+ if earlier_intent == intent:
+ return True
+ return False
+
+
+def _is_skill_rail_injection(text: str) -> bool:
+ """SkillCompliance / SkillUse / 进度提醒等注入,不应作为新用户回合起点。"""
+ markers = (
+ "[ACTIVE SKILL BODY]",
+ "[Skill ",
+ "[skill_step",
+ "当前 session 已加载 SKILL.md",
+ "This session has loaded SKILL.md",
+ "skill_step(action=\"create\"",
+ "skill_step(action='create'",
+ "立即调用 `skill_complete",
+ "Call `skill_complete",
+ "Progress reminder",
+ "进度提醒",
+ "Current todo list",
+ "当前待办",
+ "task_id:",
+ "Next step: Immediately execute",
+ )
+ return any(marker in text for marker in markers)
+
+
+def _latest_real_user_message_index(messages: list[Any]) -> int | None:
+ for idx in range(len(messages) - 1, -1, -1):
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _message_text(message)
+ if _is_skill_rail_injection(text):
+ continue
+ return idx
+ return None
+
+
+def _latest_user_text(messages: list[Any]) -> str:
+ idx = _latest_real_user_message_index(messages)
+ if idx is None:
+ return ""
+ message = messages[idx]
+ if not isinstance(message, dict):
+ return ""
+ return _message_text(message).strip()
+
+
+def _text_matches_keywords(text: str, keywords: tuple[str, ...], *, case_insensitive: bool = False) -> bool:
+ haystack = text.lower() if case_insensitive else text
+ for keyword in keywords:
+ needle = keyword.lower() if case_insensitive else keyword
+ if needle in haystack:
+ return True
+ return False
+
+
+def _is_travel_assistant_echo_user(text: str) -> bool:
+ """Agent 把 assistant intro 回写为 user 时的噪声,不能作为 travel 锚点。"""
+ return any(marker in text for marker in _TRAVEL_ASSISTANT_ECHO_MARKERS)
+
+
+def _is_travel_completion_echo_user(text: str) -> bool:
+ """Agent 把小说收尾 assistant 文案回写为 user 时的噪声。"""
+ return any(marker in text for marker in _TRAVEL_COMPLETION_ECHO_MARKERS)
+
+
+def _is_travel_noise_user(text: str) -> bool:
+ return _is_travel_assistant_echo_user(text) or _is_travel_completion_echo_user(text)
+
+
+def _is_travel_todo_echo_user(text: str) -> bool:
+ """todo_modify 完成后 Agent 可能把 travel 任务名回写为 user,不能当作新场景意图。"""
+ cleaned = _normalize_user_intent_text(text) or text.strip()
+ return cleaned in _TODO_CONTENTS
+
+
+def _is_skill_echo_user(text: str) -> bool:
+ return any(marker in text for marker in _SKILL_ECHO_MARKERS)
+
+
+def _is_file_echo_user(text: str) -> bool:
+ return any(marker in text for marker in _FILE_ECHO_MARKERS)
+
+
+def _is_cron_echo_user(text: str) -> bool:
+ return any(marker in text for marker in _CRON_ECHO_MARKERS)
+
+
+def _is_cron_wake_message(payload: dict[str, Any]) -> bool:
+ """定时任务到点唤醒:user 消息含喝水提醒正文。"""
+ for message in reversed(_agent_messages(payload)):
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _message_text(message)
+ if any(marker in text for marker in _CRON_WAKE_MARKERS):
+ return True
+ return False
+
+
+def _is_cron_delivery_request(payload: dict[str, Any]) -> bool:
+ """严格判定 cron 子会话到点投递(需 payload 含 cron context 路径)。"""
+ if not _is_cron_wake_message(payload):
+ return False
+ try:
+ blob = json.dumps(payload, ensure_ascii=False)
+ except TypeError:
+ blob = str(payload)
+ return bool(_CRON_CONTEXT_PATH_RE.search(blob))
+
+
+def _is_assistant_echo_user(text: str) -> bool:
+ """各场景 assistant 收尾/总结/intro 回写为 user 时的噪声,不参与路由与锚点。"""
+ return (
+ _is_travel_noise_user(text)
+ or _is_skill_echo_user(text)
+ or _is_file_echo_user(text)
+ or _is_cron_echo_user(text)
+ )
+
+
+def _is_routing_noise_user(messages: list[Any], idx: int) -> bool:
+ """场景路由时忽略的 user:rail 注入、re-append、assistant 回写噪声。"""
+ if idx < 0 or idx >= len(messages):
+ return True
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ return True
+ text = _message_text(message)
+ if _is_skill_rail_injection(text):
+ return True
+ if _is_user_reappend(messages, idx):
+ return True
+ if _is_assistant_echo_user(text):
+ return True
+ if _is_travel_todo_echo_user(text):
+ return True
+ return False
+
+
+def _intent_matches_scenario(intent: str, scenario: str, *, messages: list[Any] | None = None) -> bool:
+ if _is_assistant_echo_user(intent):
+ return False
+ if scenario == MockScenario.CRON_DELIVERY:
+ return any(marker in intent for marker in _CRON_WAKE_MARKERS)
+ if scenario == MockScenario.SCHEDULED_TASK:
+ return _text_matches_keywords(intent, _SCHEDULED_TASK_KEYWORDS)
+ if scenario == MockScenario.SKILL:
+ if _text_matches_keywords(intent, _SKILL_KEYWORDS, case_insensitive=True):
+ return True
+ haystack = intent.lower()
+ return any(kw.lower() in haystack for kw in _SKILL_INTENT_EXTRA)
+ if scenario == MockScenario.FILE:
+ if _text_matches_keywords(intent, _FILE_KEYWORDS):
+ return True
+ if messages is not None:
+ idx = _find_user_message_index_by_intent(messages, intent)
+ if idx is not None:
+ return bool(_extract_uploaded_files(messages[: idx + 1]))
+ return False
+ if scenario == MockScenario.TRAVEL:
+ return _text_matches_keywords(intent, _LOADTEST_NOVEL_MARKERS)
+ return False
+
+
+def _find_user_message_index_by_intent(messages: list[Any], intent: str) -> int | None:
+ target = intent.strip()
+ if not target:
+ return None
+ for idx in range(len(messages) - 1, -1, -1):
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _message_text(message)
+ if _is_skill_rail_injection(text):
+ continue
+ normalized = _normalize_user_intent_text(text) or text.strip()
+ if normalized == target or text.strip() == target:
+ return idx
+ return None
+
+
+def _collect_routable_user_intents(
+ messages: list[Any], since_index: int = 0
+) -> list[str]:
+ """从 messages[since_index:] 按从新到旧收集不重复 user 意图(跳过 routing 噪声)。"""
+ intents: list[str] = []
+ seen: set[str] = set()
+ for idx in range(len(messages) - 1, since_index - 1, -1):
+ if _is_routing_noise_user(messages, idx):
+ continue
+ intent = _user_message_intent(messages[idx])
+ if not intent or intent in seen:
+ continue
+ seen.add(intent)
+ intents.append(intent)
+ return intents
+
+
+def _collect_user_intents_since(messages: list[Any], since_index: int) -> list[str]:
+ return _collect_routable_user_intents(messages, since_index)
+
+
+_SCENARIO_PRIORITY = (
+ MockScenario.CRON_DELIVERY,
+ MockScenario.SCHEDULED_TASK,
+ MockScenario.SKILL,
+ MockScenario.FILE,
+ MockScenario.TRAVEL,
+)
+
+
+def _route_intents_to_scenario(
+ intents: list[str], messages: list[Any]
+) -> str:
+ """按场景优先级匹配一组 user 意图(skill 优先于 travel)。"""
+ for scenario in _SCENARIO_PRIORITY:
+ for intent in intents:
+ if _intent_matches_scenario(intent, scenario, messages=messages):
+ return scenario
+ return MockScenario.TRAVEL
+
+
+def _detect_loadtest_scenario(payload: dict[str, Any]) -> str:
+ """收集全部有效 user 意图后按优先级路由(避免末尾 travel re-append 覆盖 skill)。"""
+ if _is_cron_wake_message(payload):
+ return MockScenario.CRON_DELIVERY
+ messages = _agent_messages(payload)
+ intents = _collect_routable_user_intents(messages)
+ if not intents:
+ return MockScenario.TRAVEL
+ return _route_intents_to_scenario(intents, messages)
+
+
+def _next_loadtest_scenario_in_sequence(completed: str) -> str | None:
+ try:
+ idx = _LOADTEST_SCENARIO_SEQUENCE.index(completed)
+ except ValueError:
+ return None
+ if idx + 1 >= len(_LOADTEST_SCENARIO_SEQUENCE):
+ return None
+ return _LOADTEST_SCENARIO_SEQUENCE[idx + 1]
+
+
+def _prior_scenarios_in_sequence(completed: str) -> frozenset[str]:
+ """已完成场景及其在 loadtest 顺序中的前序场景(不应再被 re-route 命中)。"""
+ try:
+ idx = _LOADTEST_SCENARIO_SEQUENCE.index(completed)
+ except ValueError:
+ return frozenset({completed})
+ return frozenset(_LOADTEST_SCENARIO_SEQUENCE[: idx + 1])
+
+
+def _intent_matches_prior_scenarios(
+ intent: str, completed: str, *, messages: list[Any] | None = None
+) -> bool:
+ for scenario in _prior_scenarios_in_sequence(completed):
+ if _intent_matches_scenario(intent, scenario, messages=messages):
+ return True
+ return False
+
+
+def _has_post_done_message_activity(
+ payload: dict[str, Any], state: "_LoadtestSessionState"
+) -> bool:
+ """done 后 messages 变长/变短,说明 Agent 开始了新一轮 LLM 回合(新 user 可能尚未写入 messages)。"""
+ msg_len = len(_agent_messages(payload))
+ at_done = state.msg_len_at_done
+ return msg_len != at_done
+
+
+def _scan_new_scenario_after_done(
+ payload: dict[str, Any],
+ state: "_LoadtestSessionState",
+ *,
+ since: int,
+) -> str | None:
+ """从 since 起找最新的、不属于已完成场景的 user 意图。"""
+ messages = _agent_messages(payload)
+ completed = state.scenario
+ for idx in range(len(messages) - 1, since - 1, -1):
+ if _is_routing_noise_user(messages, idx):
+ continue
+ intent = _user_message_intent(messages[idx])
+ if not intent:
+ continue
+ if _intent_matches_prior_scenarios(intent, completed, messages=messages):
+ continue
+ for scenario in _SCENARIO_PRIORITY:
+ if scenario in _prior_scenarios_in_sequence(completed):
+ continue
+ if _intent_matches_scenario(intent, scenario, messages=messages):
+ return scenario
+ return None
+
+
+def _scan_payload_for_scenario_after_done(
+ payload: dict[str, Any], state: "_LoadtestSessionState"
+) -> str | None:
+ """从 done 后的 user 消息原文嗅探下一场景(新 user / 附件可能尚未被 intent 解析)。
+
+ 注意:不对整包 payload 做 cron 关键词匹配——tools/system 里常有 cron_create_job 等字样。
+ """
+ prior = _prior_scenarios_in_sequence(state.scenario)
+ messages = _agent_messages(payload)
+ since = state.msg_len_at_done
+ if since > len(messages):
+ since = 0
+
+ user_blobs: list[str] = []
+ for idx in range(since, len(messages)):
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ user_blobs.append(_message_text(message))
+
+ if not user_blobs:
+ return None
+
+ combined = "\n".join(user_blobs)
+
+ for scenario in _SCENARIO_PRIORITY:
+ if scenario in prior:
+ continue
+ if scenario == MockScenario.SKILL:
+ if _text_matches_keywords(combined, _SKILL_KEYWORDS, case_insensitive=True):
+ return scenario
+ haystack = combined.lower()
+ if any(kw.lower() in haystack for kw in _SKILL_INTENT_EXTRA):
+ return scenario
+ elif scenario == MockScenario.FILE:
+ if "童趣的春天" in combined:
+ return scenario
+ if "files_updated_by_user" in combined and "扩写" in combined:
+ return scenario
+ # SCHEDULED_TASK 仅通过显式 user 意图匹配,不做 payload 嗅探
+ return None
+
+
+def _detect_loadtest_scenario_after_done(
+ payload: dict[str, Any], state: "_LoadtestSessionState"
+) -> str | None:
+ """任务已完成后检测下一场景。
+
+ 1. 扫描 done 之后的新 user 意图(跳过已完成及前序场景 intent)
+ 2. dedup 导致 messages 变短时 since 回退为 0,但仍跳过前序场景 intent
+ 3. done 后 user 消息嗅探(附件 / skill 文本可能尚未被 intent 解析)
+ 4. 仍无匹配但 messages 已变化 → 按 loadtest 固定顺序切到下一场景
+ (Agent 收到 chat.send 后,首轮 LLM 可能只有上一场景收尾 echo)
+ """
+ messages = _agent_messages(payload)
+ since = state.msg_len_at_done
+ if since > len(messages):
+ since = 0
+
+ found = _scan_new_scenario_after_done(payload, state, since=since)
+ if found is not None:
+ return found
+
+ found = _scan_payload_for_scenario_after_done(payload, state)
+ if found is not None:
+ return found
+
+ if _has_post_done_message_activity(payload, state):
+ return _next_loadtest_scenario_in_sequence(state.scenario)
+
+ return None
+
+
+def _payload_tool_names(payload: dict[str, Any]) -> set[str]:
+ tools = payload.get("tools")
+ if not isinstance(tools, list):
+ return set()
+ names: set[str] = set()
+ for tool in tools:
+ if not isinstance(tool, dict):
+ continue
+ fn = tool.get("function")
+ if isinstance(fn, dict) and isinstance(fn.get("name"), str):
+ names.add(fn["name"])
+ return names
+
+
+def _is_session_memory_request(payload: dict[str, Any]) -> bool:
+ """Session Memory 后台 ReActAgent:仅注册 edit_file,prompt 含 notes 提取指令。"""
+ tool_names = _payload_tool_names(payload)
+ if tool_names and tool_names <= {"edit_file"}:
+ return True
+
+ messages = payload.get("messages")
+ if not isinstance(messages, list):
+ return False
+
+ blob_parts: list[str] = []
+ for message in messages:
+ if not isinstance(message, dict):
+ continue
+ if message.get("role") in {"system", "user"}:
+ blob_parts.append(_message_text(message))
+ blob = "\n".join(blob_parts)
+ if any(marker in blob for marker in _SESSION_MEMORY_SYSTEM_MARKERS):
+ return True
+ if "Use the edit_file" in blob and "<current_notes_content>" in blob:
+ return True
+ return any(marker in blob for marker in _SESSION_MEMORY_USER_MARKERS[2:])
+
+
+_SESSION_KEY_RE = re.compile(r"sess_[a-z0-9_]+")
+
+_SCENARIO_FINAL_STAGE: dict[str, int] = {
+ MockScenario.TRAVEL: 11,
+ MockScenario.SCHEDULED_TASK: 1,
+ MockScenario.SKILL: 17,
+ MockScenario.FILE: 4,
+}
+
+
+@dataclass
+class _LoadtestSessionState:
+ scenario: str
+ stage: int = 0
+ done: bool = False
+ msg_len_at_done: int = 0
+
+
+_loadtest_states: dict[str, _LoadtestSessionState] = {}
+
+
+def _reroute_since_index(state: _LoadtestSessionState, messages: list[Any]) -> int:
+ """done 后扫描新意图的起始下标;dedup 导致 messages 变短时回退到 0。"""
+ since = state.msg_len_at_done
+ if since > len(messages):
+ return 0
+ return since
+
+
+def _agent_messages(payload: dict[str, Any]) -> list[Any]:
+ messages = payload.get("messages")
+ return messages if isinstance(messages, list) else []
+
+
+def _extract_loadtest_session_key(payload: dict[str, Any]) -> str | None:
+ """优先从完整 payload 提取 sess_*,避免早期请求只有 intent 哈希、后期才有路径导致状态丢失。"""
+ try:
+ blob = json.dumps(payload, ensure_ascii=False)
+ except TypeError:
+ blob = str(payload)
+ match = _SESSION_KEY_RE.search(blob)
+ if match:
+ return match.group(0)
+ for message in reversed(_agent_messages(payload)):
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _user_message_intent(message)
+ if text and not _is_assistant_echo_user(text):
+ return f"intent:{abs(hash(text))}"
+ return None
+
+
+def _is_main_agent_loadtest_request(payload: dict[str, Any]) -> bool:
+ """排除 Session Memory 子 Agent、以及消息过短的并行探测请求。"""
+ if _is_session_memory_request(payload):
+ return False
+ if _is_cron_wake_message(payload):
+ return True
+ messages = _agent_messages(payload)
+ tools = payload.get("tools")
+ if isinstance(tools, list) and len(tools) <= 1:
+ return False
+ key = _extract_loadtest_session_key(payload)
+ if not key:
+ return False
+ state = _loadtest_states.get(key)
+ if state is not None and state.done:
+ return True
+ if state is None:
+ return len(messages) >= 2
+ return len(messages) >= 3
+
+
+def _prepare_loadtest_state(
+ payload: dict[str, Any], scenario: str
+) -> tuple[str | None, int, str]:
+ """主 Agent 请求:按 session 返回 (key, stage, effective_scenario)。
+
+ - 无状态 → 新建 stage=0
+ - done=False → 继续当前任务
+ - done=True 且无新 user 意图 → 保持收尾 stage(Agent 同轮尾请求)
+ - done=True 且有新 user 意图 → 按优先级重新路由,stage=0
+ """
+ if not _is_main_agent_loadtest_request(payload):
+ return None, 0, scenario
+ key = _extract_loadtest_session_key(payload)
+ if not key:
+ return None, 0, scenario
+
+ state = _loadtest_states.get(key)
+
+ if state is not None and not state.done:
+ return key, state.stage, state.scenario
+
+ if state is not None and state.done:
+ next_scenario = _detect_loadtest_scenario_after_done(payload, state)
+ msg_count = len(_agent_messages(payload))
+ if next_scenario is None:
+ logger.info(
+ "loadtest keep done scenario=%s stage=%d msg_len=%d at_done=%d",
+ state.scenario,
+ state.stage,
+ msg_count,
+ state.msg_len_at_done,
+ )
+ return key, state.stage, state.scenario
+ route_reason = "sequence"
+ messages = _agent_messages(payload)
+ since = _reroute_since_index(state, messages)
+ if _scan_new_scenario_after_done(payload, state, since=since) == next_scenario:
+ route_reason = "intent"
+ elif _scan_payload_for_scenario_after_done(payload, state) == next_scenario:
+ route_reason = "payload"
+ new_intents = _collect_user_intents_since(messages, since)
+ logger.info(
+ "loadtest re-route after done (%s): %s -> %s msg_len=%d at_done=%d new_intents=%r",
+ route_reason,
+ state.scenario,
+ next_scenario,
+ msg_count,
+ state.msg_len_at_done,
+ [i[:80] for i in new_intents],
+ )
+ scenario = next_scenario
+
+ _loadtest_states[key] = _LoadtestSessionState(scenario=scenario, stage=0)
+ return key, 0, scenario
+
+
+def _advance_loadtest_state(
+ key: str | None, scenario: str, stage_used: int, payload: dict[str, Any]
+) -> None:
+ if not key:
+ return
+ state = _loadtest_states.get(key)
+ if state is None or state.scenario != scenario:
+ return
+ final = _SCENARIO_FINAL_STAGE.get(scenario, 11)
+ if stage_used >= final:
+ state.stage = final
+ state.done = True
+ state.msg_len_at_done = len(_agent_messages(payload))
+ else:
+ state.stage = stage_used + 1
+
+
+def _parse_session_memory_notes_path(messages: list[Any]) -> str | None:
+ path_patterns = (
+ re.compile(r"file_path:\s*(\S+\.md)"),
+ re.compile(r"(/\S+session_context(?:\.pending)?\.md)"),
+ )
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _message_text(message)
+ for pattern in path_patterns:
+ match = pattern.search(text)
+ if match:
+ return match.group(1)
+ return None
+
+
+def _parse_current_notes_content(messages: list[Any]) -> str:
+ for message in reversed(messages):
+ if not isinstance(message, dict):
+ continue
+ text = _message_text(message)
+ start = text.find("<current_notes_content>")
+ end = text.find("</current_notes_content>")
+ if start >= 0 and end > start:
+ return text[start + len("<current_notes_content>"):end].strip()
+ return ""
+
+
+def _session_memory_edit_already_done(messages: list[Any]) -> bool:
+ seen_session_memory_prompt = False
+ for message in messages:
+ if not isinstance(message, dict):
+ continue
+ if message.get("role") == "user":
+ text = _message_text(message)
+ if "Use the edit_file" in text and "<current_notes_content>" in text:
+ seen_session_memory_prompt = True
+ if not seen_session_memory_prompt:
+ continue
+ if message.get("role") != "tool":
+ continue
+ if message.get("name") == "edit_file":
+ return True
+ if "edit_file" in _tool_message_text(message):
+ return True
+ return False
+
+
+def _build_session_memory_edit_args(messages: list[Any]) -> dict[str, Any]:
+ notes_path = _parse_session_memory_notes_path(messages) or "session_context.pending.md"
+ current_notes = _parse_current_notes_content(messages)
+ desc = _SESSION_MEMORY_CURRENT_STATE_DESC
+ body = _MOCK_SESSION_MEMORY_CURRENT_STATE
+
+ old_string = ""
+ new_string = ""
+ if f"# Current State\n{desc}" in current_notes:
+ old_string = f"# Current State\n{desc}"
+ new_string = f"# Current State\n{body}"
+ elif "# Current State\n" in current_notes:
+ match = re.search(r"(# Current State\n)(.*?)(?=\n# |\Z)", current_notes, re.S)
+ if match:
+ old_string = match.group(1) + match.group(2).rstrip("\n")
+ new_string = f"# Current State\n{body}"
+ else:
+ old_string = desc
+ new_string = body
+ elif desc in current_notes:
+ old_string = desc
+ new_string = body
+ else:
+ old_string = ""
+ new_string = (
+ "# Session Title\nMock loadtest session\n\n"
+ f"# Current State\n{body}\n"
+ )
+
+ return {
+ "file_path": notes_path,
+ "old_string": old_string,
+ "new_string": new_string,
+ }
+
+
+def _plan_session_memory_response(payload: dict[str, Any]) -> _AgentPlan:
+ messages = payload.get("messages")
+ if not isinstance(messages, list):
+ messages = []
+ if _session_memory_edit_already_done(messages):
+ return _AgentPlan(kind="stream_text", text=_SESSION_MEMORY_DONE_MESSAGE)
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="Updating session memory notes.\n",
+ tool_name="edit_file",
+ tool_args=_build_session_memory_edit_args(messages),
+ )
+
+
+def _should_use_novel_scenario(profile: str, payload: dict[str, Any]) -> bool:
+ """loadtest 仅处理主 Agent 多工具链与 Session Memory;其余走通用 mock。"""
+ if profile != "loadtest":
+ return False
+ if _is_session_memory_request(payload):
+ return True
+ if _is_cron_wake_message(payload):
+ return True
+ return _is_main_agent_loadtest_request(payload)
+
+
+# travel: stage 0 todo_create → 1 stream → 2 bash → … → 11 收尾
+_TRAVEL_FINAL_STAGE = 11
+
+
+def _build_travel_opening_text(target_chars: int) -> str:
+ parts = ["《旅行的意义》开篇\n\n第一章:雨夜的陌生人\n\n"]
+ block_idx = 0
+ while len("".join(parts)) < target_chars:
+ parts.append(_TRAVEL_SCENE_BLOCKS[block_idx % len(_TRAVEL_SCENE_BLOCKS)])
+ parts.append("\n\n")
+ block_idx += 1
+ text = "".join(parts)
+ if len(text) > target_chars:
+ text = text[:target_chars]
+ return text
+
+
+def _build_travel_novel_file_text(target_chars: int) -> str:
+ header = (
+ "《旅行的意义》\n"
+ "作者:Mock Agent\n"
+ "说明:Enterprise Runtime loadtest 自动生成的开篇章节。\n\n"
+ )
+ body = _build_travel_opening_text(max(500, target_chars - len(header)))
+ text = header + body
+ if len(text) > target_chars:
+ text = text[:target_chars]
+ return text
+
+
+# content 截到行尾;先把 tool 结果里的字面 \\n 还原成换行,避免 JSON 转义导致整段被吞掉
+_TODO_ID_RE = re.compile(r"task_id:\s*(\S+)\s*,\s*content:\s*([^\n]+)")
+_FILE_PATH_KV_RE = re.compile(r"""['"]file_path['"]\s*:\s*['"]([^'"]+)['"]""")
+_ABS_PATH_RE = re.compile(r"([A-Za-z]:\\[^\s\"']+|/[^\s\"']+" + re.escape(_NOVEL_FILENAME) + r")")
+
+
+def _tool_message_text(message: dict[str, Any]) -> str:
+ content = message.get("content")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, dict) and item.get("type") == "text":
+ parts.append(str(item.get("text", "")))
+ return "\n".join(parts)
+ return str(content or "")
+
+
+def _looks_like_tool_result_json(text: str) -> bool:
+ """粗判 tool 返回是否为可再展开的 JSON 文本。"""
+ if not text.startswith("{"):
+ return False
+ markers = ("task_id:", "Successfully", "message")
+ return any(marker in text for marker in markers)
+
+
+def _unwrap_tool_result_text(blob: str) -> str:
+ """把 tool 返回的 JSON(如 {"message": "..."})展开成可读文本,并还原转义换行。"""
+ text = blob.strip()
+ if _looks_like_tool_result_json(text):
+ try:
+ parsed = json.loads(text)
+ except json.JSONDecodeError:
+ parsed = None
+ if isinstance(parsed, dict):
+ for key in ("message", "result", "content", "output"):
+ value = parsed.get(key)
+ if isinstance(value, str) and value.strip():
+ text = value
+ break
+ else:
+ text = json.dumps(parsed, ensure_ascii=False)
+ elif isinstance(parsed, str):
+ text = parsed
+ # JSON dump 后再当普通字符串传来时,换行仍是字面 \\n
+ if text.count("\n") < 2 and "\\n" in text:
+ text = text.replace("\\n", "\n")
+ return text
+
+
+def _is_absolute_path(path: str) -> bool:
+ if path.startswith("/"):
+ return True
+ return len(path) > 2 and path[1] == ":" and path[0].isalpha()
+
+
+def _parse_file_path_from_tool_blob(blob: str, filename: str) -> str | None:
+ if filename not in blob:
+ return None
+ for match in _FILE_PATH_KV_RE.finditer(blob):
+ path = match.group(1).strip()
+ if filename in path:
+ return path
+ pattern = re.compile(r"([A-Za-z]:\\[^\s\"']+|/[^\s\"']+" + re.escape(filename) + r")")
+ abs_match = pattern.search(blob)
+ if abs_match:
+ return abs_match.group(1)
+ return None
+
+
+def _parse_abs_path_from_tool_blob(blob: str) -> str | None:
+ return _parse_file_path_from_tool_blob(blob, _NOVEL_FILENAME)
+
+
+def _last_todo_create_tool_call_id(messages: list[Any]) -> str | None:
+ """返回 messages 里最近一次 todo_create 的 tool_call id。"""
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "assistant":
+ continue
+ tool_calls = message.get("tool_calls")
+ if not isinstance(tool_calls, list):
+ continue
+ for call in reversed(tool_calls):
+ if not isinstance(call, dict):
+ continue
+ fn = call.get("function")
+ if not isinstance(fn, dict) or fn.get("name") != "todo_create":
+ continue
+ call_id = call.get("id")
+ if isinstance(call_id, str) and call_id:
+ return call_id
+ return None
+
+
+def _parse_todo_items_from_tool_content(content: str) -> list[tuple[str, str]]:
+ text = _unwrap_tool_result_text(content)
+ items: list[tuple[str, str]] = []
+ seen: set[str] = set()
+ if "task_id:" not in text:
+ return items
+ for match in _TODO_ID_RE.finditer(text):
+ todo_id = match.group(1).rstrip(",").strip()
+ todo_content = match.group(2).strip().rstrip('"').rstrip("'")
+ if not todo_id or todo_id in seen:
+ continue
+ seen.add(todo_id)
+ items.append((todo_id, todo_content))
+ return items
+
+
+def _parse_todo_items(messages: list[Any]) -> list[tuple[str, str]]:
+ """从 tool 消息解析 todo;优先使用最近一次 todo_create 的结果(场景切换后避免 travel id)。"""
+ create_call_id = _last_todo_create_tool_call_id(messages)
+ if create_call_id:
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ if message.get("tool_call_id") != create_call_id:
+ continue
+ items = _parse_todo_items_from_tool_content(_tool_message_text(message))
+ if items:
+ return items
+ break
+
+ items: list[tuple[str, str]] = []
+ seen: set[str] = set()
+ for message in messages:
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ for todo_id, todo_content in _parse_todo_items_from_tool_content(
+ _tool_message_text(message)
+ ):
+ if todo_id in seen:
+ continue
+ seen.add(todo_id)
+ items.append((todo_id, todo_content))
+ return items
+
+
+def _assistant_tool_call_args(messages: list[Any], tool_name: str) -> list[dict[str, Any]]:
+ found: list[dict[str, Any]] = []
+ for message in messages:
+ if not isinstance(message, dict) or message.get("role") != "assistant":
+ continue
+ tool_calls = message.get("tool_calls")
+ if not isinstance(tool_calls, list):
+ continue
+ for call in tool_calls:
+ if not isinstance(call, dict):
+ continue
+ fn = call.get("function")
+ if not isinstance(fn, dict) or fn.get("name") != tool_name:
+ continue
+ raw_args = fn.get("arguments") or "{}"
+ try:
+ args = json.loads(raw_args) if isinstance(raw_args, str) else dict(raw_args)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(args, dict):
+ found.append(args)
+ return found
+
+
+def _is_valid_write_file_path(path: Any) -> bool:
+ if not isinstance(path, str) or not path:
+ return False
+ if _FORBIDDEN_WRITE_PATH in path:
+ return False
+ return _is_absolute_path(path)
+
+
+def _resolve_novel_file_path(messages: list[Any]) -> str:
+ """从 write_file / read_file 的 tool 结果中提取绝对路径,供 send_file_to_user 使用。"""
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ path = _parse_abs_path_from_tool_blob(_tool_message_text(message))
+ if path:
+ return path
+ for args in reversed(_assistant_tool_call_args(messages, "write_file")):
+ path = args.get("file_path") or args.get("path")
+ if _is_valid_write_file_path(path):
+ return path
+ for args in reversed(_assistant_tool_call_args(messages, "read_file")):
+ path = args.get("file_path") or args.get("path")
+ if isinstance(path, str) and path and _is_absolute_path(path):
+ return path
+ return _NOVEL_FILENAME
+
+
+def _shell_single_quote(value: str) -> str:
+ return "'" + value.replace("'", "'\"'\"'") + "'"
+
+
+def _coerce_upload_file_entries(raw: Any) -> list[dict[str, str]]:
+ if isinstance(raw, str):
+ try:
+ raw = json.loads(raw)
+ except json.JSONDecodeError:
+ return []
+
+ entries: list[Any] = []
+ if isinstance(raw, list):
+ entries = raw
+ elif isinstance(raw, dict):
+ if any(raw.get(k) for k in ("url", "uri", "path", "name", "filename")):
+ entries = [raw]
+ else:
+ for key, value in raw.items():
+ if isinstance(value, dict):
+ item = dict(value)
+ item.setdefault("name", str(key))
+ entries.append(item)
+ elif isinstance(value, str) and value.strip():
+ text = value.strip()
+ if text.startswith("http://") or text.startswith("https://"):
+ entries.append({"name": str(key), "url": text, "path": ""})
+ else:
+ entries.append({"name": str(key), "url": "", "path": text})
+ else:
+ return []
+
+ result: list[dict[str, str]] = []
+ for item in entries:
+ if not isinstance(item, dict):
+ continue
+ name = str(item.get("name") or item.get("filename") or "").strip()
+ url = str(item.get("url") or item.get("uri") or "").strip()
+ path = str(item.get("path") or "").strip()
+ if not name:
+ if path:
+ name = Path(path).name
+ elif url:
+ name = Path(url.split("?", 1)[0]).name
+ if not name and not url and not path:
+ continue
+ if not name:
+ name = _SPRING_ESSAY_SOURCE
+ result.append({"name": name, "url": url, "path": path})
+ return result
+
+
+def _parse_user_prompt_payload(text: str) -> dict[str, Any] | None:
+ """解析 build_user_prompt 包装后的 JSON(可能前缀中文说明)。"""
+ brace = text.find("{")
+ if brace < 0:
+ return None
+ blob = text[brace:]
+ try:
+ parsed = json.loads(blob)
+ except json.JSONDecodeError:
+ # 容错:从后往前截断到最后一个 }
+ end = blob.rfind("}")
+ while end > 0:
+ try:
+ parsed = json.loads(blob[: end + 1])
+ break
+ except json.JSONDecodeError:
+ end = blob.rfind("}", 0, end)
+ else:
+ return None
+ return parsed if isinstance(parsed, dict) else None
+
+
+def _files_from_user_message_text(text: str) -> list[dict[str, str]]:
+ """从单条 user 消息文本解析附件元数据。"""
+ if not text:
+ return []
+
+ payload = _parse_user_prompt_payload(text)
+ if isinstance(payload, dict):
+ for key in ("files_updated_by_user", "files"):
+ files = _coerce_upload_file_entries(payload.get(key))
+ if files:
+ return files
+
+ urls = _HTTP_URL_RE.findall(text)
+ if urls:
+ preferred = [
+ u for u in urls
+ if _SPRING_ESSAY_SOURCE in u or "sandbox_path" in u or u.lower().endswith(".md")
+ ]
+ chosen = preferred[0] if preferred else urls[0]
+ name = Path(chosen.split("?", 1)[0]).name or _SPRING_ESSAY_SOURCE
+ if "%" in name:
+ name = unquote(name)
+ return [{"name": name, "url": chosen, "path": ""}]
+
+ return []
+
+
+def _extract_uploaded_files(messages: list[Any]) -> list[dict[str, str]]:
+ """从 user 消息提取上传附件(扫描全部 user,不仅最新一条 re-append)。"""
+ for idx in range(len(messages) - 1, -1, -1):
+ message = messages[idx]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ text = _message_text(message)
+ if _is_skill_rail_injection(text):
+ continue
+ files = _files_from_user_message_text(text)
+ if files:
+ return files
+ return []
+
+
+def _pick_upload_file(messages: list[Any]) -> dict[str, str]:
+ files = _extract_uploaded_files(messages)
+ for item in files:
+ if _SPRING_ESSAY_SOURCE in item.get("name", "") or _SPRING_ESSAY_SOURCE in item.get("path", ""):
+ return item
+ if files:
+ return files[0]
+ return {"name": _SPRING_ESSAY_SOURCE, "url": "", "path": ""}
+
+
+def _build_heredoc_write_bash(filename: str, content: str) -> str:
+ """在工作区写入 Mock 原文(无 url/path 时兜底,确保 read_file 有文件可读)。
+
+ heredoc 结束行后不能接 &&(bash -c 会报 syntax error),改用换行分隔命令。
+ """
+ delimiter = "MOCK_ESSAY_EOF"
+ while delimiter in content:
+ delimiter += "_"
+ return (
+ f"cat > {_shell_single_quote(filename)} << '{delimiter}'\n"
+ f"{content}\n"
+ f"{delimiter}\n"
+ f"ls -la {_shell_single_quote(filename)} "
+ f"&& wc -c {_shell_single_quote(filename)}"
+ )
+
+
+def _build_file_download_bash(upload: dict[str, str]) -> str:
+ """企业版附件需先 curl 下载到工作区,再 read_file。"""
+ name = upload.get("name") or _SPRING_ESSAY_SOURCE
+ url = upload.get("url") or ""
+ path = upload.get("path") or ""
+ if url:
+ return (
+ f"curl -fsSL -o {_shell_single_quote(name)} {_shell_single_quote(url)} "
+ f"&& ls -la {_shell_single_quote(name)} "
+ f"&& wc -c {_shell_single_quote(name)}"
+ )
+ if path and _is_absolute_path(path):
+ return (
+ f"cp {_shell_single_quote(path)} {_shell_single_quote(name)} "
+ f"&& ls -la {_shell_single_quote(name)} "
+ f"&& wc -c {_shell_single_quote(name)}"
+ )
+ # 兜底:写入 Mock 原文到当前工作区(避免 find 找不到文件导致 read_file 404)
+ return _build_heredoc_write_bash(name, _load_spring_essay_source())
+
+
+def _resolve_spring_local_read_path(messages: list[Any], upload: dict[str, str]) -> str:
+ """read_file 使用的本地路径:优先绝对 path,否则用下载/写入后的文件名。"""
+ path = upload.get("path") or ""
+ if path and _is_absolute_path(path):
+ return path
+ resolved = _resolve_spring_source_path(messages)
+ if _is_absolute_path(resolved):
+ return resolved
+ name = upload.get("name") or _SPRING_ESSAY_SOURCE
+ return name
+
+
+def _load_spring_essay_source() -> str:
+ try:
+ return _SPRING_ESSAY_SOURCE_PATH.read_text(encoding="utf-8")
+ except OSError:
+ return (
+ "# 童趣的春天\n\n"
+ "春天,是童年记忆中最温柔的序曲。每当春风拂过脸颊,"
+ "我便仿佛又回到了那个充满好奇与惊喜的童年时光。"
+ )
+
+
+def _build_spring_essay_expanded(*, target_chars: int = _SPRING_ESSAY_TARGET_CHARS) -> str:
+ source = _load_spring_essay_source()
+ body = source.split("---", 1)[0].strip()
+ parts = [body]
+ section_idx = 0
+ while len("".join(parts)) < target_chars:
+ parts.append(_SPRING_EXPANSION_SECTIONS[section_idx % len(_SPRING_EXPANSION_SECTIONS)])
+ section_idx += 1
+ text = "\n\n".join(parts)
+ footer = (
+ f"\n\n---\n**字数统计**:约{target_chars}字\n"
+ f"**主题**:童趣的春天(扩写版)\n"
+ "**说明**:Mock Agent 自动扩写生成"
+ )
+ return text + footer
+
+
+def _resolve_spring_source_path(messages: list[Any]) -> str:
+ for message in reversed(messages):
+ if not isinstance(message, dict):
+ continue
+ text = _tool_message_text(message) if message.get("role") == "tool" else _message_text(message)
+ path = _parse_file_path_from_tool_blob(text, _SPRING_ESSAY_SOURCE)
+ if path:
+ return path
+ for args in reversed(_assistant_tool_call_args(messages, "read_file")):
+ path = args.get("file_path") or args.get("path")
+ if isinstance(path, str) and path and _SPRING_ESSAY_SOURCE in path:
+ return path
+ return _SPRING_ESSAY_SOURCE
+
+
+def _resolve_spring_output_path(messages: list[Any]) -> str:
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ path = _parse_file_path_from_tool_blob(_tool_message_text(message), _SPRING_ESSAY_OUTPUT)
+ if path:
+ return path
+ for args in reversed(_assistant_tool_call_args(messages, "write_file")):
+ path = args.get("file_path") or args.get("path")
+ if isinstance(path, str) and path and _SPRING_ESSAY_OUTPUT in path:
+ return path
+ return _SPRING_ESSAY_OUTPUT
+
+
+def _todo_modify_complete_args(
+ messages: list[Any],
+ task_index: int,
+ *,
+ fallback_contents: tuple[str, ...] | None = None,
+) -> dict[str, Any]:
+ """只更新 status=completed,不改写 content,避免错误解析污染任务文案。"""
+ todos = _parse_todo_items(messages)
+ todo_id: str | None = None
+ if fallback_contents and 0 <= task_index < len(fallback_contents):
+ want = fallback_contents[task_index]
+ for tid, content in todos:
+ if content == want or content.startswith(want) or want in content:
+ todo_id = tid
+ break
+ if todo_id is None and 0 <= task_index < len(todos):
+ todo_id = todos[task_index][0]
+ elif todo_id is None and todos:
+ todo_id = todos[min(task_index, len(todos) - 1)][0]
+ if not todo_id:
+ todo_id = "mock-todo-1"
+ return {
+ "action": "update",
+ "todos": [
+ {
+ "id": todo_id,
+ "status": "completed",
+ }
+ ],
+ }
+
+
+@dataclass
+class _AgentPlan:
+ kind: str
+ text: str | None = None
+ tool_name: str | None = None
+ tool_args: dict[str, Any] | None = None
+
+
+def _plan_travel_flow_response(
+ payload: dict[str, Any],
+ *,
+ stage: int,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> _AgentPlan:
+ """小说《旅行的意义》场景:todo → stream → bash → write → read → todo×5 → send → 收尾。"""
+ messages = _agent_messages(payload)
+ opening = _build_travel_opening_text(min(excerpt_chars, novel_chars))
+ file_body = _build_travel_novel_file_text(min(novel_chars, LOADTEST_WRITE_MAX_CHARS))
+
+ if stage == 0:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_INTRO_PLAN,
+ tool_name="todo_create",
+ tool_args={"tasks": _TODO_TASKS},
+ )
+ if stage == 1:
+ return _AgentPlan(kind="stream_text", text=opening)
+ if stage == 2:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_INTRO_PERMISSION_BASH,
+ tool_name="bash",
+ tool_args={"command": _PERMISSION_PROBE_BASH},
+ )
+ if stage == 3:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="权限已确认。现在把开篇写入工作区文件:\n",
+ tool_name="write_file",
+ tool_args={"file_path": _NOVEL_FILENAME, "content": file_body},
+ )
+ if stage == 4:
+ path = _resolve_novel_file_path(messages)
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="让我检查一下当前文件的内容:\n",
+ tool_name="read_file",
+ tool_args={"file_path": path},
+ )
+ if stage == 5:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_INTRO_PERMISSION_TODO_MODIFY,
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(
+ messages, 0, fallback_contents=_TODO_CONTENTS
+ ),
+ )
+ if stage == 6:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="权限已确认。现在继续更新任务状态并完善人物介绍:\n" + _CHARACTER_INTRO,
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(
+ messages, 1, fallback_contents=_TODO_CONTENTS
+ ),
+ )
+ if stage == 7:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="人物介绍已完善,标记「故事背景设定」完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(
+ messages, 2, fallback_contents=_TODO_CONTENTS
+ ),
+ )
+ if stage == 8:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="背景设定已就绪,标记「故事冲突与悬念设置」完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(
+ messages, 3, fallback_contents=_TODO_CONTENTS
+ ),
+ )
+ if stage == 9:
+ path = _resolve_novel_file_path(messages)
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="现在让我完成最后一个任务,将文件发送给你:\n",
+ tool_name="send_file_to_user",
+ tool_args={"abs_file_path_list": [path]},
+ )
+ if stage == 10:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="文件已发送,标记「整理并发送开篇文件」完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(
+ messages, 4, fallback_contents=_TODO_CONTENTS
+ ),
+ )
+ return _AgentPlan(kind="stream_text", text=_NOVEL_FINAL_MESSAGE)
+
+
+def _resolve_beijing_guide_path(messages: list[Any]) -> str:
+ """从 write_file / tool 结果解析攻略绝对路径,供 send_file_to_user 使用。"""
+ for message in reversed(messages):
+ if not isinstance(message, dict) or message.get("role") != "tool":
+ continue
+ path = _parse_file_path_from_tool_blob(_tool_message_text(message), _BEIJING_GUIDE_FILENAME)
+ if path:
+ return path
+ for args in reversed(_assistant_tool_call_args(messages, "write_file")):
+ path = args.get("file_path") or args.get("path")
+ if isinstance(path, str) and path and _BEIJING_GUIDE_FILENAME in path:
+ return path
+ return _BEIJING_GUIDE_FILENAME
+
+
+def _plan_scheduled_task_flow_response(
+ payload: dict[str, Any],
+ *,
+ stage: int,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> _AgentPlan:
+ """定时任务场景:调用 cron_create_job 创建一次性延迟任务 → 返回确认消息。"""
+ _ = payload, novel_chars, excerpt_chars
+ if stage == 0:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_CRON_INTRO,
+ tool_name="cron_create_job",
+ tool_args=_CRON_JOB_ARGS,
+ )
+ return _AgentPlan(kind="stream_text", text=_CRON_DONE_MESSAGE)
+
+
+def _plan_cron_delivery_response(
+ payload: dict[str, Any],
+ *,
+ stage: int,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> _AgentPlan:
+ """定时任务到点:仅返回一句喝水提醒,不触发 travel / 通用 mock。"""
+ _ = payload, stage, novel_chars, excerpt_chars
+ return _AgentPlan(kind="stream_text", text=_CRON_DELIVERY_MESSAGE)
+
+
+def _plan_skill_flow_response(
+ payload: dict[str, Any],
+ *,
+ stage: int,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> _AgentPlan:
+ """技能场景:install_skill → skill_tool → skill_step → 搜索 → write_file → skill_complete。"""
+ _ = novel_chars, excerpt_chars
+ messages = _agent_messages(payload)
+
+ if stage == 0:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_INTRO,
+ tool_name="install_skill",
+ tool_args=_SKILL_INSTALL_ARGS_SHORT,
+ )
+ if stage == 1:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_INSTALL_RETRY_INTRO,
+ tool_name="install_skill",
+ tool_args=_SKILL_INSTALL_ARGS_FULL,
+ )
+ if stage == 2:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="技能安装成功!现在让我加载这个技能的 SKILL.md 来了解如何使用它:\n",
+ tool_name="skill_tool",
+ tool_args={"skill_name": _SKILL_NAME, "relative_file_path": "SKILL.md"},
+ )
+ if stage == 3:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_AFTER_LOAD_INTRO,
+ tool_name="skill_step",
+ tool_args={"action": "create", "tasks": _SKILL_STEP_TASKS},
+ )
+ if stage == 4:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="接下来为北京3日游攻略创建新的任务清单:\n",
+ tool_name="todo_create",
+ tool_args={"tasks": _SKILL_TODO_TASKS, "force": True},
+ )
+ if stage == 5:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_AFTER_PLAN_INTRO,
+ tool_name="free_search",
+ tool_args={"query": "北京3日游攻略 故宫 颐和园 长城 2026"},
+ )
+ if stage == 6:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="让我抓取详细内容来获取景点信息:\n",
+ tool_name="fetch_webpage",
+ tool_args={"url": "https://www.zhihu.com/question/beijing-travel-guide"},
+ )
+ if stage == 7:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="很好!已获取故宫和颐和园的详细信息。让我继续搜索天气、美食和交通信息:\n",
+ tool_name="free_search",
+ tool_args={"query": "北京7月天气预报 旅游穿衣 美食推荐"},
+ )
+ if stage == 8:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_AFTER_SEARCH_INTRO,
+ tool_name="skill_step",
+ tool_args={
+ "action": "complete_batch",
+ "indices": [1, 2, 3],
+ "results": ["北京坐标已确认", "天气预报已获取", "景点信息已收集"],
+ },
+ )
+ if stage == 9:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="信息收集完成。先把「安装旅游规划技能」标记为完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(messages, 0, fallback_contents=_SKILL_TODO_CONTENTS),
+ )
+ if stage == 10:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="继续更新任务状态,标记「收集北京旅游信息」已完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(messages, 1, fallback_contents=_SKILL_TODO_CONTENTS),
+ )
+ if stage == 11:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_BEFORE_WRITE_INTRO,
+ tool_name="write_file",
+ tool_args={
+ "file_path": _BEIJING_GUIDE_FILENAME,
+ "content": _load_beijing_guide_content(),
+ },
+ )
+ if stage == 12:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_AFTER_WRITE_INTRO,
+ tool_name="skill_step",
+ tool_args={
+ "action": "complete_batch",
+ "indices": [4, 5],
+ "results": ["3日行程已规划", "攻略文档已生成"],
+ },
+ )
+ if stage == 13:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="攻略文档已写好,标记「生成北京3日游攻略」完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(messages, 2, fallback_contents=_SKILL_TODO_CONTENTS),
+ )
+ if stage == 14:
+ guide_path = _resolve_beijing_guide_path(messages)
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_BEFORE_SEND_INTRO,
+ tool_name="send_file_to_user",
+ tool_args={"abs_file_path_list": [guide_path]},
+ )
+ if stage == 15:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="文件已发送,标记「交付攻略文档」完成:\n",
+ tool_name="todo_modify",
+ tool_args=_todo_modify_complete_args(messages, 3, fallback_contents=_SKILL_TODO_CONTENTS),
+ )
+ if stage == 16:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text=_SKILL_BEFORE_COMPLETE_INTRO,
+ tool_name="skill_complete",
+ tool_args={"skill_name": _SKILL_NAME},
+ )
+ return _AgentPlan(kind="stream_text", text=_SKILL_DONE_MESSAGE)
+
+
+def _plan_file_flow_response(
+ payload: dict[str, Any],
+ *,
+ stage: int,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> _AgentPlan:
+ """文件扩写场景:bash(下载/确认) → read_file → write_file → send_file_to_user → 确认消息。"""
+ _ = novel_chars, excerpt_chars
+ messages = _agent_messages(payload)
+ upload = _pick_upload_file(messages)
+ source_path = _resolve_spring_local_read_path(messages, upload)
+ output_path = _resolve_spring_output_path(messages)
+ if output_path == _SPRING_ESSAY_OUTPUT:
+ # 与源文件同目录写出扩写版,便于 send_file_to_user
+ src_parent = Path(source_path).parent if _is_absolute_path(source_path) else None
+ if src_parent is not None and str(src_parent) not in {".", ""}:
+ output_path = str(src_parent / _SPRING_ESSAY_OUTPUT)
+ expanded_body = _build_spring_essay_expanded(target_chars=_SPRING_ESSAY_TARGET_CHARS)
+
+ if stage == 0:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="我先把上传的作文下载到工作区并确认文件:\n",
+ tool_name="bash",
+ tool_args={"command": _build_file_download_bash(upload)},
+ )
+ if stage == 1:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="接下来读取原文内容:\n",
+ tool_name="read_file",
+ tool_args={"file_path": source_path},
+ )
+ if stage == 2:
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="正在把作文扩写到约 6000 字并写入文件:\n",
+ tool_name="write_file",
+ tool_args={"file_path": output_path, "content": expanded_body},
+ )
+ if stage == 3:
+ send_path = _resolve_spring_output_path(messages)
+ if send_path == _SPRING_ESSAY_OUTPUT and output_path != _SPRING_ESSAY_OUTPUT:
+ send_path = output_path
+ return _AgentPlan(
+ kind="intro_and_tool_call",
+ text="扩写完成,现在把文件发回给你:\n",
+ tool_name="send_file_to_user",
+ tool_args={"abs_file_path_list": [send_path]},
+ )
+ return _AgentPlan(kind="stream_text", text=_FILE_DONE_MESSAGE)
+
+
+_SCENARIO_PLANNERS: dict[str, Any] = {
+ MockScenario.TRAVEL: _plan_travel_flow_response,
+ MockScenario.SCHEDULED_TASK: _plan_scheduled_task_flow_response,
+ MockScenario.CRON_DELIVERY: _plan_cron_delivery_response,
+ MockScenario.SKILL: _plan_skill_flow_response,
+ MockScenario.FILE: _plan_file_flow_response,
+}
+
+
+def _plan_loadtest_response(
+ payload: dict[str, Any],
+ *,
+ novel_chars: int,
+ excerpt_chars: int,
+) -> tuple[_AgentPlan, str, int]:
+ """按场景分发 Mock 响应计划,返回 (plan, scenario, stage)。"""
+ if _is_session_memory_request(payload):
+ return _plan_session_memory_response(payload), MockScenario.TRAVEL, 0
+
+ if _is_cron_wake_message(payload):
+ plan = _plan_cron_delivery_response(
+ payload,
+ stage=0,
+ novel_chars=novel_chars,
+ excerpt_chars=excerpt_chars,
+ )
+ return plan, MockScenario.CRON_DELIVERY, 0
+
+ routed_scenario = _detect_loadtest_scenario(payload)
+ key, stage, scenario = _prepare_loadtest_state(payload, routed_scenario)
+ planner = _SCENARIO_PLANNERS.get(scenario, _plan_travel_flow_response)
+ plan = planner(
+ payload,
+ stage=stage,
+ novel_chars=novel_chars,
+ excerpt_chars=excerpt_chars,
+ )
+ _advance_loadtest_state(key, scenario, stage, payload)
+ return plan, scenario, stage
+
+
+def _mock_usage(*, completion_chars: int, prompt_tokens: int = 10) -> dict[str, int]:
+ """与 OpenAI usage 字段对齐,供 AgentServer 汇总为 chat.usage_summary。"""
+ prompt = max(1, prompt_tokens)
+ completion = max(20, completion_chars // 4)
+ return {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": prompt + completion,
+ }
+
+
+async def _write_sse_headers(writer: asyncio.StreamWriter) -> None:
+ headers = (
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/event-stream\r\n"
+ "Cache-Control: no-cache\r\n"
+ "Connection: close\r\n"
+ "\r\n"
+ )
+ writer.write(headers.encode("utf-8"))
+ await writer.drain()
+
+
+async def _write_sse_finish(
+ writer: asyncio.StreamWriter,
+ model: str,
+ *,
+ finish_reason: str = "stop",
+ completion_chars: int = 0,
+ prompt_tokens: int = 10,
+) -> None:
+ usage = _mock_usage(completion_chars=completion_chars, prompt_tokens=prompt_tokens)
+ final_chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {},
+ "finish_reason": finish_reason,
+ }
+ ],
+ "usage": usage,
+ }
+ writer.write(_sse_event(final_chunk))
+ await writer.drain()
+ # stream_options.include_usage 风格:额外发一帧仅含 usage 的 chunk,便于 SDK 聚合。
+ usage_only_chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [],
+ "usage": usage,
+ }
+ writer.write(_sse_event(usage_only_chunk))
+ writer.write(_sse_event("[DONE]"))
+ await writer.drain()
+
+
+async def _stream_text_content(
+ writer: asyncio.StreamWriter,
+ model: str,
+ text: str,
+ *,
+ chunk_chars: int,
+ token_interval_s: float,
+ log_label: str = "content",
+) -> None:
+ await _write_sse_headers(writer)
+ total_chunks = max(1, (len(text) + chunk_chars - 1) // chunk_chars)
+ for offset in range(0, len(text), chunk_chars):
+ piece = text[offset:offset + chunk_chars]
+ chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"content": piece},
+ "finish_reason": None,
+ }
+ ],
+ }
+ writer.write(_sse_event(chunk))
+ await writer.drain()
+ chunk_no = offset // chunk_chars + 1
+ if chunk_no == 1 or chunk_no == total_chunks or chunk_no % 40 == 0:
+ logger.info(
+ "Streamed %s chunk %d/%d (%d chars, total=%d)",
+ log_label,
+ chunk_no,
+ total_chunks,
+ len(piece),
+ len(text),
+ )
+ if chunk_no < total_chunks and token_interval_s > 0:
+ await asyncio.sleep(token_interval_s)
+ await _write_sse_finish(writer, model, finish_reason="stop", completion_chars=len(text))
+
+
+async def _emit_tool_call_sse(
+ writer: asyncio.StreamWriter,
+ model: str,
+ tool_name: str,
+ tool_args: dict[str, Any],
+ *,
+ token_interval_s: float,
+) -> str:
+ call_id = f"call_mock_{secrets.token_hex(12)}"
+ tool_args_json = json.dumps(tool_args, ensure_ascii=False)
+
+ first = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": call_id,
+ "type": "function",
+ "function": {"name": tool_name, "arguments": ""},
+ }
+ ]
+ },
+ "finish_reason": None,
+ }
+ ],
+ }
+ writer.write(_sse_event(first))
+ await writer.drain()
+
+ arg_step = 96
+ for offset in range(0, len(tool_args_json), arg_step):
+ piece = tool_args_json[offset:offset + arg_step]
+ chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"arguments": piece},
+ }
+ ]
+ },
+ "finish_reason": None,
+ }
+ ],
+ }
+ writer.write(_sse_event(chunk))
+ await writer.drain()
+ if token_interval_s > 0:
+ await asyncio.sleep(token_interval_s)
+
+ logger.info(
+ "Streamed tool_call name=%s args_len=%d call_id=%s",
+ tool_name,
+ len(tool_args_json),
+ call_id,
+ )
+ return call_id
+
+
+async def _stream_tool_call(
+ writer: asyncio.StreamWriter,
+ model: str,
+ tool_name: str,
+ tool_args: dict[str, Any],
+ *,
+ token_interval_s: float,
+) -> None:
+ await _write_sse_headers(writer)
+ await _emit_tool_call_sse(
+ writer,
+ model,
+ tool_name,
+ tool_args,
+ token_interval_s=token_interval_s,
+ )
+ await _write_sse_finish(
+ writer,
+ model,
+ finish_reason="tool_calls",
+ completion_chars=len(tool_name) + len(json.dumps(tool_args, ensure_ascii=False)),
+ )
+
+
+async def _stream_content_and_tool_call(
+ writer: asyncio.StreamWriter,
+ model: str,
+ intro: str,
+ tool_name: str,
+ tool_args: dict[str, Any],
+ *,
+ chunk_chars: int,
+ token_interval_s: float,
+) -> None:
+ await _write_sse_headers(writer)
+ total_chunks = max(1, (len(intro) + chunk_chars - 1) // chunk_chars)
+ for offset in range(0, len(intro), chunk_chars):
+ piece = intro[offset:offset + chunk_chars]
+ chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"content": piece},
+ "finish_reason": None,
+ }
+ ],
+ }
+ writer.write(_sse_event(chunk))
+ await writer.drain()
+ if offset // chunk_chars + 1 < total_chunks and token_interval_s > 0:
+ await asyncio.sleep(token_interval_s)
+ await _emit_tool_call_sse(
+ writer,
+ model,
+ tool_name,
+ tool_args,
+ token_interval_s=token_interval_s,
+ )
+ tool_args_json = json.dumps(tool_args, ensure_ascii=False)
+ await _write_sse_finish(
+ writer,
+ model,
+ finish_reason="tool_calls",
+ completion_chars=len(intro) + len(tool_name) + len(tool_args_json),
+ )
+
+
+async def _stream_chat_completion(
+ writer: asyncio.StreamWriter,
+ model: str,
+ *,
+ token_count: int,
+ token_interval_s: float,
+ text: str | None = None,
+ chunk_chars: int = LOADTEST_STREAM_CHUNK_CHARS,
+) -> None:
+ if text is not None:
+ await _stream_text_content(
+ writer,
+ model,
+ text,
+ chunk_chars=max(32, chunk_chars),
+ token_interval_s=token_interval_s,
+ log_label="novel",
+ )
+ return
+
+ await _write_sse_headers(writer)
+ completion_chars = 0
+ for i in range(1, token_count + 1):
+ token = f"mock token{i}"
+ completion_chars += len(token)
+ chunk = {
+ "id": "mock-chatcmpl-stream",
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"content": token},
+ "finish_reason": None,
+ }
+ ],
+ }
+ writer.write(_sse_event(chunk))
+ await writer.drain()
+ logger.info("Streamed token: %s", token)
+ if i < token_count and token_interval_s > 0:
+ await asyncio.sleep(token_interval_s)
+ await _write_sse_finish(
+ writer,
+ model,
+ finish_reason="stop",
+ completion_chars=completion_chars,
+ )
+
+
+def _non_stream_completion(
+ model: str,
+ *,
+ content: str | None = None,
+ tool_call: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ message: dict[str, Any] = {"role": "assistant", "content": content}
+ finish_reason = "stop"
+ if tool_call is not None:
+ message["tool_calls"] = [tool_call]
+ message["content"] = content
+ finish_reason = "tool_calls"
+ completion_chars = len(content or "")
+ if tool_call is not None:
+ fn = tool_call.get("function") if isinstance(tool_call.get("function"), dict) else {}
+ completion_chars += len(str(fn.get("name") or "")) + len(str(fn.get("arguments") or ""))
+ return {
+ "id": "mock-chatcmpl-123",
+ "object": "chat.completion",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "message": message,
+ "finish_reason": finish_reason,
+ }
+ ],
+ "usage": _mock_usage(completion_chars=completion_chars),
+ }
+
+
+async def _handle_request(
+ reader: asyncio.StreamReader,
+ writer: asyncio.StreamWriter,
+ *,
+ token_count: int,
+ token_interval_s: float,
+ stats: _RequestStats,
+ profile: str,
+ novel_chars: int,
+ chunk_chars: int,
+ excerpt_chars: int,
+) -> None:
+ stream = False
+ try:
+ method, path, headers, payload = await _read_http_request(reader)
+ stream = _wants_stream(headers, payload)
+ await stats.begin(stream=stream)
+ logger.info(
+ "Request: %s %s stream=%s body_bytes=%s accept=%s",
+ method,
+ path,
+ payload.get("stream"),
+ headers.get("content-length", "?"),
+ headers.get("accept", ""),
+ )
+
+ if method == "GET" and path == "/health":
+ body = json.dumps({"status": "ok"})
+ writer.write(_http_response(200, body))
+ await writer.drain()
+ return
+
+ if method == "GET" and path.rstrip("/") == "/v1/models":
+ writer.write(_http_response(200, _models_payload()))
+ await writer.drain()
+ return
+
+ if method == "POST" and path.rstrip("/") == "/v1/chat/completions":
+ model = str(payload.get("model") or "mock-model")
+ use_loadtest = _should_use_novel_scenario(profile, payload)
+ if use_loadtest:
+ plan, scenario, stage = _plan_loadtest_response(
+ payload,
+ novel_chars=novel_chars,
+ excerpt_chars=excerpt_chars,
+ )
+ if _is_session_memory_request(payload):
+ logger.info(
+ "Session memory scenario kind=%s tool=%s notes_path=%s",
+ plan.kind,
+ plan.tool_name,
+ _parse_session_memory_notes_path(payload.get("messages") or []),
+ )
+ else:
+ logger.info(
+ "Agent loadtest scenario=%s kind=%s stage=%d novel_chars=%d excerpt_chars=%d",
+ scenario,
+ plan.kind,
+ stage,
+ novel_chars,
+ excerpt_chars,
+ )
+ if stream:
+ if (
+ plan.kind == "intro_and_tool_call"
+ and plan.tool_name
+ and plan.tool_args is not None
+ ):
+ await _stream_content_and_tool_call(
+ writer,
+ model,
+ plan.text or "",
+ plan.tool_name,
+ plan.tool_args,
+ chunk_chars=chunk_chars,
+ token_interval_s=token_interval_s,
+ )
+ elif plan.kind == "tool_call" and plan.tool_name and plan.tool_args is not None:
+ await _stream_tool_call(
+ writer,
+ model,
+ plan.tool_name,
+ plan.tool_args,
+ token_interval_s=token_interval_s,
+ )
+ else:
+ await _stream_chat_completion(
+ writer,
+ model,
+ token_count=token_count,
+ token_interval_s=token_interval_s,
+ text=plan.text or _NOVEL_FINAL_MESSAGE,
+ chunk_chars=chunk_chars,
+ )
+ return
+
+ if (
+ plan.kind in {"tool_call", "intro_and_tool_call"}
+ and plan.tool_name
+ and plan.tool_args is not None
+ ):
+ tool_call = {
+ "id": f"call_mock_{secrets.token_hex(12)}",
+ "type": "function",
+ "function": {
+ "name": plan.tool_name,
+ "arguments": json.dumps(plan.tool_args, ensure_ascii=False),
+ },
+ }
+ response = _non_stream_completion(model, content=plan.text, tool_call=tool_call)
+ else:
+ response = _non_stream_completion(model, content=plan.text or _NOVEL_FINAL_MESSAGE)
+ body = json.dumps(response, ensure_ascii=False)
+ writer.write(_http_response(200, body))
+ await writer.drain()
+ return
+
+ if stream:
+ logger.info(
+ "Generic mock tokens (profile=%s, use --profile loadtest for novel scenario)",
+ profile,
+ )
+ await _stream_chat_completion(
+ writer,
+ model,
+ token_count=token_count,
+ token_interval_s=token_interval_s,
+ )
+ return
+
+ content = " ".join(f"mock token{i}" for i in range(1, token_count + 1))
+ logger.info("Non-stream response content: %s", content[:120])
+ response = _non_stream_completion(model, content=content)
+ body = json.dumps(response, ensure_ascii=False)
+ writer.write(_http_response(200, body))
+ await writer.drain()
+ return
+
+ writer.write(_http_response(404, json.dumps({"error": "not found"})))
+ await writer.drain()
+ except Exception as exc:
+ logger.exception("Error handling request: %s", exc)
+ writer.write(_http_response(500, json.dumps({"error": str(exc)})))
+ await writer.drain()
+ finally:
+ await stats.end()
+ writer.close()
+ await writer.wait_closed()
+
+
+async def _stats_loop(stats: _RequestStats, interval_s: float) -> None:
+ while True:
+ await asyncio.sleep(interval_s)
+ active, total, stream_total = await stats.snapshot()
+ logger.info(
+ "[stats] active=%d total=%d stream_total=%d",
+ active,
+ total,
+ stream_total,
+ )
+
+
+def _configure_logging() -> None:
+ class _TimestampFormatter(logging.Formatter):
+ def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:
+ from datetime import datetime
+
+ dt = datetime.fromtimestamp(record.created)
+ base = dt.strftime(datefmt or "%Y-%m-%d %H:%M:%S")
+ return f"{base}.{int(record.msecs):03d}"
+
+ root = logging.getLogger()
+ root.handlers.clear()
+ root.setLevel(logging.INFO)
+ handler = logging.StreamHandler(sys.stdout)
+ handler.setFormatter(_TimestampFormatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
+ root.addHandler(handler)
+
+
+def _argv_has(flag: str) -> bool:
+ return flag in sys.argv
+
+
+def _env_int(name: str) -> int | None:
+ raw = os.environ.get(name, "").strip()
+ if not raw:
+ return None
+ try:
+ return int(raw)
+ except ValueError as exc:
+ raise ValueError(f"{name} 须为整数,当前={raw!r}") from exc
+
+
+def _env_float(name: str) -> float | None:
+ raw = os.environ.get(name, "").strip()
+ if not raw:
+ return None
+ try:
+ return float(raw)
+ except ValueError as exc:
+ raise ValueError(f"{name} 须为数字,当前={raw!r}") from exc
+
+
+def _resolve_stream_params(args: argparse.Namespace) -> tuple[int, float]:
+ """token 数 / 间隔:CLI > 环境变量 > profile 默认(e2e=20/2s,loadtest=5/0.05s)。"""
+ if _argv_has("--stream-token-count"):
+ token_count = args.stream_token_count
+ else:
+ env_count = _env_int("MOCK_LLM_STREAM_TOKEN_COUNT")
+ if env_count is not None:
+ token_count = env_count
+ elif args.profile == "loadtest":
+ token_count = LOADTEST_STREAM_TOKEN_COUNT
+ else:
+ token_count = DEFAULT_STREAM_TOKEN_COUNT
+
+ if _argv_has("--stream-token-interval"):
+ token_interval = args.stream_token_interval
+ else:
+ env_interval = _env_float("MOCK_LLM_STREAM_TOKEN_INTERVAL")
+ if env_interval is not None:
+ token_interval = env_interval
+ elif args.profile == "loadtest":
+ token_interval = LOADTEST_STREAM_TOKEN_INTERVAL_S
+ else:
+ token_interval = DEFAULT_STREAM_TOKEN_INTERVAL_S
+
+ return max(1, token_count), max(0.0, token_interval)
+
+
+async def main(
+ host: str,
+ port: int,
+ *,
+ token_count: int,
+ token_interval_s: float,
+ stats_interval_s: float,
+ profile: str,
+ novel_chars: int,
+ chunk_chars: int,
+ excerpt_chars: int,
+) -> None:
+ stats = _RequestStats()
+ stats_task: asyncio.Task[None] | None = None
+ if stats_interval_s > 0:
+ stats_task = asyncio.create_task(_stats_loop(stats, stats_interval_s))
+
+ async def _handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ await _handle_request(
+ reader,
+ writer,
+ token_count=token_count,
+ token_interval_s=token_interval_s,
+ stats=stats,
+ profile=profile,
+ novel_chars=novel_chars,
+ chunk_chars=chunk_chars,
+ excerpt_chars=excerpt_chars,
+ )
+
+ server = await asyncio.start_server(_handler, host, port)
+ addr = server.sockets[0].getsockname()
+ logger.info(
+ "Mock LLM server listening on http://%s:%d (profile=%s tokens=%d interval=%ss novel_chars=%d chunk_chars=%d)",
+ addr[0],
+ addr[1],
+ profile,
+ token_count,
+ token_interval_s,
+ novel_chars,
+ chunk_chars,
+ )
+ if profile == "loadtest":
+ logger.info(
+ "loadtest profile active: per-session stage + done flag; "
+ "re-route after task done: intent/payload/sequence "
+ "(priority: cron_delivery>scheduled_task>skill>file>travel; skip prior completed scenarios)"
+ )
+ logger.info("Health: http://%s:%d/health", addr[0], addr[1])
+
+ stop_event = asyncio.Event()
+
+ def _request_stop(*_args: object) -> None:
+ stop_event.set()
+
+ loop = asyncio.get_running_loop()
+ for sig in (getattr(signal, "SIGINT", None), getattr(signal, "SIGTERM", None)):
+ if sig is None:
+ continue
+ try:
+ loop.add_signal_handler(sig, _request_stop)
+ except NotImplementedError:
+ signal.signal(sig, lambda *_a: _request_stop())
+
+ try:
+ async with server:
+ serve_task = asyncio.create_task(server.serve_forever())
+ await stop_event.wait()
+ server.close()
+ await server.wait_closed()
+ serve_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await serve_task
+ finally:
+ if stats_task is not None:
+ stats_task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await stats_task
+ active, total, stream_total = await stats.snapshot()
+ logger.info(
+ "[shutdown] active=%d total=%d stream_total=%d",
+ active,
+ total,
+ stream_total,
+ )
+
+
+def _parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="OpenAI 兼容 Mock LLM(Enterprise Runtime 压测 / E2E)",
+ )
+ parser.add_argument("--host", default="127.0.0.1", help="监听地址,压测对外服务可用 0.0.0.0")
+ parser.add_argument("--port", type=int, default=19999, help="HTTP 端口")
+ parser.add_argument(
+ "--profile",
+ choices=("e2e", "loadtest"),
+ default="e2e",
+ help="e2e: mock token;loadtest: 模拟 Agent 多工具小说创作(todo/write_file/read_file/send_file)",
+ )
+ parser.add_argument(
+ "--novel-chars",
+ type=int,
+ default=LOADTEST_NOVEL_CHARS,
+ help="loadtest 小说场景正文总字数(默认 32000,模拟长文而非真实十万字)",
+ )
+ parser.add_argument(
+ "--stream-chunk-chars",
+ type=int,
+ default=LOADTEST_STREAM_CHUNK_CHARS,
+ help="流式 SSE 每次输出的字符数(loadtest 小说场景)",
+ )
+ parser.add_argument(
+ "--chat-excerpt-chars",
+ type=int,
+ default=LOADTEST_CHAT_EXCERPT_CHARS,
+ help="loadtest 第 2 轮在聊天区展示的开篇章节字数(默认 6000)",
+ )
+ parser.add_argument(
+ "--stream-token-count",
+ type=int,
+ default=DEFAULT_STREAM_TOKEN_COUNT,
+ help=(
+ "e2e 固定 mock token 个数(mock token1..N)。"
+ "优先级:本参数 > 环境变量 MOCK_LLM_STREAM_TOKEN_COUNT > "
+ f"profile 默认(e2e={DEFAULT_STREAM_TOKEN_COUNT},loadtest={LOADTEST_STREAM_TOKEN_COUNT})"
+ ),
+ )
+ parser.add_argument(
+ "--stream-token-interval",
+ type=float,
+ default=DEFAULT_STREAM_TOKEN_INTERVAL_S,
+ help=(
+ "相邻 token 间隔(秒)。"
+ "优先级:本参数 > 环境变量 MOCK_LLM_STREAM_TOKEN_INTERVAL > "
+ f"profile 默认(e2e={DEFAULT_STREAM_TOKEN_INTERVAL_S},loadtest={LOADTEST_STREAM_TOKEN_INTERVAL_S})"
+ ),
+ )
+ parser.add_argument(
+ "--stats-interval",
+ type=float,
+ default=30.0,
+ help="周期性打印 [stats] 的间隔(秒);0 表示关闭",
+ )
+ return parser.parse_args()
+
+
+if __name__ == "__main__":
+ _configure_logging()
+ cli_args = _parse_args()
+ count, interval = _resolve_stream_params(cli_args)
+ try:
+ asyncio.run(
+ main(
+ cli_args.host,
+ cli_args.port,
+ token_count=count,
+ token_interval_s=interval,
+ stats_interval_s=max(0.0, cli_args.stats_interval),
+ profile=cli_args.profile,
+ novel_chars=max(1000, cli_args.novel_chars),
+ chunk_chars=max(32, cli_args.stream_chunk_chars),
+ excerpt_chars=max(200, cli_args.chat_excerpt_chars),
+ )
+ )
+ except KeyboardInterrupt:
+ pass
diff --git a/packages/jiuwenclaw-ee/claw_manager/scripts/single_pod_n_concurrency_test.py b/packages/jiuwenclaw-ee/claw_manager/scripts/single_pod_n_concurrency_test.py
new file mode 100644
index 0000000000..1a17d1925b
--- /dev/null
+++ b/packages/jiuwenclaw-ee/claw_manager/scripts/single_pod_n_concurrency_test.py
@@ -0,0 +1,462 @@
+#!/usr/bin/env python3
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""单 AgentServer Pod、N 路会话数据面压测。
+
+对齐 ``dev/enterprise_kub`` 的 WebChannel ``chat.send`` 压测方式,以及
+``single-pod-n-concurrency`` 规格的 SP-02 / SP-12 主路径:
+
+- 1 个 AgentServer(同一 ``group_id`` + 同一 ``bot_id``)
+- N 个不同 ``user_id``(``u_1_<run>`` … ``u_N_<run>``)→ N 个工作区
+- N 个不同 ``session_id``(``sess_1_<run>`` … ``sess_N_<run>``)→ N 个执行器
+- 齐发 N 路 ``chat.send``,断言每路被接受且对话跑完
+
+``session_id`` 用下划线 ``sess_*``,以便现成 Mock LLM 按会话拆状态;``<run>`` 默认每轮
+随机 8 位 hex,避免复用 MySQL checkpoint / 工作区导致 loadtest 被当成上一轮收尾。
+
+默认 ``--flow single``:每路一条短消息,配合 Mock LLM 验证功能是否正常。
+``--flow loadtest`` 时复用 ``enterprise_runtime_concurrent_test.py`` 的
+travel → skill → file → cron 四步(需 ``mock_llm_server.py --profile loadtest``)。
+
+典型用法(jiuwenswarm 仓库根目录)::
+
+ # 当前 mz 环境:Web NodePort 30086,N=8
+ .venv/bin/python packages/jiuwenclaw-ee/claw_manager/scripts/single_pod_n_concurrency_test.py \\
+ --host 192.168.1.90 --web-port 30086 --concurrency 8
+
+ # 完整四步 loadtest
+ .venv/bin/python packages/jiuwenclaw-ee/claw_manager/scripts/single_pod_n_concurrency_test.py \\
+ --ws-url ws://192.168.1.90:30086/ws --concurrency 8 --flow loadtest
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import importlib.util
+import logging
+import sys
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlparse
+
+_SCRIPT_DIR = Path(__file__).resolve().parent
+_CONCURRENT_SCRIPT = _SCRIPT_DIR / "enterprise_runtime_concurrent_test.py"
+_DOWNLOAD_DIR_PREFIX = _SCRIPT_DIR / "download"
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_SINGLE_CONTENT = "请只回复:mock-ok。不要调用任何工具,不要提问。"
+
+
+def _load_concurrent_mod():
+ spec = importlib.util.spec_from_file_location(
+ "enterprise_runtime_concurrent_test", _CONCURRENT_SCRIPT
+ )
+ if spec is None or spec.loader is None:
+ raise RuntimeError(f"无法加载 {_CONCURRENT_SCRIPT}")
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _resolve_run_id(run_id: str | None) -> str:
+ text = (run_id or "").strip()
+ if text:
+ return text
+ return uuid.uuid4().hex[:8]
+
+
+def build_identities(
+ concurrency: int,
+ *,
+ group_id: str,
+ bot_id: str,
+ user_prefix: str,
+ session_prefix: str,
+ run_id: str,
+) -> list[dict[str, Any]]:
+ """SP-02 身份:每路独立 user_id / session_id,共享 group_id / bot_id。
+
+ 使用 ``{prefix}_{i}_{run_id}``(下划线)。``sess_*`` 能被 Mock LLM 现有正则识别,
+ 每轮不同的 ``run_id`` 避免撞上上一轮 checkpoint。
+ """
+ if concurrency <= 0:
+ raise ValueError("--concurrency 须 > 0")
+ if not str(run_id).strip():
+ raise ValueError("run_id 不能为空")
+ suffix = str(run_id).strip()
+ return [
+ {
+ "index": i,
+ "group_id": group_id,
+ "bot_id": bot_id,
+ "user_id": f"{user_prefix}_{i}_{suffix}",
+ "session_id": f"{session_prefix}_{i}_{suffix}",
+ }
+ for i in range(1, concurrency + 1)
+ ]
+
+
+def _resolve_ws_url(args: argparse.Namespace) -> str:
+ if args.ws_url:
+ url = str(args.ws_url).strip()
+ parsed = urlparse(url)
+ if parsed.scheme not in ("ws", "wss"):
+ raise ValueError(f"--ws-url 须为 ws:// 或 wss://,当前 scheme={parsed.scheme!r}")
+ if not parsed.netloc:
+ raise ValueError(f"--ws-url 无效(缺少 host): {url!r}")
+ return url
+ return f"ws://{args.host}:{args.web_port}{args.ws_path}"
+
+
+def _browser_origin_header(ws_url: str) -> dict[str, str]:
+ """由 WebSocket URL 推导浏览器 Origin 头。"""
+ parsed = urlparse(ws_url)
+ host = parsed.hostname or "127.0.0.1"
+ http_scheme = "https" if parsed.scheme == "wss" else "http"
+ port = parsed.port
+ default_port = 443 if http_scheme == "https" else 80
+ if port is not None and port != default_port:
+ origin = f"{http_scheme}://{host}:{port}"
+ else:
+ origin = f"{http_scheme}://{host}"
+ return {"Origin": origin}
+
+
+def _configure_cli_logging() -> None:
+ class _TimestampFormatter(logging.Formatter):
+ def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:
+ from datetime import datetime
+
+ dt = datetime.fromtimestamp(record.created)
+ base = dt.strftime(datefmt or "%Y-%m-%d %H:%M:%S")
+ return f"{base}.{int(record.msecs):03d}"
+
+ root = logging.getLogger()
+ root.handlers.clear()
+ root.setLevel(logging.INFO)
+ fmt = _TimestampFormatter("%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
+ out = logging.StreamHandler(sys.stdout)
+ out.setLevel(logging.INFO)
+ out.setFormatter(fmt)
+ err = logging.StreamHandler(sys.stderr)
+ err.setLevel(logging.ERROR)
+ err.setFormatter(fmt)
+ root.addHandler(out)
+ root.addHandler(err)
+
+
+def _make_run_download_dir(*, when: time.struct_time | None = None) -> Path:
+ """生成本次压测专用下载目录:download_YYYYMMDD_HHMMSS。"""
+ stamp = time.strftime("%Y%m%d_%H%M%S", when or time.localtime())
+ return Path(f"{_DOWNLOAD_DIR_PREFIX}_{stamp}")
+
+
+def _parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser(
+ description="单 AgentServer Pod N 并发 chat.send(不同 user_id + session_id)",
+ )
+ p.add_argument("--host", default="192.168.1.90", help="Gateway / Web Node 地址")
+ p.add_argument("--web-port", type=int, default=30086, help="Web NodePort,默认 30086")
+ p.add_argument("--ws-path", default="/ws", help="WebSocket 路径,默认 /ws")
+ p.add_argument("--ws-url", help="完整 WebSocket URL,设置后忽略 --host/--web-port")
+ p.add_argument(
+ "--concurrency",
+ "-n",
+ type=int,
+ default=8,
+ metavar="N",
+ help="并发会话数,默认 8(每路一个 user_id + 一个 session_id)",
+ )
+ p.add_argument("--group-id", default="load-g", help="全员同一 group_id,默认 load-g")
+ p.add_argument(
+ "--bot-id",
+ default="bot_main",
+ help="全员同一 bot_id,默认 bot_main(须与 Manager 里已配置的智能体一致)",
+ )
+ p.add_argument(
+ "--user-prefix",
+ default="u",
+ help="user_id 形如 {prefix}_1_<run-id> … {prefix}_N_<run-id>",
+ )
+ p.add_argument(
+ "--session-prefix",
+ default="sess",
+ help="session_id 形如 {prefix}_1_<run-id> … {prefix}_N_<run-id>(须为 sess_ 以便 Mock 识别)",
+ )
+ p.add_argument(
+ "--run-id",
+ default="",
+ help="本轮身份后缀,默认自动生成 8 位 hex;显式传入可复现同一批 user/session",
+ )
+ p.add_argument(
+ "--flow",
+ choices=("single", "loadtest"),
+ default="single",
+ help="single:每路一条短消息(默认);loadtest:travel/skill/file/cron 四步",
+ )
+ p.add_argument(
+ "--content",
+ default=_DEFAULT_SINGLE_CONTENT,
+ help="--flow single 时的用户消息",
+ )
+ p.add_argument("--mode", default="agent.fast", help="运行模式,默认 agent.fast")
+ p.add_argument(
+ "--accept-timeout",
+ type=float,
+ default=60.0,
+ help="等待 chat.send 被接受的最长时间(秒)",
+ )
+ p.add_argument(
+ "--final-timeout",
+ type=float,
+ default=180.0,
+ help="--flow single 等待整轮完成的最长时间(秒),默认 180",
+ )
+ p.add_argument(
+ "--loadtest-final-timeout",
+ type=float,
+ default=7200.0,
+ help="--flow loadtest 等待整轮完成的最长时间(秒)",
+ )
+ p.add_argument(
+ "--cron-delivery-timeout",
+ type=float,
+ default=120.0,
+ help="loadtest cron 步等待到点投递的最长时间(秒)",
+ )
+ p.add_argument(
+ "--accept-only",
+ action="store_true",
+ help="只等 Gateway 接受,不等 Agent 跑完",
+ )
+ p.add_argument("--no-auto-allow", action="store_true", help="禁用权限弹窗自动放行")
+ p.add_argument("--ws-event-log", action="store_true", help="打印每路 WS event 名")
+ p.add_argument(
+ "--essay-file",
+ type=Path,
+ default=_SCRIPT_DIR / "童趣的春天.md",
+ help="loadtest 作文附件路径",
+ )
+ return p.parse_args()
+
+
+async def _run(args: argparse.Namespace) -> int:
+ mod = _load_concurrent_mod()
+ run_id = _resolve_run_id(args.run_id)
+ identities = build_identities(
+ args.concurrency,
+ group_id=args.group_id,
+ bot_id=args.bot_id,
+ user_prefix=args.user_prefix,
+ session_prefix=args.session_prefix,
+ run_id=run_id,
+ )
+ ws_url = _resolve_ws_url(args)
+ ws_headers = _browser_origin_header(ws_url)
+ final_timeout = (
+ args.loadtest_final_timeout if args.flow == "loadtest" else args.final_timeout
+ )
+
+ loadtest_steps = None
+ single_steps = None
+ if args.flow == "loadtest":
+ loadtest_steps = mod.build_default_loadtest_steps(args.essay_file)
+ else:
+ single_steps = (
+ mod.LoadTestStep(name="single", content=args.content, expect_file=False),
+ )
+
+ user_ids = [item["user_id"] for item in identities]
+ session_ids = [item["session_id"] for item in identities]
+ logger.info(
+ "[plan] ws=%s concurrency=%d flow=%s mode=%s",
+ ws_url,
+ args.concurrency,
+ args.flow,
+ args.mode,
+ )
+ logger.info(
+ "[plan] 五列口径: 会话=%d / Pod=1 / Bot=1 (%s) / 工作区=%d / 执行器=%d",
+ args.concurrency,
+ args.bot_id,
+ args.concurrency,
+ args.concurrency,
+ )
+ logger.info(
+ "[plan] run_id=%s group_id=%s bot_id=%s user_id=%s..%s session_id=%s..%s",
+ run_id,
+ args.group_id,
+ args.bot_id,
+ user_ids[0],
+ user_ids[-1],
+ session_ids[0],
+ session_ids[-1],
+ )
+ if args.flow == "single":
+ logger.info("[plan] content=%r", args.content)
+ else:
+ logger.info(
+ "[plan] loadtest steps=%s",
+ " -> ".join(step.name for step in loadtest_steps or ()),
+ )
+
+ progress = mod.ProgressTracker(total=args.concurrency)
+ registry = mod.ActiveSessionRegistry()
+ download_dir = None
+ if loadtest_steps and any(step.download_deliverable for step in loadtest_steps):
+ download_dir = _make_run_download_dir()
+ logger.info("[plan] download_dir=%s", download_dir)
+
+ t0 = time.perf_counter()
+ task_objs = [
+ asyncio.create_task(
+ mod.run_single_request(
+ ws_url=ws_url,
+ ws_headers=ws_headers,
+ index=item["index"] - 1,
+ shard=0,
+ shard2=0,
+ group_id=item["group_id"],
+ bot_id=item["bot_id"],
+ user_id=item["user_id"],
+ content=args.content,
+ mode=args.mode,
+ accept_timeout=args.accept_timeout,
+ accept_only=args.accept_only,
+ final_timeout=final_timeout,
+ cron_delivery_timeout=args.cron_delivery_timeout,
+ auto_allow=not args.no_auto_allow,
+ ws_event_log=args.ws_event_log,
+ progress=progress,
+ registry=registry,
+ steps=loadtest_steps or single_steps,
+ download_dir=download_dir,
+ session_id=item["session_id"],
+ )
+ )
+ for item in identities
+ ]
+ try:
+ raw_results = await asyncio.gather(*task_objs, return_exceptions=True)
+ except asyncio.CancelledError:
+ logger.info("[shutdown] 收到中断,正在 cancel 进行中的会话…")
+ await registry.cancel_all()
+ for task in task_objs:
+ task.cancel()
+ await asyncio.gather(*task_objs, return_exceptions=True)
+ raise
+ elapsed = time.perf_counter() - t0
+
+ results = []
+ for item, raw in zip(identities, raw_results, strict=True):
+ if isinstance(raw, Exception):
+ fail = mod.RequestResult(
+ index=item["index"] - 1,
+ shard=0,
+ shard2=0,
+ session_id=item["session_id"],
+ req_id="",
+ group_id=item["group_id"],
+ bot_id=item["bot_id"],
+ user_id=item["user_id"],
+ ok=False,
+ accepted=False,
+ error=str(raw),
+ )
+ results.append(fail)
+ else:
+ results.append(raw)
+
+ def _is_success(r: Any) -> bool:
+ if args.accept_only:
+ return bool(r.accepted and r.ok)
+ return bool(r.final_received and r.ok)
+
+ completed = sum(1 for r in results if _is_success(r))
+ failed = args.concurrency - completed
+ distinct_users = {r.user_id for r in results}
+ distinct_sessions = {r.session_id for r in results if r.session_id}
+
+ logger.info("\n[requests] 各路身份与结果:")
+ for r in sorted(results, key=lambda x: x.index):
+ status = "ok" if _is_success(r) else "fail"
+ logger.info(
+ "[requests] idx=%02d status=%s accepted=%s final=%s total_ms=%.0f "
+ "user_id=%s session_id=%s group_id=%s bot_id=%s error=%s",
+ r.index,
+ status,
+ r.accepted,
+ r.final_received,
+ r.total_ms,
+ r.user_id,
+ r.session_id,
+ r.group_id,
+ r.bot_id,
+ r.error or "-",
+ )
+
+ stats = mod.LoadTestStats(
+ total=args.concurrency,
+ completed=completed,
+ failed=failed,
+ elapsed_s=elapsed,
+ accept_ms=[r.accept_ms for r in results if r.accept_ms > 0],
+ total_ms=[r.total_ms for r in results if r.total_ms > 0],
+ )
+ logger.info("\n[assert] distinct_user_id=%d (期望 %d)", len(distinct_users), args.concurrency)
+ logger.info(
+ "[assert] distinct_session_id=%d (期望 %d)",
+ len(distinct_sessions),
+ args.concurrency,
+ )
+ logger.info("[assert] distinct_group_id=%s distinct_bot_id=%s", {args.group_id}, {args.bot_id})
+ logger.info("[result] %s", stats.summary())
+
+ identity_ok = (
+ len(distinct_users) == args.concurrency
+ and len(distinct_sessions) == args.concurrency
+ )
+ if not identity_ok:
+ logger.error("[fail] user_id / session_id 未按 N 路展开")
+ return 1
+ return 0 if failed == 0 else 1
+
+
+def main() -> int:
+ try:
+ _configure_cli_logging()
+ _load_concurrent_mod()
+ except Exception:
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
+ logger.exception("加载 enterprise_runtime_concurrent_test.py 失败")
+ return 1
+
+ try:
+ import websockets # noqa: F401
+ except ImportError:
+ logger.error("缺少 websockets,请: pip install websockets 或使用仓库 .venv")
+ return 1
+
+ args = _parse_args()
+ try:
+ return asyncio.run(_run(args))
+ except KeyboardInterrupt:
+ return 130
+ except ValueError as err:
+ logger.error("[invalid-args] %s", err)
+ return 2
+ except OSError as connect_err:
+ logger.error("[connect-failed] %s", connect_err)
+ logger.error("请确认 Web NodePort / Gateway 可访问,且 --host/--web-port/--ws-url 正确。")
+ return 1
+ except Exception as err:
+ logger.error("[failed] %s", err)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git "a/packages/jiuwenclaw-ee/claw_manager/scripts/\347\253\245\350\266\243\347\232\204\346\230\245\345\244\251.md" "b/packages/jiuwenclaw-ee/claw_manager/scripts/\347\253\245\350\266\243\347\232\204\346\230\245\345\244\251.md"
new file mode 100644
index 0000000000..c4e0e2d9cd
--- /dev/null
+++ "b/packages/jiuwenclaw-ee/claw_manager/scripts/\347\253\245\350\266\243\347\232\204\346\230\245\345\244\251.md"
@@ -0,0 +1,18 @@
+# 童趣的春天
+
+春天,是童年记忆中最温柔的序曲。每当春风拂过脸颊,我便仿佛又回到了那个充满好奇与惊喜的童年时光。
+
+清晨,当第一缕阳光洒在窗台上,我便迫不及待地推开窗户。院子里,桃树已经开满了粉色的花朵,像一个个害羞的小姑娘。我最喜欢和小伙伴们一起在花树下玩耍,仰头看着那些在花间忙碌的小蜜蜂,它们嗡嗡地唱着歌,为春天增添了无限生机。
+
+午后,是春天最美好的时刻。我们总是跑到村外的田野里,那里有金黄的油菜花,有紫色的蚕豆花,还有各种叫不出名字的野花。我们像一群快乐的小鸟,在花海中穿梭,采撷最美的花朵,编成花环戴在头上。有时候,我们会比赛谁捉的蝴蝶最多,那些白色的、黄色的、带斑点的蝴蝶在花丛中翩翩起舞,像极了会飞的花朵。
+
+最难忘的是放风筝的日子。爸爸会用旧报纸和竹条给我做风筝,我在风筝上画上自己喜欢的图案。当春风正好,我们便跑到空旷的草地上,看着风筝一点点升高,最后变成天空中的一个小点。线轴在手中转动,心也随着风筝飞向了远方。那时候的快乐,简单而纯粹。
+
+春天的夜晚,总是伴随着蛙鸣声。我们躺在院子里,看着天上的星星,听着大人们讲关于春天的故事。奶奶说,春天是万物复苏的季节,所有的生命都在这个时候醒来。我们似懂非懂地点着头,心中却充满了对这个世界的好奇。
+
+如今,虽然已经长大,但每到春天,那些童年的记忆便会如春风般拂过心头。那些简单而纯粹的快乐,那些对世界的好奇与探索,都深深地刻在了我的心里。春天,不仅是一个季节,更是童年最美好的开始,是永远回不去的纯真年代。
+
+---
+**字数统计**:约520字
+**主题**:童趣的春天
+**创作时间**:2026年7月3日
\ No newline at end of file