Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions core/openmate_core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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 设置 → 知识库选择 → 添加聊天)
Expand Down Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions core/openmate_core/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
50 changes: 44 additions & 6 deletions extensions/openmate-feishu/openmate_feishu/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand All @@ -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)
Expand All @@ -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),
Expand Down
Loading
Loading