feishu_drive_tool.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. """Feishu Drive Tools -- document comment operations via Feishu/Lark API.
  2. List / reply-to / add document comments through the generic BaseRequest path (lazy SDK
  3. import), sharing client/request plumbing with feishu_doc_tool via ``tools.feishu_lark``.
  4. The lark client is injected per-thread by the feishu_comment event handler.
  5. """
  6. import logging
  7. from tools.feishu_lark import (
  8. _check_feishu,
  9. build_request,
  10. get_client,
  11. lark_call,
  12. set_client)
  13. from tools.registry import registry, tool_error, tool_result
  14. logger = logging.getLogger(__name__)
  15. def _comment_op(keys, missing_msg, label, method, uri, queries=None, body=None, flag_success=False):
  16. """Handler factory: client check, then required ``keys`` (stripped) → lark_call → result.
  17. All keys except ``content`` are URI path params. ``queries(args)`` / ``body(args, values)``
  18. build the request pieces; ``flag_success`` adds ``success=True`` to the result (writes).
  19. """
  20. def _handler(args: dict, **kwargs) -> str:
  21. client = get_client()
  22. values = tuple(args.get(k, "").strip() for k in keys)
  23. if client is None:
  24. return tool_error("Feishu client not available")
  25. if not all(values):
  26. return tool_error(missing_msg)
  27. code, msg, data = lark_call(
  28. client, method, uri, paths={k: v for k, v in zip(keys, values) if k != "content"},
  29. queries=queries and queries(args), body=body and body(args, values))
  30. if code != 0:
  31. return tool_error(f"{label} failed: code={code} msg={msg}")
  32. return tool_result(success=True, data=data) if flag_success else tool_result(data)
  33. return _handler
  34. def _file_type(args: dict) -> str:
  35. return args.get("file_type", "docx") or "docx"
  36. def _paged_queries(args: dict, *extra) -> list:
  37. """Query params shared by the listing endpoints; page_token goes last (after any extra)."""
  38. queries = [
  39. ("file_type", _file_type(args)), ("user_id_type", "open_id"),
  40. ("page_size", str(args.get("page_size", 100))), *extra]
  41. page_token = args.get("page_token", "")
  42. if page_token:
  43. queries.append(("page_token", page_token))
  44. return queries
  45. _FILE_TOKEN_PROP = {"type": "string", "description": "The document file token."}
  46. _FILE_TYPE_PROP = {"type": "string", "description": "File type (default: docx).", "default": "docx"}
  47. _PAGE_TOKEN_PROP = {"type": "string", "description": "Pagination token for next page."}
  48. _COMMENTS_URI = "/open-apis/drive/v1/files/:file_token/comments"
  49. _REPLIES_URI = "/open-apis/drive/v1/files/:file_token/comments/:comment_id/replies"
  50. _ADD_COMMENT_URI = "/open-apis/drive/v1/files/:file_token/new_comments"
  51. FEISHU_DRIVE_LIST_COMMENTS_SCHEMA = {
  52. "name": "feishu_drive_list_comments",
  53. "description": (
  54. "List comments on a Feishu document. "
  55. "Use is_whole=true to list whole-document comments only."
  56. ),
  57. "parameters": {
  58. "type": "object",
  59. "properties": {
  60. "file_token": _FILE_TOKEN_PROP,
  61. "file_type": _FILE_TYPE_PROP,
  62. "is_whole": {
  63. "type": "boolean",
  64. "description": "If true, only return whole-document comments.",
  65. "default": False,
  66. },
  67. "page_size": {
  68. "type": "integer",
  69. "description": "Number of comments per page (max 100).",
  70. "default": 100,
  71. },
  72. "page_token": _PAGE_TOKEN_PROP,
  73. },
  74. "required": ["file_token"],
  75. },
  76. }
  77. FEISHU_DRIVE_LIST_REPLIES_SCHEMA = {
  78. "name": "feishu_drive_list_comment_replies",
  79. "description": "List all replies in a comment thread on a Feishu document.",
  80. "parameters": {
  81. "type": "object",
  82. "properties": {
  83. "file_token": _FILE_TOKEN_PROP,
  84. "comment_id": {
  85. "type": "string",
  86. "description": "The comment ID to list replies for.",
  87. },
  88. "file_type": _FILE_TYPE_PROP,
  89. "page_size": {
  90. "type": "integer",
  91. "description": "Number of replies per page (max 100).",
  92. "default": 100,
  93. },
  94. "page_token": _PAGE_TOKEN_PROP,
  95. },
  96. "required": ["file_token", "comment_id"],
  97. },
  98. }
  99. FEISHU_DRIVE_REPLY_SCHEMA = {
  100. "name": "feishu_drive_reply_comment",
  101. "description": (
  102. "Reply to a local comment thread on a Feishu document. "
  103. "Use this for local (quoted-text) comments. "
  104. "For whole-document comments, use feishu_drive_add_comment instead."
  105. ),
  106. "parameters": {
  107. "type": "object",
  108. "properties": {
  109. "file_token": _FILE_TOKEN_PROP,
  110. "comment_id": {
  111. "type": "string",
  112. "description": "The comment ID to reply to.",
  113. },
  114. "content": {
  115. "type": "string",
  116. "description": "The reply text content (plain text only, no markdown).",
  117. },
  118. "file_type": _FILE_TYPE_PROP,
  119. },
  120. "required": ["file_token", "comment_id", "content"],
  121. },
  122. }
  123. FEISHU_DRIVE_ADD_COMMENT_SCHEMA = {
  124. "name": "feishu_drive_add_comment",
  125. "description": (
  126. "Add a new whole-document comment on a Feishu document. "
  127. "Use this for whole-document comments or as a fallback when "
  128. "reply_comment fails with code 1069302."
  129. ),
  130. "parameters": {
  131. "type": "object",
  132. "properties": {
  133. "file_token": _FILE_TOKEN_PROP,
  134. "content": {
  135. "type": "string",
  136. "description": "The comment text content (plain text only, no markdown).",
  137. },
  138. "file_type": _FILE_TYPE_PROP,
  139. },
  140. "required": ["file_token", "content"],
  141. },
  142. }
  143. _handle_list_comments = _comment_op(
  144. ("file_token",), "file_token is required", "List comments", "GET", _COMMENTS_URI,
  145. queries=lambda a: _paged_queries(a, *([("is_whole", "true")] if a.get("is_whole", False) else [])))
  146. _handle_list_replies = _comment_op(
  147. ("file_token", "comment_id"), "file_token and comment_id are required", "List replies", "GET",
  148. _REPLIES_URI, queries=_paged_queries)
  149. # Replies use the rich "content.elements[text_run]" body shape; file_type is a query param.
  150. _handle_reply_comment = _comment_op(
  151. ("file_token", "comment_id", "content"), "file_token, comment_id, and content are required",
  152. "Reply comment", "POST", _REPLIES_URI, queries=lambda a: [("file_type", _file_type(a))],
  153. body=lambda a, v: {"content": {"elements": [{"type": "text_run", "text_run": {"text": v[-1]}}]}},
  154. flag_success=True)
  155. # new_comments takes the flat "reply_elements[text]" shape with file_type in the body.
  156. _handle_add_comment = _comment_op(
  157. ("file_token", "content"), "file_token and content are required", "Add comment", "POST",
  158. _ADD_COMMENT_URI,
  159. body=lambda a, v: {"file_type": _file_type(a), "reply_elements": [{"type": "text", "text": v[-1]}]},
  160. flag_success=True)
  161. for _schema, _handler, _desc, _emoji in (
  162. (FEISHU_DRIVE_LIST_COMMENTS_SCHEMA, _handle_list_comments, "List document comments", "\U0001f4ac"),
  163. (FEISHU_DRIVE_LIST_REPLIES_SCHEMA, _handle_list_replies, "List comment replies", "\U0001f4ac"),
  164. (FEISHU_DRIVE_REPLY_SCHEMA, _handle_reply_comment, "Reply to a document comment", "\u2709\ufe0f"),
  165. (FEISHU_DRIVE_ADD_COMMENT_SCHEMA, _handle_add_comment, "Add a whole-document comment", "\u2709\ufe0f"),
  166. ):
  167. registry.register(
  168. name=_schema["name"], toolset="feishu_drive", schema=_schema, handler=_handler,
  169. check_fn=_check_feishu, requires_env=[], is_async=False, description=_desc, emoji=_emoji)