group_protocol.py 21 KB

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