group_protocol.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. """Shared protocol limits and input normalization for YaoYao Group Chat."""
  2. from __future__ import annotations
  3. import unicodedata
  4. from pathlib import Path
  5. from typing import Any, Literal
  6. from uuid import UUID
  7. from pydantic import (
  8. BaseModel,
  9. ConfigDict,
  10. Field,
  11. StrictBool,
  12. StrictInt,
  13. field_validator,
  14. model_validator,
  15. )
  16. PROTOCOL_VERSION = 7
  17. MAX_AGENTS_PER_ROOM = 8
  18. MAX_MESSAGE_BYTES = 64 * 1024
  19. MAX_TOOL_STATE_BYTES = 256 * 1024
  20. MAX_INTERACTION_PAYLOAD_BYTES = 64 * 1024
  21. MAX_MESSAGE_PAGE_SIZE = 100
  22. MAX_EVENT_BATCH_SIZE = 200
  23. MAX_EVENT_FRAME_BYTES = 2 * 1024 * 1024
  24. MAX_AGENT_DEPTH = 2
  25. DEFAULT_MAX_REPLY_ROUNDS = 3
  26. UNLIMITED_REPLY_ROUNDS = -1
  27. MAX_FINITE_REPLY_ROUNDS = 100
  28. MAX_AGENT_DISPLAY_NAME_LENGTH = 100
  29. MAX_ROOM_CONCURRENCY = 3
  30. MAX_PLUGIN_CONCURRENCY = 4
  31. INITIAL_CONTEXT_MESSAGE_LIMIT = 50
  32. CONTEXT_CHARACTER_BUDGET = 32_000
  33. REASONING_EFFORTS = frozenset({
  34. "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
  35. })
  36. # These literals address the room as a whole and must never become a member
  37. # display-name or alias target. Keep the stable wire spelling for existing
  38. # clients while accepting the localized spelling shown by the iOS UI.
  39. ALL_MENTION_ALIASES = ("所有人", "all")
  40. _ALL_MENTION_ALIAS_KEYS = frozenset(
  41. alias.casefold() for alias in ALL_MENTION_ALIASES
  42. )
  43. EVENT_TYPES = frozenset({
  44. "room.created",
  45. "room.updated",
  46. "room.deleted",
  47. "agent.created",
  48. "agent.updated",
  49. "agent.deleted",
  50. "agent.status",
  51. "message.upsert",
  52. "topic.updated",
  53. "interaction.requested",
  54. "interaction.resolved",
  55. "run.updated",
  56. })
  57. def limits_payload() -> dict[str, int]:
  58. """Return the public, lower-camel protocol limits advertised to clients."""
  59. return {
  60. "maxAgentsPerRoom": MAX_AGENTS_PER_ROOM,
  61. "maxMessageBytes": MAX_MESSAGE_BYTES,
  62. "maxToolStateBytes": MAX_TOOL_STATE_BYTES,
  63. "maxInteractionPayloadBytes": MAX_INTERACTION_PAYLOAD_BYTES,
  64. "maxMessagePageSize": MAX_MESSAGE_PAGE_SIZE,
  65. "maxEventBatchSize": MAX_EVENT_BATCH_SIZE,
  66. "maxEventFrameBytes": MAX_EVENT_FRAME_BYTES,
  67. "maxAgentDepth": MAX_AGENT_DEPTH,
  68. "defaultMaxReplyRounds": DEFAULT_MAX_REPLY_ROUNDS,
  69. "unlimitedReplyRoundsValue": UNLIMITED_REPLY_ROUNDS,
  70. "maxAgentDisplayNameLength": MAX_AGENT_DISPLAY_NAME_LENGTH,
  71. "maxRoomConcurrency": MAX_ROOM_CONCURRENCY,
  72. "maxPluginConcurrency": MAX_PLUGIN_CONCURRENCY,
  73. }
  74. class GroupModel(BaseModel):
  75. """Public request base with lower-camel aliases and forbidden extras."""
  76. model_config = ConfigDict(populate_by_name=True, extra="forbid")
  77. class AgentSeed(GroupModel):
  78. profile: str = Field(min_length=1, max_length=100)
  79. display_name: str | None = Field(
  80. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  81. )
  82. description: str = Field(default="", max_length=500)
  83. reply_without_mention: StrictBool = Field(
  84. default=False, alias="replyWithoutMention"
  85. )
  86. is_host: StrictBool = Field(default=False, alias="isHost")
  87. model: str | None = Field(default=None, max_length=4096)
  88. provider: str | None = Field(default=None, max_length=4096)
  89. reasoning_effort: str | None = Field(
  90. default=None, alias="reasoningEffort", max_length=32
  91. )
  92. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  93. @field_validator("model", "provider", "reasoning_effort")
  94. @classmethod
  95. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  96. return normalize_optional_agent_configuration(value)
  97. @field_validator("reasoning_effort")
  98. @classmethod
  99. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  100. return validate_reasoning_override(value)
  101. @model_validator(mode="after")
  102. def validate_model_selection(self) -> "AgentSeed":
  103. validate_model_provider_pair(self.model, self.provider)
  104. return self
  105. @field_validator("display_name")
  106. @classmethod
  107. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  108. return validate_optional_display_name(value)
  109. class CreateRoomRequest(GroupModel):
  110. request_id: UUID = Field(alias="requestId")
  111. name: str = Field(min_length=1, max_length=100)
  112. cwd: str = Field(default="", max_length=4096)
  113. max_reply_rounds: StrictInt = Field(
  114. default=DEFAULT_MAX_REPLY_ROUNDS, alias="maxReplyRounds"
  115. )
  116. agents: list[AgentSeed] = Field(min_length=1, max_length=MAX_AGENTS_PER_ROOM)
  117. @field_validator("max_reply_rounds")
  118. @classmethod
  119. def validate_max_reply_rounds(cls, value: int) -> int:
  120. return normalize_max_reply_rounds(value)
  121. @model_validator(mode="after")
  122. def validate_unique_host(self) -> "CreateRoomRequest":
  123. if sum(agent.is_host for agent in self.agents) > 1:
  124. raise ValueError("Room may contain only one host Agent")
  125. return self
  126. class UpdateRoomRequest(GroupModel):
  127. request_id: UUID = Field(alias="requestId")
  128. name: str | None = Field(default=None, min_length=1, max_length=100)
  129. cwd: str | None = Field(default=None, max_length=4096)
  130. max_reply_rounds: StrictInt | None = Field(default=None, alias="maxReplyRounds")
  131. @field_validator("name", "cwd", "max_reply_rounds", mode="before")
  132. @classmethod
  133. def reject_explicit_null(cls, value: Any) -> Any:
  134. if value is None:
  135. raise ValueError("field must not be null")
  136. return value
  137. @model_validator(mode="after")
  138. def require_change(self) -> "UpdateRoomRequest":
  139. if not ({"name", "cwd", "max_reply_rounds"} & self.model_fields_set):
  140. raise ValueError("Room update requires name, cwd, or maxReplyRounds")
  141. return self
  142. @field_validator("max_reply_rounds")
  143. @classmethod
  144. def validate_max_reply_rounds(cls, value: int | None) -> int | None:
  145. return None if value is None else normalize_max_reply_rounds(value)
  146. class AddAgentRequest(GroupModel):
  147. request_id: UUID = Field(alias="requestId")
  148. profile: str = Field(min_length=1, max_length=100)
  149. display_name: str | None = Field(
  150. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  151. )
  152. description: str = Field(default="", max_length=500)
  153. reply_without_mention: StrictBool = Field(
  154. default=False, alias="replyWithoutMention"
  155. )
  156. is_host: StrictBool = Field(default=False, alias="isHost")
  157. model: str | None = Field(default=None, max_length=4096)
  158. provider: str | None = Field(default=None, max_length=4096)
  159. reasoning_effort: str | None = Field(
  160. default=None, alias="reasoningEffort", max_length=32
  161. )
  162. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  163. @field_validator("model", "provider", "reasoning_effort")
  164. @classmethod
  165. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  166. return normalize_optional_agent_configuration(value)
  167. @field_validator("reasoning_effort")
  168. @classmethod
  169. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  170. return validate_reasoning_override(value)
  171. @model_validator(mode="after")
  172. def validate_model_selection(self) -> "AddAgentRequest":
  173. validate_model_provider_pair(self.model, self.provider)
  174. return self
  175. @field_validator("display_name")
  176. @classmethod
  177. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  178. return validate_optional_display_name(value)
  179. class UpdateAgentRequest(GroupModel):
  180. request_id: UUID = Field(alias="requestId")
  181. display_name: str | None = Field(
  182. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  183. )
  184. description: str | None = Field(default=None, max_length=500)
  185. enabled: StrictBool | None = None
  186. reply_without_mention: StrictBool | None = Field(
  187. default=None, alias="replyWithoutMention"
  188. )
  189. is_host: StrictBool | None = Field(default=None, alias="isHost")
  190. model: str | None = Field(default=None, max_length=4096)
  191. provider: str | None = Field(default=None, max_length=4096)
  192. reasoning_effort: str | None = Field(
  193. default=None, alias="reasoningEffort", max_length=32
  194. )
  195. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  196. @field_validator(
  197. "display_name", "description", "enabled", "reply_without_mention", "is_host",
  198. mode="before"
  199. )
  200. @classmethod
  201. def reject_explicit_null(cls, value: Any) -> Any:
  202. if value is None:
  203. raise ValueError("field must not be null")
  204. return value
  205. @field_validator("display_name")
  206. @classmethod
  207. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  208. return validate_optional_display_name(value)
  209. @field_validator("model", "provider", "reasoning_effort")
  210. @classmethod
  211. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  212. return normalize_optional_agent_configuration(value)
  213. @field_validator("reasoning_effort")
  214. @classmethod
  215. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  216. return validate_reasoning_override(value)
  217. @model_validator(mode="after")
  218. def require_change(self) -> "UpdateAgentRequest":
  219. if not (
  220. {
  221. "display_name", "description", "enabled", "reply_without_mention",
  222. "is_host",
  223. "model", "provider", "reasoning_effort", "fast_mode",
  224. }
  225. & self.model_fields_set
  226. ):
  227. raise ValueError(
  228. "Agent update requires a mutable agent field"
  229. )
  230. model_fields = {"model", "provider"} & self.model_fields_set
  231. if model_fields and model_fields != {"model", "provider"}:
  232. raise ValueError("model and provider must be updated together")
  233. if model_fields:
  234. validate_model_provider_pair(self.model, self.provider)
  235. return self
  236. def normalize_optional_agent_configuration(value: str | None) -> str | None:
  237. if value is None:
  238. return None
  239. normalized = value.strip()
  240. if not normalized:
  241. raise ValueError("configuration value must not be blank")
  242. return normalized
  243. def validate_reasoning_override(value: str | None) -> str | None:
  244. if value is not None and value not in REASONING_EFFORTS:
  245. raise ValueError("reasoningEffort is invalid")
  246. return value
  247. def validate_model_provider_pair(model: str | None, provider: str | None) -> None:
  248. if (model is None) != (provider is None):
  249. raise ValueError("model and provider must both be set or both be null")
  250. class RequestIDRequest(GroupModel):
  251. request_id: UUID = Field(alias="requestId")
  252. class SendMessageRequest(GroupModel):
  253. request_id: UUID = Field(alias="requestId")
  254. client_message_id: UUID = Field(alias="clientMessageId")
  255. topic_id: UUID | None = Field(default=None, alias="topicId")
  256. content: str
  257. mention_agent_ids: list[UUID] = Field(
  258. alias="mentionAgentIds", max_length=MAX_AGENTS_PER_ROOM
  259. )
  260. @field_validator("content")
  261. @classmethod
  262. def validate_content_bytes(cls, value: str) -> str:
  263. try:
  264. encoded = value.encode("utf-8")
  265. except UnicodeEncodeError as error:
  266. raise ValueError("content must be valid UTF-8") from error
  267. if len(encoded) > MAX_MESSAGE_BYTES:
  268. raise ValueError("content exceeds maximum size")
  269. if not value.strip():
  270. raise ValueError("content must not be blank")
  271. return value
  272. class ApprovalRequest(GroupModel):
  273. request_id: UUID = Field(alias="requestId")
  274. choice: Literal["once", "session", "always", "deny"]
  275. permanent: StrictBool = False
  276. @model_validator(mode="after")
  277. def validate_choice(self) -> "ApprovalRequest":
  278. if (self.choice == "always") != self.permanent:
  279. raise ValueError("permanent must be true exactly for choice=always")
  280. return self
  281. class ClarificationRequest(GroupModel):
  282. request_id: UUID = Field(alias="requestId")
  283. response: str
  284. @field_validator("response")
  285. @classmethod
  286. def validate_response_bytes(cls, value: str) -> str:
  287. try:
  288. encoded = value.encode("utf-8")
  289. except UnicodeEncodeError as error:
  290. raise ValueError("response must be valid UTF-8") from error
  291. if not value.strip():
  292. raise ValueError("response must not be blank")
  293. if len(encoded) > MAX_MESSAGE_BYTES:
  294. raise ValueError("response exceeds maximum size")
  295. return value
  296. def normalize_room_name(value: str) -> str:
  297. """Return a trimmed room name within the protocol's character limit."""
  298. normalized = value.strip()
  299. if not 1 <= len(normalized) <= 100:
  300. raise ValueError("Room name must contain 1 to 100 characters")
  301. return normalized
  302. def normalize_display_name(value: str) -> tuple[str, str]:
  303. """Return a trimmed display name and its case-insensitive uniqueness key."""
  304. normalized = value.strip()
  305. if not 1 <= len(normalized) <= MAX_AGENT_DISPLAY_NAME_LENGTH:
  306. raise ValueError(
  307. f"Display name must contain 1 to {MAX_AGENT_DISPLAY_NAME_LENGTH} characters"
  308. )
  309. uniqueness_key = normalized.casefold()
  310. if uniqueness_key in _ALL_MENTION_ALIAS_KEYS:
  311. raise ValueError("Display name is reserved")
  312. return normalized, uniqueness_key
  313. def is_reserved_mention_alias(value: str) -> bool:
  314. """Return whether a member-facing name would claim a room-wide Mention."""
  315. return value.strip().casefold() in _ALL_MENTION_ALIAS_KEYS
  316. def validate_optional_display_name(value: str | None) -> str | None:
  317. """Reject only non-empty reserved names; blank still means use the fallback."""
  318. if value is not None and value.strip() and is_reserved_mention_alias(value):
  319. raise ValueError("Display name is reserved")
  320. return value
  321. def normalize_max_reply_rounds(value: object) -> int:
  322. """Validate a finite reply-round ceiling or the explicit unlimited marker."""
  323. if isinstance(value, bool) or not isinstance(value, int):
  324. raise ValueError("maxReplyRounds must be an integer")
  325. if value == UNLIMITED_REPLY_ROUNDS:
  326. return value
  327. if not 1 <= value <= MAX_FINITE_REPLY_ROUNDS:
  328. raise ValueError(
  329. f"maxReplyRounds must be -1 or 1 to {MAX_FINITE_REPLY_ROUNDS}"
  330. )
  331. return value
  332. def normalize_interaction_id(value: object) -> str:
  333. """Canonicalize an opaque Gateway interaction identity for URL use."""
  334. if not isinstance(value, str):
  335. raise ValueError("interactionId must be a string")
  336. normalized = value.strip()
  337. if (
  338. not normalized
  339. or len(normalized) > 200
  340. or any(unicodedata.category(character) == "Cc" for character in normalized)
  341. ):
  342. raise ValueError("interactionId is invalid")
  343. return normalized
  344. def normalize_room_cwd(value: str) -> str:
  345. """Validate and canonicalize an optional room working directory."""
  346. if not isinstance(value, str):
  347. raise ValueError("Room cwd must be a string")
  348. if value and any(unicodedata.category(character) == "Cc" for character in value):
  349. raise ValueError("Room cwd must not contain control characters")
  350. normalized = value.strip()
  351. if not normalized:
  352. return ""
  353. path = Path(normalized)
  354. if not path.is_absolute():
  355. raise ValueError("Room cwd must be an absolute path")
  356. try:
  357. resolved = path.resolve()
  358. is_directory = resolved.is_dir()
  359. except (OSError, RuntimeError) as error:
  360. raise ValueError("Room cwd could not be resolved") from error
  361. if not is_directory:
  362. raise ValueError("Room cwd must exist and be a directory")
  363. return str(resolved)