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
3 changes: 3 additions & 0 deletions core/openmate_core/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ class Message:
title: str = ""
#: User IDs from the service's real @ elements, for live handling only.
mention_ids: List[str] = field(default_factory=list)
#: this reading says less than one before may have (a card read without its body, Feishu 2026-12-03): a text the
#: store has already stays; a message new to the store is kept with this one. Not stored.
keep_text: bool = False


@dataclass
Expand Down
4 changes: 3 additions & 1 deletion core/openmate_core/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,9 @@ def run(db):
"type = CASE WHEN ? != '' THEN ? ELSE type END, blocked = 1 "
"WHERE chat_id = ? AND id = ? AND (text != ? OR blocked = 0)",
(m.text or "", m.text or "", m.text or "", kind, m.chat_id, m.id, m.text or ""))
elif m.text:
elif m.text and not (m.keep_text and blank is None):
# (a reading that says less than one before keeps the stored text: blank is None here means it
# has one)
# a blocked message stays so (a later reading that is not the note, a decode failure's
# placeholder, never brings it to the archive); only a recall's notice replaces its note
db.execute("UPDATE messages SET text = ?, type = ? WHERE chat_id = ? AND id = ? AND text != ? "
Expand Down
113 changes: 108 additions & 5 deletions extensions/openmate-feishu/openmate_feishu/larkagentx.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@
CARDS_REREAD = "messages.PullMessagesByIdsRequest" # a card's message read again as a newer client (newer_api)
CARD_REREAD_AGAIN = 600.0 # a card read again with no body is not read again before this long (an edit's push may)…
CARD_REREAD_TRIES = 3 # …and at most this often in CARD_ASK_OFF; HTTP errors 3 times in a row: not read again that long
CARD_KEEP = 2000 # cards whose last reading with a body is kept (one read later without it shows that, never less)
CARD_DUE_MOST = 50 # pushed cards (an edit as it goes) left for after their wait, to be read once more then…
CARD_DUE_EVERY = 5.0 # …looked at this often while some are waiting; one that could not be read is tried again
CARD_DUE_AGAIN = 30.0 # this long after…
CARD_DUE_TRIES = 3 # …this many times in all
CARDS_ASK_MOST = 50 # cards asked for at once (CARDS_ASK)
CARD_HOLES_KEEP = 500 # cards read with no words, waiting to be asked for by their message id
CARD_ASK_TRIES = 3 # …asked for at most this often (a failed ask leaves it for the next read)
Expand Down Expand Up @@ -1095,6 +1100,8 @@ def __init__(self, lx: types.SimpleNamespace, region: str):
self._card_asked: Dict[str, float] = {} # pushed card → when it was asked for (CARD_PUSH_AGAIN)
self._card_ask_off = 0.0 # time.monotonic() until which cards are not asked for (CARD_ASK_OFF)
self._card_reread: Dict[str, Tuple[int, float]] = {} # card → (readings again with no body, the last's time)
self._card_kept: Dict[str, Tuple[str, Tuple[str, ...]]] = {} # card → (its text, its @s) with a body, newest last
self._card_due: Dict[str, tuple] = {} # pushed card skipped in its wait → (its chat, when to read[, tries])
self._card_reread_off = 0.0 # time.monotonic() until which no card is read again (HTTP errors)
self._card_reread_refused = 0
self._card_ask_refused = 0 # HTTP errors in a row asking for cards
Expand Down Expand Up @@ -1202,6 +1209,7 @@ def _set_session(self, auth, client, acct: Account, creds: dict, since: Optional
self._person_avatars.clear()
self._peers.clear()
self._doc_writer = None
self._forget_cards()
self._auth, self._client, self._me, self._creds = auth, client, acct, creds
self._session_no += 1
self._members.clear() # a sign-in reads every chat's members anew
Expand Down Expand Up @@ -1347,6 +1355,7 @@ def logout(self) -> None:
self._peers.clear()
self._members.clear()
self._doc_writer = None
self._forget_cards()
with self._groups_mu:
self._groups, self._groups_join, self._groups_owner, self._groups_at = [], {}, "", 0.0
self._groups_whole_ids = set()
Expand Down Expand Up @@ -1524,7 +1533,11 @@ def _deliver(self, inbox: "queue.Queue", client, me: Account, on_message, on_rec
while True:
self._refresh_groups(client, me) # cheap unless due: due ones read in a thread of their own
try:
item = inbox.get(timeout=GROUPS_SPACING)
self._cards_due(client, me, on_message) # pushed cards whose wait is over, read as they are now
except Exception as e:
log.info("cards due could not be read (%s)", type(e).__name__)
try:
item = inbox.get(timeout=CARD_DUE_EVERY if self._card_due else GROUPS_SPACING)
except queue.Empty:
continue
if item is None:
Expand Down Expand Up @@ -2141,6 +2154,16 @@ def _message(self, d: dict, me_id: str, client) -> Optional[Message]:
data = dict(data, _extras=extras)
text, has_body, card_ats = card_read(data, self._rich_reader, self._known_names(chat_id, me_id))
mentions |= {u for u in card_ats if u == "all" or u.isdigit()}
if has_body:
self._card_keep(msg_id, text, mentions)
else:
# a reading without its body (an edit pushed in its wait, a reading the service gave less) never shows
# less than one before did: the text and @s of the last reading with its body, until a newer one comes
with self._lock:
kept = self._card_kept.get(msg_id)
if kept is not None:
text = kept[0]
mentions |= set(kept[1])
if not has_body: # its content is kept apart: asked for by its message id (_fill_cards)
header = data.get("cardHeader") or {}
with self._lock:
Expand Down Expand Up @@ -2310,7 +2333,20 @@ def _position(self, chat_id: str, value, client) -> int:
def _rich_reader(self, rich: dict) -> str:
return str(self.lx.decoders.extract_rich_text(rich) or "")

def _fill_cards(self, client, msgs: List[Message], me_id: str, pushed: bool = False) -> None:
def _fill_cards(self, client, msgs: List[Message], me_id: str, pushed: bool = False, force: bool = False) -> None:
"""_fill_some_cards, then: a card still without its body is marked keep_text (the core keeps a text it has).
force: read again whatever waited before (a pushed card due after its wait, _cards_due)."""
with self._lock:
bodiless = [m for m in msgs if m is not None and m.type == "CARD" and m.id in self._card_holes]
before = {m.id: m.text for m in bodiless}
try:
self._fill_some_cards(client, msgs, me_id, pushed, force)
finally:
for m in bodiless:
if m.text == before[m.id]: # not filled: what it shows is less than a reading with its body
m.keep_text = True

def _fill_some_cards(self, client, msgs: List[Message], me_id: str, pushed: bool = False, force: bool = False) -> None:
"""Cards read with no words besides their header (their content is kept apart: a long one, a newer one, as
_message noted): asked for by their message ids at once (entities.BatchPullUniversalCardsByBizRequest: the
message's universal card entity), and their text, @s and at_me taken from it. One that still says nothing is
Expand All @@ -2330,14 +2366,16 @@ def _fill_cards(self, client, msgs: List[Message], me_id: str, pushed: bool = Fa
for k in [k for k, t in asked.items() if now - t > CARD_PUSH_AGAIN]:
del asked[k]
if len(self._card_pushes) >= CARD_PUSH_ASKS_PER_MINUTE or m.id in asked:
if m.id in asked and (m.id in self._card_due or len(self._card_due) < CARD_DUE_MOST):
self._card_due[m.id] = (m.chat_id, asked[m.id] + CARD_PUSH_AGAIN) # read then, as it is
continue
self._card_pushes.append(now)
asked[m.id] = now
want.append((m, self._card_holes.pop(m.id)))
if not want:
return
if client is not None:
want = self._reread_cards(client, want, me_id, pushed)
want = self._reread_cards(client, want, me_id, pushed, force)
if not want:
return
with self._lock:
Expand Down Expand Up @@ -2401,13 +2439,14 @@ def _fill_cards(self, client, msgs: List[Message], me_id: str, pushed: bool = Fa
continue
m.text = clip_lines(h["head"] + words, CARD_TEXT_MOST)
got = set(sorted(u for u in ats if u.isdigit())[:MENTIONS_MOST]) | ({"all"} & set(ats))
self._card_keep(m.id, m.text, got)
if "all" in got:
m.at_all = True
m.mention_ids = sorted(set(m.mention_ids or []) | (got - {"all"}))
if me_id and me_id in got and not m.mine:
m.at_me = True

def _reread_cards(self, client, want: list, me_id: str, pushed: bool = False) -> list:
def _reread_cards(self, client, want: list, me_id: str, pushed: bool = False, force: bool = False) -> list:
"""Cards with no body read again by their message ids as a newer client (newer_api, CARDS_REREAD: one request
for them all): Feishu leaves a newer card's content out for the version LarkAgentX names and sends the
"upgrade" stand-in instead (seen 2026-12-03: such a card's entity had only its card id, version and that rich
Expand All @@ -2424,7 +2463,8 @@ def _reread_cards(self, client, want: list, me_id: str, pushed: bool = False) ->
del self._card_reread[k]
for m, h in want:
tries, at = self._card_reread.get(m.id, (0, 0.0))
if tries and not (pushed and m.edited) and (tries >= CARD_REREAD_TRIES or now - at < CARD_REREAD_AGAIN):
if tries and not force and not (pushed and m.edited) and (
tries >= CARD_REREAD_TRIES or now - at < CARD_REREAD_AGAIN):
left.append((m, h))
else:
go.append((m, h))
Expand Down Expand Up @@ -2483,6 +2523,69 @@ def _reread_cards(self, client, want: list, me_id: str, pushed: bool = False) ->
len(read), len(part))
return left

def _forget_cards(self) -> None:
"""Under self._lock: what this session knew of cards (signed out, or another account): none of the next's."""
self._card_holes.clear()
self._card_pushes.clear()
self._card_asked.clear()
self._card_reread.clear()
self._card_kept.clear()
self._card_due.clear()
self._cards_noted.clear()
self._card_ask_off = self._card_reread_off = 0.0
self._card_ask_refused = self._card_reread_refused = 0

def _card_keep(self, mid: str, text: str, mentions) -> None:
"""A card's reading with its body: what a later one without it shows (CARD_KEEP of them, the newest last)."""
with self._lock:
self._card_kept.pop(mid, None)
self._card_kept[mid] = (text, tuple(sorted(mentions)))
while len(self._card_kept) > CARD_KEEP:
del self._card_kept[next(iter(self._card_kept))]

def _cards_due(self, client, me: Account, on_message) -> None:
"""Pushed cards skipped in their wait (an edit as it goes: CARD_PUSH_AGAIN) are read once more when it is
over, as the card is then, and handed to the core again: the last edit's content, not the one before. Off
the connection's loop, from _deliver, at most CARD_DUE_MOST at a time."""
now = time.monotonic()
with self._lock:
due = [(mid, v) for mid, v in self._card_due.items() if v[1] <= now][:CARD_DUE_MOST]
for mid, _ in due:
del self._card_due[mid]
if not due or client is None:
return
try:
ans = client.api("messages.PullMessagesByIdsRequest", {"messageIds": [mid for mid, _ in due]}) or {}
except Exception as e:
log.info("cards %s could not be read once more (%s)", ",".join(mid for mid, _ in due[:5]), type(e).__name__)
with self._lock: # a few times more, a while apart (CARD_DUE_TRIES)
if not self._still(me):
return # signed out or another account meanwhile: nothing of the one before is kept
for mid, v in due:
tries = (v[2] if len(v) > 2 else 0) + 1
if tries < CARD_DUE_TRIES and mid not in self._card_due and len(self._card_due) < CARD_DUE_MOST:
self._card_due[mid] = (v[0], now + CARD_DUE_AGAIN, tries)
return
with self._lock:
still = self._still(me)
if not still:
return # signed out or another account meanwhile: its cards are none of the next one's
chats = {mid: v[0] for mid, v in due}
for k, v in ((ans.get("messages") if isinstance(ans, dict) else None) or {}).items():
mid = _id(v.get("id")) if isinstance(v, dict) else ""
mid = mid or _id(k)
if mid not in chats or str(v.get("status") or "") in ("2", "DELETED"):
continue
try:
d = self._entity_dict(dict(v, id=mid), chat_id=chats[mid])
msg = self._message(d, me.id, client) if d is not None and d.get("from_id") else None
if msg is None or msg.type != "CARD":
continue
self._fill_cards(client, [msg], me.id, force=True) # read again as it is now, whatever waited before
on_message(msg)
except Exception as e:
log.info("card %s read once more could not be taken (%s)", mid, type(e).__name__)

def _card_reread_noted(self, part, now: float) -> None:
"""Cards read again with no body (or not read): one more try each, at now (bounded like _card_holes)."""
with self._lock:
Expand Down
2 changes: 1 addition & 1 deletion extensions/openmate-feishu/persona-extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": 1,
"id": "openmate-feishu",
"name": "飞书(OpenMate)",
"version": "0.11.72",
"version": "0.11.73",
"description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down
Loading
Loading