diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index 3bb011d..e42f5bd 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -205,6 +205,11 @@ def __init__(self, platform: Platform, timing: Optional[Timing] = None, backend_ # only for a connector whose manifest declares it (the hub asks no other, and the method stays off then) self._methods["history.chats"] = self.m_history_chats self._methods["archive.history"] = self.m_archive_history + if "items" in self._capabilities(): + if platform.items_list is not None: + self._methods["items.list"] = lambda p: platform.items_list(self, p) + if platform.items_doc_title is not None: + self._methods["items.doc_title"] = lambda p: platform.items_doc_title(self, p) self.outbound: Optional[Outbound] = None if OUTBOUND in self._capabilities(): # Persona's outbound sends (outbound.py): declared ones only, as history self.outbound = Outbound(self) @@ -338,6 +343,11 @@ def _startup(self) -> None: self.setup_error = e.message self.setup_kind = e.kind log.warning("backend not available: %s", e.kind) + if self.platform.start_services is not None: + try: + self.platform.start_services(self) + except Exception: + log.exception("the platform's optional services could not start") self.agent = AgentRunner(self) if not self.connector_on or self.hub_role == "member": # the user turned the connector off, or another hub does the chat-driven work: nothing answers or @@ -2152,9 +2162,8 @@ def _media(self, params: dict, most: int) -> dict: def m_archive_changes(self, params: dict) -> dict: cursor = str(params.get("cursor") or "") - if cursor and not cursor.isdigit(): - raise RPCError("cursor 不是这个连接器给出的") - after = int(cursor) if cursor else 0 + feeds = self.platform.archive_feeds + after, checkpoints = _archive_cursor(cursor, bool(feeds)) most_chats = _int(params.get("limit"), 100, 1, 500) if self.store is None: return {"batches": [], "next": cursor, "more": False} @@ -2216,7 +2225,14 @@ def rule(cid: str) -> Optional[bool]: chat = self.store.get_chat(chat_id) out.append({"chat": views.archive_chat(chat, chat_id), "messages": [views.archive_message(r, me, self.platform.handle_kind) for r in msgs]}) - return {"batches": out, "next": str(scanned), "more": more} + next_cursor = str(scanned) + if feeds: + for name, read in feeds.items(): + extra, checkpoints[name], pending = read(self, checkpoints.get(name, 0), most_chats - len(out)) + out.extend(extra) + more = more or pending + next_cursor = "v1:" + next_cursor + "".join(":%s=%d" % entry for entry in sorted(checkpoints.items())) + return {"batches": out, "next": next_cursor, "more": more} # ------------------------------------------------------------------ history (the knowledge base's import and its # per-chat settings: Persona lists history.chats in 设置 → 知识库选择 → 添加聊天) @@ -2350,6 +2366,26 @@ def m_archive_history(self, params: dict) -> dict: _SEQ_MOST = (1 << 63) - 1 # SQLite's integers +# 飞书从此版本开始使用 v1: 组合游标,手动回滚后旧程序会拒绝这个游标,须在 Persona 删除此连接器的知识库内容后重新归档。 +# 自动回滚只在新版未能启动时发生,此时尚未发出组合游标。 +def _archive_cursor(raw: str, compound: bool) -> tuple: + def seq(value): + if not (len(value) <= 19 and value.isascii() and value.isdigit()) or int(value) > _SEQ_MOST: + raise RPCError("cursor 不是这个连接器给出的") + return int(value) + + if not compound or not raw.startswith("v1:"): + return seq(raw) if raw else 0, {} + _, first, *feeds = raw.split(":") + checkpoints = {} + for feed in feeds: + key, _, value = feed.partition("=") + if not (key.isascii() and key.isidentifier()) or key in checkpoints: + raise RPCError("cursor 不是这个连接器给出的") + checkpoints[key] = seq(value) + return seq(first), checkpoints + + def _cursor(key: tuple) -> str: return "%r:%d" % (float(key[0]), int(key[1])) # repr: the time reads back exactly diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index 4a56c51..ff48dc7 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -37,6 +37,13 @@ class Platform: #: the sidebar's usage bars (manifest contributes.usage; the hub's usage.query): (the UI, params) → {"accounts": [...]} #: as docs/extensions/extensions.md "Usage extensions" has it; None: the platform contributes no usage usage_query: Optional[Callable[[Any, dict], dict]] = None + #: Optional platform services started after the store and change notifier are available. + start_services: Optional[Callable[[Any], None]] = None + #: Additional archive feeds, with independent cursors. A feed takes (app, after, available batches). + archive_feeds: Dict[str, Callable[[Any, int, int], tuple]] = field(default_factory=dict) + #: Knowledge item RPCs, advertised only with the manifest's items capability. + items_list: Optional[Callable[[Any, dict], dict]] = None + items_doc_title: Optional[Callable[[Any, dict], dict]] = None #: the contribution ids of the core's chats page and its card. Contribution ids are one namespace per hub, so a #: second platform installed beside another needs its own (Feishu keeps "chats", the id its users' layouts know) chats_page: str = "chats" diff --git a/extensions/openmate-feishu/openmate_feishu/__init__.py b/extensions/openmate-feishu/openmate_feishu/__init__.py index 5254c14..2c05e29 100644 --- a/extensions/openmate-feishu/openmate_feishu/__init__.py +++ b/extensions/openmate-feishu/openmate_feishu/__init__.py @@ -52,9 +52,13 @@ def platform(manifest_path: str = "") -> Platform: login_hint_scanned="已扫码,请在飞书手机 App 上点“确认登录”", login_hint_expired="二维码过期了,已换一张新的,请重新扫码", ui_pages=_agenda_pages, + start_services=_start_meetings, + archive_feeds={"meetings": _archive_meetings}, + items_list=_meeting_items, + items_doc_title=_meeting_doc_title, usage_query=_starkmesh_usage, # the sidebar's usage bars: the StarkMesh pool, from the 中转站 page's read legacy_blocked_texts=(DLP_BLOCKED_TEXT,), # what told a blocked message before 0.11.29 stored the mark - tools=_media_tools, # matefeishu_media and matefeishu_members (read-only) + tools=_read_tools, media_tool=CONNECTOR_ID + "_media", inbox_topics=True, agent_task_wait=True, # a request whose conversation handed out work stays open until the answer comes @@ -71,12 +75,44 @@ def _verify_at(app, chat_id, wanted): return verify(app, chat_id, wanted) -def _media_tools(app): - # matefeishu_media (a message's pictures and files) and matefeishu_members (a chat's people and bots, for real @s) +def _read_tools(app): from .media import media_tools + from .meetings import tools as meeting_tools from .members import members_tools - return dict(media_tools(app), **members_tools(app)) + return {**media_tools(app), **members_tools(app), **meeting_tools(app)} + + +def _start_meetings(app): + from openmate_core.fixture import FixtureBackend + + from .meetings import Meetings + from .today import PAGE + + def redraw(): + if app.peer is not None: + for page in (PAGE, "calendar"): + app.peer.notify("ui.invalidate", {"contribution": page}) + + meetings = Meetings(app, on_change=redraw) + if app.connector_on and not isinstance(app.backend, FixtureBackend): + meetings.start() + app.meetings = meetings + + +def _archive_meetings(app, after, limit): + service = getattr(app, "meetings", None) + return service.archive(after, limit) if service else ([], after, False) + + +def _meeting_items(app, params): + service = getattr(app, "meetings", None) + return service.items(params) if service else {"items": []} + + +def _meeting_doc_title(app, params): + service = getattr(app, "meetings", None) + return service.doc_title(params) if service else {"title": ""} def _starkmesh_usage(ui, params): @@ -100,6 +136,7 @@ def _agenda_pages(app): from . import agenda, starkmesh, starkmesh_alerts, today shared = agenda.Agenda(app) + meetings = getattr(app, "meetings", None) persona = today.PersonaToday(app) wechat = today.PeerToday(app) # openmate-wechat's chats, when it is installed beside this one mesh_read = starkmesh.StarkMesh(app) @@ -123,8 +160,9 @@ def tell(): mesh.mesh._fresh.on_ready = drawn_again(starkmesh.PAGE, starkmesh.CARD, today.PAGE) board._fresh.on_ready = drawn_again(agents.PAGE, agents.CARD, today.PAGE) return { - agenda.PAGE: agenda.CalendarPage(app, shared), agenda.CARD: agenda.CalendarPage(app, shared, card=True), - today.PAGE: today.TodayPage(app, shared, persona, mesh=mesh, agents=board, wechat=wechat), + agenda.PAGE: agenda.CalendarPage(app, shared, meetings=meetings), + agenda.CARD: agenda.CalendarPage(app, shared, card=True), + today.PAGE: today.TodayPage(app, shared, persona, mesh=mesh, agents=board, wechat=wechat, meetings=meetings), today.CARD: today.TodayPage(app, shared, persona, card=True, wechat=wechat), starkmesh.PAGE: mesh, starkmesh.CARD: starkmesh.StarkMeshCard(mesh), agents.PAGE: agents.AgentsPage(app, board), agents.CARD: agents.AgentsPage(app, board, card=True), diff --git a/extensions/openmate-feishu/openmate_feishu/agenda.py b/extensions/openmate-feishu/openmate_feishu/agenda.py index e962cab..2a0ae39 100644 --- a/extensions/openmate-feishu/openmate_feishu/agenda.py +++ b/extensions/openmate-feishu/openmate_feishu/agenda.py @@ -9,194 +9,30 @@ from __future__ import annotations import datetime as _dt -import json -import logging -import os -import shlex -import shutil -import subprocess import time from typing import Any, Callable, Dict, List, Optional, Tuple from openmate_core.ui import Fresh, NotYet, Page, day_start, empty, row, stat -log = logging.getLogger("openmate.calendar") +from .larkcli import CalendarError, LarkCLI +from .meetings import ACTION as MEETING_OPEN PAGE = "calendar" CARD = "calendar-today" DAYS = 7 AHEAD = 30.0 # older than this, read again in the background (the page shows the last read meanwhile) -STALE = 900.0 # older than this, a draw waits for a new read +STALE = 900.0 # older than this, a draw shows a loading state until the new read arrives KEEP = 300.0 # while running, read this often anyway, so that a draw after a long while does not wait -TIMEOUT = 25 REFRESH = 120 LATER_MOST = 30 PENDING_MOST = 30 # a page holds 300 items: invitations are also in their day's list TODAY_MOST = 60 -PAGE_WAIT = 12.0 # the 日程 page waits this long at most for a first read (Persona gives a page 20 seconds) +PAGE_WAIT = 12.0 # an open-calendar-event action can wait for a first read WEEKDAYS = "一二三四五六日" RSVP = {"needs_action": ("待回复", "caution"), "tentative": ("暂定", "caution"), "accept": ("已接受", "neutral"), "decline": ("已拒绝", "neutral")} -class CalendarError(Exception): - def __init__(self, message: str, kind: str = "failed"): - super().__init__(message) - self.message = message - self.kind = kind - - -class LarkCLI: - """lark-cli as the user installed it: `calendar +agenda` (a read), and `drive +add-reply` for 自动代答 in a - document's comment (a reply as the user, under a comment they were @-mentioned in).""" - - def __init__(self, config: dict, run: Callable = subprocess.run): - self.setting = str(config.get("lark_cli") or "").strip() - self.profile = str(config.get("lark_cli_profile") or "").strip() - self._run = run - self._bin: Optional[str] = None - - def bin(self) -> str: - if self._bin is not None: - return self._bin - name = self.setting or "lark-cli" - path = "" - if os.path.isabs(name): - path = name if os.access(name, os.X_OK) else "" - else: - path = shutil.which(name) or "" - if not path: # an npm install lives in a version manager's directory that only a login shell has - try: - out = self._run([os.environ.get("SHELL") or "/bin/zsh", "-lc", "command -v " + shlex.quote(name)], - capture_output=True, text=True, timeout=15, stdin=subprocess.DEVNULL).stdout or "" - except (OSError, subprocess.SubprocessError): - out = "" - lines = [x.strip() for x in out.splitlines() if x.strip()] - path = lines[-1] if lines and os.path.isabs(lines[-1]) else "" - self._bin = path - return path - - def fetch_doc(self, doc_url: str, most: int) -> str: - """A document's text as Markdown (a read as the user), at most `most` characters; "" when it can't be read.""" - b = self.bin() - if not b or not doc_url: - return "" - args = [b] + (["--profile", self.profile] if self.profile else []) + [ - "docs", "+fetch", "--as", "user", "--doc", doc_url, "--doc-format", "markdown", "--format", "json"] - env = dict(os.environ) - env["PATH"] = os.path.dirname(b) + os.pathsep + env.get("PATH", "") - try: - p = self._run(args, capture_output=True, text=True, timeout=TIMEOUT, env=env, stdin=subprocess.DEVNULL) - d = json.loads(p.stdout or "{}") - except (subprocess.SubprocessError, OSError, ValueError): - return "" - if not isinstance(d, dict) or not d.get("ok"): - return "" - data = d.get("data") - text = "" - if isinstance(data, str): - text = data - elif isinstance(data, dict): - for k in ("markdown", "content", "text", "body"): - if isinstance(data.get(k), str) and data[k].strip(): - text = data[k] - break - return text.strip()[:most] - - def add_reply(self, doc_url: str, comment_id: str, text: str) -> str: - """Reply to a document's comment as the user; the reply's id ("" when lark-cli doesn't say).""" - b = self.bin() - if not b: - self._bin = None - raise CalendarError("没找到 lark-cli,回复不了文档评论", "missing") - if not doc_url or not comment_id or not text.strip(): - raise CalendarError("缺文档链接、评论 id 或内容", "failed") - content = json.dumps([{"type": "text", "text": text}], ensure_ascii=False) - args = [b] + (["--profile", self.profile] if self.profile else []) + [ - "drive", "+add-reply", "--as", "user", "--url", doc_url, "--comment-id", comment_id, "--content", content, - "--format", "json"] - env = dict(os.environ) - env["PATH"] = os.path.dirname(b) + os.pathsep + env.get("PATH", "") - try: - p = self._run(args, capture_output=True, text=True, timeout=TIMEOUT, env=env, stdin=subprocess.DEVNULL) - except subprocess.TimeoutExpired: - raise CalendarError("lark-cli 回复评论超时了;回复可能已经发出,请到文档里看一下", "uncertain") - except OSError: - raise CalendarError("lark-cli 启动不了", "missing") - out = p.stdout or "" - if getattr(p, "returncode", 0) and not out.strip(): - out = p.stderr or "" # a failure's JSON comes on stderr - try: - d = json.loads(out) - except ValueError: # it ran and said nothing readable: the reply may be in the document - raise CalendarError("lark-cli 回复评论后的回答看不懂;回复可能已经发出,请到文档里看一下", "uncertain") - if not isinstance(d, dict) or not d.get("ok"): - err = d.get("error") if isinstance(d, dict) and isinstance(d.get("error"), dict) else {} - kind = "%s %s" % (err.get("type") or "", err.get("subtype") or "") - if "authorization" in kind or "scope" in kind or "login" in kind or "token" in kind: - raise CalendarError("还没授权回复文档评论:在这台电脑上运行 lark-cli%s auth login,按提示在飞书里确认" % ( - " --profile " + self.profile if self.profile else ""), "auth") - if any(w in kind for w in ("validation", "invalid", "not_found", "permission", "forbidden")): - raise CalendarError("lark-cli 回复评论失败(%s)" % kind.strip(), "failed") # refused: nothing went - # a network failure, a timeout or anything else: the reply may be in the document - raise CalendarError("lark-cli 回复评论时出错(%s);回复可能已经发出,请到文档里看一下" % (kind.strip() or "原因不明"), - "uncertain") - data = d.get("data") if isinstance(d.get("data"), dict) else {} - return str(data.get("reply_id") or data.get("id") or "") - - def user_name(self) -> str: - """Who lark-cli acts as for the user (its signed-in user's name), "" when it can't tell.""" - b = self.bin() - if not b: - return "" - args = [b] + (["--profile", self.profile] if self.profile else []) + ["auth", "status"] - env = dict(os.environ) - env["PATH"] = os.path.dirname(b) + os.pathsep + env.get("PATH", "") - try: - p = self._run(args, capture_output=True, text=True, timeout=20, env=env, stdin=subprocess.DEVNULL) - d = json.loads(p.stdout or "{}") - except (subprocess.TimeoutExpired, OSError, ValueError): - return "" - user = ((d.get("identities") or {}).get("user") or {}) if isinstance(d, dict) else {} - if not isinstance(user, dict) or not user.get("available"): - return "" - return str(user.get("userName") or "").strip() - - def agenda(self, start: _dt.datetime, end: _dt.datetime) -> List[dict]: - b = self.bin() - if not b: - self._bin = None # installed later: look again next time - raise CalendarError("没找到 lark-cli:先在这台电脑上安装飞书 lark-cli,或在扩展设置里填它的路径(lark_cli)", "missing") - args = [b] + (["--profile", self.profile] if self.profile else []) + [ - "calendar", "+agenda", "--as", "user", "--start", start.isoformat(), "--end", end.isoformat(), "--format", "json"] - env = dict(os.environ) - env["PATH"] = os.path.dirname(b) + os.pathsep + env.get("PATH", "") # an npm shim runs `env node` - try: - p = self._run(args, capture_output=True, text=True, timeout=TIMEOUT, env=env, stdin=subprocess.DEVNULL) - except subprocess.TimeoutExpired: - raise CalendarError("lark-cli 读日程超时了,稍后会再试", "timeout") - except OSError: - raise CalendarError("lark-cli 启动不了", "missing") - try: - d = json.loads(p.stdout or "{}") - except ValueError: - raise CalendarError("lark-cli 的回答看不懂(版本不对?)", "failed") - if not isinstance(d, dict): - raise CalendarError("lark-cli 的回答看不懂(版本不对?)", "failed") - if not d.get("ok"): - err = d.get("error") if isinstance(d.get("error"), dict) else {} - kind = "%s %s" % (err.get("type") or "", err.get("subtype") or "") - if "authorization" in kind or "scope" in kind or "login" in kind or "token" in kind: - login = "lark-cli%s auth login --scope calendar:calendar.event:read" % ( - " --profile " + self.profile if self.profile else "") - raise CalendarError("还没授权读日程:在这台电脑上运行 %s,按提示在飞书里确认" % login, "auth") - raise CalendarError("lark-cli 读日程失败(%s)" % (kind.strip() or "原因不明"), "failed") - data = d.get("data") - if isinstance(data, dict): - data = data.get("items") or data.get("events") or [] - return [e for e in (data or []) if isinstance(e, dict)] - - def event_time(t, tz) -> Tuple[Optional[_dt.datetime], bool]: """(the moment, all-day) of a start_time / end_time: {datetime, timezone}, {date}, or a timestamp.""" if not isinstance(t, dict): @@ -260,8 +96,7 @@ def badge(self) -> Optional[dict]: class Agenda: - """The next DAYS days of events: lark-cli takes seconds, so a draw shows the last read and reads again behind it - (Fresh); a new day, or a read older than STALE, waits.""" + """The next DAYS days of events, read in the background (Fresh).""" def __init__(self, app, clock: Callable[[], float] = time.time, cli: Optional[LarkCLI] = None, spawn: Optional[Callable] = None): @@ -292,10 +127,11 @@ def events(self, wait: Optional[float] = None) -> List[Event]: class CalendarPage(Page): - def __init__(self, app, agenda: Agenda, card: bool = False): + def __init__(self, app, agenda: Agenda, card: bool = False, meetings=None): self.app = app self.agenda = agenda self.card = card + self.meetings = meetings def warm(self) -> None: self.agenda.warm() @@ -336,12 +172,16 @@ def _row(self, e: Event, with_day: bool, interactive: bool, part: str) -> dict: def render(self, params: dict) -> dict: version = int(params.get("ui_version") or 1) + recent = self.meetings.section(version) if self.meetings is not None and not self.card else None try: - events = self.agenda.events(PAGE_WAIT) + events = self.agenda.events(0.0) except CalendarError as e: - if e.kind == "loading": - return {"sections": [{"items": [empty("正在读取日程", "稍后自动刷新", version)]}], "refresh_after": 5} - return {"sections": [{"items": [empty("日程读不到", e.message, version)]}], "refresh_after": REFRESH * 5} + loading = e.kind == "loading" + sections = [{"items": [empty("正在读取日程" if loading else "日程读不到", + "稍后自动刷新" if loading else e.message, version)]}] + if recent: + sections.append(recent) + return {"sections": sections, "refresh_after": 5 if loading else REFRESH * 5} now, today, later = self._split(events) sections: List[Dict[str, Any]] = [{"items": [self._stats(now, today, events, version)]}] if self.card: @@ -359,11 +199,15 @@ def render(self, params: dict) -> dict: sections.append({"title": "接下来 %d 天" % (DAYS - 1), "items": [self._row(e, True, True, "later") for e in later[:LATER_MOST]], **({"footer": "还有 %d 个" % (len(later) - LATER_MOST)} if len(later) > LATER_MOST else {})}) + if recent: + sections.append(recent) return {"title": "日程", "sections": sections, "refresh_after": REFRESH} def action(self, params: dict) -> dict: a = params.get("action") aid = str(a.get("id") if isinstance(a, dict) else a or "") + if self.meetings is not None and aid.startswith(MEETING_OPEN): + return self.meetings.open(aid) if aid.startswith("open:"): try: events = self.agenda.events(PAGE_WAIT) diff --git a/extensions/openmate-feishu/openmate_feishu/larkcli.py b/extensions/openmate-feishu/openmate_feishu/larkcli.py new file mode 100644 index 0000000..e6d31e0 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/larkcli.py @@ -0,0 +1,319 @@ +"""Run the locally installed lark-cli with one concurrency budget per extension process.""" + +from __future__ import annotations + +import json +import logging +import os +import re +import shlex +import shutil +import subprocess +import threading +import time +from typing import Callable, Optional + +log = logging.getLogger("openmate.larkcli") +TIMEOUT = 25 +MISSING = "没找到 lark-cli:先在这台电脑上安装飞书 lark-cli,或在扩展设置里填它的路径(lark_cli)" +CALENDAR_SCOPE = "calendar:calendar.event:read" +BIN_RETRY = 300 +_SLOTS = threading.BoundedSemaphore(2) +_SCOPE = re.compile(r"\b[a-z][a-z0-9_.]*:(?:[a-z][a-z0-9_.]*:)*(?:readonly|read|list|search)\b") +_AUTH_REASONS = frozenset({ + "missing_scope", "missing_scopes", "invalid_token", "token_invalid", "token_expired", "expired_token", + "invalid_access_token", "access_token_invalid", "access_token_expired", + "not_authenticated", "unauthenticated", "not_logged_in", "not_signed_in", "login_required", "login_expired", +}) +_AUTH_MESSAGE = re.compile( + r"\b(?:missing (?:required )?scopes?|(?:invalid|expired) (?:(?:access|refresh) )?token|" + r"token (?:is |has )?(?:invalid|expired)|not (?:logged in|signed in|authenticated)|(?:log ?in|sign ?in) required)\b" +) +# Only these shortcuts return individually identifiable results in a failed envelope. +_BATCH_RESULTS = {"minutes +detail": ("minutes", "minute_token"), "vc +detail": ("meetings", "meeting_id")} + + +def _command_size(args): + return 3 if tuple(args[:2]) in (("drive", "metas"), ("minutes", "minutes")) else 2 + + +class CalendarError(Exception): + def __init__(self, message: str, kind: str = "failed", *, refused: bool = False, scope: str = ""): + super().__init__(message) + self.message = message + self.kind = kind + self.refused = refused + self.scope = scope + + +class CallStats: + def __init__(self, interval=3600): + self.interval = interval + self.lock = threading.Lock() + self.calls = {} + + def record(self, command, elapsed, failed): + with self.lock: + if not self.calls: + timer = threading.Timer(self.interval, self.flush) + timer.daemon = True + timer.start() + count, failures, total, slowest = self.calls.get(command, (0, 0, 0.0, 0.0)) + self.calls[command] = count + 1, failures + int(failed), total + elapsed, max(slowest, elapsed) + + def flush(self): + with self.lock: + calls, self.calls = self.calls, {} + if calls: + log.info("lark-cli: %s", "; ".join( + "%s calls=%d failures=%d total=%.2fs max=%.2fs" % (name, *stats) + for name, stats in sorted(calls.items()))) + + +_STATS = CallStats() + + +def _json_object(output): + try: + data = json.loads(output or "") + return data if isinstance(data, dict) else None + except ValueError: + # Progress and warning lines can surround a single pretty-printed JSON error on stderr. + decoder = json.JSONDecoder() + for start in re.finditer(r"(?m)^\s*(?=\{)", output or ""): + try: + data, _ = decoder.raw_decode(output, start.end()) + except ValueError: + continue + if isinstance(data, dict) and ("ok" in data or "error" in data): + return data + return None + + +def _batch_payload(command, payload): + keys = _BATCH_RESULTS.get(command) + if keys is None or not isinstance(payload, dict): + return None + field, id_field = keys + items = payload.get(field) + if isinstance(items, list) and any(isinstance(item, dict) and item.get(id_field) for item in items): + return payload + return None + + +def doc_content(data) -> str: + if isinstance(data, str): + return data.strip() + if isinstance(data, dict): + document = data.get("document") + for src in (data, document if isinstance(document, dict) else {}): + for key in ("markdown", "content", "text", "body"): + value = src.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +class LarkCLI: + def __init__(self, config: dict, run: Callable = subprocess.run, store=None): + self.setting = str(config.get("lark_cli") or "").strip() + self.profile = str(config.get("lark_cli_profile") or "").strip() + self._run = run + self._bin: Optional[str] = None + self._bin_retry_at = 0.0 + self._bin_lock = threading.Lock() + self._store = store + self._user = None + + def bin(self, timeout: float = 15) -> str: + deadline = time.monotonic() + timeout + if not self._bin_lock.acquire(timeout=max(timeout, 0.0)): + raise CalendarError("找 lark-cli 超时了", "timeout", refused=True) + try: + now = time.monotonic() + if self._bin: + return self._bin + if self._bin == "" and now < self._bin_retry_at: + return "" + remaining = deadline - now + if remaining <= 0: + raise CalendarError("找 lark-cli 超时了", "timeout", refused=True) + self._bin = self._find_bin(remaining) + if not self._bin: + self._bin_retry_at = time.monotonic() + BIN_RETRY + return self._bin + finally: + self._bin_lock.release() + + def _find_bin(self, timeout: float) -> str: + name = self.setting or "lark-cli" + if os.path.isabs(name): + path = name if os.access(name, os.X_OK) else "" + else: + path = shutil.which(name) or "" + if not path: + try: + out = self._run([os.environ.get("SHELL") or "/bin/zsh", "-lc", "command -v " + shlex.quote(name)], + capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL).stdout or "" + except OSError: + out = "" + lines = [line.strip() for line in out.splitlines() if line.strip()] + path = lines[-1] if lines and os.path.isabs(lines[-1]) else "" + return path + + def login_hint(self, scope="") -> str: + profile = " --profile " + shlex.quote(self.profile) if self.profile else "" + return "lark-cli%s auth login%s" % (profile, " --scope " + shlex.quote(scope) if scope else "") + + def _error(self, data) -> CalendarError: + err = data.get("error") + if isinstance(err, str): + err = {"message": err} + err = err if isinstance(err, dict) else {} + reasons = {str(err.get(k) or "").strip().lower() for k in ("type", "subtype")} + message = str(err.get("message") or "").lower() + if reasons & {"permission_denied", "forbidden"} or any( + phrase in message for phrase in ("lacks permission", "no permission", "no read permission")): + return CalendarError("lark-cli 没有读取权限", "permission", refused=True) + missing = err.get("missing_scopes") or data.get("missing_scopes") + if missing or reasons & _AUTH_REASONS or _AUTH_MESSAGE.search(message): + scope = " ".join(dict.fromkeys(_SCOPE.findall(str(missing or err.get("hint") or err.get("message") or "")))) + return CalendarError("还没授权:在这台电脑上运行 %s,按提示在飞书里确认" % self.login_hint(scope), + "auth", refused=True, scope=scope) + detail = " ".join(sorted(reasons)) + words = detail + " " + message + if any(w in words for w in ("permission", "forbidden", "no access", "access denied")): + return CalendarError("lark-cli 没有读取权限", "permission", refused=True) + if "timeout" in words or "timed out" in words: + return CalendarError("lark-cli 超时了,稍后会再试", "timeout") + refused = "authorization" in reasons or any(w in detail for w in ("validation", "invalid", "not_found")) + return CalendarError("lark-cli 调用失败", refused=refused) + + def call(self, args, timeout: float = TIMEOUT): + """Return data from the CLI envelope, or the top-level auth status object.""" + began = time.monotonic() + deadline = began + timeout + command = " ".join(args[:_command_size(args)]) + failed = True + acquired = False + try: + try: + b = self.bin(min(deadline - time.monotonic(), 15)) + except subprocess.TimeoutExpired: + raise CalendarError("找 lark-cli 超时了", "timeout", refused=True) from None + if not b: + raise CalendarError(MISSING, "missing", refused=True) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise CalendarError("找 lark-cli 超时了", "timeout", refused=True) + acquired = _SLOTS.acquire(timeout=remaining) + remaining = deadline - time.monotonic() + if not acquired or remaining <= 0: + raise CalendarError("lark-cli 等候执行超时了", "timeout", refused=True) + cmd = [b] + (["--profile", self.profile] if self.profile else []) + list(args) + env = dict(os.environ) + env["PATH"] = os.path.dirname(b) + os.pathsep + env.get("PATH", "") + try: + p = self._run(cmd, capture_output=True, text=True, timeout=remaining, env=env, stdin=subprocess.DEVNULL) + except subprocess.TimeoutExpired: + raise CalendarError("lark-cli 超时了,稍后会再试", "timeout") from None + except OSError: + self._bin = None + raise CalendarError("lark-cli 启动不了", "missing", refused=True) from None + data = _json_object(p.stdout) + if not getattr(p, "returncode", 0) and data is not None: + if data.get("ok"): + failed = False + return data.get("data") + if list(args[:2]) == ["auth", "status"] and "identities" in data: + failed = False + return data + reports = [report for report in (data, _json_object(p.stderr)) if report] + for report in reports: + if report.get("error") or report.get("missing_scopes"): + raise self._error(report) + for report in reports: + if report.get("ok") is False: + payload = _batch_payload(command, report.get("data")) + if payload is not None: + return payload + if any(report.get("ok") is False for report in reports): + raise CalendarError("lark-cli 调用失败") + raise CalendarError("lark-cli 的回答看不懂(版本不对?)") + finally: + if acquired: + _SLOTS.release() + _STATS.record(command, time.monotonic() - began, failed) + + def read(self, args, timeout: float = TIMEOUT): + n = _command_size(args) + return self.call([*args[:n], "--as", "user", *args[n:], "--format", "json"], timeout) + + def read_doc(self, doc: str) -> str: + return doc_content(self.read(["docs", "+fetch", "--doc", doc, "--doc-format", "markdown"])) + + def fetch_doc(self, doc_url: str, most: int) -> str: + if doc_url: + try: + return self.read_doc(doc_url)[:most] + except CalendarError: + pass + return "" + + def add_reply(self, doc_url: str, comment_id: str, text: str) -> str: + if not doc_url or not comment_id or not text.strip(): + raise CalendarError("缺文档链接、评论 id 或内容") + content = json.dumps([{"type": "text", "text": text}], ensure_ascii=False) + try: + data = self.read(["drive", "+add-reply", "--url", doc_url, "--comment-id", comment_id, "--content", content]) + except CalendarError as e: + if e.kind == "auth": + raise CalendarError("还没授权回复文档评论:在这台电脑上运行 %s,按提示在飞书里确认" % + self.login_hint(), "auth") from None + if e.kind == "missing": + raise CalendarError("没找到 lark-cli,回复不了文档评论", "missing") from None + if e.refused: + raise CalendarError("lark-cli 回复评论失败(%s)" % e.message) from None + raise CalendarError("%s;回复可能已经发出,请到文档里看一下" % e.message, "uncertain") from None + return str(data.get("reply_id") or data.get("id") or "") if isinstance(data, dict) else "" + + def _identity(self): + status = self.call(["auth", "status"], 20) + identities = status.get("identities") if isinstance(status, dict) else None + user = identities.get("user") if isinstance(identities, dict) else None + return user if isinstance(user, dict) and user.get("available") else {} + + def user_name(self) -> str: + # Document replies check again before sending, even when the meeting worker has a cached identity. + try: + return str(self._identity().get("userName") or "").strip() + except CalendarError: + return "" + + def user_open_id(self, refresh: bool = False) -> str: + if self._user is None or refresh: + self._user = None + user = self._identity() + owner = str(user.get("openId") or "").strip() + if self._store is not None and self._store.meta_get("lark_cli_open_id") != owner: + self._store.meta_set("lark_cli_open_id", owner) + self._user = user + return str(self._user.get("openId") or "").strip() + + @property + def cached_user_name(self) -> str: + return str((self._user or {}).get("userName") or "").strip() + + def agenda(self, start, end): + try: + data = self.read(["calendar", "+agenda", "--start", start.isoformat(), "--end", end.isoformat()]) + except CalendarError as e: + if e.kind == "auth": + raise CalendarError("还没授权读日程:在这台电脑上运行 %s,按提示在飞书里确认" % + self.login_hint(CALENDAR_SCOPE), "auth") from None + if e.kind == "timeout": + raise CalendarError("lark-cli 读日程超时了,稍后会再试", "timeout") from None + raise + if isinstance(data, dict): + data = data.get("items") or data.get("events") + return [e for e in data if isinstance(e, dict)] if isinstance(data, list) else [] diff --git a/extensions/openmate-feishu/openmate_feishu/layout.py b/extensions/openmate-feishu/openmate_feishu/layout.py index f84337b..d265323 100644 --- a/extensions/openmate-feishu/openmate_feishu/layout.py +++ b/extensions/openmate-feishu/openmate_feishu/layout.py @@ -19,6 +19,7 @@ ("status", "状态", True, "需要我、日程、飞书、微信、Agent、中转站,各一块,带状态标签"), ("needs", "需要我", True, "要你回复、决定或验收的事"), ("calendar", "日程", False, "今天的会和待回复的邀请"), + ("meetings", "会议", False, "最近开完的会:纪要有没有进知识库、会上分给我的待办"), ("feishu", "飞书今天", False, "今天活跃的群"), ("wechat", "微信今天", False, "今天活跃的微信群(装了微信扩展才有)"), ("agents", "Agent", False, "等你、可能卡住、在跑的 Agent"), diff --git a/extensions/openmate-feishu/openmate_feishu/meeting_store.py b/extensions/openmate-feishu/openmate_feishu/meeting_store.py new file mode 100644 index 0000000..e884e3c --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/meeting_store.py @@ -0,0 +1,156 @@ +"""The Feishu meeting cache and its append-only archive positions, in the extension's existing store.""" + +from __future__ import annotations + +import json + +_SCHEMA = ( + """CREATE TABLE IF NOT EXISTS meetings ( + meeting_id TEXT PRIMARY KEY, owner TEXT NOT NULL, topic TEXT NOT NULL, + start REAL, end REAL, note_id TEXT NOT NULL DEFAULT '', minute_token TEXT NOT NULL DEFAULT '', + note_doc_token TEXT NOT NULL DEFAULT '', verbatim_doc_token TEXT NOT NULL DEFAULT '', + note_url TEXT NOT NULL DEFAULT '', note_title TEXT NOT NULL DEFAULT '', + minute_url TEXT NOT NULL DEFAULT '', app_link TEXT NOT NULL DEFAULT '', + state TEXT NOT NULL DEFAULT 'pending', summary TEXT NOT NULL DEFAULT '', + todos TEXT NOT NULL DEFAULT '[]', chapters TEXT NOT NULL DEFAULT '[]', people TEXT NOT NULL DEFAULT '[]', + links TEXT NOT NULL DEFAULT '[]', + transcript TEXT, tries INTEGER NOT NULL DEFAULT 0, misses INTEGER NOT NULL DEFAULT 0, + next_try REAL NOT NULL DEFAULT 0, updated REAL NOT NULL, kb_seq INTEGER NOT NULL DEFAULT 0, + transcript_seq INTEGER NOT NULL DEFAULT 0, transcript_tries INTEGER NOT NULL DEFAULT 0, + transcript_next REAL NOT NULL DEFAULT 0, archive_offered INTEGER NOT NULL DEFAULT 0 + )""", + "CREATE INDEX IF NOT EXISTS meetings_end ON meetings(owner, end DESC, meeting_id)", + "CREATE INDEX IF NOT EXISTS meetings_due ON meetings(owner, state, next_try)", + "CREATE INDEX IF NOT EXISTS meetings_kb ON meetings(owner, kb_seq)", + "CREATE INDEX IF NOT EXISTS meetings_transcript_kb ON meetings(owner, transcript_seq)", + "CREATE INDEX IF NOT EXISTS meetings_transcript_due ON meetings(owner, state, transcript_next)" + " WHERE transcript IS NULL AND transcript_next >= 0", + "CREATE INDEX IF NOT EXISTS meetings_minute ON meetings(owner, minute_token)", + "CREATE INDEX IF NOT EXISTS meetings_note ON meetings(owner, note_doc_token)", +) +_JSON = ("todos", "chapters", "people", "links") +_SEQ_KEY = "meetings_archive_seq" +_BRIEF = "meeting_id, topic, start, end, note_url, minute_url, app_link, state" + + +def _row(raw): + out = dict(raw) + for key in _JSON: + if key in out: + out[key] = json.loads(out[key]) + return out + + +class MeetingStore: + def __init__(self, store): + self.store = store + store._tx(self._setup) + + @staticmethod + def _setup(db): + for sql in _SCHEMA: + db.execute(sql) + + def has_rows(self, owner): + return self.store._one("SELECT 1 FROM meetings WHERE owner=? LIMIT 1", (owner,)) is not None + + def discover(self, owner, found, now): + if not found: + return + # The same meeting may be seen by another identity. It belongs to that identity only after a fresh read. + def write(db): + db.executemany("DELETE FROM meetings WHERE meeting_id=? AND owner!=?", [(mid, owner) for mid in found]) + db.executemany( + "INSERT INTO meetings(meeting_id, owner, topic, app_link, updated) VALUES (?, ?, ?, ?, ?) " + "ON CONFLICT(meeting_id) DO NOTHING", + [(mid, owner, topic, link, now) for mid, (topic, link) in found.items()]) + self.store._tx(write) + + def known(self, owner, found): + if not found: + return set() + marks = ",".join("?" for _ in found) + return {r[0] for r in self.store._all( + "SELECT meeting_id FROM meetings WHERE meeting_id IN (%s) AND owner=?" % marks, (*found, owner))} + + def due(self, owner, now): + return [_row(r) for r in self.store._all( + "SELECT * FROM meetings WHERE owner=? AND state='pending' AND next_try<=? ORDER BY next_try", + (owner, now))] + + def due_transcripts(self, owner, now): + return [_row(r) for r in self.store._all( + "SELECT * FROM meetings WHERE owner=? AND state='ready' AND transcript IS NULL AND transcript_next>=0 " + "AND transcript_next<=? ORDER BY transcript_next LIMIT 20", (owner, now))] + + def save(self, owner, mid, fields): + """Assign archive positions in the same transaction that first makes their content available.""" + def write(db): + row = db.execute("SELECT kb_seq, transcript_seq FROM meetings WHERE meeting_id=? AND owner=?", + (mid, owner)).fetchone() + if row is None: + return False + values = {key: json.dumps(value, ensure_ascii=False) if key in _JSON else value + for key, value in fields.items()} + notify = False + for key, present in (("kb_seq", fields.get("state") == "ready"), + ("transcript_seq", bool(fields.get("transcript")))): + if present and not row[key]: + db.execute("INSERT INTO meta(key,value) VALUES (?, '1') ON CONFLICT(key) DO UPDATE " + "SET value=CAST(value AS INTEGER)+1", (_SEQ_KEY,)) + values[key] = int(db.execute("SELECT value FROM meta WHERE key=?", (_SEQ_KEY,)).fetchone()[0]) + notify = True + db.execute("UPDATE meetings SET " + ", ".join(key + "=?" for key in values) + + " WHERE meeting_id=? AND owner=?", (*values.values(), mid, owner)) + return notify + return self.store._tx(write) + + def recent(self, owner, since, now, limit, *, view="", query=""): + columns = _BRIEF + clauses = ["owner=?", "end BETWEEN ? AND ?"] + args = [owner, since, now] + if view == "items": + columns += ", minute_token" + clauses.append("(state='denied' OR (state='ready' AND archive_offered=1))") + if view == "page": + columns += ", todos, archive_offered" + columns += ", (SELECT value FROM meta WHERE key='account_name') AS self_name" + if query: + clauses.append("instr(lower(topic), lower(?))>0") + args.append(query) + return [_row(r) for r in self.store._all( + "SELECT " + columns + " FROM meetings WHERE " + " AND ".join(clauses) + + " ORDER BY end DESC, meeting_id LIMIT ?", (*args, limit))] + + def get(self, owner, mid): + row = self.store._one("SELECT * FROM meetings WHERE meeting_id=? AND owner=? AND end IS NOT NULL", (mid, owner)) + return _row(row) if row else None + + def cached_title(self, owner, kind, token): + columns = {"minutes": ("minute_token", "topic"), "docx": ("note_doc_token", "note_title")}.get(kind) + if not columns: + return "" + field, title = columns + row = self.store._one("SELECT " + title + " FROM meetings WHERE owner=? AND " + field + "=?" + " AND " + title + "!='' LIMIT 1", (owner, token)) + return row[0] if row else "" + + def high_water(self): + return int(self.store.meta_get(_SEQ_KEY, "0")) + + def archive(self, owner, after, limit): + return [_row(r) for r in self.store._all( + """WITH events(seq, meeting_id, part) AS ( + SELECT kb_seq, meeting_id, 'note' FROM meetings WHERE owner=? AND kb_seq>? + UNION ALL + SELECT transcript_seq, meeting_id, 'transcript' FROM meetings WHERE owner=? AND transcript_seq>? + ) + SELECT meetings.*, events.seq, events.part FROM events JOIN meetings USING(meeting_id) + ORDER BY events.seq LIMIT ?""", (owner, after, owner, after, limit))] + + def offered(self, owner, ids): + if not ids: + return False + return self.store._tx(lambda db: db.executemany( + "UPDATE meetings SET archive_offered=1 WHERE owner=? AND meeting_id=? AND archive_offered=0", + [(owner, mid) for mid in ids]).rowcount > 0) diff --git a/extensions/openmate-feishu/openmate_feishu/meeting_text.py b/extensions/openmate-feishu/openmate_feishu/meeting_text.py new file mode 100644 index 0000000..b998108 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/meeting_text.py @@ -0,0 +1,120 @@ +"""Turn the mixed Markdown and DocxXML returned by lark-cli into meeting text.""" + +from __future__ import annotations + +import re +from html.parser import HTMLParser + +_HEADING = re.compile(r"^\s*#(?:[ \t]+(.*))?$") +_SECTIONS = {"总结", "待办", "相关链接"} +_TASK = re.compile(r"^\s*[-*+]\s+\[([ xX])\]\s+(.+)") +_OWNER = re.compile(r"^(.+?)\s*[((]([^()()]+)[))]\s*$") +_LINK = re.compile(r"\]\((https://[^\s)]+)\)") +_TURN = re.compile(r"(?P[^#>::\s][^::\n]*?)\s+(?P\d{2,}:[0-5]\d:[0-5]\d)") +_UNTIMED_TURN = re.compile(r"(?P[^#>::\s][^::\n]{0,59}?)[::]\s*(?P.+)") + + +class _Document(HTMLParser): + def __init__(self): + super().__init__(convert_charrefs=True) + self.parts = [] + self.people = {} + self._skip = [] + + def handle_starttag(self, tag, attrs): + if self._skip or tag in ("title", "whiteboard", "readonly-block", "script", "style"): + if tag not in ("br", "img", "hr", "input"): + self._skip.append(tag) + return + if tag == "cite": + attrs = dict(attrs) + if attrs.get("type") == "user": + ident, name = attrs.get("user-id") or "", attrs.get("user-name") or "" + if ident or name: + self.people[ident or name] = {"name": name, "open_id": ident} + self.parts.append(name or ident) + elif tag == "li": + self.parts.append("\n- ") + elif re.fullmatch(r"h[1-6]", tag): + self.parts.append("\n" + "#" * int(tag[1]) + " ") + elif tag in ("p", "div", "blockquote", "column", "br"): + self.parts.append("\n") + + def handle_endtag(self, tag): + if self._skip: + if self._skip[-1] == tag: + self._skip.pop() + return + if tag in ("p", "div", "li", "blockquote", "column", "grid", "td", "tr") or re.fullmatch(r"h[1-6]", tag): + self.parts.append("\n") + + def handle_data(self, data): + if not self._skip: + self.parts.append(data) + + def text(self): + return re.sub(r"\n[ \t]*\n(?:[ \t]*\n)+", "\n\n", "".join(self.parts)).strip() + + +def plain_text(raw): + doc = _Document() + doc.feed(raw) + doc.close() + return doc.text() + + +def parse_note(raw): + doc = _Document() + doc.feed(raw) + doc.close() + parts = {} + current = "" + for line in doc.text().splitlines(): + heading = _HEADING.fullmatch(line) + if heading: + title = (heading[1] or "").strip().rstrip("#").rstrip() + current = title if title in _SECTIONS else "" + elif current: + parts.setdefault(current, []).append(line) + todos = [] + for line in parts.get("待办", []): + task = _TASK.match(line) + if task: + owner = _OWNER.fullmatch(task[2].strip()) + todos.append({"text": owner[1].strip() if owner else task[2].strip(), + "owner": owner[2].strip() if owner else "", "done": task[1].lower() == "x"}) + return dict(summary="\n".join(parts.get("总结", [])).strip(), todos=todos, + people=list(doc.people.values()), links=_LINK.findall("\n".join(parts.get("相关链接", [])))) + + +def _seconds(stamp): + seconds = 0 + for part in stamp.split(":"): + seconds = seconds * 60 + int(part) + return seconds + + +def transcript_turns(text, *, allow_untimed=False): + """Yield speaker, offset and text from timestamped turns, skipping the document preamble.""" + source = text.splitlines() + pattern = _TURN + # A raw Minutes download can carry speaker labels without timestamps. + if allow_untimed and not any(_TURN.fullmatch(line.strip()) for line in source): + pattern = _UNTIMED_TURN + turn = None + lines = [] + for line in source: + stripped = line.strip() + if not stripped: + continue + match = pattern.fullmatch(stripped) + if match: + if lines: + yield (*turn, "\n".join(lines)) + parts = match.groupdict() + turn = parts["name"], _seconds(parts["stamp"]) if "stamp" in parts else None + lines = [parts["text"]] if "text" in parts else [] + elif turn is not None: + lines.append(line) + if lines: + yield (*turn, "\n".join(lines)) diff --git a/extensions/openmate-feishu/openmate_feishu/meetings.py b/extensions/openmate-feishu/openmate_feishu/meetings.py new file mode 100644 index 0000000..ff44ca2 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/meetings.py @@ -0,0 +1,647 @@ +"""Synchronize finished Feishu meetings, then serve the cached rows to Persona.""" + +from __future__ import annotations + +import datetime as dt +import json +import logging +import re +import tempfile +import threading +import time +from pathlib import Path +from urllib.parse import urlsplit + +from openmate_core.ui import empty, row +from openmate_core.views import rfc3339 + +from .larkcli import CalendarError, LarkCLI +from .meeting_store import MeetingStore +from .meeting_text import parse_note, plain_text, transcript_turns + +log = logging.getLogger("openmate.meetings") +DAY = 86400 +ACTIVE = 600 +IDLE = 1800 +IDENTITY_REFRESH = IDLE +TITLE_TTL = 7 * DAY +TRANSCRIPT_LIMIT = 200 * 1024 +TRUNCATED = "\n(逐字稿太长,后面截掉了)" +SCOPES = ("vc:meeting.search:read vc:meeting:readonly minutes:minutes:readonly minutes:minutes.basic:read " + "docx:document:readonly drive:drive.metadata:readonly") +ACTION = "meeting:open:" +_RETRY_FIELDS = {"tries", "misses", "next_try", "transcript_tries", "transcript_next"} +_BADGES = { + "pending": ("等纪要", "caution"), + "none": ("没有纪要", "neutral"), + "denied": ("看不了", "caution"), + "failed": ("读取失败", "caution"), +} + + +def _data(value): + return value if isinstance(value, dict) else {} + + +def _entries(value): + return [x for x in value if isinstance(x, dict)] if isinstance(value, list) else [] + + +def _number(value, default, lo, hi): + try: + return min(hi, max(lo, int(value))) + except (TypeError, ValueError, OverflowError): + return default + + +def _time(value, tz): + if value: + try: + parsed = dt.datetime.fromisoformat(str(value).replace("Z", "+00:00")) + return (parsed if parsed.tzinfo else parsed.replace(tzinfo=tz)).timestamp() + except (ValueError, OverflowError, OSError): + pass + return None + + +def _url(value): + if not isinstance(value, str) or any(ord(c) < 32 for c in value): + return "" + try: + parsed = urlsplit(value) + return value if parsed.scheme == "https" and parsed.hostname and parsed.username is None else "" + except ValueError: + return "" + + +def _link(meeting): + return meeting["note_url"] or meeting["minute_url"] or meeting["app_link"] + + +def _span(meeting, tz): + start, end = meeting["start"], meeting["end"] + stop = dt.datetime.fromtimestamp(end, tz) + if start is None: + return stop.strftime("%Y-%m-%d %H:%M 结束") + begin = dt.datetime.fromtimestamp(start, tz) + end_format = "%H:%M" if begin.date() == stop.date() else "%Y-%m-%d %H:%M" + duration = max(0, int((end - start) / 60)) + return "%s–%s · %d 分钟" % (begin.strftime("%Y-%m-%d %H:%M"), stop.strftime(end_format), duration) + + +def _brief(meeting): + return dict(meeting_id=meeting["meeting_id"], topic=meeting["topic"], state=meeting["state"], url=_link(meeting), + start=rfc3339(meeting["start"]) if meeting["start"] is not None else "", + end=rfc3339(meeting["end"])) + + +def _clip_transcript(raw): + data = raw.encode("utf-8") + if len(data) <= TRANSCRIPT_LIMIT: + return raw + return data[:TRANSCRIPT_LIMIT - len(TRUNCATED.encode("utf-8"))].decode("utf-8", "ignore").rstrip() + TRUNCATED + + +def _backoff(attempt): + return ACTIVE * (2 ** min(attempt - 1, 10)) + + +class SyncStopped(Exception): + """An in-flight round has no more authorized work.""" + + +class Meetings: + def __init__(self, app, cli=None, clock=time.time, on_change=None): + self.app = app + self.cli = cli or LarkCLI(app.config, store=app.store) + self.db = MeetingStore(app.store) + self.clock = clock + self.on_change = on_change or (lambda: None) + self.looked = float("-inf") + self._identity_at = float("-inf") + self._identity = ("", "") + self._synced = False + self._notice = "" + self._titles = {} # keyed by verified identity, kind, token + self._round = threading.Lock() + + @property + def enabled(self): + return self.app.config.get("meetings", True) + + @property + def kb_enabled(self): + return self.enabled and self.app.config.get("meetings_kb", True) + + @property + def transcript_enabled(self): + return self.app.config.get("meeting_transcript", False) + + def start(self): + threading.Thread(target=self._loop, daemon=True, name="openmate-meetings").start() + + def _loop(self): + stop = self.app.closing + last = float("-inf") + identity_due = self.clock() + IDLE / 2 + while not stop.is_set(): + now = self.clock() + interval = ACTIVE if now - self.looked < IDLE else IDLE + try: + if self.enabled and now - last >= interval: + last = now + self.sync() + elif self.enabled and now >= identity_due: + # Discoveries that find no work do one search. Probe for external login changes separately. + self.check_identity() + identity_due = now + IDENTITY_REFRESH + except Exception: + if not stop.is_set(): + log.exception("meeting synchronization failed") + stop.wait(15) + + def look(self): + if self.enabled: + self.looked = self.clock() + + def _running(self): + return self.enabled and not self.app.closing.is_set() + + def _read(self, args, timeout=25): + if not self._running(): + raise SyncStopped() + return _data(self.cli.read(args, timeout)) + + def _set_identity(self, now): + try: + owner = self.cli.user_open_id(refresh=True) + except CalendarError: + self._identity = ("", "") + self._identity_at = float("-inf") + self._synced = False + raise + if owner != self._identity[0]: + self._titles.clear() + self._synced = False + self._identity = owner, self.cli.cached_user_name + self._identity_at = now + if not owner: + raise CalendarError("", "auth") + return owner + + def sync(self): + """One background round. Rows and notifications are committed in small transactions, with no CLI under a lock.""" + self._background(self._sync) + + def check_identity(self): + now = self.clock() + if now - self._identity_at >= IDLE / 2: + self._background(lambda: self._set_identity(now)) + + def _background(self, work): + if not self._running() or not self._round.acquire(blocking=False): + return + previous = self._identity, self._synced, self._notice + try: + work() + except SyncStopped: + pass + except CalendarError as e: + if e.kind == "auth": + self._identity = ("", "") + self._identity_at = float("-inf") + self._synced = False + self._titles.clear() + self._notice = "还没授权读会议:在这台电脑上运行 %s,按提示在飞书里确认" % ( + self.cli.login_hint(e.scope or SCOPES)) + elif e.kind == "missing": + self._identity = ("", "") + self._identity_at = float("-inf") + self._synced = False + self._notice = e.message + else: + log.info("meeting synchronization paused (%s)", e.kind) + finally: + self._round.release() + if not self.app.closing.is_set() and previous != (self._identity, self._synced, self._notice): + self.on_change() + if previous[0][0] != self._identity[0] and self.kb_enabled: + self.app.mark_changed("chats", "items") + + def _sync(self): + now = self.clock() + owner = self._identity[0] or self._set_identity(now) + found = self._discover(owner, now) + due = self.db.due(owner, now) + transcripts = self.db.due_transcripts(owner, now) if self.transcript_enabled else [] + known = self.db.known(owner, found) + new = found.keys() - known + if now - self._identity_at >= 30 and (new or due or transcripts): + # Recheck before an active round writes anything. An idle round just searches. + if self._set_identity(now) != owner: + self._sync() + return + if not self._running(): + raise SyncStopped() + if new: + self.db.discover(owner, {mid: found[mid] for mid in found if mid in new}, now) + due = self.db.due(owner, now) + changed = self._sync_notes(due, now) + if self.transcript_enabled: + # Includes those that just became ready. Their transcript gets its own archive position. + changed |= self._sync_transcripts(owner, now) + self._synced = True + self._notice = "" + if changed and not self.app.closing.is_set(): + self.on_change() + + def _discover(self, owner, now): + date = dt.datetime.fromtimestamp(now, self.app.tz).date() + days = _number(self.app.config.get("meetings_days"), 14, 1, 30) if self.db.has_rows(owner) else 30 + command = ["vc", "+search", "--participant-ids", owner, "--start", str(date - dt.timedelta(days=days)), + "--end", str(date + dt.timedelta(days=1)), "--page-size", "30"] + found, token = {}, "" + for _ in range(5): + answer = self._read(command + (["--page-token", token] if token else [])) + for item in _entries(answer.get("items")): + mid = str(item.get("id") or "") + if not mid: + continue + topic = str(item.get("display_info") or "").partition("\n")[0].strip() or "(无标题)" + found[mid] = (topic, _url(_data(item.get("meta_data")).get("app_link"))) + following = str(answer.get("page_token") or "") + if not answer.get("has_more") or not following or following == token: + break + token = following + return found + + def _save(self, meeting, now, **fields): + if not self._running(): + raise SyncStopped() + notify = self.db.save(meeting["owner"], meeting["meeting_id"], dict(fields, updated=now)) + if notify and self.kb_enabled: + self.app.mark_changed("chats") + elif fields.get("state") == "denied" and self.kb_enabled: + self.app.mark_changed("items") + # Retry bookkeeping alone doesn't change what the pages display. + return any(meeting[key] != value for key, value in fields.items() if key not in _RETRY_FIELDS) + + def _pending(self, meeting, now, **fields): + end = fields.get("end", meeting["end"]) + misses = meeting["misses"] + 1 + if end is None or end > now: + return self._save(meeting, now, **fields, next_try=now + ACTIVE, tries=0, misses=0) + if now >= end + DAY: + return self._save(meeting, now, **fields, state="none", next_try=0, tries=0) + return self._save(meeting, now, **fields, next_try=min(end + DAY, now + _backoff(misses)), misses=misses, tries=0) + + def _failed(self, meeting, now, error, **fields): + if error.kind in ("auth", "missing"): + raise error + if error.kind == "permission": + return self._save(meeting, now, **fields, state="denied", next_try=0) + tries = meeting["tries"] + 1 + return self._save(meeting, now, **fields, state="failed" if tries >= 6 else "pending", tries=tries, + next_try=0 if tries >= 6 else now + _backoff(tries)) + + def _sync_notes(self, due, now): + ready = [] + changed = False + for i in range(0, len(due), 5): + group = due[i:i + 5] + try: + answer = self._read(["vc", "+detail", "--meeting-ids", ",".join(m["meeting_id"] for m in group)]) + except CalendarError as e: + for meeting in group: + changed |= self._failed(meeting, now, e) + continue + details = {str(x.get("meeting_id")): x for x in _entries(answer.get("meetings"))} + for meeting in group: + detail = details.get(meeting["meeting_id"]) + if not detail: + changed |= self._failed(meeting, now, CalendarError("会议详情缺失")) + elif detail.get("error"): + changed |= self._failed(meeting, now, self.cli._error(detail)) + else: + changed |= self._sync_note(meeting, detail, now, ready) + # One metadata request per round, across all detail batches. + tokens = list(dict.fromkeys(fields["note_doc_token"] for _, fields in ready if fields.get("note_doc_token"))) + metas = {} + if tokens: + try: + metas = {x.get("doc_token"): x for x in self._metas("docx", tokens)} + except CalendarError as e: + if e.kind in ("auth", "missing"): + raise + if e.kind != "permission": + for meeting, fields in ready: + if fields.get("note_doc_token"): + changed |= self._failed(meeting, now, e, **fields) + ready = [(m, fields) for m, fields in ready if not fields.get("note_doc_token")] + for meeting, fields in ready: + meta = metas.get(fields.get("note_doc_token"), {}) + fields.update(note_url=_url(meta.get("url")), note_title=str(meta.get("title") or "")) + changed |= self._save(meeting, now, **fields, state="ready", next_try=0, tries=0) + return changed + + def _sync_note(self, meeting, detail, now, ready): + fields = dict(start=_time(detail.get("start_time"), self.app.tz), end=_time(detail.get("end_time"), self.app.tz), + topic=str(detail.get("topic") or meeting["topic"]), + note_id=str(detail.get("note_id") or ""), minute_token=str(detail.get("minute_token") or "")) + if not fields["end"] or fields["end"] > now or not (fields["note_id"] or fields["minute_token"]): + return self._pending(meeting, now, **fields) + try: + if fields["note_id"]: + note = _data(self._read(["note", "+detail", "--note-id", fields["note_id"]]).get("note")) + fields.update(note_doc_token=str(note.get("note_doc_token") or ""), + verbatim_doc_token=str(note.get("verbatim_doc_token") or "")) + result = parse_note(self._doc(fields["note_doc_token"])) if fields["note_doc_token"] else {} + fields.update(result) + else: + artifacts = self._minute_artifacts(fields["minute_token"], ["--summary", "--todo", "--chapter"]) + fields.update(summary=str(artifacts.get("summary") or ""), chapters=_entries(artifacts.get("chapters")), + todos=[dict(text=str(t["content"]), owner=str(t.get("owner") or ""), + done=bool(t.get("is_done"))) + for t in _entries(artifacts.get("todos")) if t.get("content")]) + if not any(fields.get(key) for key in ("summary", "todos", "chapters")): + return self._pending(meeting, now, **fields) + if fields["minute_token"]: + try: + fields["minute_url"] = _url(self._minute(fields["minute_token"]).get("url")) + except CalendarError as e: + if e.kind != "permission": + raise + except CalendarError as e: + return self._failed(meeting, now, e, **fields) + ready.append((meeting, fields)) + return False + + def _minute(self, token, timeout=25): + return _data(self._read(["minutes", "minutes", "get", "--params", + json.dumps({"minute_token": token})], timeout).get("minute")) + + def _minute_artifacts(self, token, options): + answer = self._read(["minutes", "+detail", "--minute-tokens", token, *options]) + item = next((x for x in _entries(answer.get("minutes")) if x.get("minute_token") == token), None) + if item is None: + raise CalendarError("妙记详情缺失") + if item.get("error"): + raise self.cli._error(item) + return _data(item.get("artifacts")) + + def _metas(self, kind, tokens, timeout=25): + payload = {"request_docs": [{"doc_token": token, "doc_type": kind} for token in tokens], "with_url": True} + return _entries(self._read(["drive", "metas", "batch_query", "--data", json.dumps(payload)], timeout).get("metas")) + + def _doc(self, token): + if not self._running(): + raise SyncStopped() + return self.cli.read_doc(token) + + def _transcript(self, meeting): + if meeting["verbatim_doc_token"]: + return _clip_transcript(plain_text(self._doc(meeting["verbatim_doc_token"]))) + if not meeting["minute_token"]: + return "" + with tempfile.TemporaryDirectory(prefix="meeting-", dir=self.app.data_dir) as work: + data = self._minute_artifacts(meeting["minute_token"], ["--transcript", "--output-dir", work]) + if not data.get("transcript_file"): + return "" + try: + base = Path(work).resolve() + path = Path(data["transcript_file"]) + if not path.is_absolute(): + path = path if path.is_file() else base / path + path = path.resolve() + if base not in path.parents or not path.is_file(): + raise CalendarError("妙记逐字稿路径无效") + with path.open("rb") as f: + raw = f.read(TRANSCRIPT_LIMIT + 4).decode("utf-8", "ignore") + return _clip_transcript(raw) + except (OSError, ValueError, RuntimeError, TypeError): + raise CalendarError("读不到妙记逐字稿") from None + + def _sync_transcripts(self, owner, now): + changed = False + for meeting in self.db.due_transcripts(owner, now): + if not self.transcript_enabled: + break + try: + text = self._transcript(meeting) + if not text and (meeting["verbatim_doc_token"] or meeting["minute_token"]): + raise CalendarError("逐字稿还未生成") + except CalendarError as e: + if e.kind in ("auth", "missing"): + raise + tries = meeting["transcript_tries"] + 1 + after = -1 if tries >= 6 or e.kind == "permission" else now + _backoff(tries) + self._save(meeting, now, transcript_tries=tries, transcript_next=after) + continue + changed |= self._save(meeting, now, transcript=text or None, transcript_next=-1) + return changed + + def archive(self, after, limit): + high = self.db.high_water() + if not self.kb_enabled: + return [], max(after, high), False + owner = self._identity[0] + if not owner: + return [], after, False + size = min(20, limit) + initial = after + changes = self.db.archive(owner, after, size + 1) + more = len(changes) > size + out, offered = {}, set() + for meeting in changes[:size]: + after = meeting["seq"] + chat_id = "meeting-" + meeting["meeting_id"] + transcript = meeting["part"] == "transcript" + if transcript and not self.transcript_enabled: + continue + messages = self._messages(meeting, chat_id, transcript) + if not messages: + continue + batch = out.setdefault(chat_id, {"chat": dict(id=chat_id, name=meeting["topic"], kind="meeting", + updated_at=rfc3339(meeting["end"])), "messages": []}) + batch["messages"].extend(messages) + offered.add(meeting["meeting_id"]) + if owner != self._identity[0]: + return [], initial, False + if self.db.offered(owner, offered): + self.app.mark_changed("items") + return list(out.values()), after if more else max(after, high), more + + def _messages(self, meeting, chat_id, transcript): + def message(suffix, position, sender, text, at): + return dict(id=chat_id + "-" + suffix, position=str(position), sender_name=sender, + text=text, at=rfc3339(at), type="TEXT") + + end = meeting["end"] + if transcript: + start = meeting["start"] if meeting["start"] is not None else end + turns = [] + elapsed = -1 + source = transcript_turns(meeting["transcript"] or "", allow_untimed=not meeting["verbatim_doc_token"]) + for i, (speaker, offset, text) in enumerate(source): + elapsed = elapsed + 1 if offset is None else offset + turns.append(message("t%d" % i, 5 + i, speaker, text, start + elapsed)) + return turns + + head = [meeting["topic"], _span(meeting, self.app.tz)] + people = [p["name"] for p in meeting["people"] if p["name"]][:30] + if people: + head.append("参会人:" + "、".join(people)) + for label, col in (("智能纪要", "note_url"), ("妙记", "minute_url")): + if meeting[col]: + head.append(label + ":" + meeting[col]) + related = list(dict.fromkeys(_url(link) for link in meeting["links"])) + for link in related: + if link and link not in (meeting["note_url"], meeting["minute_url"]): + head.append("相关链接:" + link) + todos = "\n".join("- [%s] %s%s" % ("x" if t["done"] else " ", t["text"], + "(" + t["owner"] + ")" if t["owner"] else "") + for t in meeting["todos"]) + chapters = "\n".join((" · ".join(str(c[k]) for k in ("title", "summary_content") if c.get(k))) + for c in meeting["chapters"]).strip() + sections = [("head", "会议信息", "\n".join(head)), + ("summary", "智能纪要" if meeting["note_id"] else "妙记", meeting["summary"]), + ("todos", "待办", todos), ("chapters", "章节", chapters)] + return [message(suffix, i, sender, text, end) + for i, (suffix, sender, text) in enumerate(sections, 1) if text] + + def items(self, params): + owner = self._identity[0] + if not self.kb_enabled or not owner: + return {"items": []} + now = self.clock() + items = [] + for meeting in self.db.recent(owner, now - 30 * DAY, now, 200, view="items"): + chat = "meeting-" + meeting["meeting_id"] + item = dict(kind="meetings", id=meeting["minute_token"] or "vc-" + meeting["meeting_id"], + title=meeting["topic"], at=rfc3339(meeting["start"] or meeting["end"])) + if _link(meeting): + item["url"] = _link(meeting) + if meeting["state"] == "ready": + item["where"] = self.app.platform.connector_id + "-" + chat + items.append(item) + return {"items": items if owner == self._identity[0] else []} + + def doc_title(self, params): + return {"title": self._doc_title(params.get("url"))} + + def _doc_title(self, url): + if not self.kb_enabled or not _url(url): + return "" + match = re.fullmatch(r"/(minutes|docx|wiki)/([A-Za-z0-9_-]+)/?", urlsplit(url).path) + if not match: + return "" + kind, token = match.groups() + owner = self._identity[0] + title = self.db.cached_title(owner, kind, token) if owner else "" + if title: + return title if owner == self._identity[0] else "" + key = (owner, kind, token) + now = self.clock() + cached = self._titles.get(key) + if cached and now - cached[0] < TITLE_TTL: + return cached[1] if owner == self._identity[0] else "" + try: + if kind == "minutes": + title = self._minute(token, timeout=8).get("title") + else: + title = next((x.get("title") for x in self._metas(kind, [token], timeout=8) + if x.get("doc_token") == token), "") + except (CalendarError, SyncStopped): + return "" + if not title or owner != self._identity[0]: + return "" + if owner: + if len(self._titles) >= 512: + self._titles.clear() + self._titles[key] = now, str(title) + return str(title) + + def tool(self, args): + if not self.enabled: + return "会议和妙记功能没开" + self.look() + owner = self._identity[0] + mid = str(args.get("meeting_id") or "").strip() + now = self.clock() + if mid: + meeting = self.db.get(owner, mid) if owner else None + if not meeting or meeting["end"] > now or owner != self._identity[0]: + return "没有找到这场已结束的会议" + result = _brief(meeting) + result.update({k: meeting[k] for k in ("summary", "todos", "chapters")}) + if meeting["transcript"]: + result["transcript"] = meeting["transcript"][:20000] + else: + days = _number(args.get("days"), 7, 1, 30) + query = str(args.get("query") or "").strip() + recent = self.db.recent(owner, now - days * DAY, now, 50, query=query) if owner else [] + result = {"meetings": [_brief(m) for m in recent] if owner == self._identity[0] else []} + if self._notice: + result["notice"] = self._notice + return json.dumps(result, ensure_ascii=False) + + def open(self, aid): + self.look() + owner = self._identity[0] + meeting = self.db.get(owner, aid[len(ACTION):]) if self.enabled and owner else None + if meeting and owner == self._identity[0] and meeting["end"] <= self.clock() and _link(meeting): + return {"open_url": _link(meeting)} + return {"toast": "这场会议没有可以打开的链接"} + + def section(self, version, *, today=False): + if not self.enabled: + return None + self.look() + title = "会议" if today else "最近的会议" + if self._notice: + return {"title": title, "items": [empty("会议读不到", self._notice, version)]} + owner, name = self._identity + if not self._synced or not owner: + return None + now = self.clock() + meetings = self.db.recent(owner, now - (2 if today else 7) * DAY, now, 150 if today else 20, view="page") + if owner != self._identity[0]: + return None + rows = [self._row(m) for m in (meetings[:5] if today else meetings)] + if today: + account = getattr(self.app, "account", None) + stored_name = meetings[0]["self_name"] if meetings else None + me = {owner, name, stored_name, getattr(account, "name", "")} - {"", None} + todos = [(m, i, t) for m in meetings for i, t in enumerate(m["todos"]) + if not t["done"] and t["owner"] in me][:5] + if todos: + rows.append({"type": "text", "text": "会上分给我的"}) + rows.extend(row(t["text"], m["topic"], action=ACTION + m["meeting_id"], + key="meeting-todo:%s:%d" % (m["meeting_id"], i)) for m, i, t in todos) + return {"title": title, "items": rows or [empty("这段时间没有已结束的会议", "", version)]} + + def _row(self, meeting): + state = meeting["state"] + if state == "ready": + badge = ("已入库", "positive") if meeting["archive_offered"] else ( + ("待入库", "neutral") if self.kb_enabled else ("未入库", "neutral")) + else: + badge = _BADGES[state] + mid = meeting["meeting_id"] + return row(meeting["topic"], _span(meeting, self.app.tz), action=ACTION + mid, key="meeting:" + mid, + badge={"text": badge[0], "tone": badge[1]}) + + +def tools(app): + name = app.cid + "_meetings" + schema = {"name": name, "description": "只读查询最近结束的飞书会议、总结和待办。提供 meeting_id 查看单场会议的纪要。", + "input_schema": {"type": "object", "properties": { + "query": {"type": "string", "description": "会议主题关键词"}, + "days": {"type": "integer", "minimum": 1, "maximum": 30, "default": 7}, + "meeting_id": {"type": "string"}}}} + + def read(args): + service = getattr(app, "meetings", None) + return service.tool(args) if service else "会议和妙记尚未同步" + + return {name: (schema, read)} diff --git a/extensions/openmate-feishu/openmate_feishu/today.py b/extensions/openmate-feishu/openmate_feishu/today.py index b292911..c82ccc1 100644 --- a/extensions/openmate-feishu/openmate_feishu/today.py +++ b/extensions/openmate-feishu/openmate_feishu/today.py @@ -27,6 +27,7 @@ from . import layout as layout_mod from .agenda import PAGE as CALENDAR_PAGE from .agenda import Agenda, CalendarError, Event +from .meetings import ACTION as MEETING_OPEN log = logging.getLogger("openmate.today") @@ -49,7 +50,6 @@ PEER = "openmate-wechat" # the extension whose chats 今天 shows too PEER_NAME = "微信" PEER_WAIT = 3.0 # a draw waits this long at most for WeChat's read (the rest of the page does not wait for it) -CAL_WAIT = 5.0 # …and for a first read of the calendar (Persona gives a page 20 seconds in all) PAGE_WAIT_OPEN = 12.0 # an 打开 waits this long at most for the calendar RENDER_BUDGET = 14.0 # every read of one draw together: started at once, each waited for out of what is left PERSONA_WAIT = 9.0 @@ -302,7 +302,7 @@ def todo_due(t: dict, tz) -> Tuple[Optional[_dt.datetime], str]: class TodayPage(Page): def __init__(self, app, agenda: Agenda, persona: PersonaToday, chats: Optional[ChatsToday] = None, card: bool = False, mesh=None, agents: Optional[agents_mod.AgentsRead] = None, - wechat: Optional[PeerToday] = None): + wechat: Optional[PeerToday] = None, meetings=None): self.app = app self.agenda = agenda self.persona = persona @@ -311,6 +311,7 @@ def __init__(self, app, agenda: Agenda, persona: PersonaToday, chats: Optional[C self.mesh = mesh # starkmesh.StarkMeshPage: its block on the page once a key is set self.agents = agents # the Agent progress read: the Agent block sorts by it (else Persona's working / waiting) self.wechat = wechat # WeChat's chats (one read shared by the page and the card) + self.meetings = meetings def warm(self) -> None: self.agenda.warm() @@ -326,11 +327,11 @@ def layout(self) -> layout_mod.Layout: def title(self, now) -> str: return "今天 · %s 周%s" % (now.strftime("%m月%d日").lstrip("0"), WEEKDAYS[now.weekday()]) - def _calendar(self, now, wait: float = CAL_WAIT) -> Tuple[List[Event], List[Event], int, str]: + def _calendar(self, now) -> Tuple[List[Event], List[Event], int, str]: """(today's events still to come or on now, invitations waiting for an answer, how many in the next six days, why it is missing or "").""" try: - events = self.agenda.events(wait) + events = self.agenda.events(0.0) except CalendarError as e: return [], [], 0, e.message tomorrow = _dt.datetime.fromtimestamp(day_start(self.app.tz, now.timestamp()), self.app.tz) + _dt.timedelta(days=1) @@ -340,6 +341,8 @@ def _calendar(self, now, wait: float = CAL_WAIT) -> Tuple[List[Event], List[Even def render(self, params: dict) -> dict: version = int(params.get("ui_version") or 1) + if self.meetings is not None and not self.card: + self.meetings.look() tz = self.app.tz now = _dt.datetime.fromtimestamp(self.agenda.clock(), tz) state = state_of(params) @@ -386,7 +389,7 @@ def left() -> float: "dms": sum(1 for t in chat_needs if t["kind"] == "dm"), "messages": 0, "chats": 0} groups = [] if self.card else self._safe(self.chats.active_groups, []) t2 = time.monotonic() - today, pending, later, cal_missing = self._calendar(now, min(CAL_WAIT, left())) + today, pending, later, cal_missing = self._calendar(now) t3 = time.monotonic() if t3 - t0 > SLOW: log.info("%s took %dms: Persona %dms, chats %dms, calendar %dms", CARD if self.card else PAGE, @@ -406,6 +409,8 @@ def _safe(fn, default): def action(self, params: dict) -> dict: a = params.get("action") aid = str(a.get("id") if isinstance(a, dict) else a or "") + if self.meetings is not None and aid.startswith(MEETING_OPEN): + return self.meetings.open(aid) if aid.startswith("open:"): try: events = self.agenda.events(PAGE_WAIT_OPEN) @@ -495,9 +500,12 @@ def _dismiss(self, kind: str, ident: str, seen: Optional[str] = None) -> str: def absent(self) -> set: """The blocks with nothing to show on this manager: 微信今天 without WeChat beside this extension.""" + absent = set() + if self.meetings is None or not self.meetings.enabled: + absent.add("meetings") if self.wechat is None or self.wechat.read(1.0).get("state") in ("absent", "denied"): - return {"wechat"} - return set() + absent.add("wechat") + return absent # ---- WeChat's chats @@ -750,6 +758,7 @@ def card(self) -> dict: def full(self, state: Optional[dict] = None) -> dict: lay = self.page.layout() build = {"status": self.status_block, "needs": self.needs_card, "calendar": self.calendar_card, + "meetings": lambda: self.page.meetings.section(self.version, today=True) if self.page.meetings else None, "feishu": self.feishu_card, "wechat": self.wechat_card, "agents": self.agents_block, "mesh": self.mesh_card, "auto": self.auto_card, "todos": self.todos_card, "shortcuts": self.shortcuts_block, "bookmarks": self.bookmarks_block} diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index 42f4725..506fc2d 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.73", + "version": "0.11.74", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -16,8 +16,8 @@ { "id": "matefeishu", "name": "飞书(OpenMate)", - "capabilities": ["status", "tools", "actions", "events", "inbox", "archive", "history", "login", "threads", "outbound_send"], - "agent_tools": ["matefeishu_status", "matefeishu_chats", "matefeishu_messages", "matefeishu_search", "matefeishu_docs", "matefeishu_agent_reply", "matefeishu_starkmesh", "matefeishu_media", "matefeishu_members"], + "capabilities": ["status", "tools", "actions", "events", "inbox", "archive", "history", "login", "threads", "outbound_send", "items"], + "agent_tools": ["matefeishu_status", "matefeishu_chats", "matefeishu_messages", "matefeishu_search", "matefeishu_docs", "matefeishu_agent_reply", "matefeishu_starkmesh", "matefeishu_media", "matefeishu_members", "matefeishu_meetings"], "confirm_always": ["matefeishu_*"], "sends_as_user": true, "poll_seconds": 60, @@ -276,6 +276,30 @@ "title": "lark-cli 配置档", "description": "lark-cli 的 --profile:你为 Persona 登录的那个飞书应用。留空用 lark-cli 的默认配置档。需要日历只读权限(calendar:calendar.event:read)。" }, + "meetings": { + "type": "boolean", + "title": "会议和妙记", + "description": "通过 lark-cli 只读读取你参加过的飞书视频会议的智能纪要和妙记,在今天页和日程页显示,并存进知识库。", + "default": true + }, + "meetings_kb": { + "type": "boolean", + "title": "会议纪要进知识库", + "default": true + }, + "meeting_transcript": { + "type": "boolean", + "title": "逐字稿也进知识库", + "description": "逐字稿很长,会多占知识库整理用的模型额度。", + "default": false + }, + "meetings_days": { + "type": "integer", + "title": "会议回看天数", + "minimum": 1, + "maximum": 30, + "default": 14 + }, "starkmesh_url": { "type": "string", "format": "uri", diff --git a/extensions/openmate-feishu/tests/test_agenda.py b/extensions/openmate-feishu/tests/test_agenda.py index 3fd107b..67960ba 100644 --- a/extensions/openmate-feishu/tests/test_agenda.py +++ b/extensions/openmate-feishu/tests/test_agenda.py @@ -112,7 +112,7 @@ def test_the_command_is_a_read_of_the_next_days(self): _, _, runner2, fake2 = pages(config={"lark_cli_profile": ""}) pages_default = agenda.CalendarPage(types.SimpleNamespace(config={}, tz=TZ), agenda.Agenda( types.SimpleNamespace(config={"lark_cli": fake2}, tz=TZ), clock=lambda: NOW, - cli=agenda.LarkCLI({"lark_cli": fake2}, run=runner2))) + cli=agenda.LarkCLI({"lark_cli": fake2}, run=runner2), spawn=INPLACE)) pages_default.render({"ui_version": 6}) self.assertNotIn("--profile", runner2.calls[0][0]) @@ -145,9 +145,7 @@ def __call__(self, args, **kw): app = types.SimpleNamespace(config=cfg, tz=TZ) shared = agenda.Agenda(app, clock=lambda: NOW, cli=agenda.LarkCLI(cfg, run=Slow())) page = agenda.CalendarPage(app, shared) - old = agenda.PAGE_WAIT - agenda.PAGE_WAIT = 0.2 - self.addCleanup(setattr, agenda, "PAGE_WAIT", old) + self.addCleanup(gate.set) view = page.render({"ui_version": 6}) self.assertEqual(view["refresh_after"], 5) self.assertIn("正在读取日程", str(view)) @@ -234,7 +232,7 @@ def test_a_failed_read_keeps_the_last_events(self): runner = Runner() page, _, _, _ = pages(runner=runner, clock=lambda: now[0]) page.render({"ui_version": 6}) - runner.answer = {"ok": False, "error": {"type": "authorization"}} + runner.answer = {"ok": False, "error": {"type": "authorization", "subtype": "token_expired"}} now[0] += 61 self.assertEqual(section(page.render({"ui_version": 6}), "今天")[0]["title"], "站会", "the last read stays") now[0] += 900 @@ -318,6 +316,11 @@ def test_read_once_a_minute(self): page.render({"ui_version": 6}) self.assertEqual(len(runner.calls), 2) + def test_fetch_doc_accepts_nested_document_content(self): + runner = Runner({"ok": True, "data": {"document": {"content": " # 总结\n\n周会 "}}}) + cli = agenda.LarkCLI({"lark_cli": "/bin/sh"}, run=runner) + self.assertEqual(cli.fetch_doc("doxexample1", 100), "# 总结\n\n周会") + if __name__ == "__main__": unittest.main() diff --git a/extensions/openmate-feishu/tests/test_feishu.py b/extensions/openmate-feishu/tests/test_feishu.py index e20be07..314fde4 100644 --- a/extensions/openmate-feishu/tests/test_feishu.py +++ b/extensions/openmate-feishu/tests/test_feishu.py @@ -52,7 +52,7 @@ def test_identity(self): def test_connector(self): self.assertEqual(CONN["id"], openmate_feishu.CONNECTOR_ID) self.assertEqual(CONN["capabilities"], ["status", "tools", "actions", "events", "inbox", "archive", "history", "login", "threads", - "outbound_send"]) + "outbound_send", "items"]) self.assertEqual(CONN["kinds"], ["dm", "mention", "group"]) self.assertEqual(sorted(CONN["kind_descriptions"]), sorted(CONN["kinds"])) descs = list(CONN["kind_descriptions"].values()) @@ -64,6 +64,7 @@ def test_connector(self): self.assertIs(CONN["sends_as_user"], True) # /agent replies go out unconfirmed and are put in the ledger self.assertNotIn("matefeishu_send", CONN["agent_tools"]) self.assertNotIn("matefeishu_send_dm", CONN["agent_tools"]) + self.assertIn("matefeishu_meetings", CONN["agent_tools"]) def test_permissions(self): perms = MANIFEST["permissions"] @@ -97,7 +98,8 @@ def test_configuration(self): "auto_reply_header", "auto_reply_at_asker", "auto_reply_full", "agent_reply_suffix", "history_chats", "triage_rules", "inbox_triage_chats", "inbox_private_dms", - "lark_cli", "lark_cli_profile", "starkmesh_url", "starkmesh_alerts", "starkmesh_alert_left", + "lark_cli", "lark_cli_profile", "meetings", "meetings_kb", "meeting_transcript", + "meetings_days", "starkmesh_url", "starkmesh_alerts", "starkmesh_alert_left", "needs_hours", "bookmarks"]) self.assertEqual([(s["name"], s.get("hint")) for s in MANIFEST["secrets"]], [("starkmesh_key", "last4")]) self.assertIn("config:starkmesh_url:http", MANIFEST["permissions"]["network"]) diff --git a/extensions/openmate-feishu/tests/test_larkcli.py b/extensions/openmate-feishu/tests/test_larkcli.py new file mode 100644 index 0000000..275c12a --- /dev/null +++ b/extensions/openmate-feishu/tests/test_larkcli.py @@ -0,0 +1,172 @@ +"""Process-wide concurrency and hourly stats for the CLI executor.""" + +import json +import logging +import os +import subprocess +import threading +import unittest +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import Mock, patch + +from test_agenda import agenda +from openmate_feishu import larkcli + + +RESOURCE_DENIAL = { + "type": "authorization", "subtype": "permission_denied", "code": "2091005", + "message": "user lacks permission for the requested resource", + "hint": "check the resource owner has granted access to this user", + "log_id": "log_example", "troubleshooter": "https://example.com/help", "identity": "user", +} + + +def rejected(payload, *, on_stderr=False): + output = json.dumps({"ok": False, "identity": "user", **payload}) + return subprocess.CompletedProcess([], 1, "" if on_stderr else output, + "读取中…\n" + output if on_stderr else "") + + +class ExecutorTest(unittest.TestCase): + def test_resource_denial_takes_precedence_over_authorization_type(self): + for denial in (RESOURCE_DENIAL, {"subtype": "forbidden"}, {"message": "No permission for this resource"}, + {"message": "No read permission for minute obcnexample1"}, + {"message": "user lacks permission for the requested resource"}): + with self.subTest(denial=denial): + error = {"type": "authorization", **denial} + cli = larkcli.LarkCLI({"lark_cli": "/bin/sh"}, run=Mock(return_value=rejected({"error": error}))) + with self.assertRaises(larkcli.CalendarError) as result: + cli.read(["minutes", "minutes", "get"]) + self.assertEqual((result.exception.kind, result.exception.refused), ("permission", True)) + self.assertNotIn("auth login", result.exception.message) + + def test_missing_scope_uses_the_returned_scope_list(self): + scopes = ["mail:user_mailbox.message:readonly", "mail:user_mailbox.folder:readonly"] + error = {"type": "authorization", "subtype": "missing_scope", "identity": "user", + "message": "missing required scope(s): " + ", ".join(scopes), + "hint": 'run `lark-cli auth login --scope "' + " ".join(scopes) + '"`', + "missing_scopes": scopes} + reply = rejected({"error": error}, on_stderr=True) + cli = larkcli.LarkCLI({"lark_cli": "/bin/sh", "lark_cli_profile": "example"}, run=Mock(return_value=reply)) + with self.assertRaises(larkcli.CalendarError) as result: + cli.call(["mail", "+example"]) + self.assertEqual((result.exception.kind, result.exception.refused), ("auth", True)) + self.assertEqual(result.exception.scope, " ".join(scopes)) + self.assertIn("lark-cli --profile example auth login --scope '" + " ".join(scopes) + "'", result.exception.message) + + def test_authorization_requires_a_scope_token_or_login_reason(self): + for detail, kind in ( + ({}, "failed"), + ({"subtype": "invalid_token"}, "auth"), + ({"message": "the access token has expired"}, "auth"), + ({"message": "user is not logged in"}, "auth"), + ): + with self.subTest(detail=detail): + reply = rejected({"error": {"type": "authorization", **detail}}) + cli = larkcli.LarkCLI({"lark_cli": "/bin/sh"}, run=Mock(return_value=reply)) + with self.assertRaises(larkcli.CalendarError) as result: + cli.call(["auth", "status"]) + self.assertEqual(result.exception.kind, kind) + + def test_reply_permission_denial_is_a_definite_failure(self): + run = Mock(return_value=rejected({"error": RESOURCE_DENIAL}, on_stderr=True)) + cli = larkcli.LarkCLI({"lark_cli": "/bin/sh"}, run=run) + with self.assertRaises(larkcli.CalendarError) as result: + cli.add_reply("https://example.com/docx/doxexample1", "comment_example", "已阅") + self.assertEqual(result.exception.kind, "failed") + self.assertNotIn("可能已经发出", result.exception.message) + + def test_failed_batch_needs_matching_items_and_no_top_level_error(self): + items = {"minutes": [{"minute_token": "obcnexample1", "error": "No read permission"}]} + output = rejected({"data": items}) + scope_error = {"type": "authorization", "subtype": "missing_scope", "missing_scopes": ["minutes:minutes:readonly"]} + for args, reply, kind in ( + (["minutes", "+detail"], rejected({"data": items, "error": scope_error}), "auth"), + (["minutes", "+detail"], subprocess.CompletedProcess([], 1, output.stdout, + rejected({"error": scope_error}, on_stderr=True).stderr), "auth"), + (["minutes", "+detail"], rejected({"data": {"minutes": []}}), "failed"), + (["drive", "+add-reply"], output, "failed"), + ): + with self.subTest(args=args, kind=kind): + cli = larkcli.LarkCLI({"lark_cli": "/bin/sh"}, run=Mock(return_value=reply)) + with self.assertRaises(larkcli.CalendarError) as result: + cli.call(args) + self.assertEqual(result.exception.kind, kind) + + def test_missing_binary_lookup_is_cached_without_taking_a_slot(self): + shell = Mock(return_value=subprocess.CompletedProcess([], 1, "", "")) + cli = larkcli.LarkCLI({}, run=shell) + now = [100.0] + with patch.object(larkcli.shutil, "which", return_value=None), patch.object( + larkcli, "_SLOTS" + ) as slots, patch.object(larkcli.time, "monotonic", side_effect=lambda: now[0]): + for _ in range(2): + with self.assertRaises(larkcli.CalendarError) as error: + cli.call(["vc", "+search"]) + self.assertEqual(error.exception.kind, "missing") + shell.assert_called_once() + self.assertEqual(shell.call_args.args[0][1:], ["-lc", "command -v lark-cli"]) + now[0] += 300 + with self.assertRaises(larkcli.CalendarError): + cli.call(["vc", "+search"]) + self.assertEqual(shell.call_count, 2) + slots.acquire.assert_not_called() + + def test_global_two_slots_queue_time_counts(self): + started = 0 + count = 0 + peak = 0 + second = threading.Event() + release = threading.Event() + lock = threading.Lock() + + def run(args, **kwargs): + nonlocal started, count, peak + self.assertEqual(kwargs["stdin"], subprocess.DEVNULL) + self.assertTrue(kwargs["env"]["PATH"].startswith("/bin" + os.pathsep)) + with lock: + started += 1 + count += 1 + peak = max(count, peak) + if count == 2: + second.set() + try: + self.assertTrue(release.wait(3)) + return subprocess.CompletedProcess(args, 0, '{"ok":true,"data":{"items":[]}}', "") + finally: + with lock: + count -= 1 + + clis = [agenda.LarkCLI({"lark_cli": "/bin/sh"}, run=run) for _ in range(5)] + with ThreadPoolExecutor(5) as pool: + try: + calls = [pool.submit(cli.call, ["vc", "+search"], 5) for cli in clis[:2]] + self.assertTrue(second.wait(2)) + timed = [pool.submit(cli.call, ["vc", "+search"], 0.05) for cli in clis[2:]] + for call in timed: + with self.assertRaisesRegex(agenda.CalendarError, "等候执行超时"): + call.result(timeout=2) + self.assertEqual(started, 2) + finally: + release.set() + for call in calls: + self.assertEqual(call.result(timeout=2), {"items": []}) + for got in pool.map(lambda cli: cli.call(["vc", "+search"], 2), clis): + self.assertEqual(got, {"items": []}) + self.assertEqual(peak, 2) + + def test_stats_emit_one_hourly_line_with_failures_and_no_idle_line(self): + stats = larkcli.CallStats() + with patch.object(larkcli.threading, "Timer") as timer: + stats.record("vc +search", 2.0, False) + stats.record("vc +search", 3.0, True) + stats.record("note +detail", 1.1, False) + timer.assert_called_once_with(3600, stats.flush) + with self.assertLogs("openmate.larkcli", logging.INFO) as logs: + timer.call_args.args[1]() + self.assertEqual(len(logs.output), 1) + self.assertIn("vc +search calls=2 failures=1 total=5.00s max=3.00s", logs.output[0]) + self.assertIn("note +detail calls=1 failures=0 total=1.10s max=1.10s", logs.output[0]) + with patch.object(larkcli.log, "info") as log: + stats.flush() + log.assert_not_called() diff --git a/extensions/openmate-feishu/tests/test_layout.py b/extensions/openmate-feishu/tests/test_layout.py index 99b466e..6e0554c 100644 --- a/extensions/openmate-feishu/tests/test_layout.py +++ b/extensions/openmate-feishu/tests/test_layout.py @@ -41,7 +41,7 @@ def test_edit_mode_moves_hides_and_widens(self): edit = out["view"] self.assertEqual(json.loads(edit["state"]), {"edit": 1}) rows = [it for it in edit["sections"][0]["items"] if it["type"] == "row"] - self.assertEqual([r["title"] for r in rows], [b[1] for b in layout.BLOCKS if b[0] != "wechat"], "微信今天 only with WeChat") + self.assertEqual([r["title"] for r in rows], [b[1] for b in layout.BLOCKS if b[0] not in ("wechat", "meetings")]) first = [a["title"] for a in rows[0]["actions"]] self.assertEqual(first, ["下移", "隐藏", "改成半行"], "the first can't go up; status is a whole row") self.assertIn("hub 升级后生效", rows[2]["subtitle"], "a half row before UI version 8 says when it counts") @@ -66,11 +66,12 @@ def test_edit_mode_moves_hides_and_widens(self): def test_a_stored_layout_meets_a_newer_version(self): page, _, _ = make() - older = ["todos"] + [b[0] for b in layout.BLOCKS if b[0] not in ("todos", "agents")] # a version without "agents" + older = ["todos"] + [b[0] for b in layout.BLOCKS if b[0] not in ("todos", "agents", "meetings")] page.app.store.meta_set(layout.KEY, json.dumps({"order": older[:3] + ["gone", "needs"] + older[3:], "hidden": ["gone", "status"], "wide": {"todos": True, "needs": "yes"}})) lay = page.layout() - self.assertEqual(lay.order, ["todos", "status", "needs", "calendar", "feishu", "wechat", "agents", "mesh", "auto", "shortcuts", "bookmarks"], + self.assertEqual(lay.order, ["todos", "status", "needs", "calendar", "meetings", "feishu", "wechat", "agents", "mesh", + "auto", "shortcuts", "bookmarks"], "a block the stored order lacks goes after the one before it by default; unknown and repeated ones go") self.assertEqual(lay.hidden, ["status"]) self.assertEqual(lay.wide, {"todos": True}) diff --git a/extensions/openmate-feishu/tests/test_meetings.py b/extensions/openmate-feishu/tests/test_meetings.py new file mode 100644 index 0000000..46cd5a8 --- /dev/null +++ b/extensions/openmate-feishu/tests/test_meetings.py @@ -0,0 +1,542 @@ +"""The meetings connector end to end, with synthetic lark-cli answers.""" + +import datetime as dt +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from test_agenda import INPLACE, NOW, TZ, Runner, items, section +from test_larkcli import RESOURCE_DENIAL, rejected +from test_today import make + +from openmate_core.app import ConnectorApp +from openmate_core.backend import Chat, Message +from openmate_core.store import Store +from openmate_feishu import agenda, platform +from openmate_feishu.larkcli import LarkCLI +from openmate_feishu.meeting_text import parse_note, plain_text, transcript_turns +from openmate_feishu.meetings import ACTION, ACTIVE, DAY, TRANSCRIPT_LIMIT, TRUNCATED, Meetings + +DOC_URL = "https://example.com/docx/doxexample1" +MINUTE_URL = "https://example.com/minutes/obcnexample1" +APP_LINK = "https://example.com/client/vctab/open?meetingId=example1" +CONTENT = """智能纪要:周会 +

会议主题:周会

参会人: +

+# 总结 +一起讨论了接口。 +

安排如下:

+- 下周评审 + +# 待办 +- [ ] 整理接口清单(张三) +- [x] 联调 (李四) +- [ ] 发会议纪要 +- [ ] 补示例(示例用户) +- [ ] 核对清单(ou_example) +

跳过控件正文

+# 相关链接 +- 妙记:[周会](https://example.com/minutes/obcnexample1) +- 参考:[接口](https://example.com/docx/doxexample3) +""" +VERBATIM = """# 文字记录:周会 2026年12月3日 + +> 会议主题:周会 +> 会议时间:2026年12月3日(周三) 15:00 - 15:04 (GMT+08:00) +> 相关链接:[智能纪要:周会 2026年12月3日](https://example.com/docx/doxexample1) + +张三 00:00:40{trailing} +开始评审。 +请看清单: +> 示例用户 00:00:50 +下一行继续。 + +李四 00:01:21 +我整理材料。 +""".format(trailing=" ") + + +class MeetingTextTest(unittest.TestCase): + def test_verbatim_document_ignores_preamble_and_quoted_speakers(self): + self.assertEqual(list(transcript_turns(plain_text(VERBATIM))), [ + ("张三", 40, "开始评审。\n请看清单:\n> 示例用户 00:00:50\n下一行继续。"), + ("李四", 81, "我整理材料。")]) + + def test_unrecognized_top_level_heading_ends_note_section(self): + note = parse_note("""# 总结 +确认评审时间。 +## 时间 +周一下午。 +# 智能章节 +章节内容。 +# 待办 +- [ ] 整理清单(张三) +# 补充信息 +- [ ] 示例信息 +# 相关链接 +- [纪要](https://example.com/docx/doxexample1) +# 附录 +- [参考](https://example.com/docx/doxexample2) +""") + self.assertEqual(note["summary"], "确认评审时间。\n## 时间\n周一下午。") + self.assertEqual(note["todos"], [{"text": "整理清单", "owner": "张三", "done": False}]) + self.assertEqual(note["links"], [DOC_URL]) + + +class CLI: + def __init__(self): + self.calls = [] + self.owner = "ou_example" + self.found = ["example1"] + self.next_page = None + self.details = {} + self.errors = {} + self.replies = {} + self.minute_entry = {} + self.transcript_file = "" + self.meta_title = "智能纪要:周会" + + def __call__(self, args, **kwargs): + assert args[:3] == ["/bin/sh", "--profile", "example"] + args = args[3:] + cmd = " ".join(args[:3] if args[:2] in (["drive", "metas"], ["minutes", "minutes"]) else args[:2]) + self.calls.append((cmd, args, kwargs)) + assert all("apply-permission" not in arg for arg in args) + if cmd != "auth status": + assert args[args.index("--as") + 1] == "user" and args[-2:] == ["--format", "json"] + if cmd in self.replies: + return self.replies[cmd] + if cmd in self.errors: + error = self.errors[cmd] + if isinstance(error, BaseException): + raise error + return subprocess.CompletedProcess(args, 1, "", "读取中…\n" + json.dumps( + {"ok": False, "error": error}, indent=2) + "\n读取结束") + if cmd == "auth status": + user = {"available": bool(self.owner), "openId": self.owner, "userName": "张三"} + return subprocess.CompletedProcess(args, 0, json.dumps({"identities": {"user": user}}), "") + + def option(key): + return args[args.index(key) + 1] + + if cmd == "vc +search": + assert option("--participant-ids") == self.owner + more = bool(self.next_page and "--page-token" not in args) + found = self.found if "--page-token" not in args else self.next_page + data = {"items": [dict(id=mid, display_info="周会\n录制:周会", meta_data={"app_link": APP_LINK}) + for mid in found], "has_more": more, "page_token": "cursor-example" if more else ""} + elif cmd == "vc +detail": + ids = option("--meeting-ids").split(",") + assert len(ids) <= 5 + data = {"meetings": [dict(meeting_id=mid, **self.details[mid]) for mid in ids if mid in self.details]} + elif cmd == "note +detail": + token = option("--note-id") + data = {"note": dict(note_id=token, note_doc_token="doxexample1", verbatim_doc_token="doxexample2")} + elif cmd == "docs +fetch": + raw = CONTENT if option("--doc") == "doxexample1" else VERBATIM + data = {"document": {"content": raw, "revision_id": 12}} + elif cmd == "minutes +detail": + token = option("--minute-tokens") + entry = dict(minute_token=token, **self.minute_entry) + if "--transcript" in args and self.transcript_file: + root = Path(option("--output-dir")) + path = root / "artifact-example" / "transcript.txt" + path.parent.mkdir() + path.write_text(self.transcript_file) + entry = dict(minute_token=token, artifacts={"transcript_file": str(path)}) + data = {"minutes": [entry]} + elif cmd == "minutes minutes get": + data = {"minute": dict(title="周会", url=MINUTE_URL)} + elif cmd == "drive metas batch_query": + docs = json.loads(option("--data"))["request_docs"] + data = {"metas": [dict(doc_token=d["doc_token"], title=self.meta_title, url=DOC_URL) for d in docs]} + else: + raise AssertionError(cmd) + return subprocess.CompletedProcess(args, 0, json.dumps({"ok": True, "data": data}), "") + + def commands(self): + return [c for c, _, _ in self.calls] + + +class MeetingsTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.tmp = tmp.name + self.app = ConnectorApp(platform(), env={}) + self.app.config = {"lark_cli": "/bin/sh", "lark_cli_profile": "example"} + self.app.data_dir = self.tmp + self.app.tz = TZ + self.app.store = Store(os.path.join(self.tmp, "openmate.db")) + self.addCleanup(lambda: self.app.store.close()) + self.app.initialized = True + self.app.ready.set() + self.scopes = [] + self.app.mark_changed = lambda *scopes: self.scopes.extend(scopes) + self.cli = CLI() + self.now = NOW + self.service = self.create_service() + self.cli.details["example1"] = self.detail(note=True, minute=True) + + def create_service(self): + cli = LarkCLI(self.app.config, run=self.cli, store=self.app.store) + self.app.meetings = Meetings(self.app, cli=cli, clock=lambda: self.now) + return self.app.meetings + + def detail(self, note=False, minute=False, end=None): + stop = dt.datetime.fromtimestamp(self.now - 1800 if end is None else end, TZ) + start = stop - dt.timedelta(minutes=40) + return dict(topic="周会", start_time=start.strftime("%Y-%m-%d %H:%M"), end_time=stop.strftime("%Y-%m-%d %H:%M"), + note_id="note_example" if note else "", minute_token="obcnexample1" if minute else "") + + def row(self, mid="example1"): + return self.service.db.get(self.cli.owner, mid) + + def archive(self, cursor="", limit=100): + return self.app.handle("connector.archive.changes", {"cursor": cursor, "limit": limit}) + + def test_sync_note_and_idle_search(self): + self.service.sync() + self.assertEqual(self.cli.commands(), ["auth status", "vc +search", "vc +detail", "note +detail", "docs +fetch", + "minutes minutes get", "drive metas batch_query"]) + search = self.cli.calls[1][1] + self.assertEqual(search[search.index("--start") + 1], "2026-10-17") + self.assertEqual(self.app.store.meta_get("lark_cli_open_id"), "ou_example") + self.assertEqual(self.service.cli.user_open_id(), "ou_example") + meeting = self.row() + self.assertEqual(meeting["state"], "ready") + self.assertEqual(meeting["summary"], "一起讨论了接口。\n\n安排如下:\n\n- 下周评审") + self.assertEqual(meeting["todos"][:3], [ + {"text": "整理接口清单", "owner": "张三", "done": False}, {"text": "联调", "owner": "李四", "done": True}, + {"text": "发会议纪要", "owner": "", "done": False}]) + self.assertEqual(meeting["people"], [{"name": "张三", "open_id": "ou_example"}, {"name": "李四", "open_id": "ou_other"}]) + self.assertEqual(meeting["links"][0], MINUTE_URL) + self.assertEqual((meeting["note_url"], meeting["minute_url"]), (DOC_URL, MINUTE_URL)) + self.assertIsNone(meeting["transcript"]) + self.assertIn("chats", self.scopes) + self.assertIn("items", self.scopes) + self.cli.calls.clear() + self.now += ACTIVE + self.service.sync() + self.assertEqual(self.cli.commands(), ["vc +search"]) + search = self.cli.calls[0][1] + self.assertEqual(search[search.index("--start") + 1], "2026-11-02") + + def test_search_pagination_detail_batching_and_single_metadata_lookup(self): + self.cli.found = ["example%d" % i for i in range(1, 6)] + self.cli.next_page = ["example6"] + self.cli.details.update({mid: self.detail(note=True) for mid in self.cli.found + self.cli.next_page}) + self.service.sync() + self.assertEqual(self.cli.commands().count("vc +search"), 2) + self.assertEqual(self.cli.commands().count("vc +detail"), 2) + self.assertEqual(self.cli.commands().count("drive metas batch_query"), 1) + self.assertEqual(self.row("example6")["state"], "ready") + + def test_background_starts_now_and_changes_interval_when_viewed(self): + start = self.now + rounds, probes = [], [] + + class Stop: + def is_set(stop): + return self.now >= start + 3000 + + def wait(stop, seconds): + self.now += seconds + if self.now == start + 1800: + self.service.look() + + with patch.object(self.app, "closing", Stop()), patch.object( + self.service, "sync", side_effect=lambda: rounds.append(self.now - start) + ), patch.object(self.service, "check_identity", side_effect=lambda: probes.append(self.now - start)): + self.service._loop() + self.assertEqual(rounds, [0, 1800, 2400]) + self.assertEqual(probes, [900, 2700]) + + def test_pending_backoff_then_none_and_ongoing_skip(self): + self.cli.found += ["example2"] + self.cli.details = {"example1": self.detail(), "example2": self.detail(note=True, end=self.now + DAY * 2)} + self.service.sync() + self.assertNotIn("note +detail", self.cli.commands()) + self.assertEqual(self.row()["state"], "pending") + self.assertEqual(self.row()["next_try"], self.now + 600) + self.assertEqual(len(self.service.db.recent(self.cli.owner, self.now - DAY, self.now, 20)), 1) + self.now += 600 + self.service.sync() + self.assertEqual(self.row()["next_try"], self.now + 1200) + self.now += DAY + self.service.sync() + self.assertEqual(self.row()["state"], "none") + + def test_denied_minutes_never_requests_permission(self): + self.cli.details["example1"] = self.detail(minute=True) + self.cli.minute_entry = {"error": "No read permission for minute obcnexample1. Ask the user before running +apply-permission."} + self.service.sync() + self.assertEqual(self.row()["state"], "denied") + self.assertFalse(self.archive()["batches"]) + self.assertEqual(self.cli.commands()[-1], "minutes +detail") + entries = self.app.handle("connector.items.list", {})["items"] + self.assertEqual(entries[0]["id"], "obcnexample1") + self.assertNotIn("where", entries[0]) + + def test_all_failed_minutes_batch_is_denied_without_retry(self): + self.cli.details["example1"] = self.detail(minute=True) + self.cli.replies["minutes +detail"] = rejected({ + "data": {"minutes": [{"minute_token": "obcnexample1", "title": "", "note_id": "", + "error": "No read permission for minute obcnexample1. Ask the user before running: " + "minutes +apply-permission --minute-token obcnexample1 --perm view"}]}, + "meta": {"count": 1}, + }) + self.service.sync() + meeting = self.row() + self.assertEqual((meeting["state"], meeting["tries"], meeting["next_try"]), ("denied", 0, 0)) + self.assertEqual(self.cli.commands()[-1], "minutes +detail") + + def test_minutes_metadata_acl_does_not_stop_note_sync(self): + self.cli.found += ["example2"] + self.cli.details["example2"] = self.detail(note=True) + self.cli.replies["minutes minutes get"] = rejected({"error": RESOURCE_DENIAL}) + self.service.sync() + self.assertEqual((self.row()["state"], self.row()["minute_url"]), ("ready", "")) + self.assertEqual(self.row("example2")["state"], "ready") + self.assertNotIn("auth login", str(self.service.section(8))) + + def test_vc_detail_classifies_each_failed_item_and_preserves_successes(self): + self.cli.found += ["example2", "example3"] + self.cli.replies["vc +detail"] = rejected({ + "data": {"meetings": [ + {"meeting_id": "example1", "error": RESOURCE_DENIAL}, + {"meeting_id": "example2", "error": "upstream request timed out"}, + {"meeting_id": "example3", **self.detail(note=True)}, + ]}, + "meta": {"count": 3}, + }) + self.service.sync() + records = self.app.store._all("SELECT meeting_id, state, tries FROM meetings ORDER BY meeting_id") + self.assertEqual([tuple(row) for row in records], [ + ("example1", "denied", 0), ("example2", "pending", 1), ("example3", "ready", 0)]) + + def test_auth_from_stderr_stops_round_and_renders_hint(self): + self.cli.found += ["example2"] + self.cli.details["example2"] = self.detail(note=True) + self.cli.errors["note +detail"] = {"type": "authorization", "subtype": "missing_scope", + "missing_scopes": ["docx:document:readonly"]} + self.service.sync() + self.assertEqual(self.cli.commands().count("note +detail"), 1) + self.assertNotIn("docs +fetch", self.cli.commands()) + notice = self.service.section(8, today=True)["items"][0] + self.assertIn("lark-cli --profile example auth login --scope docx:document:readonly", notice["detail"]) + self.assertEqual(self.service.db.due(self.cli.owner, self.now)[0]["tries"], 0) + del self.cli.errors["note +detail"] + self.service.sync() + self.assertEqual(self.row()["state"], "ready") + + def test_failed_reads_stop_after_six_attempts(self): + self.cli.errors["vc +detail"] = subprocess.TimeoutExpired("lark-cli", 25) + for tries in range(1, 7): + self.service.sync() + meeting = self.service.db.due(self.cli.owner, self.now + DAY) if tries < 6 else [] + self.assertEqual(len(meeting), int(tries < 6)) + self.now += ACTIVE * 2 ** (tries - 1) + self.assertIsNone(self.row()) + # A failed detail has no end time until one successful detail call; it is deliberately hidden from pages. + record = self.app.store._one("SELECT state, tries FROM meetings WHERE meeting_id='example1'") + self.assertEqual(tuple(record), ("failed", 6)) + + def test_owner_switch_filters_cached_rows_and_does_not_export(self): + self.service.sync() + self.assertTrue(self.service.section(6)["items"]) + self.cli.owner = "ou_replacement" + self.cli.found = [] + self.now += 1800 + self.service.check_identity() + self.assertIsNone(self.service.section(6)) + self.assertFalse(self.archive("0")["batches"]) + self.service.sync() + self.assertEqual(self.app.store.meta_get("lark_cli_open_id"), "ou_replacement") + self.assertEqual(json.loads(self.service.tool({}))["meetings"], []) + self.assertNotIn("周会", str(self.service.section(6))) + self.assertFalse(self.archive("0")["batches"]) + self.assertEqual(self.app.handle("connector.items.list", {}), {"items": []}) + self.assertNotIn("open_url", self.service.open(ACTION + "example1")) + + def test_legacy_and_incremental_archive_with_limits(self): + self.service.sync() + self.app.store.upsert_chat(Chat("chat_example", "group", "示例群聊"), now=self.now) + self.app.store.add_messages([Message(id="message_example", chat_id="chat_example", text="示例消息", + at=self.now, position=1)], from_history=False) + chat = self.archive("0", limit=1) + self.assertEqual(chat["batches"][0]["chat"]["id"], "chat_example") + self.assertTrue(chat["more"]) + first = self.archive(chat["next"], limit=1) + self.assertEqual(first["next"], "v1:1:meetings=1") + batch = first["batches"][0] + self.assertEqual(batch["chat"], {"id": "meeting-example1", "name": "周会", "kind": "meeting", + "updated_at": "2026-11-16T01:30:00Z"}) + lines = batch["messages"] + self.assertEqual([x["id"] for x in lines], ["meeting-example1-" + part for part in ("head", "summary", "todos")]) + self.assertEqual([x["position"] for x in lines], ["1", "2", "3"]) + self.assertTrue(all(x["type"] == "TEXT" and x["at"] == batch["chat"]["updated_at"] for x in lines)) + self.assertIn("张三、李四", lines[0]["text"]) + self.assertEqual(lines[1]["sender_name"], "智能纪要") + self.assertIn("[x] 联调(李四)", lines[2]["text"]) + self.assertEqual(self.archive(first["next"]), {"batches": [], "next": first["next"], "more": False}) + self.assertEqual(self.archive("1")["batches"], [batch]) + + def test_archive_cap_and_disabled_cursor_skips_delivered_window(self): + self.cli.found = ["example%d" % i for i in range(1, 23)] + self.cli.details = {mid: self.detail(note=True) for mid in self.cli.found} + self.service.sync() + first = self.archive("0") + self.assertEqual(len(first["batches"]), 20) + self.assertTrue(first["more"]) + self.app.config["meetings_kb"] = False + skipped = self.archive(first["next"]) + self.assertEqual(skipped, {"batches": [], "next": "v1:0:meetings=22", "more": False}) + self.assertEqual(self.app.handle("connector.items.list", {}), {"items": []}) + self.app.config["meetings_kb"] = True + self.assertFalse(self.archive(skipped["next"])["batches"]) + entries = self.service.items({})["items"] + self.assertEqual(sum("where" in entry for entry in entries), 20) + + def test_items_list_and_title_resolution_cache(self): + self.cli.found += ["example2"] + self.cli.details["example2"] = self.detail(note=True) + self.service.sync() + self.archive("0", limit=1) + result = self.app.handle("connector.items.list", {})["items"] + by_id = {item["id"]: item for item in result} + self.assertEqual(by_id["obcnexample1"], dict(kind="meetings", id="obcnexample1", title="周会", url=DOC_URL, + at="2026-11-16T00:50:00Z", where="matefeishu-meeting-example1")) + self.assertNotIn("vc-example2", by_id) + count = len(self.cli.calls) + self.assertEqual(self.service.doc_title({"url": MINUTE_URL}), {"title": "周会"}) + self.assertEqual(self.service.doc_title({"url": DOC_URL}), {"title": self.cli.meta_title}) + self.assertEqual(len(self.cli.calls), count) + wiki = "https://example.com/wiki/wikiexample1" + self.assertEqual(self.service.doc_title({"url": wiki}), {"title": self.cli.meta_title}) + self.assertLessEqual(self.cli.calls[-1][2]["timeout"], 8) + self.cli.errors["drive metas batch_query"] = subprocess.TimeoutExpired("lark-cli", 8) + self.assertEqual(self.service.doc_title({"url": wiki + "?x=1"}), {"title": self.cli.meta_title}) + self.assertEqual(self.service.doc_title({"url": "https://example.com/wiki/wikiexample2"}), {"title": ""}) + self.now += 7 * DAY + self.assertEqual(self.service.doc_title({"url": wiki}), {"title": ""}) + + def test_ready_items_appear_with_where_only_after_archive_offers_them(self): + self.service.sync() + self.assertEqual(self.row()["state"], "ready") + self.assertEqual(self.service.items({}), {"items": []}) + self.scopes.clear() + batch, cursor, _ = self.service.archive(0, 20) + self.assertEqual(len(batch), 1) + self.assertEqual(self.service.items({})["items"][0]["where"], "matefeishu-meeting-example1") + self.assertEqual(self.scopes, ["items"]) + self.assertEqual(self.service.archive(cursor, 20)[0], []) + self.assertEqual(self.scopes, ["items"]) + + def test_unchanged_pending_retry_does_not_invalidate_pages(self): + self.cli.details["example1"] = self.detail() + self.service.sync() + self.assertEqual(self.row()["state"], "pending") + with patch.object(self.service, "on_change") as redraw: + self.now = self.row()["next_try"] + self.service.sync() + self.assertGreater(self.row()["next_try"], self.now) + redraw.assert_not_called() + self.now = self.row()["next_try"] + self.cli.details["example1"]["note_id"] = "note_example" + self.service.sync() + self.assertEqual(self.row()["state"], "ready") + redraw.assert_called_once() + + def test_transcript_later_appends_unique_messages_after_restart(self): + self.service.sync() + first = self.archive("0")["next"] + self.service = self.create_service() + self.app.config["meeting_transcript"] = True + self.service.sync() + result = self.archive(first) + lines = result["batches"][0]["messages"] + self.assertEqual([m["id"] for m in lines], ["meeting-example1-t0", "meeting-example1-t1"]) + self.assertEqual([m["sender_name"] for m in lines], ["张三", "李四"]) + self.assertEqual(lines[0]["at"], "2026-11-16T00:50:40Z") + self.assertEqual(lines[1]["at"], "2026-11-16T00:51:21Z") + self.assertFalse(self.archive(result["next"])["batches"]) + + def test_minutes_artifacts_and_file_transcript_size_and_cleanup(self): + self.cli.details["example1"] = self.detail(minute=True) + self.cli.minute_entry = {"artifacts": {"summary": "接口待评审", "todos": [{"content": "整理材料", "is_done": False}], + "chapters": [{"title": "背景", "summary_content": "评审安排"}]}} + self.cli.transcript_file = "张三:开始\n" + "例" * TRANSCRIPT_LIMIT + self.app.config["meeting_transcript"] = True + self.service.sync() + meeting = self.row() + self.assertTrue(meeting["transcript"].endswith(TRUNCATED)) + self.assertLessEqual(len(meeting["transcript"].encode("utf-8")), TRANSCRIPT_LIMIT) + self.assertEqual(meeting["todos"], [{"text": "整理材料", "owner": "", "done": False}]) + self.assertFalse(list(Path(self.tmp).glob("meeting-*"))) + lines = self.archive("0")["batches"][0]["messages"] + self.assertEqual(lines[1]["sender_name"], "妙记") + self.assertIn("背景 · 评审安排", lines[3]["text"]) + self.assertEqual(lines[4]["sender_name"], "张三") + + def test_today_and_calendar_are_local_and_open_links(self): + page, card, _ = make() + page.meetings = self.service + app = self.app + sample = agenda.Agenda(app, clock=lambda: self.now, cli=LarkCLI(app.config, run=Runner()), spawn=INPLACE) + calendar = agenda.CalendarPage(app, sample, meetings=self.service) + params = {"ui_version": 6} + self.assertNotIn("最近的会议", str(calendar.render(params))) + self.assertNotIn("会上分给我的", str(page.render(params))) + self.service.sync() + self.archive("0") + self.app.store.meta_set("account_name", "示例用户") + before = len(self.cli.calls) + calendar_view = calendar.render(params) + items(calendar_view) + recent = section(calendar_view, "最近的会议") + self.assertEqual(recent[0]["badge"]["text"], "已入库") + self.assertEqual(recent[0]["action"], {"id": ACTION + "example1"}) + today_view = page.render(params) + today_rows = section(today_view, "会议") + self.assertEqual([r.get("title") or r.get("text") for r in today_rows], + ["周会", "会上分给我的", "整理接口清单", "补示例", "核对清单"]) + self.assertNotIn("会上分给我的", str(card.render(params))) + for view in (page, calendar): + self.assertEqual(view.action({"action": recent[0]["action"]}), {"open_url": DOC_URL}) + self.app.config["meetings"] = False + self.service.sync() + self.assertNotIn("最近的会议", str(calendar.render(params))) + self.assertNotIn("会上分给我的", str(page.render(params))) + self.assertEqual(len(self.cli.calls), before) + + def test_meeting_block_reads_one_indexed_query(self): + self.service.sync() + db = self.app.store._db + queries = [] + db.set_trace_callback(queries.append) + try: + self.service.section(8, today=True) + finally: + db.set_trace_callback(None) + self.assertEqual(len(queries), 1) + plan = " ".join(r[3] for r in db.execute("EXPLAIN QUERY PLAN " + queries[0])) + self.assertIn("meetings_end", plan) + + def test_tool_list_filter_detail_and_disabled(self): + self.service.sync() + before = len(self.cli.calls) + + def call(**args): + return self.app.handle("connector.tools.call", {"name": "matefeishu_meetings", "args": args})["text"] + + self.assertEqual(json.loads(call(days=5, query="周会"))["meetings"][0]["url"], DOC_URL) + self.assertEqual(json.loads(call(query="示例评审"))["meetings"], []) + self.assertIn("接口", json.loads(call(meeting_id="example1"))["summary"]) + self.app.config["meetings"] = False + self.assertIn("没开", call()) + self.assertEqual(len(self.cli.calls), before) diff --git a/extensions/openmate-feishu/tests/test_today_wechat.py b/extensions/openmate-feishu/tests/test_today_wechat.py index aad083c..905dbc3 100644 --- a/extensions/openmate-feishu/tests/test_today_wechat.py +++ b/extensions/openmate-feishu/tests/test_today_wechat.py @@ -250,7 +250,7 @@ def test_a_layout_keeps_its_order_while_wechat_is_away(self): st = json.dumps({"edit": 1}) page.action({"ui_version": 6, "action": {"id": "layout:down:feishu"}, "state": st}) page.action({"ui_version": 6, "action": {"id": "layout:up:feishu"}, "state": st}) - self.assertEqual(page.layout().order[3:6], ["feishu", "wechat", "agents"], "back as it was, 微信今天 in its place") + self.assertEqual(page.layout().order[4:7], ["feishu", "wechat", "agents"], "back as it was, 微信今天 in its place") def test_one_read_for_the_page_and_the_card(self): page, card, hub, _ = make() diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index d2e6fbc..3d3dbe0 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.67", + "version": "0.1.68", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.74/openmate-feishu-0.11.74.tar.gz b/packages/openmate-feishu/0.11.74/openmate-feishu-0.11.74.tar.gz new file mode 100644 index 0000000..6a2ca2e Binary files /dev/null and b/packages/openmate-feishu/0.11.74/openmate-feishu-0.11.74.tar.gz differ diff --git a/packages/openmate-wechat/0.1.68/openmate-wechat-0.1.68.tar.gz b/packages/openmate-wechat/0.1.68/openmate-wechat-0.1.68.tar.gz new file mode 100644 index 0000000..292ee4f Binary files /dev/null and b/packages/openmate-wechat/0.1.68/openmate-wechat-0.1.68.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index 755807f..f3bbc05 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.73", + "version": "0.11.74", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -38,7 +38,8 @@ "history", "login", "threads", - "outbound_send" + "outbound_send", + "items" ], "agent_tools": [ "matefeishu_status", @@ -49,7 +50,8 @@ "matefeishu_agent_reply", "matefeishu_starkmesh", "matefeishu_media", - "matefeishu_members" + "matefeishu_members", + "matefeishu_meetings" ], "confirm_always": [ "matefeishu_*" @@ -393,6 +395,30 @@ "title": "lark-cli 配置档", "description": "lark-cli 的 --profile:你为 Persona 登录的那个飞书应用。留空用 lark-cli 的默认配置档。需要日历只读权限(calendar:calendar.event:read)。" }, + "meetings": { + "type": "boolean", + "title": "会议和妙记", + "description": "通过 lark-cli 只读读取你参加过的飞书视频会议的智能纪要和妙记,在今天页和日程页显示,并存进知识库。", + "default": true + }, + "meetings_kb": { + "type": "boolean", + "title": "会议纪要进知识库", + "default": true + }, + "meeting_transcript": { + "type": "boolean", + "title": "逐字稿也进知识库", + "description": "逐字稿很长,会多占知识库整理用的模型额度。", + "default": false + }, + "meetings_days": { + "type": "integer", + "title": "会议回看天数", + "minimum": 1, + "maximum": 30, + "default": 14 + }, "starkmesh_url": { "type": "string", "format": "uri", @@ -482,9 +508,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.73/openmate-feishu-0.11.73.tar.gz", - "sha256": "ade6d172e567b3308f26f8e01eca9698b5768f8e110d04d3bf45bdb1c37ae9b9", - "size": 379976 + "url": "packages/openmate-feishu/0.11.74/openmate-feishu-0.11.74.tar.gz", + "sha256": "159d2b84b267fe8f3644c76a45f2910f932ddf76052e7b3976beb3a6d73bff97", + "size": 395090 } ] }, @@ -493,7 +519,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.67", + "version": "0.1.68", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -790,9 +816,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.67/openmate-wechat-0.1.67.tar.gz", - "sha256": "eeb58f03d2e6b1e44628e9276dacf413247874e3dfaa507aec67caf97316de95", - "size": 306493 + "url": "packages/openmate-wechat/0.1.68/openmate-wechat-0.1.68.tar.gz", + "sha256": "7ce721ea93ca5adc295f419f2162604c89db55ade78523604b9e56d5150aaa57", + "size": 307349 } ] } diff --git a/tests/test_actions.py b/tests/test_actions.py index 0141f86..749961d 100644 --- a/tests/test_actions.py +++ b/tests/test_actions.py @@ -21,8 +21,8 @@ def test_names_schemas_and_manifest(self): tools = h.c("tools.list")["tools"] actions = h.c("actions.list")["tools"] names = [t["name"] for t in tools] - self.assertEqual(names, [CID + "_" + n for n in ("status", "chats", "messages", "search", "docs", "agent_reply", "starkmesh", "media", - "members")]) + self.assertEqual(names, [CID + "_" + n for n in ("status", "chats", "messages", "search", "docs", "agent_reply", + "starkmesh", "media", "members", "meetings")]) self.assertEqual([a["name"] for a in actions], [CID + "_send", CID + "_send_dm"]) for t in tools + actions: self.assertTrue(t["description"]) diff --git a/tests/test_history.py b/tests/test_history.py index 668d4be..ad6c225 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -299,7 +299,7 @@ def test_wechat_does_not_offer_history(self): import openmate_wechat h = Harness(self, platform=openmate_wechat.platform()) - for method in ("history.chats", "archive.history"): + for method in ("history.chats", "archive.history", "items.list", "items.doc_title"): with self.assertRaises(HubSideError) as e: h.c(method, chat="x") self.assertEqual(e.exception.code, "no_capability") diff --git a/tests/test_protocol.py b/tests/test_protocol.py index b239c69..1f7468c 100644 --- a/tests/test_protocol.py +++ b/tests/test_protocol.py @@ -53,10 +53,25 @@ def test_calls_right_after_initialize_wait_for_startup(self): p = h.c("login.step", step="") # waits for the program to be ready instead of refusing self.assertEqual(p["kind"], "qr") + def test_optional_service_start_failure_leaves_agent_and_pages_available(self): + def fail(app): + raise RuntimeError("示例会议表建表失败") + + platform = dataclasses.replace(openmate_feishu.platform(), start_services=fail) + with self.assertLogs("openmate", level="ERROR") as logs: + h = Harness(self, platform=platform, config={"lark_cli": "/example/missing-lark-cli"}) + self.assertIn("示例会议表建表失败", "\n".join(logs.output)) + self.assertIsNotNone(h.app.agent) + self.assertEqual(h.app.setup_error, "") + for page in ("chats", "calendar", "openmate-today"): + response = h.hub.request("ui.render", {"contribution": page, "ui_version": 6}) + self.assertTrue(response["sections"], page) + self.assertEqual(h.c("items.list"), {"items": []}) + def test_unknown_and_undeclared(self): h = Harness(self) for method, code in (("nonexistent.method", "unknown_method"), ("connector.nonexistent_method", "unknown_method"), - ("connector.history.anchors", "no_capability"), ("connector.items.list", "no_capability"), + ("connector.history.anchors", "no_capability"), ("connector.recall.do", "no_capability")): with self.assertRaises(HubSideError) as e: h.hub.request(method, {"contribution": CID}) @@ -66,6 +81,8 @@ def test_unknown_and_undeclared(self): self.assertEqual(e.exception.code, "no_contribution") # the contribution may be left out when there is only one self.assertIn("state", h.hub.request("connector.status", {})) + self.assertEqual(h.c("items.list"), {"items": []}) + self.assertEqual(h.c("items.doc_title", url="https://example.com/"), {"title": ""}) def test_usage_query(self): # the sidebar's usage bars (contributes.usage): Feishu answers for its StarkMesh pool (here not set up, so it