diff --git a/README.md b/README.md index e46be09..a5ec06a 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/person | 知识库 | 按游标增量归档聊天记录,附件 20 MB 以内按需下载 | | 知识库选群 | 飞书声明了 Persona 的“历史”能力:在 Persona 的“设置 → 知识库选择 → 单项设置 → 添加聊天”里选来源“飞书(OpenMate)”,能搜到这个扩展存过的会话,添加后打开“全部保存”,这个群以后的消息就全部进知识库(不打开时只存 @我 和我发言前后的消息)。旧消息可以用 Persona 的历史导入补进来,只能补扩展登录以来存下的部分 | | 只读工具 | `matefeishu_status`、`matefeishu_chats`、`matefeishu_messages`(可按时间段和关键词查,会自己往前补读历史)、`matefeishu_search`(搜人和群)、`matefeishu_docs`(通过管理端的 lark-cli 只读集成搜文档)、`matefeishu_starkmesh`(中转站额度:还剩多少号、多久重置、哪些号不可用,早报用它)、`matefeishu_media`(按消息 id 以现在登录的账号把图片或文件下载到本机临时目录(每次重新下载,25 MB 以内),返回本地路径;`matefeishu_messages` 和 /agent 上下文里带图片或文件的消息写着「看图:matefeishu_media message=…」) | -| 写操作 | `matefeishu_send`、`matefeishu_send_dm`:每次都在手机上确认全文和发给谁;同一个请求只执行一次;结果不确定时绝不重发 | +| 写操作 | `matefeishu_send`、`matefeishu_send_dm`:每次都在手机上确认全文和发给谁;同一个请求只执行一次;结果不确定时绝不重发。正文可以用 Markdown 的一个子集排版,发成飞书富文本:`**粗体**`、`[文字](https://链接)`、`- ` / `1. ` 开头的列表(不嵌套)、`` `行内代码` ``、围栏代码块、`# ` 标题(显示成加粗的一行)、`> ` 引用;一种都没用就照旧按纯文本发。确认卡上标明按富文本发送、用到哪些格式,下面是写的原文(链接地址可见)。`at` 和正文里的「@名字」照旧变成真 @,但带格式发送时,写在代码、链接或裸链接里的「@名字」不算,那个人的 @ 单独放在最前面一段(纯文本照旧);含 @ 的那一段里的行内代码按原样(带反引号)显示,确认卡上会注明 | | `/agent` | 你自己在飞书里发 `/agent …`,或者发一条真正 @ 你自己的消息(`@自己 …`,@ 后面的话就是要办的事;不以“/”开头,群里别的机器人不会当成自己的命令;设置“@自己 也交给 Agent”默认打开,可关),交给 Agent 处理并以你的身份回复到提问的地方:话题里问的回到话题;话题里勾了“也发到群里”的,回复同样回到话题、也发到群里,并引用这条请求;群聊主界面问的(包括引用回复),在主界面引用回复这条请求;私聊里是引用回复,AI 标记放在回复最后一行(话题折叠时直接显示答案;设置“AI 标记位置”可改回第一行);同一话题里接着发会进同一个会话;助手已经把活派给 Agent(建了待办、Agent 还在做)时,话题里你自己的追问直接转给那个 Agent,话题里回一句“已转给正在做这件事的 Agent”,结果照常经助手回到话题(写“问 Persona”“问助手”、任务结束了、Agent 不在了,就照旧交给助手;设置“话题里的追问直接转给干活的 Agent”可关);`/stop`、`/停止`、`/停` 可以停下。请求上的表情说明状态:🤔 处理中,✅ 做完了,❌ 失败或超时(停下就撤掉 🤔;三个表情都能在设置里换)。中途进度只占一条消息、原地更新,最终结果另发一条新回复(会提醒你),那条进度消息标成已完成。回复不经手机确认,每一条都记进 Persona 的“以你身份发出的消息”记录,所以安装时 Persona 会提示这个扩展会“以你的身份发消息” | | Persona 渠道 | 在 Persona 的“设置 › 渠道”里显示为“飞书(OpenMate)”(绑定、账号、开关跟着连接器走),不用装官方 larkx 也能把飞书当成 Persona 的一个渠道。只在你指定的一个会话里生效:扩展设置里的“Persona 渠道会话”填会话 id(问 Persona 助手“飞书里 xx 群的 chat id”即可,要是这个扩展收到过消息的会话),请用只有你自己的群;默认留空,留空时渠道什么都不收也不发。那个会话就是你和 Persona 的对话,相当于官方飞书机器人的私聊:你自己说的每一句都交给 Persona 统一的渠道流程(开头的 `/agent` 可写可不写;默认进主对话,可在“设置 › 渠道”改目标;`/new`、`/status` 等 Persona 渠道命令也能用),回答以你的身份回到提问处(话题里问的回到话题,主界面问的引用回复);`/stop`、`/停止`、`/停` 打断渠道正在跑的对话。Agent 要你回答或批准时(渠道驱动的对话,或“设置 › 渠道”里打开了“所有 Agent 的问题”),问题以你的身份发到这个会话,直接回复就是作答;你在 App 等别处答了,这条问题会自动撤回。别的会话里的 `/agent`、进度原地更新、自动代答、话题追问转给 Agent 都和原来一样 | | 历史补收 | 首次登录和每次重连后补收最近会话里漏掉的消息 | diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index 41fa02e..26c3eed 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -342,6 +342,8 @@ def __init__(self, app): self._thread: Optional[threading.Thread] = None self._last_prune = 0.0 self._posted: Dict[str, float] = {} # hashes of what /agent posted lately: their echoes are never requests + self._own: Dict[tuple, List[float]] = {} # a tool's formatted sends (own_send): their echoes are none either + self._own_gen = 0 # one more at each forget: a send's end from the account before is none of the next one's self._asked: Dict[str, float] = {} # run id → when its session's status was last asked self._handing: Dict[str, tuple] = {} # run id → (chat, thread, asked at) of a follow-up being handed to an Agent self._handed = threading.Condition(self._mu) @@ -464,6 +466,50 @@ def _echo(self, text: str) -> bool: del self._posted[k] return self._digest(text) in self._posted + def own_send(self, chat_id: str, words: str, message_id: str = "", failed: bool = False, + gen: Optional[int] = None) -> int: + """A formatted send of a tool's into the chat, known by the words it reads back as ("> /stop" reads "/stop", + "**/agent** x" reads "/agent x"), so its echo is never a request or a stop: before the send (words alone), + after it (its message id: the words stand for it no more, so the user's own line of the same words there is + theirs), or failed (surely not sent: they stand for nothing). Only in that chat, at most 10 minutes. Returns + the account's generation before the send; its end passes it back (gen), and one from before another account + signed in (forget) changes nothing of the new one's.""" + key = (chat_id, self._digest(words)) + with self._mu: + if gen is not None and gen != self._own_gen: + return self._own_gen + self._prune_own() + if message_id: + self._own_pop(key) + self._own[("id", chat_id, str(message_id))] = [time.time()] + elif failed: + self._own_pop(key) + else: + self._own.setdefault(key, []).append(time.time()) + return self._own_gen + + def _own_pop(self, key) -> None: + sends = self._own.get(key) or [] + if sends: + sends.pop(0) + if not sends: + self._own.pop(key, None) + + def _prune_own(self) -> None: + now = time.time() + for k in [k for k, v in self._own.items() if all(now - at > 600 for at in v)]: + del self._own[k] + + def _own_echo(self, row: dict) -> bool: + """Whether the row is the echo of a tool's formatted send (own_send): by its id, or a POST by its words.""" + chat = row.get("chat_id") or "" + with self._mu: + self._prune_own() + if ("id", chat, str(row.get("id") or "")) in self._own: + return True + # before its id is known (or never, the send uncertain): only a POST reads so; a typed TEXT is the user's + return (row.get("type") or "").upper() == "POST" and (chat, self._digest(row.get("text") or "")) in self._own + def _remember_post(self, body: str, run: Optional[dict] = None) -> bool: """What is about to go out, so its echo is never a request; False (nothing remembered, and it must not go out) for a run wiped by the switch: checked where forget empties the echoes, so none outlives the switch. Right @@ -495,6 +541,8 @@ def forget(self) -> None: """Another account signed in: what /agent posted for the one before is no echo of the next one's lines.""" with self._mu: self._posted.clear() + self._own.clear() # (the formatted sends of the account before: their echoes are none of this one's) + self._own_gen += 1 self._handing.clear() # that account's follow-ups being handed on hold up none of the next one's self._handed.notify_all() @@ -584,7 +632,7 @@ def on_message(self, row: dict, epoch: Optional[int] = None) -> None: # the 「Persona 渠道会话」's: handed to Persona's channel flow (channel.py), whether /agent is on or not; its # echoes are told by the channel's own record of what was sent there, not /agent's text cache return - if self._echo(text) or not self.enabled: + if self._echo(text) or self._own_echo(row) or not self.enabled: return if body.lower() in STOP_WORDS: self._take_stop(row, epoch) diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index c348d0d..d408b86 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -1617,9 +1617,11 @@ def _not_handing_off(self) -> None: raise SendRejected("正在换%s账号,这条没有发出,请稍后再发" % self.platform.name) def send_as_user(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Optional[str] = None, - to_chat: bool = False, mentions: Optional[List[Tuple[str, str, int]]] = None) -> str: + to_chat: bool = False, mentions: Optional[List[Tuple[str, str, int]]] = None, + rich: bool = False) -> str: """mentions [(user id, name, offset)] (textutil.mention_spans): real @s, each "@name" at offset in text, only - where the backend can_mention (SendRejected else).""" + where the backend can_mention (SendRejected else). rich: the text is in the Markdown subset (markup) and goes + formatted, only where the backend can_format (SendRejected else).""" if not self.signed_in: raise SendRejected("还没有登录%s" % self.platform.name) self._not_handing_off() @@ -1627,22 +1629,40 @@ def send_as_user(self, chat_id: str, text: str, reply_to: Optional[str] = None, raise SendRejected("%s登录已失效,请重新扫码登录" % self.platform.name) if mentions and not getattr(self.backend, "can_mention", False): raise SendRejected("%s这里不能 @人" % self.platform.name) - if self.channel is not None: - self.channel.outgoing(chat_id, text) # its echo in the 渠道's chat is no line of the user's + if rich and not getattr(self.backend, "can_format", False): + raise SendRejected("%s这里不能发带格式的消息" % self.platform.name) + # what its echo will read: a formatted text reads as its words (the backend says them), not as written; its + # echo is never a request or a stop of /agent's ("> /stop" reads back as "/stop": agent.own_send) + heard = text + agent = self.agent if rich else None + if rich: + try: + heard = self.backend.formatted_words(text, list(mentions or ())) or text + except Exception: + heard = text + gen = agent.own_send(chat_id, heard) if agent is not None else None + if self.channel is not None: # its echo in the 渠道's chat is no line of the user's (a formatted one: a POST) + self.channel.outgoing(chat_id, heard, post=rich) # only when set: a backend that never reads "thread_chat" or takes no @s need not know the words extra: Dict[str, Any] = {} if to_chat and root: extra["to_chat"] = True if mentions: extra["mentions"] = list(mentions) + if rich: + extra["rich"] = True try: mid = self.backend.send(chat_id, text, reply_to or None, root or None, **extra) except SendRejected: if self.channel is not None: - self.channel.outgoing(chat_id, text, failed=True) # surely not sent: its text stands for nothing + self.channel.outgoing(chat_id, heard, failed=True, post=rich) # surely not sent: it stands for nothing + if agent is not None: + agent.own_send(chat_id, heard, failed=True, gen=gen) raise if self.channel is not None: - self.channel.outgoing(chat_id, text, str(mid or "")) # known by its id from now on + self.channel.outgoing(chat_id, heard, str(mid or ""), post=rich) # known by its id from now on + if agent is not None and mid: + agent.own_send(chat_id, heard, str(mid), gen=gen) return mid def send_image_as_user(self, chat_id: str, path: str, reply_to: str = "", root: str = "", diff --git a/core/openmate_core/backend.py b/core/openmate_core/backend.py index b9a9f45..4477e77 100644 --- a/core/openmate_core/backend.py +++ b/core/openmate_core/backend.py @@ -399,11 +399,22 @@ def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Op into root's thread and also into the chat's main stream, quoting reply_to (the core passes it only when true, and only for a message the backend read as "thread_chat"). A backend with can_mention also takes mentions [(user id, name, offset)]: real @s of those people, each "@name" at offset in text (textutil.mention_spans; - the core passes it only when there are some). Raise SendRejected only when it surely did not go out.""" + the core passes it only when there are some). A backend with can_format also takes rich=True (passed only + then): the text is in the Markdown subset (markup), sent formatted. Raise SendRejected only when it surely did + not go out.""" #: Whether send takes mentions (real @s that tell those people); the send tool offers them only then can_mention: bool = False + #: Whether send takes rich=True: the text is in the Markdown subset (markup) and goes formatted (the send tools + #: say the subset, and pass rich only for a text that uses it, only then) + can_format: bool = False + + def formatted_words(self, text: str, mentions: list) -> str: + """A formatted text (rich=True, its mentions as send's) as the backend will read its own message back: what + its echo is known by. Only asked where can_format; "" leaves the text as written.""" + return "" + #: Whether chats may be thread-first (Chat.topic: every message opens a topic or replies in one); the send card #: asks chat_info only then topic_groups: bool = False diff --git a/core/openmate_core/channel.py b/core/openmate_core/channel.py index be56c89..90cff70 100644 --- a/core/openmate_core/channel.py +++ b/core/openmate_core/channel.py @@ -77,6 +77,7 @@ REFS_KEEP = 30 * 86400.0 # a ref's account: as long as the send journal keeps the ref MAIN = {"reply_to": "", "root": "", "to_chat": False} PICTURE = "\x00picture" # outgoing's words for a picture being sent: its echo is a line of type IMAGE +POSTED = "\x00post:" # before outgoing's words for a formatted text: its echo is a POST (a typed TEXT of them is the user's) PICTURE_WINDOW = 120.0 # a picture sent whose outcome is not known stands for its echo this long from its start @@ -374,19 +375,20 @@ def _track(self, epoch: Optional[int], res, ref: str, kind: str) -> None: # ---------------------------------------------------------------- the program's own sends def outgoing(self, chat_id: str, text: str, message_id: Optional[str] = None, failed: bool = False, - picture: bool = False) -> None: + picture: bool = False, post: bool = False) -> None: """Something this program sends into a chat as the user (any send: the channel's, a tool's, an inbox reply): its echo in the channel chat is never a line of the user's. Called before the send with its text; after it with its id (known by that from then on; without one the text stands for it a while), or failed (surely not sent: the text stands for nothing). picture: a picture, whose echo (a line of type IMAGE, which may come - before its id is known) a picture being sent stands for.""" + before its id is known) a picture being sent stands for. post: a formatted text, whose echo is a POST (a line + of the user's typed as TEXT with the same words is theirs).""" if not self.declared or chat_id != self.chat(): return # only the channel chat's lines are read as the user's if message_id and self.app.store is not None: # known by its id first, then the text stands for it no more self.app.store.channel_msg_put(chat_id, message_id, "echo", owner=getattr(self.app, "_owner", "")) if picture and not self.declares_images_out: return # a picture stands for its echo only where the channel sends some (WeChat's: by its id, as before) - key = (chat_id, PICTURE if picture else (text or "").strip()) + key = (chat_id, PICTURE if picture else (POSTED if post else "") + (text or "").strip()) now = time.monotonic() with self._mu: for k in [k for k, v in self._outs.items() if all(now - at > ECHO_WINDOW for at in v)]: @@ -405,7 +407,8 @@ def _ours(self, chat: str, row: dict) -> bool: return True now = time.monotonic() picture = (row.get("type") or "").upper() == "IMAGE" - said = PICTURE if picture else (row.get("text") or "").strip() + posted = (row.get("type") or "").upper() == "POST" + said = PICTURE if picture else (POSTED if posted else "") + (row.get("text") or "").strip() window = PICTURE_WINDOW if picture else ECHO_WINDOW # a picture's echo comes within moments, or not at all with self._mu: return any(now - at < window for at in self._outs.get((chat, said), ())) diff --git a/core/openmate_core/fixture.py b/core/openmate_core/fixture.py index a7d99f2..0b31cfd 100644 --- a/core/openmate_core/fixture.py +++ b/core/openmate_core/fixture.py @@ -87,6 +87,7 @@ def __init__(self, now: Optional[float] = None, seed: bool = True): self.send_fail: Optional[str] = None # "rejected" | "uncertain" for the next send self.send_fail_always: Optional[str] = None self.images_ok = False # the backend can send pictures (an /agent reply's image) + self.format_ok = True # the backend sends formatted texts (rich=True: the Markdown subset) self.image_threads = False # …where a text with the same reply_to and root would go (Backend.image_threads) self.avatars_ok = False # chat_info says a chat's picture (Backend.has_avatars) self.info_asked: List[str] = [] # chat_info's calls, in order @@ -470,8 +471,12 @@ def topic_mode(self, chat_id: str) -> bool: with self.world.lock: return chat_id in self.world.topic_mode_chats + @property + def can_format(self) -> bool: + return self.world.format_ok + def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Optional[str] = None, - to_chat: bool = False, mentions: Optional[list] = None) -> str: + to_chat: bool = False, mentions: Optional[list] = None, rich: bool = False) -> str: w = self.world if w.send_delay: time.sleep(w.send_delay) @@ -484,10 +489,11 @@ def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Op raise BackendError("发送超时", "unreachable") if chat_id not in w.chats: raise SendRejected("没有这个会话") - m = w.push(chat_id, "me", text, parent_id=reply_to or "", root_id=root or "") + extra = {"type": "POST"} if rich else {} # (a formatted one comes back as a POST, as Feishu's does) + m = w.push(chat_id, "me", text, parent_id=reply_to or "", root_id=root or "", **extra) with w.lock: w.sent.append({"chat": chat_id, "text": text, "reply_to": reply_to, "root": root, "to_chat": to_chat, - "id": m.id, "mentions": list(mentions or [])}) + "id": m.id, "mentions": list(mentions or []), "rich": rich}) return m.id @property diff --git a/core/openmate_core/markup.py b/core/openmate_core/markup.py new file mode 100644 index 0000000..532212c --- /dev/null +++ b/core/openmate_core/markup.py @@ -0,0 +1,381 @@ +"""The Markdown subset a message sent as the user may be written in (on a platform whose backend can_format): what it +is made of (blocks of lines, inline runs), whether a text uses it at all, and where an "@name" is no @ (in code, in a +link). Platform-neutral: a backend turns the blocks into its own rich text. + +The subset (what the send tools tell the model): +- **bold** +- [words](https://address): words that link (http and https only); a bare address stays as written +- lines starting "- ", "* " or "+ " (a bulleted list), "1. " or "1) " (a numbered list, from its first number) +- `code` in a line, and fenced code blocks (``` or ~~~, a language after the fence may be named) +- "# " to "###### " (a heading: shown as a bold line), "> " (a quote) +- a line break is one, an empty line starts a new paragraph + +Nothing else is read as markup: single *, _, ~~, tables, nested lists (an indented item is one more item), images +(![…](…) stays words), anything inside code or a bare address. +""" + +import itertools +import re +from typing import Dict, List, NamedTuple, Optional, Tuple + +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})[ \t]*([\w+#.-]*)[ \t]*$") +HEADING = re.compile(r"^ {0,3}#{1,6}[ \t]+(\S.*?)[ \t]*$") +QUOTE = re.compile(r"^ {0,3}>(?:[ \t]+(.*?))?[ \t]*$") # "> words" or a ">" alone; ">= 80%" is words +BULLET = re.compile(r"^[ \t]*[-*+][ \t]+(\S.*?)[ \t]*$") +NUMBERED = re.compile(r"^[ \t]*(\d{1,9})[.)][ \t]+(\S.*?)[ \t]*$") +SETEXT = re.compile(r"^[-=*_][-=*_ \t]*$") +RULE = re.compile(r"^ {0,3}([-*_])([ \t]*\1){2,}[ \t]*$") # "---", "* * *": words as written, never a list +CODE_SPAN = re.compile(r"`[^`\n]+`") +_TARGET = r"(https?://[^\s()]+(?:\([^\s()]*\)[^\s()]*)*)" # one pair of round brackets may be in an address +LINK = re.compile(r"(?, ` or CJK or fullwidth punctuation (Chinese words and fullwidth +# letters in its path are in it), without the sentence marks and stars at its end ("**see https://x.org**." is +# bold: _trim_url): as written (the service links it), no markup or @ in it +URL = re.compile(r"(?i:https?)://[^\s<>\"'`\x00\x01\x03\x04\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65]+") +URL_TAIL = ".,:;!?*" +MASK = "\x01" # stands for code's words, an address: never markup, wherever the stars are +IMAGE_MASK = "\x03" # stands for an image, its text and address: words, never a link +LINK_MASK = "\x04" # stands for a link's address (LINK's, http or https in lower case): its link's +MASKS = (MASK, IMAGE_MASK, LINK_MASK) # (written in the text: "\x00", an address's end as they are; a name's mask +# "\x02" is kept, an address runs on through it) +SCHEME = re.compile(r"(?i)https?://") +# on a line masked (_masked): `code`, **bold** (no space just inside the stars), [words](its address, masked) +INLINE = re.compile(r"`([^`\n]+)`|\*\*(?=\S)(.+?)(?<=\S)\*\*|(?|&])") +NBSP = "\u00a0" + +FEATURES = (("bold", "粗体"), ("link", "链接"), ("list", "列表"), ("code", "代码"), ("heading", "标题"), ("quote", "引用")) + + +class Run(NamedTuple): + """An inline run. kind: "text", "url" (a bare address: words as written), "code" or "link"; words: what it shows; + at: where its words start in the text; url: a link's address; bold; start, end: the whole run in the text, its + markup included.""" + + kind: str + words: str + at: int + url: str + bold: bool + start: int + end: int + + +def _masked(line: str) -> str: + """The line with code's words, images and bare addresses as MASK: what no markup is read in (a "**" in code, in + an address, closes no bold; an image is no link).""" + m = ["\x00" if c in MASKS else c for c in line] # (a mark written in the text is none of these) + + def blank(a: int, b: int, mark: str = MASK) -> None: + m[a:b] = mark * (b - a) + + for c in CODE_SPAN.finditer(line): + blank(c.start() + 1, c.end() - 1) + once = "".join(m) + for x in IMAGE.finditer(once): + blank(x.start(), x.end(), IMAGE_MASK) # (its own mark: never one run with an address beside it) + once = "".join(m) + # a bare address that starts outside any "[words](address)" and runs through one keeps it: the link is in its words + candidates = [(x.start(), x.end()) for x in LINK.finditer(once)] + bare: List[Tuple[int, int]] = [] + for st in SCHEME.finditer(once): # each address from its own start (one inside a link takes none after it) + p = st.start() + if any(a <= p < b for a, b in candidates) or (bare and p < bare[-1][1]): + continue + u = URL.match(once, p) + if u: + bare.append((p, p + len(_trim_url(u.group())))) + hidden = list(once) # the links whole as MASK: no bare address starts in one, nor runs on from one + for x in LINK.finditer(once): + if any(a < x.start() < b for a, b in bare): + continue + hidden[x.start():x.end()] = MASK * (x.end() - x.start()) + blank(x.start(2), x.end(2), LINK_MASK) # its address is one piece: a "**" in it closes no bold + for u in URL.finditer("".join(hidden)): + blank(u.start(), u.start() + len(_trim_url(u.group()))) + return "".join(m) + + +def _trim_url(url: str) -> str: + """A bare address without the sentence marks and stars at its end (nor a ")" it does not open).""" + while url and (url[-1] in URL_TAIL or (url[-1] == ")" and url.count(")") > url.count("("))): + url = url[:-1] + return url + + +def _words(line: str, masked: str, a: int, b: int, base: int, bold: bool) -> List[Run]: + """Words between markup: "text" runs, a bare address its own "url" run.""" + out: List[Run] = [] + pos = a + for u in re.finditer(re.escape(MASK) + "+", masked[a:b]): + ua, ub = a + u.start(), a + u.end() + if not (URL.fullmatch(line[ua:ub]) and _trim_url(line[ua:ub]) == line[ua:ub]): + continue # (a link's address: in its run) + if ua > pos: + out.append(Run("text", line[pos:ua], base + pos, "", bold, base + pos, base + ua)) + out.append(Run("url", line[ua:ub], base + ua, line[ua:ub], bold, base + ua, base + ub)) + pos = ub + if pos < b: + out.append(Run("text", line[pos:b], base + pos, "", bold, base + pos, base + b)) + return out + + +def inline(line: str, base: int = 0, bold: bool = False, masked: Optional[str] = None) -> List[Run]: + """A line's runs in order; base: where the line starts in the text. Inside **bold**, code and links are read too; + code, bare addresses and images are read before any of it (CommonMark's way: code binds first).""" + if masked is None: + masked = _masked(line) + out: List[Run] = [] + pos = 0 + for m in INLINE.finditer(masked): + if m.start() > pos: + out += _words(line, masked, pos, m.start(), base, bold) + if m.group(1) is not None: + out.append(Run("code", line[m.start(1):m.end(1)], base + m.start(1), "", bold, base + m.start(), + base + m.end())) + elif m.group(2) is not None: + a, b = m.start(2), m.end(2) + out += inline(line[a:b], base + a, True, masked[a:b]) + else: + out.append(Run("link", line[m.start(3):m.end(3)], base + m.start(3), line[m.start(4):m.end(4)], bold, + base + m.start(), base + m.end())) + pos = m.end() + if pos < len(line): + out += _words(line, masked, pos, len(line), base, bold) + return out + + +def _md_escape(words: str) -> str: + return MD_SPECIAL.sub(r"\\\1", words) + + +def _md_line(runs: List[Run]) -> str: + """A line's runs as Markdown: the words escaped (a lone * or _ stays a star), bold runs together in one **…**.""" + out: List[str] = [] + for bold, group in itertools.groupby(runs, key=lambda r: r.bold): + parts = [] + for r in group: + if r.kind == "code": # (fenced by more backticks than any run in its words) + ticks = "`" * (max([len(t) for t in re.findall(r"`+", r.words)] + [0]) + 1) + pad = " " if r.words.startswith("`") or r.words.endswith("`") else "" + parts.append("%s%s%s%s%s" % (ticks, pad, r.words, pad, ticks)) + elif r.kind == "link": + parts.append("[%s](%s)" % (_md_escape(r.words), r.url.replace("&", "\\&"))) # (no entity: "©") + elif r.kind == "url": + parts.append(r.words) + else: + parts.append(_md_escape(r.words)) + piece = "".join(parts) + core = piece.strip() + if bold and core: + lead, trail = piece[:len(piece) - len(piece.lstrip())], piece[len(piece.rstrip()):] + piece = "%s**%s**%s" % (lead, core, trail) + out.append(piece) + line = "".join(out) + indent = len(line) - len(line.lstrip(" \t")) + line = NBSP * indent + line[indent:] # an indent kept, never an indented code block + # never a list or a heading of its own: "1. x" -> "1\. x", "- x" -> "\- x", "## x" -> "\## x" ("1.5" as is) + line = re.sub(r"^(\d+)([.)])(?=\s|$)", r"\1\\\2", line) + return re.sub(r"^([+-]|#+)(?=\s|$)", r"\\\1", line) + + +class Block(dict): + """A block of the text. kind: "paragraph", "heading", "quote", "bullets", "numbers" or "code". lines: [(words, + where they start in the text)]: a paragraph's or a quote's lines, a heading's one, a list's items (numbers: from + number); code: lang and body. start, end: the block's place in the text.""" + + kind = property(lambda self: self["kind"]) + lines = property(lambda self: self.get("lines") or []) + start = property(lambda self: self["start"]) + end = property(lambda self: self["end"]) + number = property(lambda self: int(self.get("number", 1))) # a numbered list's first number + + def runs(self, src: Optional[str] = None) -> List[List[Run]]: + """Each line's runs (a heading's are bold); a line that is a rule ("*****", "---") is words as written. src: + the text the blocks were read from with its @s' names masked (without_names): the runs' words and addresses + are taken from it, as written.""" + out = [[Run("text", words, at, "", False, at, at + len(words))] if RULE.match(words) + else inline(words, at, self.kind == "heading") for words, at in self.lines] + if src is None: + return out + return [[r._replace(words=src[r.at:r.at + len(r.words)], + url=src[r.end - 1 - len(r.url):r.end - 1] if r.kind == "link" else + src[r.at:r.at + len(r.url)] if r.url else "") for r in line] for line in out] + + def has_code(self) -> bool: + """Whether a line of it has `code`.""" + return any(r.kind == "code" for line in self.runs() for r in line) + + def markdown(self, src: Optional[str] = None) -> str: + """The block as Markdown on its own, made from its runs (literal words escaped, each line as one, a list's + items unindented): what a backend that renders Markdown shows for it, as the other blocks show. src: as + runs'.""" + k = self.kind + if k == "code": + body = self["body"] + if src is not None: # (as written: a name in it too; a CRLF as an LF, as the body reads) + body = "\n".join(line[:-1] if line.endswith("\r") else line + for line in src[self["body_at"]:self["body_end"]].split("\n")) if body else "" + ticks = max([len(t) for t in re.findall(r"`{3,}", body)] + [2]) + 1 # a fence the body never closes + return "%s%s\n%s%s%s" % ("`" * ticks, self.get("lang") or "", body, "\n" if body else "", "`" * ticks) + # a line of only - = * _ is words, in a quote or a list too (never a heading's underline) + lines = [(lambda w: "\\" + w if SETEXT.match(w) else w)(_md_line(runs)) for runs in self.runs(src)] + if k == "quote": + return "\n".join("> " + w for w in lines) + if k == "bullets": + return "\n".join("- " + w for w in lines) + if k == "numbers": + return "\n".join("%d. %s" % (self.number + i, w) for i, w in enumerate(lines)) + return " \n".join(lines) # a paragraph (a heading: its one bold line): each line break a hard one + + +def _closes(line: str, fence: str) -> bool: + """Whether the line closes the fence: up to 3 spaces (no tab), its mark at least as many times, nothing else.""" + lead = len(line) - len(line.lstrip(" ")) + s = line[lead:].rstrip() + return lead <= 3 and len(s) >= len(fence) and s == fence[0] * len(s) + + +def _starts_block(line: str) -> bool: + return bool(FENCE.match(line) or HEADING.match(line) or QUOTE.match(line) + or (not RULE.match(line) and (BULLET.match(line) or NUMBERED.match(line)))) + + +def blocks(text: str) -> List[Block]: + """The text's blocks in order (empty lines between them only; none when the text is empty).""" + raw = (text or "").split("\n") + offs: List[int] = [] + at = 0 + for line in raw: + offs.append(at) + at += len(line) + 1 + lines = [line[:-1] if line.endswith("\r") else line for line in raw] # a CRLF ends a line as an LF does + n, i = len(lines), 0 + out: List[Block] = [] + + def end_of(j: int) -> int: + return offs[j] + len(lines[j]) + + while i < n: + line = lines[i] + fence = FENCE.match(line) + if fence: + j = i + 1 + while j < n and not _closes(lines[j], fence.group(1)): + j += 1 + body = "\n".join(lines[i + 1:j]) + last = min(j, n - 1) # not closed: it runs to the end + out.append(Block(kind="code", lang=fence.group(2).lower(), body=body, start=offs[i], end=end_of(last), + body_at=offs[i + 1] if i + 1 < n else end_of(i), + body_end=(offs[j] - 1) if j < n else len(text or ""))) + i = j + 1 + continue + if not line.strip(): + i += 1 + continue + m = HEADING.match(line) + if m: + out.append(Block(kind="heading", lines=[(m.group(1), offs[i] + m.start(1))], start=offs[i], end=end_of(i))) + i += 1 + continue + if QUOTE.match(line): + got, j = [], i + while j < n and QUOTE.match(lines[j]) and not FENCE.match(lines[j]): + q = QUOTE.match(lines[j]) + if q.group(1) is not None: + got.append((q.group(1), offs[j] + q.start(1))) + j += 1 + if got: + out.append(Block(kind="quote", lines=got, start=offs[i], end=end_of(j - 1))) + i = j + continue + if not RULE.match(line) and (BULLET.match(line) or NUMBERED.match(line)): + pattern = NUMBERED if NUMBERED.match(line) else BULLET + got, j = [], i + while j < n and not RULE.match(lines[j]) and pattern.match(lines[j]): + m = pattern.match(lines[j]) + g = 2 if pattern is NUMBERED else 1 + got.append((m.group(g), offs[j] + m.start(g))) + j += 1 + b = Block(kind="numbers" if pattern is NUMBERED else "bullets", lines=got, start=offs[i], end=end_of(j - 1)) + if pattern is NUMBERED: + b["number"] = int(NUMBERED.match(line).group(1)) + out.append(b) + i = j + continue + got, j = [], i + while j < n and lines[j].strip() and (j == i or not _starts_block(lines[j])): + got.append((lines[j].rstrip(), offs[j])) # its indent kept (" run()") + j += 1 + out.append(Block(kind="paragraph", lines=got, start=offs[i], end=end_of(j - 1))) + i = j + return out + + +def without_names(text: str, names=()) -> str: + """The text with each "@name" of the names (those to @) masked: a name is never markup ("@**Ops**" is a name).""" + for name in sorted({n for n in names if n}, key=len, reverse=True): + text = text.replace("@" + name, "@" + "\x02" * len(name)) + return text + + +def features(text: str, names=()) -> List[str]: + """What markup of the subset the text uses, in words (粗体, 链接, 列表, 代码, 标题, 引用): [] for a plain text, which + goes as it always did. names: those to @, whose "@name" is never markup.""" + seen: Dict[str, bool] = {} + for b in blocks(without_names(text, names)): + if b.kind == "code": + seen["code"] = True + continue + if b.kind in ("bullets", "numbers"): + seen["list"] = True + elif b.kind in ("heading", "quote"): + seen[b.kind] = True + for line in b.runs(): + for r in line: + if r.kind == "code": + seen["code"] = True + elif r.kind == "link": + seen["link"] = True + if r.bold and b.kind != "heading": + seen["bold"] = True + return [words for key, words in FEATURES if seen.get(key)] + + +def formatted(text: str, names=()) -> bool: + """Whether the text uses the subset at all (else it is sent as plain text, as before); names: as features'.""" + return bool(features(text, names)) + + +def no_mentions(text: str) -> List[Tuple[int, int]]: + """Where an "@name" is no @: code (fenced or `inline`), links and bare addresses, as (start, end) places.""" + out: List[Tuple[int, int]] = [] + for b in blocks(text): + if b.kind == "code": + out.append((b.start, b.end)) + continue + for line in b.runs(): + out.extend((r.start, r.end) for r in line if r.kind in ("code", "link", "url")) + for words, at in b.lines: # an image's address too (its text is words, never an @'s place) + plain = CODE_SPAN.sub(lambda c: "`" + MASK * (len(c.group()) - 2) + "`", words) + out.extend((at + x.start(), at + x.end()) for x in IMAGE.finditer(plain)) + return out + + +FRONT_END = "\n\n" # after the @s a formatted text does not write (textutil.mention_spans' front_end): a paragraph + + +def code_as_written(text: str, ats: List[int]) -> bool: + """Whether a block with an @ in it (ats: where each "@name" is in the text) has `code`: it goes as words then + (an @ is no Markdown's), its code's backticks shown, and the card says so.""" + return any(b.kind != "code" and b.has_code() and any(b.start <= a < b.end for a in ats) for b in blocks(text)) + + +def block_of(bs: List[Block], at: int) -> Optional[Block]: + """The block a place in the text is in (None: between blocks).""" + for b in bs: + if b.start <= at < b.end or (at == b.end and b.start < b.end): + return b + return None diff --git a/core/openmate_core/textutil.py b/core/openmate_core/textutil.py index 09917ba..8c9ba0e 100644 --- a/core/openmate_core/textutil.py +++ b/core/openmate_core/textutil.py @@ -97,11 +97,14 @@ def strip_leading_mentions(text: str) -> str: return _LEADING_MENTIONS.sub("", text or "", count=1).lstrip() -def mention_pieces(text: str, mentions: Sequence[Tuple[str, str]]) -> List[Tuple[str, str]]: +def mention_pieces(text: str, mentions: Sequence[Tuple[str, str]], skip: Sequence[Tuple[int, int]] = (), + front_end: str = " ") -> List[Tuple[str, str]]: """The text as pieces ("text", words) and ("at", user id) in order. A mention [(user id, name)] goes where the text first writes its "@name" that no other mention took and that is no longer name's start (at a place the longest - name written there wins: "@Annette" is Annette's even when Ann is @-ed too, and never Ann's + "ette"). A mention - the text does not write goes in front, in the order given, a space between them and after the last.""" + name written there wins: "@Annette" is Annette's even when Ann is @-ed too, and never Ann's + "ette"), outside the + places in skip [(start, end)] (code, a link's words: markup.no_mentions). A mention the text does not write goes + in front, in the order given, a space between them and front_end after the last (a space; a line break before a + formatted text, so its first block stays one).""" names = [n for _, n in mentions if n] spots: List[Tuple[int, int, str]] = [] # (start, end, user id) of each mention written in the text taken = set() @@ -115,7 +118,8 @@ def mention_pieces(text: str, mentions: Sequence[Tuple[str, str]]) -> List[Tuple if at < 0: break longer = any(len(n) > len(name) and text.startswith("@" + n, at) for n in names) - if not longer and not any(a < at + len(word) and at < b for a, b, _ in spots): + hidden = any(a < at + len(word) and at < b for a, b in skip) + if not longer and not hidden and not any(a < at + len(word) and at < b for a, b, _ in spots): spots.append((at, at + len(word), uid)) taken.add(uid) break @@ -126,8 +130,10 @@ def mention_pieces(text: str, mentions: Sequence[Tuple[str, str]]) -> List[Tuple if i: out.append(("text", " ")) out.append(("at", uid)) - if front and text and not text[0].isspace(): - out.append(("text", " ")) + # (a space only where the text does not start with one; a line break unless it starts with one: "@甲" before an + # indented " - 一" stays a line of its own) + if front and text and (not text[0].isspace() if front_end == " " else not text.startswith(front_end)): + out.append(("text", front_end)) pos = 0 for a, b, uid in sorted(spots): if a > pos: @@ -139,15 +145,17 @@ def mention_pieces(text: str, mentions: Sequence[Tuple[str, str]]) -> List[Tuple return out -def mention_spans(text: str, mentions: Sequence[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str, int]]]: +def mention_spans(text: str, mentions: Sequence[Tuple[str, str]], skip: Sequence[Tuple[int, int]] = (), + front_end: str = " ") -> Tuple[str, List[Tuple[str, str, int]]]: """The text as it will read once its mentions are @s (those it does not write go in front as "@name": what the confirm card shows, what is sent and what the echo of it is known by), and where each @ is in it: [(user id, - name, offset of its "@name")]. A backend builds its @s from these places and never searches the text again.""" + name, offset of its "@name")]. A backend builds its @s from these places and never searches the text again. + skip, front_end: as mention_pieces'.""" names = dict(mentions) out: List[str] = [] spans: List[Tuple[str, str, int]] = [] size = 0 - for kind, value in mention_pieces(text, mentions): + for kind, value in mention_pieces(text, mentions, skip, front_end): if kind == "at": word = "@" + (names.get(value) or value) spans.append((value, names.get(value) or value, size)) diff --git a/core/openmate_core/tools.py b/core/openmate_core/tools.py index a501c27..7b00635 100644 --- a/core/openmate_core/tools.py +++ b/core/openmate_core/tools.py @@ -14,6 +14,7 @@ from . import modelimages, views from .backend import BackendError +from . import markup from .textutil import clip, local_stamp, mention_spans, one_line from .wire import RPCError @@ -99,10 +100,30 @@ def _page_tools(app) -> dict: _USER_ID = re.compile(r"[A-Za-z0-9_.:@-]{1,64}") # what a user id looks like on any platform (the backend checks its own) +# what the send tools say of the Markdown subset (markup) where the backend can_format +FORMAT_WORDS = ("完整内容。可以用 Markdown 的这几种写法排版,发出去按%s的格式显示:**粗体**;[文字](https://链接)(只认 http/https," + "裸链接照原样发);以「- 」开头的行是无序列表,「1. 」开头的是有序列表(不支持嵌套);`行内代码`;```围栏代码块```" + "(开头的 ``` 后可写语言);「# 」开头的行显示成加粗的一行;「> 」开头的是引用;空一行另起一段。" + "别的写法(单个 *、表格、图片等)照原样发。一种都不用就按纯文本发") + + +def _text_words(app) -> str: + """The text field's description: the Markdown subset where the backend can_format, plain text else.""" + if getattr(app.backend, "can_format", False): + return FORMAT_WORDS % app.platform.name + return "完整内容(纯文本)" + + +def _rich(app, text: str, names=()) -> bool: + """Whether the text goes as formatted text: it uses the subset (markup.formatted; the names to @ are no markup) + and the backend can_format.""" + return bool(getattr(app.backend, "can_format", False)) and markup.formatted(text, names) + + def write_tools(app) -> List[dict]: c, p = app.cid, app.platform.name send = {"chat": {"type": "string", "description": "会话 id"}, - "text": {"type": "string", "description": "完整内容(纯文本)"}, + "text": {"type": "string", "description": _text_words(app)}, "reply_to": {"type": "string", "description": "要回复的消息 id,可选"}} what = "以我的身份在%s会话(私聊或群)里发一条消息,可以回复某条消息。每次都要我在手机上确认全文和发给谁。" % p if getattr(app.backend, "can_mention", False): @@ -116,7 +137,7 @@ def write_tools(app) -> List[dict]: {"name": c + "_send", "description": what, "input_schema": _obj(send, ["chat", "text"])}, {"name": c + "_send_dm", "description": "以我的身份私聊一个%s用户(没有私聊会话时先建一个)。每次都要我在手机上确认全文和发给谁。" % p, "input_schema": _obj({"user": {"type": "string", "description": "对方的用户 id(%s_search 给出)" % c}, - "text": {"type": "string", "description": "完整内容(纯文本)"}}, ["user", "text"])}, + "text": {"type": "string", "description": _text_words(app)}}, ["user", "text"])}, ] @@ -563,9 +584,15 @@ def _send_card(app, a: dict) -> tuple: text = _check_text(_need(a, "text", "消息内容")) reply_to = str(a.get("reply_to") or "").strip() mentions = _mentions(app, a, chat_id) + names = [n for _, n in mentions] + rich = _rich(app, text, names) spans: List[tuple] = [] if mentions: # the text as it will read: one not written goes in front (the card, the send and its echo agree) - text, spans = mention_spans(text, mentions) + if rich: # never an @ in code or in a link's words; those in front on a line of their own + text, spans = mention_spans(text, mentions, markup.no_mentions(markup.without_names(text, names)), + markup.FRONT_END) + else: + text, spans = mention_spans(text, mentions) text = _check_text(text) p = app.platform.name chat = app.store.get_chat(chat_id) if app.store is not None else None @@ -610,19 +637,36 @@ def _send_card(app, a: dict) -> tuple: lines.append("在这个话题群里开一个新话题") if mentions: lines.append("会 @ 并提醒:" + "、".join("%s(%s)" % (n, u) for u, n in mentions)) + if rich: + lines.append(_rich_line(app, text, [at for _, _, at in spans], names)) lines += ["——", text] - return chat_id, text, reply_to, visible, "\n".join(lines), spans + return chat_id, text, reply_to, visible, "\n".join(lines), spans, rich + + +def _rich_line(app, text: str, ats=(), names=()) -> str: + """The card's word on a formatted text: what shows formatted (the text below it is as written), and where code + stays as written (a block with an @: markup.code_as_written). names: those @-ed, never markup.""" + plain = markup.without_names(text, names) + line = "按%s富文本发送:下面的%s会按格式显示(这里是写的原文,链接的地址就是括号里的)" % ( + app.platform.name, "、".join(markup.features(plain))) + if markup.code_as_written(plain, list(ats)): + line += ";有 @ 的那一段里的行内代码按原样显示(带反引号)" + return line def _dm_card(app, a: dict) -> tuple: user = _need(a, "user", "用户 id") text = _check_text(_need(a, "text", "消息内容")) + rich = _rich(app, text) name = "" if app.store is not None: name = app.store.name(user) who = "%s(%s)" % (name, user) if name else "用户 %s" % user - summary = "以你的身份私聊 %s(%s)\n——\n%s" % (who, app.platform.name, text) - return user, text, name or user, summary + head = "以你的身份私聊 %s(%s)" % (who, app.platform.name) + if rich: + head += "\n" + _rich_line(app, text) + summary = "%s\n——\n%s" % (head, text) + return user, text, name or user, summary, rich def describe(app, params: dict) -> dict: @@ -630,10 +674,10 @@ def describe(app, params: dict) -> dict: a = _args(params) c = app.cid if name == c + "_send": - _, _, _, visible, summary, _ = _send_card(app, a) + _, _, _, visible, summary, _, _ = _send_card(app, a) return {"action": {"name": name, "visible": visible}, "summary": summary} if name == c + "_send_dm": - _, _, visible, summary = _dm_card(app, a) + _, _, visible, summary, _ = _dm_card(app, a) return {"action": {"name": name, "visible": visible}, "summary": summary} raise RPCError("没有这个写操作:%s" % name) @@ -656,7 +700,7 @@ def as_asked() -> None: if name == c + "_send": try: - chat_id, text, reply_to, visible, _, mentions = _send_card(app, a) + chat_id, text, reply_to, visible, _, mentions, rich = _send_card(app, a) root = None if reply_to: quoted = app.store.message(chat_id, reply_to) @@ -673,12 +717,12 @@ def as_asked() -> None: def send(): as_asked() - mid = app.send_as_user(chat_id, text, reply_to or None, root, mentions=mentions or None) + mid = app.send_as_user(chat_id, text, reply_to or None, root, mentions=mentions or None, rich=rich) return {"text": "已发送到%s" % visible, "message_ref": mid} return _result(app.send_once(key, name, send)) if name == c + "_send_dm": - user, text, who, _ = _dm_card(app, a) + user, text, who, _, rich = _dm_card(app, a) earlier = app.store.send_get(key) if earlier is None: # The chat first, before the request id is taken: a failure here leaves the id free for a retry. @@ -694,7 +738,7 @@ def send(): def send(): as_asked() # again: opening the chat asked the service, and the account may have changed meanwhile - mid = app.send_as_user(chat_id, text) + mid = app.send_as_user(chat_id, text, rich=rich) return {"text": "已私聊 %s" % who, "message_ref": mid} return _result(app.send_once(key, name, send)) diff --git a/extensions/openmate-feishu/openmate_feishu/larkagentx.py b/extensions/openmate-feishu/openmate_feishu/larkagentx.py index 458af7e..15f6764 100644 --- a/extensions/openmate-feishu/openmate_feishu/larkagentx.py +++ b/extensions/openmate-feishu/openmate_feishu/larkagentx.py @@ -38,6 +38,7 @@ from openmate_core.backend import (Account, Backend, BackendError, Chat, CredentialsExpired, DocMention, LoginDone, LoginQR, Media, Message, Person, SendRejected) +from openmate_core import markup from openmate_core.textutil import mention_spans, span_pieces from . import DLP_BLOCKED_TEXT, launch, pin # DLP_BLOCKED_TEXT: a blocked message's note (Message.blocked) @@ -84,9 +85,10 @@ STATUS_NORMAL, STATUS_MODIFIED = 1, 3 # entities.Message.Status: as sent, edited CODE_BLOCK_TAGS = (31, 37) # CODE_BLOCK, CODE_BLOCK_V2: their own properties, not a TextProperty # DOCS (22) included: the newer rich text's block around its paragraphs (not a document; read "[文档]" before) -BLOCK_TAGS = frozenset((3, 4, 14, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 37, 39, 40, 41, 42, 43, 44, 45, 46)) +BLOCK_TAGS = frozenset((3, 4, 14, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 37, 39, 40, 41, 42, 43, 44, 45, 46, 49)) # RichTextElement.Tag: P, FIGURE, DIV, H1-H3, UL, OL, LI, QUOTE, CODE_BLOCK, HR, CODE_BLOCK_V2, TABLE…, COLUMNS, COLUMN, -# H4-H6: blocks (a new line where one starts, in an @自己 request); B, I, U, LINK, CODE, A run on in the line +# H4-H6, MARKDOWN: blocks (a new line where one starts, in an @自己 request); B, I, U, LINK, CODE, A run on in the line +MARKDOWN_TAG = 49 # a block of Markdown the clients render (MarkdownProperty: its source in field 1) PUSH_CMD = 6 PUSH_DOC_FEED_CMD = 14004 # improto.Command.PUSH_DOC_FEED: a document's notices (comments, @-mentions…) PUSH_FEED_CARDS_CMD = 1002 # feed.PushFeedCardsRequest: feed cards changed, among them chats moved to 完成 (done) @@ -544,6 +546,200 @@ def with_mentions(pkt, text: str, mentions): return pkt +# ---------------------------------------------------------------- formatted sends (POST) +# +# A text in the Markdown subset (openmate_core.markup) goes as a POST whose rich text is the tree Feishu's web client +# sends: a DOCS root over blocks (P, UL/OL over LI, QUOTE over P), in them TEXT runs (bold: the run's fontWeight style, +# also listed in the elements' styles and styleRefs), A links and AT @s; every container's property set, empty. Code +# (a fenced block, and a block with `code` in it and no @) goes as a MARKDOWN element holding that block's Markdown: +# the server flattens an inline CODE element to plain words and the clients show a CODE_BLOCK as an empty frame. +# The shapes follow two public reverse-engineered clients, both checked against the real service: +# github.com/cv-cat/LarkAgentX larkx/proto/compose.py (commit f18c68c) and github.com/SugarMGP/LarkX AGENTS.md +# ("富文本消息", commit ab20b16); the code here is written anew. + +DOCS_TAG, P_TAG, TEXT_TAG, A_TAG, UL_TAG, OL_TAG, LI_TAG, QUOTE_TAG = 22, 3, 1, 6, 26, 27, 28, 29 +ANCHOR_CUSTOM_EDIT = 3 # AnchorProperty.Scene CUSTOM_EDIT: a link with words of its own +BOLD_STYLE = ("fontWeight", "bold") + + +class _Tree: + """A post's rich text, in plain Python (as_post makes it the protobuf): els {id: {"tag", "prop", "kids", + "bold"}}, ids numbered from 1 in the order made (as the web client numbers them); root: the DOCS element. + prop: None (a container), ("text", words), ("at", user id, name), ("a", address, words), ("md", markdown), + ("ul",), ("ol", first number).""" + + def __init__(self): + self.els: Dict[str, dict] = {} + self.root = "" + + def add(self, tag: int, prop=None, kids=(), bold: bool = False) -> str: + eid = str(len(self.els) + 1) + self.els[eid] = {"tag": tag, "prop": prop, "kids": list(kids), "bold": bool(bold)} + return eid + + def people(self) -> List[str]: + """The user ids @-ed, each once, in order.""" + return list(dict.fromkeys(el["prop"][1] for el in self.els.values() if el["tag"] == AT_TAG)) + + +def post_tree(text: str, spans) -> _Tree: + """The rich text of a formatted text (markup) whose @s are spans [(user id, name, offset of its "@name")] + (mention_spans' with markup.no_mentions skipped). ValueError when it has no words, or an @ is not in a run of + words (inside code, a link, across markup): it cannot be made as written.""" + t = _Tree() + left = sorted(spans or (), key=lambda s: s[2]) + # each @'s name is one piece wherever it is written, whatever it is made of ("Sam`ops", "**x**" are names, never + # markup): the blocks are read with the names masked (as the card and the placing read them: without_names), and + # every run of words is taken from the text itself + bs = markup.blocks(markup.without_names(text, [name for _, name, _ in left])) + used: Set[int] = set() + + def runs(line) -> List[str]: + ids: List[str] = [] + for r in line: + if r.kind == "link": + ids.append(t.add(A_TAG, ("a", r.url, r.words), bold=r.bold)) + continue + if r.kind == "code": # (a block with an @: no Markdown of it) the code's words, as written + ids.append(t.add(TEXT_TAG, ("text", "`%s`" % r.words), bold=r.bold)) + continue + if r.kind == "url": # a bare address, whole (an @ never inside it: it is left over, and refused) + ids.append(t.add(TEXT_TAG, ("text", text[r.at:r.at + len(r.words)]), bold=r.bold)) + continue + pos, end = r.at, r.at + len(r.words) + for i, (uid, name, at) in enumerate(left): + stop = at + len("@" + name) + if i in used or not (pos <= at < end): + continue + if stop > end: + raise ValueError("an @ runs across markup") + if at > pos: + ids.append(t.add(TEXT_TAG, ("text", text[pos:at]), bold=r.bold)) + ids.append(t.add(AT_TAG, ("at", uid, name))) + used.add(i) + pos = stop + if pos < end: + ids.append(t.add(TEXT_TAG, ("text", text[pos:end]), bold=r.bold)) + return ids + + blocks: List[str] = [] + for b in bs: + ats = any(b.start <= at < b.end for _, _, at in left) + if b.kind == "code" or (not ats and b.has_code()): + blocks.append(t.add(MARKDOWN_TAG, ("md", b.markdown(text)))) # (its words as written: names too) + continue + lines = b.runs(text) + if b.kind in ("paragraph", "heading"): + kids: List[str] = [] + for i, line in enumerate(lines): + if i: + kids.append(t.add(TEXT_TAG, ("text", "\n"))) + kids += runs(line) + blocks.append(t.add(P_TAG, None, kids)) + elif b.kind == "quote": + blocks.append(t.add(QUOTE_TAG, None, [t.add(P_TAG, None, runs(line)) for line in lines])) + else: + items = [t.add(LI_TAG, None, runs(line)) for line in lines] + prop = ("ol", b.number) if b.kind == "numbers" else ("ul",) + blocks.append(t.add(OL_TAG if b.kind == "numbers" else UL_TAG, prop, items)) + if len(used) != len(left): + raise ValueError("an @ is not in the words") + if not blocks: + raise ValueError("no words") + t.root = t.add(DOCS_TAG, None, blocks) + return t + + +def tree_words(t: _Tree) -> str: + """The words of a post's rich text as rich_text reads them back (the same walk: each element before its children, + a block after words starts a new line; a link reads "words address"): its echo's text, and its innerText.""" + out: List[str] = [] + gap = False + seen: Set[str] = set() + + def visit(eid: str, depth: int = 0) -> None: + nonlocal gap + if eid in seen or eid not in t.els or depth > 20: + return + seen.add(eid) + el = t.els[eid] + if el["tag"] in BLOCK_TAGS: + gap = bool(out) + p = el["prop"] + w = "" + if p and p[0] in ("text", "md"): + w = p[1] + elif p and p[0] == "at": + w = "@" + (p[2] or p[1]) + elif p and p[0] == "a": + href, words = p[1].strip(), p[2].strip() + href = href if URL_RE.match(href) else "" + w = "%s %s" % (words, href) if href and words and words != href else (href or words) + # (a container is no piece of words, nor a link or a Markdown block without any: only what rich_pieces keeps) + if p is not None and (p[0] in ("text", "at") or w.strip()): + if gap and w: + out.append("\n") + gap = False + out.append(w) + for k in el["kids"]: + visit(k, depth + 1) + + visit(t.root) + text = "".join(out) + return text if text.strip() else "" + + +def as_post(pkt, t: _Tree): + """LarkAgentX's text packet (build_send_message_packet, its place already decided: a thread, a topic, a quote) + made a POST of the rich text t, its @s listed (atUserIdList) so Feishu tells them.""" + from larkx.proto import lark_all_pb2 + + E = lark_all_pb2.entities.RichTextElement + req = lark_all_pb2.messages.PutMessageRequest() + req.ParseFromString(pkt.payload) + req.type = POST + req.content.ClearField("richText") + rich = req.content.richText + els = rich.elements + if any(el["bold"] for el in t.els.values()): + els.styles.add(name=BOLD_STYLE[0], value=BOLD_STYLE[1]) + for eid, el in t.els.items(): + e = els.dictionary[eid] + e.tag = el["tag"] + p = el["prop"] + if p is None: + prop = b"" # a container's property is set, empty (unset: the gateway refuses the packet) + elif p[0] == "text": + prop = E.TextProperty(content=p[1]).SerializeToString() + elif p[0] == "at": + prop = E.AtProperty(userId=str(p[1]), content="@" + (p[2] or p[1])).SerializeToString() + rich.atIds.append(eid) + elif p[0] == "a": + prop = E.AnchorProperty(href=p[1], content=p[2], textContent=p[2], isCustom=True, + scene=ANCHOR_CUSTOM_EDIT).SerializeToString() + rich.anchorIds.append(eid) + elif p[0] == "md": + prop = E.MarkdownProperty(content=p[1]).SerializeToString() + rich.markdownIds.append(eid) + elif p[0] == "ol": + prop = E.OLProperty(type=0, start=int(p[1])).SerializeToString() + else: + prop = E.ULProperty(type=0).SerializeToString() + e.property = prop + e.childIds.extend(el["kids"]) + if el["bold"]: + e.style[BOLD_STYLE[0]] = BOLD_STYLE[1] + els.styleRefs[BOLD_STYLE[0]].styleIds.append(0) + rich.elementIds.append(t.root) + rich.innerText = tree_words(t) or " " # (set: the gateway refuses a rich text without it) + rich.version = 1 + del req.atUserIdList[:] + for uid in t.people(): + req.atUserIdList.append(int(uid)) + pkt.payload = req.SerializeToString() + return pkt + + def done_cards(cards, box=None, only: Optional[Set[str]] = None) -> Dict[str, float]: """{chat id: when it last changed (seconds, 0 when unknown)} of the chats' feed cards in 完成: by each card's feedType, else the push's own (box). Other cards (a thread's, a document's), cards on their way out and, with @@ -2402,6 +2598,7 @@ def _is_dm(self, client, chat_id: str) -> bool: #: send takes mentions: real @s, Feishu tells those people can_mention = True + can_format = True # send's rich=True: the Markdown subset as a POST (post_tree, as_post) #: chats may be thread-first (a topic group, a group in topic mode): Chat.topic says which topic_groups = True @@ -2460,10 +2657,19 @@ def _upload_image(self, client, data: bytes, mime: str) -> str: raise SendRejected("%s收下了图片,但回答里没有图片的凭据,图片没有发出" % self.region.label) return token + def formatted_words(self, text: str, mentions: list) -> str: + """Backend.formatted_words: the post's words as they read back (tree_words).""" + try: + text, spans = self._mention_list(text, mentions, True) + return tree_words(post_tree(text, spans)) + except (SendRejected, ValueError): + return "" + def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Optional[str] = None, - to_chat: bool = False, mentions: Optional[List[Tuple[str, str]]] = None, _image: str = "", - _client=None) -> str: - """Backend.send. mentions [(user id, name, offset)]: real @s (with_mentions). A group in topic mode + to_chat: bool = False, mentions: Optional[List[Tuple[str, str]]] = None, rich: bool = False, + _image: str = "", _client=None) -> str: + """Backend.send. mentions [(user id, name, offset)]: real @s (with_mentions). rich: the text in the Markdown + subset, sent as a POST (post_tree, as_post; its @s made there), placed as a text would be. A group in topic mode (topic_mode) takes a reply only into its topic, the thread way, and a new message (a topic of its own) only from a newer client: a new message it refused so goes once more that way (newer_post), and only that one. _image: an uploaded picture's cryptoToken (send_image): the message is that picture, in the same place, sent @@ -2477,10 +2683,16 @@ def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Op for v in (reply_to, root): if v and not v.isdigit(): raise SendRejected("要回复的%s消息 id 不对" % self.region.label) - text, people = self._mention_list(text, mentions) + text, people = self._mention_list(text, mentions, rich and not _image) client, _ = self._session() if client is None: raise SendRejected("还没有登录%s" % self.region.label) + tree = None + if rich and not _image: # (after the session is taken, as a text's packet is: no wider gap before it) + try: + tree = post_tree(text, people) + except ValueError: + raise SendRejected("这条消息的格式没法照写的样子发出(@ 的人要写在普通文字里,不能在代码或链接里)") if _client is not None and client is not _client: raise SendRejected("刚换了%s账号,这张图片没有发出" % self.region.label) b = self.lx.builders @@ -2493,6 +2705,8 @@ def build(root_id: str = "", thread_chat: bool = False): pkt = b.build_send_message_packet(text, chat_id, rid) if _image: return as_image(pkt, _image) + if tree is not None: + return as_post(pkt, tree) return with_mentions(pkt, text, people) if people else pkt new_in_group = False # a new message to a group (one in topic mode takes it from a newer client only) @@ -2591,9 +2805,10 @@ def _new_topic_again(self, client, chat_id: str, build) -> str: raise BackendError("%s的回答里没有消息 id,不确定是否发出" % self.region.label, "unknown") return msg_id - def _mention_list(self, text: str, mentions) -> Tuple[str, List[Tuple[str, str, int]]]: + def _mention_list(self, text: str, mentions, rich: bool = False) -> Tuple[str, List[Tuple[str, str, int]]]: """send's text and mentions checked: [(user id, name, offset)] where the text writes "@name" at offset (the - core's, mention_spans), or [(user id, name)] placed here the same way; each user id canonical, at most + core's, mention_spans), or [(user id, name)] placed here the same way (rich: a formatted text's way, none in + code or a link, those not written on a line of their own in front); each user id canonical, at most MENTIONS_MOST people (SendRejected else).""" spans: List[Tuple[str, str, int]] = [] pairs: List[Tuple[str, str]] = [] @@ -2613,7 +2828,12 @@ def _mention_list(self, text: str, mentions) -> Tuple[str, List[Tuple[str, str, if pairs: if spans: raise SendRejected("要 @ 的人不对") - text, spans = mention_spans(text, pairs) + if rich: + names = [n for _, n in pairs] + text, spans = mention_spans(text, pairs, markup.no_mentions(markup.without_names(text, names)), + markup.FRONT_END) + else: + text, spans = mention_spans(text, pairs) if len({uid for uid, _, _ in spans}) > MENTIONS_MOST: raise SendRejected("一条消息最多 @ %d 个人" % MENTIONS_MOST) return text, spans @@ -3087,6 +3307,11 @@ def visit(k: str, depth: int = 0) -> None: if words: out.append(("code", words)) continue + if tag == MARKDOWN_TAG and prop: # its Markdown as written (a bot's post, a formatted send's code) + words = next((w for n, w in wire_fields(prop) if n == 1), "") + if words.strip(): + out.append(("text", words)) + continue if tag in TEXT_TAGS and prop: try: tp = P.TextProperty() diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index 56468e1..b21685e 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.51", + "version": "0.11.52", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/extensions/openmate-feishu/tests/test_larkagentx.py b/extensions/openmate-feishu/tests/test_larkagentx.py index 58c2dcf..b5cff05 100644 --- a/extensions/openmate-feishu/tests/test_larkagentx.py +++ b/extensions/openmate-feishu/tests/test_larkagentx.py @@ -1072,6 +1072,131 @@ def test_create_chat(self): # ---------------------------------------------------------------- reads + def patch_posts(self): + """as_post on the fake packet (a dict; the real one: the smoke test): the tree it would carry.""" + real = larkagentx.as_post + larkagentx.as_post = lambda pkt, tree: dict(pkt, post=tree) + self.addCleanup(setattr, larkagentx, "as_post", real) + + def test_a_formatted_text_goes_as_a_post_where_a_text_would(self): + b = self.b + self.patch_packets() + self.patch_posts() + rich = "**结论**:\n- 一\n- 二" + b.send("500", rich, rich=True) + tree = self.last()["post"] + self.assertEqual([el["tag"] for el in tree.els.values()].count(larkagentx.LI_TAG), 2) + self.assertNotIn("mentions", self.last(), "its @s are in the tree, never with_mentions'") + self.assertEqual((self.last()["root"], self.last()["reply_in_thread"]), ("", False)) + b.send("500", rich, reply_to="90", root="90", rich=True) + self.assertEqual((self.last()["root"], self.last()["reply_in_thread"], "post" in self.last()), ("90", True, True), + "into the thread, as a text") + b.send("500", rich, reply_to="85", rich=True) + self.assertEqual((self.last()["root"], self.last()["reply_in_thread"]), ("85", False), "a quote, as a text") + b.send("502", rich, reply_to="60", root="60", rich=True) + self.assertEqual((self.last()["root"], self.last()["reply_in_thread"]), ("60", False), "a topic group's own way") + b.send("500", "**粗** @张三 看", mentions=[("7001", "张三", 6)], rich=True) + ats = [el["prop"] for el in self.last()["post"].els.values() if el["tag"] == larkagentx.AT_TAG] + self.assertEqual(ats, [("at", "7001", "张三")], "the @ at its place") + self.assertEqual(self.last()["post"].people(), ["7001"]) + b.send("500", "看 `x` 一下", mentions=[("7001", "张三")], rich=True) + tree = self.last()["post"] + self.assertEqual([el["prop"] for el in tree.els.values() if el["tag"] == larkagentx.AT_TAG][0][1], "7001", + "named only: placed here the formatted way, in front") + b.send("500", "普通 @张三", mentions=[("7001", "张三", 3)]) + self.assertNotIn("post", self.last(), "not formatted: a text, as before") + self.assertEqual(self.last()["mentions"], [("7001", "张三", 3)]) + S.post_answers = [self.refused(), self.as_sent] # a group in topic mode: the retry is a post too + S.chats["514"] = {"id": "514", "type": 2, "chatMode": 1} + b.send("514", rich, rich=True) + first, again = S.posts[-2], S.posts[-1] + self.assertEqual(("post" in first, "post" in again, again["newer"]), + (True, True, {"x-command-version": larkagentx.NEWER_COMMAND_VERSION})) + + def test_a_formatted_text_that_cannot_be_made_is_surely_not_sent(self): + b = self.b + self.patch_posts() + n = len(S.posts) + with self.assertRaises(SendRejected) as e: # an @ placed in code: never there, never anywhere else + b.send("500", "`@张三`", mentions=[("7001", "张三", 1)], rich=True) + self.assertIn("@", e.exception.message) + self.assertEqual(len(S.posts), n, "nothing posted") + + def test_formatted_words_are_what_reads_back(self): + b = self.b + self.assertEqual(b.formatted_words("**粗** [文档](https://example.com/d)\n- 一", []), + "粗 文档 https://example.com/d\n一") + self.assertEqual(b.formatted_words("看 **这里**", [("7001", "张三")]), "@张三\n看 这里", "front: a line of its own") + + +class PostTreeTest(unittest.TestCase): + """The formatted send's rich text, in plain Python (post_tree, tree_words); its protobuf: the smoke test.""" + + def tree(self, text, spans=()): + t = larkagentx.post_tree(text, list(spans)) + return t, {eid: (el["tag"], el["prop"], el["kids"], el["bold"]) for eid, el in t.els.items()} + + def test_blocks_runs_and_ids(self): + t, els = self.tree("先看 **结论** 和 [文档](https://example.com/x)\n第二行\n\n1. 甲\n2. 乙\n\n> 引用") + root = els[t.root] + self.assertEqual(root[0], larkagentx.DOCS_TAG) + self.assertEqual([els[k][0] for k in root[2]], [larkagentx.P_TAG, larkagentx.OL_TAG, larkagentx.QUOTE_TAG]) + para = [els[k] for k in els[root[2][0]][2]] + self.assertEqual([(tag, prop, bold) for tag, prop, _, bold in para], [ + (1, ("text", "先看 "), False), (1, ("text", "结论"), True), (1, ("text", " 和 "), False), + (6, ("a", "https://example.com/x", "文档"), False), (1, ("text", "\n"), False), (1, ("text", "第二行"), False)]) + self.assertEqual(els[root[2][1]][1], ("ol", 1)) + self.assertEqual(list(t.els), [str(i) for i in range(1, len(t.els) + 1)], "numbered from 1 as made") + self.assertEqual(larkagentx.tree_words(t), "先看 结论 和 文档 https://example.com/x\n第二行\n甲\n乙\n引用") + + def test_code_goes_as_markdown_unless_its_block_has_an_at(self): + t, els = self.tree("```py\nprint(1)\n```\n- 改了 `a.py`\n- 好") + root = els[t.root] + self.assertEqual([els[k][:2] for k in root[2]], [(49, ("md", "```py\nprint(1)\n```")), + (49, ("md", "- 改了 `a.py`\n- 好"))]) + text = "@张三 改了 `a.py`" + t, els = self.tree(text, [("7001", "张三", 0)]) + para = [els[k][1] for k in els[els[t.root][2][0]][2]] + self.assertEqual(para, [("at", "7001", "张三"), ("text", " 改了 "), ("text", "`a.py`")], "the code as written") + + def test_a_name_is_one_piece_whatever_it_is_made_of(self): + text = "@Sam`ops\n\n**hello**" + t, els = self.tree(text, [("7001", "Sam`ops", 0)]) + self.assertEqual([el[1] for el in els.values() if el[0] == larkagentx.AT_TAG], [("at", "7001", "Sam`ops")]) + self.assertEqual(larkagentx.tree_words(t), "@Sam`ops\nhello") + + def test_a_name_written_twice_is_masked_both_times(self): + text = "@A`B @A`B @Ann `test`" + t, els = self.tree(text, [("1", "A`B", 0), ("2", "Ann", 10)]) + self.assertEqual([el[1] for el in els.values() if el[0] == larkagentx.AT_TAG], [("at", "1", "A`B"), ("at", "2", "Ann")]) + + def test_names_masked_for_reading_are_written_as_they_are(self): + text = "@Ann [profile](https://example.org/@Ann)\n\n跑 `@Ann` 的\n\n```\n@Ann\n```" + t, els = self.tree(text, [("1", "Ann", 0)]) + props = [el[1] for el in els.values() if el[1]] + self.assertIn(("a", "https://example.org/@Ann", "profile"), props) + self.assertIn(("md", "跑 `@Ann` 的"), props) + self.assertIn(("md", "```\n@Ann\n```"), props) + self.assertFalse(any("\x02" in str(p) for p in props)) + + def test_mentions_must_be_in_words(self): + with self.assertRaises(ValueError): # (in a bare address: never split for an @) + larkagentx.post_tree("**看** https://e.org/@张三", [("7001", "张三", 20)]) + with self.assertRaises(ValueError): + larkagentx.post_tree("[@张三](https://example.com/x)", [("7001", "张三", 1)]) + with self.assertRaises(ValueError): + larkagentx.post_tree("看看", [("7001", "张三", 9)]) + with self.assertRaises(ValueError): + larkagentx.post_tree("\n\n", []) + + def test_a_markdown_element_is_read(self): + words = "**粗** `x`".encode("utf-8") + prop = b"\x0a" + bytes([len(words)]) + words + rich = {"elementIds": ["d"], "elements": {"dictionary": { + "d": {"tag": 22, "property": b"", "childIds": ["m"]}, "m": {"tag": 49, "property": prop}}}} + self.assertEqual(larkagentx.rich_text(rich, None), "**粗** `x`", "a bot's Markdown post reads as written") + + class ReadTest(Base): def setUp(self): super().setUp() diff --git a/extensions/openmate-feishu/tests/test_smoke_larkx.py b/extensions/openmate-feishu/tests/test_smoke_larkx.py index 95c0856..ee7cf2a 100644 --- a/extensions/openmate-feishu/tests/test_smoke_larkx.py +++ b/extensions/openmate-feishu/tests/test_smoke_larkx.py @@ -177,6 +177,37 @@ out["mentions"] = [els, [rt.elements.dictionary[k].tag for k in rt.atIds], list(lr.atUserIdList), rt.innerText, pr.content.richText.innerText, larkagentx.rich_text(back, b.lx.P), lr.rootId, lr.isReplyInThread, len(set(rt.elementIds)) == len(rt.elementIds), pkt.cmd] +from openmate_core import markup +src = "**结论**:看 [文档](https://example.com/d)\n- 一项 @张三\n- 二项\n\n3. 三\n\n改 `a.py`\n\n```py\nx = 1\n```" +text, spans = mention_spans(src, [("7001", "张三"), ("7002", "李四")], markup.no_mentions(src), markup.FRONT_END) +tree = larkagentx.post_tree(text, spans) +pkt = larkagentx.as_post(b.lx.builders.build_send_message_packet(text, "900", "rid", root_id="80"), tree) +lr = LA.messages.PutMessageRequest(); lr.ParseFromString(pkt.payload) +pr = P.PutMessageRequest(); pr.ParseFromString(pkt.payload) +rt = lr.content.richText +d = rt.elements.dictionary +def shape(k): + el = d[k] + kids = [shape(c) for c in el.childIds] + if el.tag == E.TEXT: + tp = E.TextProperty(); tp.ParseFromString(el.property); return ["text", tp.content, dict(el.style)] + if el.tag == E.AT: + ap = E.AtProperty(); ap.ParseFromString(el.property); return ["at", ap.userId, ap.content] + if el.tag == E.A: + an = E.AnchorProperty(); an.ParseFromString(el.property) + return ["a", an.href, an.content, an.textContent, an.isCustom, an.scene] + if el.tag == 49: + mp = E.MarkdownProperty(); mp.ParseFromString(el.property); return ["md", mp.content] + if el.tag == E.OL: + op = E.OLProperty(); op.ParseFromString(el.property); return ["ol", op.start, kids] + return [E.Tag.Name(el.tag), el.HasField("property"), el.property.hex(), kids] +back = {"elementIds": list(rt.elementIds), "elements": {"dictionary": {k: {"tag": d[k].tag, "property": d[k].property, + "childIds": list(d[k].childIds)} for k in d}}} +out["formatted"] = [lr.type, lr.chatId, lr.rootId, lr.parentId, lr.isReplyInThread, list(lr.atUserIdList), + [shape(k) for k in rt.elementIds], [d[k].tag for k in rt.atIds], [d[k].tag for k in rt.anchorIds], + [d[k].tag for k in rt.markdownIds], [[x.name, x.value] for x in rt.elements.styles], + {k: list(v.styleIds) for k, v in rt.elements.styleRefs.items()}, rt.innerText, rt.version, + larkagentx.rich_text(back, b.lx.P), larkagentx.tree_words(tree), pr.content.richText.innerText, pkt.cmd] import types from larkx import client as lxc sent_headers = [] @@ -305,6 +336,20 @@ def test_backend_under_the_real_package(self): [["at", "7002", "@李四"], ["text", " 请 "], ["at", "7001", "@张三"], ["text", " 看"]], [5, 5], [7002, 7001], "@李四 请 @张三 看", "@李四 请 @张三 看", "@李四 请 @张三 看", "80", False, True, 5], "real @s, read back by LarkAgentX's classes and our own reader") + bold = {"fontWeight": "bold"} + words = "@李四\n结论:看 文档 https://example.com/d\n一项 @张三\n二项\n三\n改 `a.py`\n```py\nx = 1\n```" + self.assertEqual(out["formatted"], [ + 2, "900", "80", "80", True, [7002, 7001], + [["DOCS", True, "", [ + ["P", True, "", [["at", "7002", "@李四"]]], + ["P", True, "", [["text", "结论", bold], ["text", ":看 ", {}], + ["a", "https://example.com/d", "文档", "文档", True, 3]]], + ["UL", True, "0800", [["LI", True, "", [["text", "一项 ", {}], ["at", "7001", "@张三"]]], + ["LI", True, "", [["text", "二项", {}]]]]], + ["ol", 3, [["LI", True, "", [["text", "三", {}]]]]], + ["md", "改 `a.py`"], ["md", "```py\nx = 1\n```"]]]], + [5, 5], [6], [49, 49], [["fontWeight", "bold"]], {"fontWeight": [0]}, words, 1, words, words, words, 5], + "a formatted text: a POST in the place a text would go, its tree as the web client's, read back the same") self.assertEqual(out["recall"], [9, ["id"], "101"], "the delete-message request: the message's id alone") self.assertEqual(out["newer_post"], [True, ["ok", "ok", "ok"], ["5.7.0", "8.7.11", "5.7.0"], ["3.9.32"], ["5"]], "LarkAgentX's own post, through the headered requests: a newer command version on that post only") diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index fab0437..36d5da6 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.48", + "version": "0.1.49", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.52/openmate-feishu-0.11.52.tar.gz b/packages/openmate-feishu/0.11.52/openmate-feishu-0.11.52.tar.gz new file mode 100644 index 0000000..770e9c1 Binary files /dev/null and b/packages/openmate-feishu/0.11.52/openmate-feishu-0.11.52.tar.gz differ diff --git a/packages/openmate-wechat/0.1.49/openmate-wechat-0.1.49.tar.gz b/packages/openmate-wechat/0.1.49/openmate-wechat-0.1.49.tar.gz new file mode 100644 index 0000000..31f7b5c Binary files /dev/null and b/packages/openmate-wechat/0.1.49/openmate-wechat-0.1.49.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index e2e7679..19902fa 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.51", + "version": "0.11.52", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -423,9 +423,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.51/openmate-feishu-0.11.51.tar.gz", - "sha256": "e72d92ec9648f71c9a76cab07e71b56c38b1b919fa4923f913c382ecf2b49364", - "size": 281414 + "url": "packages/openmate-feishu/0.11.52/openmate-feishu-0.11.52.tar.gz", + "sha256": "f568fbe0628af04ab0cb62979b996726eac95633aadb8b287486260f5192d522", + "size": 293822 } ] }, @@ -434,7 +434,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.48", + "version": "0.1.49", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -718,9 +718,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.48/openmate-wechat-0.1.48.tar.gz", - "sha256": "6a71674009b9dc7dcafaa1df0331d6bef70eede6a74d87ecddf51b736884825b", - "size": 247779 + "url": "packages/openmate-wechat/0.1.49/openmate-wechat-0.1.49.tar.gz", + "sha256": "b7f1db6c4cd258734503df4f4bd2c9d660bce9a6ec0e94139338283406af5182", + "size": 256891 } ] } diff --git a/tests/test_actions.py b/tests/test_actions.py index ba30bb0..031f0e2 100644 --- a/tests/test_actions.py +++ b/tests/test_actions.py @@ -421,6 +421,113 @@ def test_bad_args(self): self.assertEqual(self.h.sent(), []) +class FormattedSendTest(unittest.TestCase): + """A text in the Markdown subset goes formatted where the backend can_format; the card says so, plain is plain.""" + + def setUp(self): + self.h = Harness(self) + self.h.sign_in() + + def describe(self, name, args): + return self.h.c("actions.describe", name=CID + "_" + name, args=args)["summary"] + + def test_the_tools_say_the_subset_only_where_the_backend_formats(self): + actions = {a["name"]: a for a in self.h.c("actions.list")["tools"]} + for name in ("send", "send_dm"): + words = actions[CID + "_" + name]["input_schema"]["properties"]["text"]["description"] + for part in ("**粗体**", "[文字](https://链接)", "「- 」", "「1. 」", "`行内代码`", "```围栏代码块```", "纯文本"): + self.assertIn(part, words, name) + self.h.world.format_ok = False + actions = {a["name"]: a for a in self.h.c("actions.list")["tools"]} + self.assertEqual(actions[CID + "_send"]["input_schema"]["properties"]["text"]["description"], "完整内容(纯文本)") + + def test_a_formatted_send_card_and_send(self): + text = "**结论**:可以上线\n- 看 [文档](https://example.com/d)\n- 跑 `make test`" + args = {"chat": "chat_example_team", "text": text} + card = self.describe("send", args) + self.assertIn("富文本发送:下面的粗体、链接、列表、代码会按格式显示", card) + self.assertTrue(card.endswith("——\n" + text), "the text as written, its links' addresses in it") + self.h.c("actions.do", name=CID + "_send", args=args, request_id="req-rich") + self.assertEqual((self.h.sent()[-1]["text"], self.h.sent()[-1]["rich"]), (text, True)) + plain = {"chat": "chat_example_team", "text": "你好\n版本 1.5,2*3*4"} + self.assertNotIn("富文本", self.describe("send", plain)) + self.h.c("actions.do", name=CID + "_send", args=plain, request_id="req-plain") + self.assertEqual(self.h.sent()[-1]["rich"], False, "plain: sent as before") + + def test_a_formatted_dm(self): + args = {"user": "user_example_c", "text": "1. 先看\n2. 再改"} + card = self.describe("send_dm", args) + self.assertIn("下面的列表会按格式显示", card) + self.h.c("actions.do", name=CID + "_send_dm", args=args, request_id="req-rich-dm") + self.assertEqual((self.h.sent()[-1]["text"], self.h.sent()[-1]["rich"]), (args["text"], True)) + self.h.world.format_ok = False + self.assertNotIn("富文本", self.describe("send_dm", args)) + self.h.c("actions.do", name=CID + "_send_dm", args=dict(args, text="1. 再看"), request_id="req-plain-dm") + self.assertEqual(self.h.sent()[-1]["rich"], False, "a backend that cannot: as written, plain") + + def test_mentions_in_a_formatted_text(self): + text = "**请看**:@示例同事甲 跑一下 `@示例同事乙 的脚本`" + args = {"chat": "chat_example_team", "text": text, "at": ["user_example_a", "user_example_b"]} + card = self.describe("send", args) + self.assertTrue(card.endswith("——\n@示例同事乙\n\n" + text), "one only in code: in front, a paragraph of its own") + self.assertIn("有 @ 的那一段里的行内代码按原样显示", card, "that block's code is words: the card says so") + self.h.c("actions.do", name=CID + "_send", args=args, request_id="req-rich-at") + s = self.h.sent()[-1] + self.assertEqual((s["text"], s["rich"]), ("@示例同事乙\n\n" + text, True)) + self.assertEqual([(u, s["text"][at:at + len(n) + 1]) for u, n, at in s["mentions"]], + [("user_example_b", "@示例同事乙"), ("user_example_a", "@示例同事甲")]) + self.assertLess(s["mentions"][1][2], s["text"].index("`"), "the one written in the words, there") + + def test_code_beside_an_unwritten_at_still_shows_as_code(self): + args = {"chat": "chat_example_team", "text": "跑 `make test`", "at": ["user_example_a"]} + card = self.describe("send", args) + self.assertTrue(card.endswith("——\n@示例同事甲\n\n跑 `make test`"), card) + self.assertNotIn("按原样显示", card) + + def test_the_words_a_formatted_send_reads_back_as_are_no_request_there_only(self): + agent = self.h.app.agent + self.h.app.backend.formatted_words = lambda text, mentions: "/stop" # ("> /stop" reads back so) + seen = [] + real = self.h.app.backend.send + + def send(chat, text, *a, **kw): + # before its id: its echo (a POST) is known by its words; a typed TEXT of them is the user's + seen.append(agent._own_echo({"chat_id": chat, "id": "echo-first", "type": "POST", "text": "/stop"})) + seen.append(agent._own_echo({"chat_id": chat, "id": "typed", "type": "TEXT", "text": "/stop"})) + return real(chat, text, *a, **kw) + + self.h.app.backend.send = send + res = self.h.c("actions.do", name=CID + "_send", args={"chat": "chat_example_team", "text": "> /stop"}, + request_id="req-quoted-stop") + mid = self.h.sent()[-1]["id"] + self.assertEqual(seen, [True, False], "its echo before its id is known: no stop; the user's typed one is") + self.assertTrue(agent._own_echo({"chat_id": "chat_example_team", "id": mid, "text": "/stop"}), "by its id after") + self.assertFalse(agent._own_echo({"chat_id": "chat_example_team", "id": "later", "type": "POST", "text": "/stop"}), + "the user's own /stop there afterwards is theirs") + self.assertFalse(agent._own_echo({"chat_id": "chat_example_dm_a", "id": "x", "type": "POST", "text": "/stop"}), + "nor elsewhere") + self.assertTrue(res["text"]) + self.h.world.send_fail = "rejected" + with self.assertRaises(HubSideError): + self.h.c("actions.do", name=CID + "_send", args={"chat": "chat_example_team", "text": "> /stop"}, + request_id="req-quoted-stop-2") + self.assertFalse(agent._own_echo({"chat_id": "chat_example_team", "id": "y", "type": "POST", "text": "/stop"}), + "surely not sent: it stands for nothing") + gen = agent.own_send("chat_example_team", "/stop") # an uncertain one: pending, until another account signs in + agent.forget() + self.assertFalse(agent._own_echo({"chat_id": "chat_example_team", "id": "z", "type": "POST", "text": "/stop"})) + agent.own_send("chat_example_team", "/stop") # the next account's own, under way + agent.own_send("chat_example_team", "/stop", "late-id", gen=gen) # the one before's end, late: changes nothing + self.assertTrue(agent._own_echo({"chat_id": "chat_example_team", "id": "z2", "type": "POST", "text": "/stop"})) + self.assertFalse(agent._own_echo({"chat_id": "chat_example_team", "id": "late-id", "type": "POST", "text": "x"})) + + def test_rich_is_refused_where_the_backend_cannot(self): + from openmate_core.backend import SendRejected + self.h.world.format_ok = False + with self.assertRaises(SendRejected): + self.h.app.send_as_user("chat_example_team", "**x**", rich=True) + + class FilteredMessagesTest(unittest.TestCase): """matefeishu_messages with since / until / query: the reads the assistant used to script with lark-cli loops.""" diff --git a/tests/test_channel.py b/tests/test_channel.py index 9f1468e..3902573 100644 --- a/tests/test_channel.py +++ b/tests/test_channel.py @@ -202,6 +202,26 @@ def test_the_same_picture_twice_is_sent_twice_and_once_each_on_a_replay(self): send(h, ref="twice", text="", kind="push", images=same) self.assertEqual(len(h.world.images), 2) + def test_a_formatted_send_into_the_channel_chat_is_known_by_the_words_it_reads_back_as(self): + h = channel(self) + backend = h.app.backend + backend.formatted_words = lambda text, mentions: "结论\n一" # (Feishu's: tree_words of the post) + seen = [] + real = backend.send + + def send_and_look(chat, text, *a, **kw): + seen.append(sorted(k[1] for k in h.app.channel._outs)) # what an echo before its id would be known by + # its echo comes before its id, read the way Feishu reads a post back (not as written) + return real(chat, "结论\n一" if kw.get("rich") else text, *a, **kw) + + backend.send = send_and_look + mid = h.app.send_as_user(SOLO, "**结论**\n- 一", rich=True) + self.assertEqual(seen, [["\x00post:结论\n一"]], "its words, as a POST's (a typed TEXT of them is the user's)") + self.assertEqual(h.app.store.channel_msg(SOLO, mid)["dir"], "echo") + self.assertEqual(h.app.channel._outs, {}, "done: known by its id") + h.app.send_as_user(SOLO, "普通的话") + self.assertEqual(seen[-1], ["普通的话"], "plain: by its text, as before") + def test_a_wechat_picture_marks_nothing_but_its_id_as_before(self): w = channel(self, platform=openmate_wechat.platform(), agent_reply_header=" ") w.world.images_ok = True diff --git a/tests/test_markup.py b/tests/test_markup.py new file mode 100644 index 0000000..6239abc --- /dev/null +++ b/tests/test_markup.py @@ -0,0 +1,184 @@ +"""The Markdown subset a formatted send is written in (markup), and where its @s may go (textutil's skip).""" + +try: # first: every temporary directory of this run in one, removed at its end + import _runtmp # noqa: F401 +except ImportError: # (started by its path from elsewhere: its directory is not on the path) + pass +import unittest + +import harness # noqa: F401 (puts the core on the path) +from openmate_core import markup +from openmate_core.textutil import mention_spans + + +class FormattedTest(unittest.TestCase): + def test_what_is_formatted(self): + for text, words in (("**结论**:可以", ["粗体"]), ("看 [文档](https://example.com/d)", ["链接"]), + ("- 一\n- 二", ["列表"]), ("1. 一\n2) 二", ["列表"]), ("改 `a.py`", ["代码"]), + ("```\nx\n```", ["代码"]), ("## 进展", ["标题"]), ("> 原话", ["引用"]), + ("# **粗** 标题", ["标题"])): + self.assertEqual(markup.features(text), words, text) + for text in ("你好\n第二行", "版本 1.5 和 2*3*4", "a*b* c", "https://example.com/x 看下", "---", "#话题", + "[文字](ftp://x)", "** 不是粗体 **", "单个 ` 反引号", "", "1.不算列表", "-不算列表", ">= 80% 就行", + "![图](https://example.com/a.png)", "https://example.org/a**b**c", "看 https://e.com/**x**"): + self.assertEqual(markup.features(text), [], text) + self.assertFalse(markup.formatted(text), text) + + def test_blocks(self): + text = "第一行 **粗**\n第二行\n\n- 一\n* 二\n3. 三\n4. 四\n> 引\n>\n> 用\n# 标题\n```py\ncode\n```\n尾" + bs = markup.blocks(text) + self.assertEqual([b.kind for b in bs], ["paragraph", "bullets", "numbers", "quote", "heading", "code", "paragraph"]) + self.assertEqual([w for w, _ in bs[0].lines], ["第一行 **粗**", "第二行"]) + self.assertEqual([w for w, _ in bs[1].lines], ["一", "二"]) + self.assertEqual((bs[2].number, [w for w, _ in bs[2].lines]), (3, ["三", "四"])) + self.assertEqual([w for w, _ in bs[3].lines], ["引", "用"], "an empty quote line is no line") + self.assertEqual((bs[5]["lang"], bs[5]["body"]), ("py", "code")) + for b in bs: # every line's words where they are in the text + for words, at in b.lines: + self.assertEqual(text[at:at + len(words)], words) + self.assertTrue(0 <= b.start < b.end <= len(text)) + + def test_an_unclosed_fence_runs_to_the_end_and_a_longer_one_closes_only_with_its_kind(self): + bs = markup.blocks("````\na\n```\nb") + self.assertEqual([(b.kind, b["body"]) for b in bs], [("code", "a\n```\nb")]) + self.assertEqual(markup.blocks("~~~\nx\n~~~\n后")[0]["body"], "x") + + def test_crlf_ends_lines(self): + text = "```py\r\n@张三 = 1\r\n```\r\n- 一\r\n- 二" + bs = markup.blocks(text) + self.assertEqual([(b.kind, b.get("body")) for b in bs], [("code", "@张三 = 1"), ("bullets", None)]) + self.assertEqual([w for w, _ in bs[1].lines], ["一", "二"]) + self.assertTrue(any(a <= text.index("@张三") < b for a, b in markup.no_mentions(text))) + + def test_code_and_addresses_bind_first(self): + runs = markup.inline("**use `a** @Ann` now**") + self.assertEqual([(r.kind, r.words, r.bold) for r in runs], [("text", "use ", True), ("code", "a** @Ann", True), + ("text", " now", True)]) + text = "**see** https://example.com/@Ann/repo,@Ann" + hidden = [a for a, b in markup.no_mentions(text)] + self.assertIn(text.index("https://"), hidden) + out, spans = mention_spans(text, [("1", "Ann")], markup.no_mentions(text), markup.FRONT_END) + self.assertEqual(spans[0][2], out.rindex("@Ann"), "the one after the address, not the one in it") + self.assertEqual([(r.kind, r.words) for r in markup.inline("看 https://e.com/a**b**c 吧")], + [("text", "看 "), ("url", "https://e.com/a**b**c"), ("text", " 吧")]) + self.assertEqual([(r.kind, r.words) for r in markup.inline("![图](https://e.com/a.png) **x**")][:1], + [("text", "![图](https://e.com/a.png) ")], "an image is words, never a link") + self.assertEqual([(r.kind, r.words, r.bold) for r in markup.inline("**见 https://e.com/x**")], + [("text", "见 ", True), ("url", "https://e.com/x", True)], "the stars after it close the bold") + + def test_indents_and_numbers_kept(self): + bs = markup.blocks("**Python**\nif ready:\n run()\n\n0. 草稿\n1. 发布") + self.assertEqual([w for w, _ in bs[0].lines], ["**Python**", "if ready:", " run()"]) + self.assertEqual(bs[1].number, 0) + + def test_runs(self): + runs = markup.inline("看 **粗 `c` [链](https://e.com/a_(b))** 和 `x`", 10) + self.assertEqual([(r.kind, r.words, r.bold) for r in runs], [ + ("text", "看 ", False), ("text", "粗 ", True), ("code", "c", True), ("text", " ", True), + ("link", "链", True), ("text", " 和 ", False), ("code", "x", False)]) + self.assertEqual(runs[4].url, "https://e.com/a_(b)") + line = "看 **粗 `c` [链](https://e.com/a_(b))** 和 `x`" + for r in runs: + self.assertEqual(line[r.at - 10:r.at - 10 + len(r.words)], r.words) + + def test_markdown_of_a_block(self): + md = [b.markdown() for b in markup.blocks(" * 一 `x`\n * 二\n\n7. 七\n8. 八\n\n段 `c`\n---\n\n## 题 `t`\n\n> 引")] + self.assertEqual(md, ["- 一 `x`\n- 二", "7. 七\n8. 八", "段 `c` \n\\---", "**题 `t`**", "> 引"]) + md = [b.markdown() for b in markup.blocks( + "跑 `x` 和 *原样* a_b [链](https://e.com/a_b) https://e.com/c_d\n 缩进 >= 1\n\n# 今天 **上线** 跑 `test`")] + self.assertEqual(md, ["跑 `x` 和 \\*原样\\* a\\_b [链](https://e.com/a_b) https://e.com/c_d \n" + "\u00a0\u00a0\u00a0\u00a0缩进 \\>= 1", "**今天 上线 跑 `test`**"], + "literal words escaped, addresses as written, an indent kept, a heading bold all through") + self.assertEqual(markup.blocks("```\na ``` b\n```")[0].markdown(), "````\na ``` b\n````", + "a fence its body never closes") + + def test_no_mentions_in_code_or_links(self): + text = "@甲 `@乙` [@丙](https://e.com) **@丁**\n```\n@戊\n```" + places = markup.no_mentions(text) + hidden = [n for n in "甲乙丙丁戊" if any(a <= text.index("@" + n) < b for a, b in places)] + self.assertEqual(hidden, ["乙", "丙", "戊"]) + + +class SecondReviewTest(unittest.TestCase): + def test_addresses_end_before_sentence_marks_and_stars(self): + self.assertEqual([(r.kind, r.words, r.bold) for r in markup.inline("**See https://example.org**.")], + [("text", "See ", True), ("url", "https://example.org", True), ("text", ".", False)]) + self.assertEqual([(r.kind, r.words, r.url, r.bold) for r in markup.inline("**[docs](https://e.org/a**b)**")], + [("link", "docs", "https://e.org/a**b", True)], "a link's address is one piece") + text = "**看** https://example.org/项目/@Ann,然后 @Ann" + out, spans = mention_spans(text, [("1", "Ann")], markup.no_mentions(text), markup.FRONT_END) + self.assertEqual(spans[0][2], out.rindex("@Ann"), "Chinese words in a path are in it") + + def test_third_review(self): + for text, hidden in (("[docs](https://a.org)和https://b.org/@Ann", "https://b.org"), + ("**photo** ![pic](https://e.org/@Ann/avatar) tell @Ann", "![pic]"), + ("**look** https://e.org/\uff31\uff21/@Ann", "https://e.org")): + out, spans = mention_spans(text, [("1", "Ann")], markup.no_mentions(text), markup.FRONT_END) + self.assertTrue(out.startswith("@Ann\n\n") or spans[0][2] == out.rindex("@Ann"), text) + self.assertTrue(any(a <= text.index(hidden) < b for a, b in markup.no_mentions(text)), text) + quote = markup.blocks("> run `make`\n> ---")[0].markdown() + self.assertEqual(quote, "> run `make`\n> \\---", "a rule in a quote is words") + self.assertFalse(markup.formatted("@**Ops** thanks", ["**Ops**"]), "a name is never markup") + self.assertTrue(markup.formatted("@**Ops** **thanks**", ["**Ops**"])) + + def test_fourth_review(self): + self.assertFalse(markup.formatted("https://example.org/search?q=[guide](https://docs.example.org)"), + "a link inside a bare address is its words") + for text in ("**x** ![tile](icon.png)https://example.org/@Ann", "**x** HTTPS://example.org/@Ann"): + self.assertTrue(any(a <= text.index("@Ann") < b for a, b in markup.no_mentions(text)), text) + self.assertEqual([(r.kind, r.url) for r in markup.inline("[A](https://a.com)[B](https://b.com)[C](https://c.com)")], + [("link", "https://a.com"), ("link", "https://b.com"), ("link", "https://c.com")]) + self.assertFalse(markup.formatted("见 [文档](HTTPS://e.org/d)"), "a link's address in lower case only") + + def test_sixth_review(self): + t = "```\r\nabc\r\ndef\r\n```" + self.assertEqual(markup.blocks(t)[0].markdown(t), "```\nabc\ndef\n```") + self.assertEqual([(r.kind, r.url) for r in markup.inline("[A](https://a.org)和https://b.org/?q=[B](https://c.org)")], + [("link", "https://a.org"), ("text", ""), ("url", "https://b.org/?q=[B](https://c.org)")]) + self.assertFalse(markup.formatted('"[x](\u0004)"'), "a mark written in the text is none of the masks") + text = "**See** https://example.org/@Ann\u0004 then @Ann" + spans = mention_spans(text, [("1", "Ann")], markup.no_mentions(markup.without_names(text, ["Ann"])), + markup.FRONT_END)[1] + self.assertEqual(spans[0][2], text.rindex("@Ann"), "it ends the address as before") + name = "@A`B\n\n`@A`B`" + md = markup.blocks(markup.without_names(name, ["A`B"]))[1].markdown(name) + self.assertEqual(md, "``@A`B``", "code fenced by more backticks than are in it") + + def test_words_that_stay_words(self): + for text in ("*****", '![**map**](map.png "Map")'): + self.assertFalse(markup.formatted(text), text) + bs = markup.blocks("```\nbefore\n\t```\n@Ann\n```") + self.assertEqual([(b.kind, b["body"]) for b in bs], [("code", "before\n\t```\n@Ann")], + "a tab-indented fence closes nothing") + bs = markup.blocks("**例子**\n\n if ready:\n run()") + self.assertEqual([w for w, _ in bs[1].lines], [" if ready:", " run()"], "the first line's indent too") + + def test_markdown_escapes_only_what_it_must(self): + md = markup.blocks("1.5 ms for `run`\n1. 不是列表 `x`")[0].markdown() + self.assertEqual(md, "1.5 ms for `run`") + self.assertEqual(markup.blocks("`x` [docs](https://e.org/?q=©) a&b")[0].markdown(), + "`x` [docs](https://e.org/?q=\\©) a\\&b", "no entity is read in words or an address") + + +class CodeAsWrittenTest(unittest.TestCase): + def test_a_block_with_an_at_and_code(self): + text = "@甲\n\n跑 `make`\n\n@乙 看 `x`" + self.assertFalse(markup.code_as_written(text, [0]), "the @ in a paragraph of its own") + self.assertTrue(markup.code_as_written(text, [0, text.index("@乙")])) + + +class MentionSkipTest(unittest.TestCase): + def test_an_at_in_code_is_no_at_and_goes_in_front_on_a_line_of_its_own(self): + text = "看 `@张三` 和 @李四" + out, spans = mention_spans(text, [("1", "张三"), ("2", "李四")], markup.no_mentions(text), "\n") + self.assertEqual(out, "@张三\n看 `@张三` 和 @李四") + self.assertEqual([(u, out[at:at + len(n) + 1]) for u, n, at in spans], [("1", "@张三"), ("2", "@李四")]) + self.assertEqual(spans[1][2], out.rindex("@李四")) + self.assertEqual(mention_spans("看", [("1", "张三")])[0], "@张三 看", "as before without skip") + self.assertEqual(mention_spans(" 看", [("1", "张三")])[0], "@张三 看") + self.assertEqual(mention_spans(" - 一", [("1", "张三")], (), "\n")[0], "@张三\n - 一", "the list stays one") + self.assertEqual(mention_spans("\n- 一", [("1", "张三")], (), "\n")[0], "@张三\n- 一") + + +if __name__ == "__main__": + unittest.main()