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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 都和原来一样 |
| 历史补收 | 首次登录和每次重连后补收最近会话里漏掉的消息 |
Expand Down
50 changes: 49 additions & 1 deletion core/openmate_core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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)
Expand Down
32 changes: 26 additions & 6 deletions core/openmate_core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1617,32 +1617,52 @@ 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()
if self.link == "expired":
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 = "",
Expand Down
13 changes: 12 additions & 1 deletion core/openmate_core/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions core/openmate_core/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)]:
Expand All @@ -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), ()))
Expand Down
Loading
Loading