feishu_lark.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Shared lark_oapi plumbing for the feishu_doc / feishu_drive tool modules.
  2. Holds the per-thread client handle, the cheap availability probe, and the generic
  3. ``BaseRequest`` builder + response unpacking (same pattern as feishu_comment.py).
  4. No ``registry.register`` here on purpose: tool discovery must not import this module.
  5. """
  6. import json
  7. import threading
  8. # The lark client is injected per-thread by the feishu_comment event handler right
  9. # before it runs the agent, so concurrent comment events never see each other's client.
  10. _local = threading.local()
  11. def set_client(client):
  12. """Store a lark client for the current thread (called by feishu_comment)."""
  13. _local.client = client
  14. def get_client():
  15. """Return the lark client for the current thread, or None."""
  16. return getattr(_local, "client", None)
  17. def _check_feishu():
  18. # find_spec checks importability without executing lark_oapi's __init__, which
  19. # eagerly loads websockets/dispatcher/every api model (~5s). This probe fires at
  20. # every ``hermes`` startup; the handlers still do the real import when invoked.
  21. import importlib.util
  22. try:
  23. return importlib.util.find_spec("lark_oapi") is not None
  24. except (ImportError, ValueError):
  25. return False
  26. def build_request(method, uri, paths=None, queries=None, body=None):
  27. """Build a tenant-token BaseRequest. Raises ImportError if lark_oapi is missing."""
  28. from lark_oapi import AccessTokenType
  29. from lark_oapi.core.enum import HttpMethod
  30. from lark_oapi.core.model.base_request import BaseRequest
  31. builder = (
  32. BaseRequest.builder()
  33. .http_method(HttpMethod.GET if method == "GET" else HttpMethod.POST)
  34. .uri(uri)
  35. .token_types({AccessTokenType.TENANT}))
  36. if paths:
  37. builder = builder.paths(paths)
  38. if queries:
  39. builder = builder.queries(queries)
  40. if body is not None:
  41. builder = builder.body(body)
  42. return builder.build()
  43. def lark_call(client, method, uri, paths=None, queries=None, body=None):
  44. """Build + execute a BaseRequest; returns (code, msg, data_dict).
  45. Tool handlers run synchronously in a worker thread (no running event loop), so the
  46. blocking lark client is called directly.
  47. """
  48. response = client.request(build_request(method, uri, paths, queries, body))
  49. return getattr(response, "code", None), getattr(response, "msg", ""), response_data(response)
  50. def raw_body(response):
  51. """Parsed JSON object of the raw HTTP body, or None when absent/unparseable/not a dict."""
  52. raw = getattr(response, "raw", None)
  53. try:
  54. body = json.loads(raw.content) if raw and hasattr(raw, "content") else None
  55. except (json.JSONDecodeError, AttributeError):
  56. return None
  57. return body if isinstance(body, dict) else None
  58. def response_data(response) -> dict:
  59. """``data`` of a lark response: prefer the raw JSON body, fall back to typed .data."""
  60. body = raw_body(response)
  61. data = body.get("data", {}) if body is not None else {}
  62. if data:
  63. return data
  64. resp_data = getattr(response, "data", None)
  65. if isinstance(resp_data, dict):
  66. return resp_data
  67. return vars(resp_data) if resp_data and hasattr(resp_data, "__dict__") else data