group_protocol.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 = 11
  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_INSTRUCTIONS_LENGTH = 4_000
  30. MAX_ROOM_CONCURRENCY = 3
  31. MAX_PLUGIN_CONCURRENCY = 4
  32. INITIAL_CONTEXT_MESSAGE_LIMIT = 50
  33. CONTEXT_CHARACTER_BUDGET = 32_000
  34. REASONING_EFFORTS = frozenset({
  35. "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
  36. })
  37. ORCHESTRATION_MODES = frozenset({"free", "host"})
  38. # These literals address the room as a whole and must never become a member
  39. # display-name or alias target. Keep the stable wire spelling for existing
  40. # clients while accepting the localized spelling shown by the iOS UI.
  41. ALL_MENTION_ALIASES = ("所有人", "all")
  42. _ALL_MENTION_ALIAS_KEYS = frozenset(
  43. alias.casefold() for alias in ALL_MENTION_ALIASES
  44. )
  45. EVENT_TYPES = frozenset({
  46. "room.created",
  47. "room.updated",
  48. "room.deleted",
  49. "room.restored",
  50. "agent.created",
  51. "agent.updated",
  52. "agent.deleted",
  53. "agent.status",
  54. "message.upsert",
  55. "topic.updated",
  56. "topic.archived",
  57. "topic.restored",
  58. "room.activity",
  59. "interaction.requested",
  60. "interaction.resolved",
  61. "run.updated",
  62. })
  63. def limits_payload() -> dict[str, int]:
  64. """Return the public, lower-camel protocol limits advertised to clients."""
  65. return {
  66. "maxAgentsPerRoom": MAX_AGENTS_PER_ROOM,
  67. "maxMessageBytes": MAX_MESSAGE_BYTES,
  68. "maxToolStateBytes": MAX_TOOL_STATE_BYTES,
  69. "maxInteractionPayloadBytes": MAX_INTERACTION_PAYLOAD_BYTES,
  70. "maxMessagePageSize": MAX_MESSAGE_PAGE_SIZE,
  71. "maxEventBatchSize": MAX_EVENT_BATCH_SIZE,
  72. "maxEventFrameBytes": MAX_EVENT_FRAME_BYTES,
  73. "maxAgentDepth": MAX_AGENT_DEPTH,
  74. "defaultMaxReplyRounds": DEFAULT_MAX_REPLY_ROUNDS,
  75. "unlimitedReplyRoundsValue": UNLIMITED_REPLY_ROUNDS,
  76. "maxAgentDisplayNameLength": MAX_AGENT_DISPLAY_NAME_LENGTH,
  77. "maxRoomInstructionsLength": MAX_ROOM_INSTRUCTIONS_LENGTH,
  78. "maxRoomConcurrency": MAX_ROOM_CONCURRENCY,
  79. "maxPluginConcurrency": MAX_PLUGIN_CONCURRENCY,
  80. }
  81. class GroupModel(BaseModel):
  82. """Public request base with lower-camel aliases and forbidden extras."""
  83. model_config = ConfigDict(populate_by_name=True, extra="forbid")
  84. class AgentSeed(GroupModel):
  85. profile: str = Field(min_length=1, max_length=100)
  86. node_id: str = Field(default="local", alias="nodeId", min_length=1, max_length=64)
  87. node_label: str = Field(default="", alias="nodeLabel", max_length=100)
  88. display_name: str | None = Field(
  89. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  90. )
  91. description: str = Field(default="", max_length=500)
  92. reply_without_mention: StrictBool = Field(
  93. default=False, alias="replyWithoutMention"
  94. )
  95. is_host: StrictBool = Field(default=False, alias="isHost")
  96. model: str | None = Field(default=None, max_length=4096)
  97. provider: str | None = Field(default=None, max_length=4096)
  98. reasoning_effort: str | None = Field(
  99. default=None, alias="reasoningEffort", max_length=32
  100. )
  101. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  102. @field_validator("model", "provider", "reasoning_effort")
  103. @classmethod
  104. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  105. return normalize_optional_agent_configuration(value)
  106. @field_validator("reasoning_effort")
  107. @classmethod
  108. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  109. return validate_reasoning_override(value)
  110. @model_validator(mode="after")
  111. def validate_model_selection(self) -> "AgentSeed":
  112. validate_model_provider_pair(self.model, self.provider)
  113. return self
  114. @field_validator("display_name")
  115. @classmethod
  116. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  117. return validate_optional_display_name(value)
  118. @field_validator("node_id")
  119. @classmethod
  120. def validate_node_id(cls, value: str) -> str:
  121. return normalize_node_id(value)
  122. @field_validator("node_label")
  123. @classmethod
  124. def normalize_node_label(cls, value: str) -> str:
  125. return " ".join(value.split())
  126. class CreateRoomRequest(GroupModel):
  127. request_id: UUID = Field(alias="requestId")
  128. name: str = Field(min_length=1, max_length=100)
  129. cwd: str = Field(default="", max_length=4096)
  130. instructions: str = Field(default="", max_length=MAX_ROOM_INSTRUCTIONS_LENGTH)
  131. max_reply_rounds: StrictInt = Field(
  132. default=DEFAULT_MAX_REPLY_ROUNDS, alias="maxReplyRounds"
  133. )
  134. orchestration_mode: Literal["free", "host"] = Field(
  135. default="free", alias="orchestrationMode"
  136. )
  137. agents: list[AgentSeed] = Field(min_length=1, max_length=MAX_AGENTS_PER_ROOM)
  138. @field_validator("max_reply_rounds")
  139. @classmethod
  140. def validate_max_reply_rounds(cls, value: int) -> int:
  141. return normalize_max_reply_rounds(value)
  142. @field_validator("instructions")
  143. @classmethod
  144. def normalize_instructions(cls, value: str) -> str:
  145. return normalize_room_instructions(value)
  146. @model_validator(mode="after")
  147. def validate_unique_host(self) -> "CreateRoomRequest":
  148. if sum(agent.is_host for agent in self.agents) > 1:
  149. raise ValueError("Room may contain only one host Agent")
  150. return self
  151. class UpdateRoomRequest(GroupModel):
  152. request_id: UUID = Field(alias="requestId")
  153. name: str | None = Field(default=None, min_length=1, max_length=100)
  154. cwd: str | None = Field(default=None, max_length=4096)
  155. instructions: str | None = Field(
  156. default=None, max_length=MAX_ROOM_INSTRUCTIONS_LENGTH
  157. )
  158. max_reply_rounds: StrictInt | None = Field(default=None, alias="maxReplyRounds")
  159. orchestration_mode: Literal["free", "host"] | None = Field(
  160. default=None, alias="orchestrationMode"
  161. )
  162. @field_validator(
  163. "name", "cwd", "instructions", "max_reply_rounds", "orchestration_mode",
  164. mode="before"
  165. )
  166. @classmethod
  167. def reject_explicit_null(cls, value: Any) -> Any:
  168. if value is None:
  169. raise ValueError("field must not be null")
  170. return value
  171. @model_validator(mode="after")
  172. def require_change(self) -> "UpdateRoomRequest":
  173. if not (
  174. {"name", "cwd", "instructions", "max_reply_rounds", "orchestration_mode"}
  175. & self.model_fields_set
  176. ):
  177. raise ValueError(
  178. "Room update requires name, cwd, instructions, maxReplyRounds, or orchestrationMode"
  179. )
  180. return self
  181. @field_validator("instructions")
  182. @classmethod
  183. def normalize_instructions(cls, value: str | None) -> str | None:
  184. return None if value is None else normalize_room_instructions(value)
  185. @field_validator("max_reply_rounds")
  186. @classmethod
  187. def validate_max_reply_rounds(cls, value: int | None) -> int | None:
  188. return None if value is None else normalize_max_reply_rounds(value)
  189. class UpdateTopicRequest(GroupModel):
  190. request_id: UUID = Field(alias="requestId")
  191. title: str | None = Field(default=None, min_length=1, max_length=120)
  192. pinned: StrictBool | None = None
  193. @field_validator("title")
  194. @classmethod
  195. def normalize_title(cls, value: str | None) -> str | None:
  196. if value is None:
  197. return None
  198. normalized = " ".join(value.split()).strip()
  199. if not normalized:
  200. raise ValueError("title must not be blank")
  201. return normalized
  202. @model_validator(mode="after")
  203. def require_change(self) -> "UpdateTopicRequest":
  204. if not ({"title", "pinned"} & self.model_fields_set):
  205. raise ValueError("Topic update requires title or pinned")
  206. return self
  207. class MarkTopicReadRequest(GroupModel):
  208. request_id: UUID = Field(alias="requestId")
  209. through_seq: StrictInt = Field(alias="throughSeq", ge=0)
  210. class AddAgentRequest(GroupModel):
  211. request_id: UUID = Field(alias="requestId")
  212. profile: str = Field(min_length=1, max_length=100)
  213. node_id: str = Field(default="local", alias="nodeId", min_length=1, max_length=64)
  214. node_label: str = Field(default="", alias="nodeLabel", max_length=100)
  215. display_name: str | None = Field(
  216. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  217. )
  218. description: str = Field(default="", max_length=500)
  219. reply_without_mention: StrictBool = Field(
  220. default=False, alias="replyWithoutMention"
  221. )
  222. is_host: StrictBool = Field(default=False, alias="isHost")
  223. model: str | None = Field(default=None, max_length=4096)
  224. provider: str | None = Field(default=None, max_length=4096)
  225. reasoning_effort: str | None = Field(
  226. default=None, alias="reasoningEffort", max_length=32
  227. )
  228. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  229. @field_validator("model", "provider", "reasoning_effort")
  230. @classmethod
  231. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  232. return normalize_optional_agent_configuration(value)
  233. @field_validator("reasoning_effort")
  234. @classmethod
  235. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  236. return validate_reasoning_override(value)
  237. @model_validator(mode="after")
  238. def validate_model_selection(self) -> "AddAgentRequest":
  239. validate_model_provider_pair(self.model, self.provider)
  240. return self
  241. @field_validator("display_name")
  242. @classmethod
  243. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  244. return validate_optional_display_name(value)
  245. @field_validator("node_id")
  246. @classmethod
  247. def validate_node_id(cls, value: str) -> str:
  248. return normalize_node_id(value)
  249. @field_validator("node_label")
  250. @classmethod
  251. def normalize_node_label(cls, value: str) -> str:
  252. return " ".join(value.split())
  253. class UpdateAgentRequest(GroupModel):
  254. request_id: UUID = Field(alias="requestId")
  255. display_name: str | None = Field(
  256. default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
  257. )
  258. description: str | None = Field(default=None, max_length=500)
  259. enabled: StrictBool | None = None
  260. reply_without_mention: StrictBool | None = Field(
  261. default=None, alias="replyWithoutMention"
  262. )
  263. is_host: StrictBool | None = Field(default=None, alias="isHost")
  264. model: str | None = Field(default=None, max_length=4096)
  265. provider: str | None = Field(default=None, max_length=4096)
  266. reasoning_effort: str | None = Field(
  267. default=None, alias="reasoningEffort", max_length=32
  268. )
  269. fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
  270. @field_validator(
  271. "display_name", "description", "enabled", "reply_without_mention", "is_host",
  272. mode="before"
  273. )
  274. @classmethod
  275. def reject_explicit_null(cls, value: Any) -> Any:
  276. if value is None:
  277. raise ValueError("field must not be null")
  278. return value
  279. @field_validator("display_name")
  280. @classmethod
  281. def reject_reserved_display_name(cls, value: str | None) -> str | None:
  282. return validate_optional_display_name(value)
  283. @field_validator("model", "provider", "reasoning_effort")
  284. @classmethod
  285. def normalize_optional_configuration(cls, value: str | None) -> str | None:
  286. return normalize_optional_agent_configuration(value)
  287. @field_validator("reasoning_effort")
  288. @classmethod
  289. def validate_reasoning_effort(cls, value: str | None) -> str | None:
  290. return validate_reasoning_override(value)
  291. @model_validator(mode="after")
  292. def require_change(self) -> "UpdateAgentRequest":
  293. if not (
  294. {
  295. "display_name", "description", "enabled", "reply_without_mention",
  296. "is_host",
  297. "model", "provider", "reasoning_effort", "fast_mode",
  298. }
  299. & self.model_fields_set
  300. ):
  301. raise ValueError(
  302. "Agent update requires a mutable agent field"
  303. )
  304. model_fields = {"model", "provider"} & self.model_fields_set
  305. if model_fields and model_fields != {"model", "provider"}:
  306. raise ValueError("model and provider must be updated together")
  307. if model_fields:
  308. validate_model_provider_pair(self.model, self.provider)
  309. return self
  310. def normalize_optional_agent_configuration(value: str | None) -> str | None:
  311. if value is None:
  312. return None
  313. normalized = value.strip()
  314. if not normalized:
  315. raise ValueError("configuration value must not be blank")
  316. return normalized
  317. def normalize_node_id(value: str) -> str:
  318. normalized = value.strip().lower()
  319. if normalized == "local":
  320. return normalized
  321. try:
  322. canonical = str(UUID(normalized))
  323. except ValueError as error:
  324. raise ValueError("nodeId must be local or a canonical UUID") from error
  325. if canonical != normalized:
  326. raise ValueError("nodeId must be local or a canonical UUID")
  327. return canonical
  328. def validate_reasoning_override(value: str | None) -> str | None:
  329. if value is not None and value not in REASONING_EFFORTS:
  330. raise ValueError("reasoningEffort is invalid")
  331. return value
  332. def validate_model_provider_pair(model: str | None, provider: str | None) -> None:
  333. if (model is None) != (provider is None):
  334. raise ValueError("model and provider must both be set or both be null")
  335. class RequestIDRequest(GroupModel):
  336. request_id: UUID = Field(alias="requestId")
  337. class SendMessageRequest(GroupModel):
  338. request_id: UUID = Field(alias="requestId")
  339. client_message_id: UUID = Field(alias="clientMessageId")
  340. topic_id: UUID | None = Field(default=None, alias="topicId")
  341. content: str
  342. mention_agent_ids: list[UUID] = Field(
  343. alias="mentionAgentIds", max_length=MAX_AGENTS_PER_ROOM
  344. )
  345. @field_validator("content")
  346. @classmethod
  347. def validate_content_bytes(cls, value: str) -> str:
  348. try:
  349. encoded = value.encode("utf-8")
  350. except UnicodeEncodeError as error:
  351. raise ValueError("content must be valid UTF-8") from error
  352. if len(encoded) > MAX_MESSAGE_BYTES:
  353. raise ValueError("content exceeds maximum size")
  354. if not value.strip():
  355. raise ValueError("content must not be blank")
  356. return value
  357. class ApprovalRequest(GroupModel):
  358. request_id: UUID = Field(alias="requestId")
  359. choice: Literal["once", "session", "always", "deny"]
  360. permanent: StrictBool = False
  361. @model_validator(mode="after")
  362. def validate_choice(self) -> "ApprovalRequest":
  363. if (self.choice == "always") != self.permanent:
  364. raise ValueError("permanent must be true exactly for choice=always")
  365. return self
  366. class ClarificationRequest(GroupModel):
  367. request_id: UUID = Field(alias="requestId")
  368. response: str
  369. @field_validator("response")
  370. @classmethod
  371. def validate_response_bytes(cls, value: str) -> str:
  372. try:
  373. encoded = value.encode("utf-8")
  374. except UnicodeEncodeError as error:
  375. raise ValueError("response must be valid UTF-8") from error
  376. if not value.strip():
  377. raise ValueError("response must not be blank")
  378. if len(encoded) > MAX_MESSAGE_BYTES:
  379. raise ValueError("response exceeds maximum size")
  380. return value
  381. def normalize_room_name(value: str) -> str:
  382. """Return a trimmed room name within the protocol's character limit."""
  383. normalized = value.strip()
  384. if not 1 <= len(normalized) <= 100:
  385. raise ValueError("Room name must contain 1 to 100 characters")
  386. return normalized
  387. def normalize_room_instructions(value: str) -> str:
  388. """Normalize optional multiline room rules without changing their structure."""
  389. if not isinstance(value, str):
  390. raise ValueError("Room instructions must be a string")
  391. normalized = value.replace("\r\n", "\n").replace("\r", "\n").strip()
  392. if len(normalized) > MAX_ROOM_INSTRUCTIONS_LENGTH:
  393. raise ValueError(
  394. f"Room instructions must contain at most {MAX_ROOM_INSTRUCTIONS_LENGTH} characters"
  395. )
  396. if any(
  397. unicodedata.category(character) == "Cc" and character not in {"\n", "\t"}
  398. for character in normalized
  399. ):
  400. raise ValueError("Room instructions contain unsupported control characters")
  401. return normalized
  402. def normalize_display_name(value: str) -> tuple[str, str]:
  403. """Return a trimmed display name and its case-insensitive uniqueness key."""
  404. normalized = value.strip()
  405. if not 1 <= len(normalized) <= MAX_AGENT_DISPLAY_NAME_LENGTH:
  406. raise ValueError(
  407. f"Display name must contain 1 to {MAX_AGENT_DISPLAY_NAME_LENGTH} characters"
  408. )
  409. uniqueness_key = normalized.casefold()
  410. if uniqueness_key in _ALL_MENTION_ALIAS_KEYS:
  411. raise ValueError("Display name is reserved")
  412. return normalized, uniqueness_key
  413. def is_reserved_mention_alias(value: str) -> bool:
  414. """Return whether a member-facing name would claim a room-wide Mention."""
  415. return value.strip().casefold() in _ALL_MENTION_ALIAS_KEYS
  416. def validate_optional_display_name(value: str | None) -> str | None:
  417. """Reject only non-empty reserved names; blank still means use the fallback."""
  418. if value is not None and value.strip() and is_reserved_mention_alias(value):
  419. raise ValueError("Display name is reserved")
  420. return value
  421. def normalize_max_reply_rounds(value: object) -> int:
  422. """Validate a finite reply-round ceiling or the explicit unlimited marker."""
  423. if isinstance(value, bool) or not isinstance(value, int):
  424. raise ValueError("maxReplyRounds must be an integer")
  425. if value == UNLIMITED_REPLY_ROUNDS:
  426. return value
  427. if not 1 <= value <= MAX_FINITE_REPLY_ROUNDS:
  428. raise ValueError(
  429. f"maxReplyRounds must be -1 or 1 to {MAX_FINITE_REPLY_ROUNDS}"
  430. )
  431. return value
  432. def normalize_interaction_id(value: object) -> str:
  433. """Canonicalize an opaque Gateway interaction identity for URL use."""
  434. if not isinstance(value, str):
  435. raise ValueError("interactionId must be a string")
  436. normalized = value.strip()
  437. if (
  438. not normalized
  439. or len(normalized) > 200
  440. or any(unicodedata.category(character) == "Cc" for character in normalized)
  441. ):
  442. raise ValueError("interactionId is invalid")
  443. return normalized
  444. def normalize_room_cwd(value: str) -> str:
  445. """Validate and canonicalize an optional room working directory."""
  446. if not isinstance(value, str):
  447. raise ValueError("Room cwd must be a string")
  448. if value and any(unicodedata.category(character) == "Cc" for character in value):
  449. raise ValueError("Room cwd must not contain control characters")
  450. normalized = value.strip()
  451. if not normalized:
  452. return ""
  453. path = Path(normalized)
  454. if not path.is_absolute():
  455. raise ValueError("Room cwd must be an absolute path")
  456. try:
  457. resolved = path.resolve()
  458. is_directory = resolved.is_dir()
  459. except (OSError, RuntimeError) as error:
  460. raise ValueError("Room cwd could not be resolved") from error
  461. if not is_directory:
  462. raise ValueError("Room cwd must exist and be a directory")
  463. return str(resolved)