diff --git a/README.md b/README.md index 9c962ac..bf955e4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # OpenMate -OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/persona) 扩展,把聊天软件接进 Persona:私聊和群消息进收件箱和知识库,Persona 的助手和 Agent 可以在聊天软件里替你出面。助手以你身份主动发的每一条消息都要你先在手机上确认。有四种消息不再逐条确认,发出后会记进 Persona 的“以你身份发出的消息”记录(发出后扩展立刻退出等少数情况下,可能缺记一条):你自己发起的 `/agent` 请求的回复;你勾选的群里有人真正 @ 你时的自动代答;飞书文档评论里 @ 你时的文档代答(默认关闭,要单独打开);Persona 渠道在你指定的一个会话里的回答和问题(默认没有指定,一条都不发)。 +OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/persona) 扩展,把聊天软件接进 Persona:私聊和群消息进收件箱和知识库,Persona 的助手和 Agent 可以在聊天软件里替你出面。助手以你身份主动发的每一条消息都要你先在手机上确认。有五种消息不再逐条确认,发出后会记进 Persona 的“以你身份发出的消息”记录(发出后扩展立刻退出等少数情况下,可能缺记一条):你自己发起的 `/agent` 请求的回复;你勾选的群里有人真正 @ 你时的自动代答;飞书文档评论里 @ 你时的文档代答(默认关闭,要单独打开);Persona 渠道在你指定的一个会话里的回答和问题(默认没有指定,一条都不发);飞书 Agent 工作台在你指定的群里发的状态、回复和问题(默认关闭)。 第一个扩展是**飞书**(`openmate-feishu`)。第二个是**微信**(`openmate-wechat`,一期做 `/agent`、群里自动代答和收图片等媒体,见下文)。钉钉以后再做。 @@ -31,6 +31,7 @@ OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/person | 发送身份选项(`outbound_send`) | Persona 助手要往飞书会话发消息时,确认卡或发送人选择里多一个“以你本人身份发(飞书 · OpenMate)”的选项;还是要你在手机上选定并确认,OpenMate 才发,绝不在没确认时发出。会话按开放平台的 `oc_…` id 认:飞书在会话记录里带了这个 id,OpenMate 把它和自己的会话对上(只认你最近打开过、收到过消息的会话,认不出就显示为不可选并写明原因)。发送只用确认时那个账号,换了账号就不发;同一个请求只发一次,结果不确定时如实说不确定、不重发。要 @ 的人在这个会话的成员里按 id 或唯一的名字找,做成真 @,找不到或重名就不可选;不能 @所有人。要回到原话题里但认不出原消息时不可选(不会发成一条孤立的新消息);只是引用回复而认不出原消息时,作为新消息发并在选项上注明。不认识这项能力的旧版 Persona 会忽略它,其余功能照常 | | `/agent` | 你自己在飞书里发 `/agent …`,或者发一条真正 @ 你自己的消息(`@自己 …`,@ 后面的话就是要办的事;不以“/”开头,群里别的机器人不会当成自己的命令;设置“@自己 也交给 Agent”默认打开,可关),交给 Agent 处理并以你的身份回复到提问的地方(富文本消息:标题行之后开头写 `/agent` 也算;里面的内嵌图片最多 4 张、每张 3 MB 以内随请求一起交给 Agent 看):话题里问的回到话题;话题里勾了“也发到群里”的,回复同样回到话题、也发到群里,并引用这条请求;群聊主界面问的(包括引用回复),在主界面引用回复这条请求;私聊里是引用回复,AI 标记放在回复最后一行(话题折叠时直接显示答案;设置“AI 标记位置”可改回第一行);同一话题里接着发会进同一个会话;助手已经把活派给 Agent(建了待办、Agent 还在做)时,话题里你自己的追问直接转给那个 Agent,话题里回一句“已转给正在做这件事的 Agent”,结果照常经助手回到话题(写“问 Persona”“问助手”、任务结束了、Agent 不在了,就照旧交给助手;设置“话题里的追问直接转给干活的 Agent”可关);`/stop`、`/停止`、`/停` 可以停下。请求上的表情说明状态:🤔 处理中,✅ 做完了,❌ 失败或超时(停下就撤掉 🤔;三个表情都能在设置里换)。中途进度只占一条消息、原地更新,最终结果另发一条新回复(会提醒你),那条进度消息标成已完成。助手把活派给 Agent(建了待办)后还没给最终回复就结束了这一轮时,请求不会自动收尾:🤔 留着,这一轮最后说的话只作为进度消息显示、不当成答案;最终回复来了才标 ✅;它派出的待办都结束了(或过了 24 小时)就把 🤔 换成 ✅,不再另发消息;读不到待办时也按还没结束算。回复默认就是答给提问的人;要真正 @ 群里的人或机器人,回复工具的 `at` 只收 `matefeishu_members` 核实过的 id 和名字,正文里打的「@名字」只是普通文字。回复不经手机确认,每一条都记进 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 都和原来一样 | +| Agent 工作台 | 默认关闭。扩展设置里打开“Agent 工作台”并填“工作台话题群”(建议新建一个只有你自己的话题群,不能和“Persona 渠道会话”同一个)后,Persona 管着的每个 Agent(各台电脑上的 Claude Code、Codex 等,经 hub 的 `agents.read` 读)在群里有自己的一个话题:第一条消息原地显示状态(🟡 执行中、🟠 等你确认、🟢 待命、⚫ 已结束)、项目、分支、电脑、最近指令和更新时间;你在话题里说的话直接发给这个 Agent(`agents.control`),这一轮的回复回到话题里,长回复按字数和 UTF-8 字节切成几条,代码块跨条自动闭合续上,格式发不出时改发纯文本。另有两个默认关闭的开关:“工作台:话题里作答”把 Agent 等你回答或批准的问题发到它的话题里,回复编号、y / n 或直接写回答就是作答,在别处答了自动撤回,Persona 不让扩展替你批准的卡片会提示去 App 里处理;“工作台:指令不过模型”让 `/ls`、`/tail [行数]`(看 Agent 终端的最后几行)、`/stop` 由扩展直接回答。不用 tmux,不装 Claude Code Hook,不改任何电脑上的 `~/.claude` 或 `~/.codex`;关着时 `/agent`、自动代答、收件箱、渠道都和原来一样 | | 历史补收 | 首次登录和每次重连后补收最近会话里漏掉的消息。普通群话题里的回复(比如机器人在话题里回的卡片)不在群聊主界面里:话题推送和话题更新通知都会收;用 `matefeishu_messages` 按话题读时,会先从飞书补读这个话题最新的回复 | | 卡片 | 机器人发的卡片读成标题加正文:新版卡片(JSON 2.0)不再读成“Upgrade to the latest app version…”,按钮不算,链接只留文字(不留地址和参数),卡片里 @ 你算 @我 | @@ -118,6 +119,7 @@ OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/person - 群里自动代答:只在你勾选的群、有人真正 @ 你时回复,每群每天有上限。 - 文档代答:飞书文档评论里 @ 你时回复,默认关闭,要在设置里单独打开;它经 lark-cli 发出,发之前核对 lark-cli 登录的账号和飞书登录的账号同名(目前只能比对显示名,同名的另一个账号拦不住)。 - Persona 渠道:只发到你在设置里指定的“Persona 渠道会话”(默认没有,就一条都不发),内容是 Persona 对你在那里说的话的回答、Agent 要你回答或批准的问题和 Persona 的提示;在“设置 › 渠道”里打开“通知”“同步”后还有推送。 + - 飞书 Agent 工作台:默认关闭;打开后只发到你指定的“工作台话题群”,内容是各个 Agent 的状态(原地编辑)、你在话题里发给 Agent 的话的回复,以及(打开“话题里作答”后)Agent 等你确认的问题和(打开“指令不过模型”后)指令的结果。 ## 开发 @@ -141,7 +143,7 @@ tests/ 用假的平台后端和假的 hub 驱动完整 OpenMate is a set of open-source (MIT) [Persona](https://github.com/nwverse/persona) extensions that bridge chat apps into Persona: direct and group messages flow into the Inbox and knowledge base, and Persona's assistant and Agents can -answer in the chat app as you. Every message the assistant sends as you is confirmed on your phone first. Four kinds +answer in the chat app as you. Every message the assistant sends as you is confirmed on your phone first. Five kinds of message go out unconfirmed, and are recorded in Persona's sent-as-user ledger after they go (one can be missing when the extension exits right after sending; the connector declares `sends_as_user`): the replies to your own `/agent` requests (on Feishu also a message of yours that really @-mentions yourself, @@ -151,7 +153,9 @@ document comment that @-mentions you (through lark-cli, only while lark-cli's ac is not told apart yet); and what Persona's channel (listed under Settings › Channels) says in the one chat you name in the setting `channel_chat` (your conversation with Persona, as a bot's direct chat is): the answers to what you say there, and the questions and approvals an Agent waits on (taken back in Feishu once answered elsewhere); no chat is named by default, and then -nothing is sent. The first extension is Feishu / Lark (`openmate-feishu`, connector +nothing is sent; and, off unless you turn it on, the Feishu Agent desk (`workbench`) in the one group you name +(`workbench_chat`): one topic per Agent with its status edited in place, the answers to what you say in a topic, and +(with `workbench_asks`) the questions an Agent waits on, or (with `workbench_commands`) what `/ls`, `/tail` and `/stop` give. The first extension is Feishu / Lark (`openmate-feishu`, connector `matefeishu`); the second is WeChat (`openmate-wechat`, connector `matewechat`: phase one is `/agent`, answering real @-mentions in the groups you mark, and pictures, voice notes, videos, files and forwarded chat records fetched into local files the assistant can read, over this repository's `native/matewechat-native`, built on thisnick/agent-wechat's diff --git a/core/openmate_core/agent.py b/core/openmate_core/agent.py index 9218a85..91143a1 100644 --- a/core/openmate_core/agent.py +++ b/core/openmate_core/agent.py @@ -681,6 +681,9 @@ 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 + workbench = getattr(self.app, "workbench", None) + if workbench is not None and workbench.take(row, body, epoch): + return # a line in an Agent's topic of the Agent 工作台 (workbench.py; off unless the user turned it on) if self._echo(text) or self._own_echo(row) or not self.enabled: return if body.lower() in STOP_WORDS: diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index 2bf6376..436fd09 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -23,6 +23,7 @@ from . import views from .agent import AgentRunner from .channel import ChannelBridge +from .workbench import Workbench from .ui import UI, ChatsToday from .backend import Account, BackendError, Chat, CredentialsExpired, Message, SendRejected from .events import Changed @@ -180,6 +181,7 @@ def __init__(self, platform: Platform, timing: Optional[Timing] = None, backend_ self.changed: Optional[Changed] = None self.agent: Optional[AgentRunner] = None self.channel: Optional[ChannelBridge] = None # Persona's 渠道 (channel.py), made at the start with the agent + self.workbench: Optional[Workbench] = None # Agent 工作台 (workbench.py), off unless the user turned it on self.people: Optional[People] = None # who is a bot (made at the start, with the store) self._avatars_by: Optional[threading.Thread] = None # the round asking the service for chats' pictures self._avatars_tried: Dict[str, float] = {} # chat id → when its picture was last asked for (monotonic) @@ -355,6 +357,7 @@ def _startup(self) -> None: self.agent.enabled = False log.info("/agent and 代答 are off here (%s)", "the connector is off" if not self.connector_on else "a member hub") self.channel = ChannelBridge(self) + self.workbench = Workbench(self) self.people = People(self) self._owner = self.store.meta_get("account_id") or "" # whose this store is if self.backend is not None: @@ -372,6 +375,7 @@ def _startup(self) -> None: self._start_link(restore=True) # off: no link, nothing received or sent in the user's name self.agent.start() self.channel.start() + self.workbench.start() if self.backend is not None and getattr(self.backend, "done_marks", False): threading.Thread(target=self._done_loop, name="openmate-done", daemon=True).start() self._ui().update_badge() # the hub forgets an extension's badges when it restarts @@ -405,6 +409,8 @@ def shutdown(self) -> None: self.agent.stop() if self.channel is not None: self.channel.stop() + if self.workbench is not None: + self.workbench.stop() if self.changed is not None: self.changed.stop() if self.backend is not None: diff --git a/core/openmate_core/channel.py b/core/openmate_core/channel.py index 90cff70..7abe216 100644 --- a/core/openmate_core/channel.py +++ b/core/openmate_core/channel.py @@ -707,48 +707,59 @@ def _round(self) -> None: store.channel_ask_end(ix, ref, how) def _ended(self, a: dict, history: Dict[tuple, dict]) -> bool: - """Whether the question history says the question ended for good: its session's records since it was raised - (as the waiting list said), page after page till it is found (read once a round per session).""" - mid, sid = a["machine_id"], a["session_id"] - if not sid: - return False - since = a["raised"] or rfc3339(float(a["at"]) - 86400) - h = history.setdefault((mid, sid, since), {"statuses": {}, "cursor": ("", ""), "done": False, "failed": False}) - pages = 0 # this round's: the next round goes on from where this one stopped - while a["ix"] not in h["statuses"] and not h["done"] and not h["failed"] and pages < HISTORY_PAGES: - pages += 1 - try: - recs, cursor = self.app.hub.interaction_history(mid, sid, since, *h["cursor"]) - except HubError as e: - log.info("the question history could not be read (%s)", e.code or e.status) - h["failed"] = True - break - for r in recs: # only how one ended for good is kept: one still waiting is read again later - if str(r.get("status") or "") in FINAL: - h["statuses"].setdefault(str(r["interaction"].get("id")), str(r["status"])) - h["cursor"] = cursor - h["done"] = not cursor[0] - status = h["statuses"].get(a["ix"]) - if status is None and h["done"]: - h.update(cursor=("", ""), done=False) # read to the end without it: from the newest again next round - return status in FINAL + return ended_for_good(self.app.hub, a, history) def _take_back(self, chat: str, mid: str, epoch: int) -> str: - backend = self.app.backend - try: - backend.recall(chat, mid) - log.info("a channel question answered elsewhere was taken back") - return "recalled" - except BackendError as e: - log.info("a channel question could not be taken back (%s): marked ended instead", e.kind) - if not self.app.owns(epoch): - return "failed" + return take_back(self.app, chat, mid, epoch, "a channel question") + + +def ended_for_good(hub, a: dict, history: Dict[tuple, dict]) -> bool: + """Whether the question history says the question ended for good (the channel's, and Agent 工作台's): its + session's records since it was raised (as the waiting list said), page after page till it is found (read once a + round per session).""" + mid, sid = a["machine_id"], a["session_id"] + if not sid: + return False + since = a["raised"] or rfc3339(float(a["at"]) - 86400) + h = history.setdefault((mid, sid, since), {"statuses": {}, "cursor": ("", ""), "done": False, "failed": False}) + pages = 0 # this round's: the next round goes on from where this one stopped + while a["ix"] not in h["statuses"] and not h["done"] and not h["failed"] and pages < HISTORY_PAGES: + pages += 1 try: - backend.edit(chat, mid, self.app.agent.with_suffix(ENDED_NOTE, None, ("", ""))) - return "edited" - except BackendError as e: - log.info("a channel question could not be marked ended either (%s)", e.kind) - return "failed" + recs, cursor = hub.interaction_history(mid, sid, since, *h["cursor"]) + except HubError as e: + log.info("the question history could not be read (%s)", e.code or e.status) + h["failed"] = True + break + for r in recs: # only how one ended for good is kept: one still waiting is read again later + if str(r.get("status") or "") in FINAL: + h["statuses"].setdefault(str(r["interaction"].get("id")), str(r["status"])) + h["cursor"] = cursor + h["done"] = not cursor[0] + status = h["statuses"].get(a["ix"]) + if status is None and h["done"]: + h.update(cursor=("", ""), done=False) # read to the end without it: from the newest again next round + return status in FINAL + + +def take_back(app, chat: str, mid: str, epoch: int, what: str) -> str: + """A question's message answered elsewhere: taken back (Backend.recall), or edited to say it ended when that fails + (the channel's, and Agent 工作台's): "recalled", "edited" or "failed".""" + backend = app.backend + try: + backend.recall(chat, mid) + log.info("%s answered elsewhere was taken back", what) + return "recalled" + except BackendError as e: + log.info("%s could not be taken back (%s): marked ended instead", what, e.kind) + if not app.owns(epoch): + return "failed" + try: + backend.edit(chat, mid, app.agent.with_suffix(ENDED_NOTE, None, ("", ""))) + return "edited" + except BackendError as e: + log.info("%s could not be marked ended either (%s)", what, e.kind) + return "failed" _KIND_WORDS = {"IMAGE": "图片", "FILE": "文件", "AUDIO": "语音", "VOICE": "语音", "VIDEO": "视频", "MEDIA": "视频", diff --git a/core/openmate_core/hub.py b/core/openmate_core/hub.py index 24eb7b9..b26305c 100644 --- a/core/openmate_core/hub.py +++ b/core/openmate_core/hub.py @@ -4,8 +4,11 @@ assistant.ask POST /api/v1/assistant/conversations, POST …/conversations/{id}/stop, GET /api/v1/assistant/reporters (a reporting conversation stopped at the hub) - agents.control POST /api/v1/sessions/{mid}/{sid}/messages (a conversation's, or a task's Agent's), …/interrupt + agents.control POST /api/v1/sessions/{mid}/{sid}/messages (a conversation's, or a task's Agent's), …/interrupt, + POST /api/v1/interactions/{id}/choose, …/resolve (Agent 工作台: a question answered in its topic) agents.read GET /api/v1/sessions/{mid}/{sid}/items, …/items/{item}/full, + GET /api/v1/sessions/{mid}/{sid}/screen (Agent 工作台's /tail: the Agent's terminal as text), + GET /api/v1/sessions?summary=1&roots=1&agents_only=1 (the Agents page, Agent 工作台), GET /api/v1/sessions?machine_id=&session_id= (the session's status), GET /api/v1/sessions?state=working&include_hidden=1 (placement: how many sessions each computer has working), @@ -297,6 +300,43 @@ def interaction_history(self, machine_id: str, session_id: str, since: str, befo recs = [i for i in items if isinstance(i, dict) and isinstance(i.get("interaction"), dict)] return recs, (str(doc.get("next_before") or ""), str(doc.get("next_before_id") or "")) + def agent_sessions(self, timeout: float = 10.0) -> List[dict]: + """The Agents' conversations as the Agents page lists them (agents.read): summary rows, children folded under + their parents, the hub's own assistant conversations left out.""" + v = self.request("GET", "/api/v1/sessions", query={"summary": 1, "roots": 1, "agents_only": 1, "limit": 200}, + timeout=timeout) + sessions = v.get("sessions") if isinstance(v, dict) else None + if not isinstance(sessions, list): + raise HubError(0, "Persona hub 的会话列表看不懂", NETWORK) + return [s for s in sessions if isinstance(s, dict) and s.get("session_id") and not s.get("assistant")] + + def screen(self, machine_id: str, session_id: str, lines: int, timeout: float = 15.0) -> dict: + """An Agent's terminal as plain text (agents.read; the hub refuses one opened by pane address): {text, status}.""" + doc = self.request("GET", "/api/v1/sessions/%s/%s/screen" % (_seg(machine_id), _seg(session_id)), + query={"lines": int(lines)}, timeout=timeout) + return doc if isinstance(doc, dict) else {} + + def choose(self, interaction_id: str, rev: str, option: Optional[int] = None, options: Optional[List[int]] = None, + client_id: str = "") -> dict: + """Answer a one-tap question by its options' indexes (agents.control), as a notification does: rev binds the + indexes to the question as it was shown (409 ask_changed when it changed, 409 not_pending once it ended, + 400 not_choosable for one that needs the app).""" + body: Dict[str, Any] = {"rev": rev} + if options is not None: + body["options"] = list(options) + else: + body["option"] = option + if client_id: + body["client_id"] = client_id + return self.request("POST", "/api/v1/interactions/%s/choose" % _seg(interaction_id), body, timeout=30) or {} + + def resolve(self, interaction_id: str, resolution: dict) -> dict: + """Answer, approve or decline a waiting card (agents.control) with a Resolution ({allow}, {approve, feedback}, + {answers}, {option}); the hub refuses what only the user may decide in the app (only declining is let through), + and an ended card answers 410.""" + return self.request("POST", "/api/v1/interactions/%s/resolve" % _seg(interaction_id), dict(resolution), + timeout=30) or {} + def kb_chat_context(self, kb_chat_id: str) -> Optional[dict]: try: return self.request("GET", "/api/v1/kb/chats/%s/context" % _seg(kb_chat_id), timeout=15) diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index 94d9db6..055ea79 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -148,6 +148,7 @@ class Timing: channel_retry: Tuple[float, ...] = (2.0, 5.0) # waits before a line is handed to Persona again (channel.receive) channel_unseen: float = 60.0 # a question never seen waiting this long after it was sent is no longer followed channel_resolve: float = 600.0 # how long the channel chat named by its name is trusted before it is checked again + workbench_poll: float = 15.0 # Agent 工作台: how often the Agents (and what they wait on) are read avatar_ttl: float = 86400.0 # a chat's picture (has_avatars) is asked of the service again when it is this old… avatar_retry: float = 3600.0 # …or this long after asking failed… avatar_batch: int = 30 # …at most this many chats per round, in the background (an Inbox read never waits for it) diff --git a/core/openmate_core/store.py b/core/openmate_core/store.py index 9fb7ba2..3cf97c4 100644 --- a/core/openmate_core/store.py +++ b/core/openmate_core/store.py @@ -160,6 +160,44 @@ # only a backend whose chats say one writes it "CREATE TABLE IF NOT EXISTS open_ids (open_id TEXT PRIMARY KEY, chat_id TEXT NOT NULL, at REAL NOT NULL)", "CREATE INDEX IF NOT EXISTS open_ids_chat ON open_ids (chat_id)", + # Agent 工作台 (workbench.py): one topic per Agent in the user's own group (root_id: the status message it opened, + # edited in place; text and state as last shown), the questions put in those topics till they ended, the user's + # lines handed to an Agent whose answer goes back into the topic, and every message the workbench sent (its echo is + # never one of the user's). Tables of their own: an older version opening the store ignores them. + """CREATE TABLE IF NOT EXISTS wb_topics ( + chat_id TEXT NOT NULL, + machine_id TEXT NOT NULL, + session_id TEXT NOT NULL, + root_id TEXT NOT NULL DEFAULT '', + text TEXT NOT NULL DEFAULT '', + state TEXT NOT NULL DEFAULT '', + data TEXT NOT NULL DEFAULT '{}', + created REAL NOT NULL, + updated REAL NOT NULL, + PRIMARY KEY (chat_id, machine_id, session_id))""", + "CREATE INDEX IF NOT EXISTS wb_topics_root ON wb_topics (chat_id, root_id)", + """CREATE TABLE IF NOT EXISTS wb_asks ( + chat_id TEXT NOT NULL, + ix TEXT NOT NULL, + root_id TEXT NOT NULL DEFAULT '', + message_id TEXT NOT NULL DEFAULT '', + data TEXT NOT NULL DEFAULT '{}', + state TEXT NOT NULL DEFAULT 'open', + at REAL NOT NULL, + ended REAL NOT NULL DEFAULT 0, + PRIMARY KEY (chat_id, ix))""", + """CREATE TABLE IF NOT EXISTS wb_turns ( + chat_id TEXT NOT NULL, + id TEXT NOT NULL, + root_id TEXT NOT NULL DEFAULT '', + machine_id TEXT NOT NULL, + session_id TEXT NOT NULL, + state TEXT NOT NULL, + data TEXT NOT NULL DEFAULT '{}', + at REAL NOT NULL, + PRIMARY KEY (chat_id, id))""", + "CREATE TABLE IF NOT EXISTS wb_msgs (chat_id TEXT NOT NULL, id TEXT NOT NULL, at REAL NOT NULL, " + "PRIMARY KEY (chat_id, id))", ] _MESSAGE_COLUMNS = ( @@ -1264,6 +1302,133 @@ def run(db): self._tx(run, count=False) + # ---- Agent 工作台 ---- + + @staticmethod + def _wb_row(r) -> dict: + out = dict(r) + try: + out["data"] = json.loads(out.get("data") or "{}") + except ValueError: + out["data"] = {} + return out + + def wb_topics(self, chat_id: str) -> Dict[Tuple[str, str], dict]: + """The workbench's topics in chat, by (machine id, session id).""" + rows = self._all("SELECT * FROM wb_topics WHERE chat_id = ?", (chat_id,)) + return {(r["machine_id"], r["session_id"]): self._wb_row(r) for r in rows} + + def wb_topic_by_root(self, chat_id: str, root_id: str) -> Optional[dict]: + if not root_id: + return None + r = self._one("SELECT * FROM wb_topics WHERE chat_id = ? AND root_id = ?", (chat_id, root_id)) + return self._wb_row(r) if r else None + + def wb_topic_put(self, row: dict, now: Optional[float] = None) -> None: + at = now or time.time() + data = json.dumps(row.get("data") or {}, ensure_ascii=False) + self._tx(lambda db: db.execute( + "INSERT INTO wb_topics (chat_id, machine_id, session_id, root_id, text, state, data, created, updated) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (chat_id, machine_id, session_id) DO UPDATE SET " + "root_id = excluded.root_id, text = excluded.text, state = excluded.state, data = excluded.data, " + "updated = excluded.updated", + (row["chat_id"], row["machine_id"], row["session_id"], row.get("root_id") or "", row.get("text") or "", + row.get("state") or "", data, float(row.get("created") or at), at)), count=False) + + def wb_ask_put(self, chat_id: str, ix: str, root_id: str, message_id: str, data: dict, + now: Optional[float] = None) -> bool: + """Follow a question put in a topic (once: False when it was followed already).""" + return self._tx(lambda db: db.execute( + "INSERT OR IGNORE INTO wb_asks (chat_id, ix, root_id, message_id, data, at) VALUES (?, ?, ?, ?, ?, ?)", + (chat_id, ix, root_id or "", message_id or "", json.dumps(data or {}, ensure_ascii=False), + now or time.time())).rowcount == 1, count=False) + + def wb_ask(self, chat_id: str, ix: str) -> Optional[dict]: + r = self._one("SELECT * FROM wb_asks WHERE chat_id = ? AND ix = ?", (chat_id, ix)) + return self._wb_row(r) if r else None + + def wb_asks_open(self, chat_id: str, root_id: Optional[str] = None) -> List[dict]: + """The questions still open in chat (in one topic), the newest first.""" + if root_id is None: + rows = self._all("SELECT * FROM wb_asks WHERE chat_id = ? AND state = 'open' ORDER BY at DESC", (chat_id,)) + else: + rows = self._all("SELECT * FROM wb_asks WHERE chat_id = ? AND root_id = ? AND state = 'open' " + "ORDER BY at DESC", (chat_id, root_id)) + return [self._wb_row(r) for r in rows] + + def wb_ask_end(self, chat_id: str, ix: str, state: str, now: Optional[float] = None) -> bool: + """An open question's end (False when it was no longer open).""" + return self._tx(lambda db: db.execute( + "UPDATE wb_asks SET state = ?, ended = ? WHERE chat_id = ? AND ix = ? AND state = 'open'", + (state, now or time.time(), chat_id, ix)).rowcount == 1, count=False) + + def wb_ask_reopen(self, chat_id: str, ix: str, data: dict) -> None: + """A question not taken back yet (the service away): open again, to be tried next round.""" + self._tx(lambda db: db.execute("UPDATE wb_asks SET state = 'open', ended = 0, data = ? WHERE chat_id = ? AND ix = ?", + (json.dumps(data, ensure_ascii=False), chat_id, ix)), count=False) + + def wb_restart(self) -> None: + """At the start: a question cut off while being taken back is looked at again.""" + self._tx(lambda db: db.execute("UPDATE wb_asks SET state = 'open' WHERE state = 'recalling'"), count=False) + + def wb_turn_data(self, chat_id: str, msg_id: str, data: dict) -> None: + self._tx(lambda db: db.execute("UPDATE wb_turns SET data = ? WHERE chat_id = ? AND id = ?", + (json.dumps(data, ensure_ascii=False), chat_id, msg_id)), count=False) + + def wb_ask_state(self, chat_id: str, ix: str, state: str) -> None: + """How a question taken back ended (after wb_ask_end claimed it).""" + self._tx(lambda db: db.execute("UPDATE wb_asks SET state = ? WHERE chat_id = ? AND ix = ?", (state, chat_id, ix)), + count=False) + + def wb_turn_state(self, chat_id: str, msg_id: str, state: str) -> None: + self._tx(lambda db: db.execute("UPDATE wb_turns SET state = ? WHERE chat_id = ? AND id = ?", + (state, chat_id, msg_id)), count=False) + + def wb_turn_put(self, row: dict, now: Optional[float] = None) -> bool: + """A line handed to an Agent (once: False when it was taken already).""" + return self._tx(lambda db: db.execute( + "INSERT OR IGNORE INTO wb_turns (chat_id, id, root_id, machine_id, session_id, state, data, at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + (row["chat_id"], row["id"], row.get("root_id") or "", row["machine_id"], row["session_id"], + row.get("state") or "waiting", json.dumps(row.get("data") or {}, ensure_ascii=False), + now or time.time())).rowcount == 1, count=False) + + def wb_turn(self, chat_id: str, msg_id: str) -> Optional[dict]: + r = self._one("SELECT * FROM wb_turns WHERE chat_id = ? AND id = ?", (chat_id, msg_id)) + return self._wb_row(r) if r else None + + def wb_turns_waiting(self) -> List[dict]: + """The lines whose answer is still to go into their topic: waiting for it, or being posted.""" + return [self._wb_row(r) for r in self._all( + "SELECT * FROM wb_turns WHERE state IN ('waiting', 'posting') ORDER BY at")] + + def wb_turn_set(self, chat_id: str, msg_id: str, state: str, data: Optional[dict] = None) -> bool: + """A waiting line's progress or end (False when it is no longer waiting).""" + if data is None: + return self._tx(lambda db: db.execute( + "UPDATE wb_turns SET state = ? WHERE chat_id = ? AND id = ? AND state = 'waiting'", + (state, chat_id, msg_id)).rowcount == 1, count=False) + return self._tx(lambda db: db.execute( + "UPDATE wb_turns SET state = ?, data = ? WHERE chat_id = ? AND id = ? AND state = 'waiting'", + (state, json.dumps(data, ensure_ascii=False), chat_id, msg_id)).rowcount == 1, count=False) + + def wb_msg_add(self, chat_id: str, msg_id: str, now: Optional[float] = None) -> None: + if msg_id: + self._tx(lambda db: db.execute("INSERT OR IGNORE INTO wb_msgs (chat_id, id, at) VALUES (?, ?, ?)", + (chat_id, str(msg_id), now or time.time())), count=False) + + def wb_msg_has(self, chat_id: str, msg_id: str) -> bool: + return bool(msg_id) and self._one("SELECT 1 FROM wb_msgs WHERE chat_id = ? AND id = ?", + (chat_id, str(msg_id))) is not None + + def wb_prune(self, before: float) -> None: + def run(db): + db.execute("DELETE FROM wb_msgs WHERE at < ?", (before,)) + db.execute("DELETE FROM wb_asks WHERE state != 'open' AND at < ?", (before,)) + db.execute("DELETE FROM wb_turns WHERE state NOT IN ('waiting', 'posting') AND at < ?", (before,)) + + self._tx(run, count=False) + def autoreply_chats(self) -> List[str]: return [r["chat_id"] for r in self._all("SELECT chat_id FROM autoreply ORDER BY at")] @@ -1355,7 +1520,8 @@ def run(db): runs = [r["id"] for r in db.execute("SELECT id FROM runs").fetchall()] # the groups marked for 自动代答 and who is a person were the old account's choices and knowledge for table in ("chats", "messages", "names", "runs", "seen", "autoreply", "people", "guest_quota", "gone", - "channel_msgs", "channel_asks", "avatars", "mutes", "markdown", "open_ids", "snapshots"): + "channel_msgs", "channel_asks", "avatars", "mutes", "markdown", "open_ids", "snapshots", + "wb_topics", "wb_asks", "wb_turns", "wb_msgs"): db.execute("DELETE FROM " + table) db.execute("DELETE FROM dismissed WHERE key LIKE 'chat:%'") # its chats' 处理完 (and 恢复) marks # its history marks, and its name (the next one's is written next, when it has one) diff --git a/core/openmate_core/tools.py b/core/openmate_core/tools.py index a17f2db..560a48e 100644 --- a/core/openmate_core/tools.py +++ b/core/openmate_core/tools.py @@ -235,6 +235,9 @@ def _status(app, a: dict) -> str: lines.append("本地记录:%d 个会话,%d 条消息" % (len(app.store.chats_recent(100000)), app.store.message_count())) if app.agent is not None: lines.append("/agent:" + ("已开启(前缀 %s)" % app.agent.prefix if app.agent.enabled else "没有开启")) + wb = getattr(app, "workbench", None) + if wb is not None and wb.declared(): + lines.append("Agent 工作台:" + wb.status_line()) return "\n".join(lines) diff --git a/core/openmate_core/workbench.py b/core/openmate_core/workbench.py new file mode 100644 index 0000000..d92f103 --- /dev/null +++ b/core/openmate_core/workbench.py @@ -0,0 +1,1221 @@ +"""Agent 工作台: the user's own group as a desk for every Agent Persona runs (Claude Code, Codex, … on every computer, +as the hub lists them, agents.read), one topic per Agent. Off by default (the setting 「Agent 工作台」 and the group, +「工作台话题群」); while off nothing here reads, sends or takes a line, and /agent, 自动代答, the inbox, Persona's 渠道 and +the follow-ups of a thread go on as before. + +- The topic: the first message is the Agent's status, edited in place (🟡 执行中, 🟠 等你确认, 🟢 待命, ⚫ 已结束), with its + project, branch, computer, the last thing it was asked and when it last changed. A topic is opened for an Agent that + works or waits for the user, or did anything since the desk was turned on (a few per round, so turning it on does + not flood the group); the status is edited when the state changes, else at most every EDIT_EVERY. +- The user's own lines in a topic go to that Agent (agents.control, one client_msg_id per line: sent once however + often it is tried); its answer comes back into the topic when the turn ends, cut into pieces (split_reply: by + characters and UTF-8 bytes, a code block cut in two closed and opened again), formatted and, when the service + refuses the format, as plain text. Lines in the group's main stream stay /agent's (only the commands below are + taken there). +- 「话题里作答」 (workbench_asks, off by default): a question or approval an Agent waits on (GET /api/v1/interactions) + goes into its topic; a reply there answers it: an option's number (POST …/choose, as a notification's tap, with the + question's rev), y / n for an approval or a plan (POST …/resolve: allow, approve, a reason after n), words for a + question that takes words. The hub decides what an extension may answer (only declining for cards only the user + decides); what it refuses is said in the topic. A question answered elsewhere is taken back the way Persona's 渠道 + takes its own back (channel.ended_for_good, channel.take_back). +- 「工作台指令」 (workbench_commands, off by default): /ls lists the Agents, /tail [行数] shows the Agent's terminal + (GET …/screen; its last items when the hub has no screen for it), /stop stops its turn (…/interrupt), /help; all + answered here, no model asked. Off, they are lines like any other. + +Everything is sent as the user into that one group only, once per key (the send journal), and told to the hub's +sent-as-user ledger (setting "workbench"). Only the user's own live lines are read (as /agent reads them); an echo of +what this sent, and an AI's line, never are. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import re +import threading +import time +from typing import Dict, List, Optional, Tuple + +from . import views +from .agent import STOP_WORDS, _interrupted, agent_label, match_prefix, model_label +from .agents import kind_of, last_moved, project +from .backend import BackendError, SendRejected +from .channel import ended_for_good, take_back +from .hub import HubError +from .textutil import clip, local_stamp, one_line, rfc3339 +from .ui import day_start +from .wire import RPCError + +log = logging.getLogger("openmate.workbench") + +NEW_TOPICS_MOST = 5 # topics opened in one round at most +EDIT_EVERY = 300.0 # a topic's status is edited at most this often, unless its state changed +MACHINES_EVERY = 600.0 # the computers' names are read again this often +KEEP = 7 * 86400.0 # what the workbench remembers of its messages, questions and lines +LS_MOST = 30 +TAIL_LINES = 40 +TAIL_MOST = 120 +TAIL_CHARS = 6000 +REPLY_CHARS = 6500 # one piece of an answer: at most so many characters… +REPLY_BYTES = 18000 # …and UTF-8 bytes (a message holds about 30 KB), before the AI mark and the piece number +REPLY_PIECES_MOST = 10 +POST_TRIES = 3 # rounds an answer that did not all go out is tried again in (each piece once: the send journal) +TAKE_BACK_TRIES = 5 # rounds a question answered elsewhere is tried to be taken back in +UNSURE_LOOK = 50 # an opening status whose send is not known: looked for among the group's last so many messages +ASK_TEXT_MOST = 1500 +FAIL_NOTE = "没能发给这个 Agent:%s" + +STATES = { + "needs": ("🟠", "等你确认"), + "working": ("🟡", "执行中"), + "stuck": ("🟡", "执行中(很久没有动静)"), + "idle": ("🟢", "待命"), + "ended": ("⚫", "已结束"), +} +ASK_KINDS = {"question": "要你回答", "permission": "要你批准", "plan": "计划要你确认", "screen": "终端里在等你", + "elicitation": "要你填写"} +YES = ("y", "yes", "ok", "1", "是", "好", "好的", "同意", "允许", "批准", "可以", "确认", "行") +NO = ("n", "no", "2", "否", "不", "不行", "拒绝", "不同意", "不允许", "不批准") +COMMANDS = {"/ls": "ls", "/列表": "ls", "/tail": "tail", "/屏幕": "tail", "/stop": "stop", "/停": "stop", + "/停止": "stop", "/help": "help", "/帮助": "help"} +HELP = ("Agent 工作台的指令(扩展直接处理,不经过模型):\n" + "/ls:列出各个 Agent 的状态\n" + "/tail [行数]:在某个 Agent 的话题里发,看它终端的最后几行(默认 %d 行,最多 %d 行)\n" + "/stop:在某个 Agent 的话题里发,让它停下这一轮\n" + "话题里别的话都会发给这个 Agent。") % (TAIL_LINES, TAIL_MOST) +_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$") +_DIGITS = re.compile(r"^\d+(?:\s*[,,、\s]\s*\d+)*$") + + +# ---------------------------------------------------------------- pieces of an answer + +def _fits(text: str, chars: int, most_bytes: int) -> bool: + return len(text) <= chars and len(text.encode("utf-8")) <= most_bytes + + +def _cut_line(line: str, chars: int, most_bytes: int) -> List[str]: + """A line longer than a piece, cut by characters so each part fits both budgets.""" + out, cur, used = [], [], 0 + for ch in line: + b = len(ch.encode("utf-8")) + if cur and (len(cur) + 1 > chars or used + b > most_bytes): + out.append("".join(cur)) + cur, used = [], 0 + cur.append(ch) + used += b + if cur or not out: + out.append("".join(cur)) + return out + + +def split_reply(text: str, chars: int = REPLY_CHARS, most_bytes: int = REPLY_BYTES) -> List[str]: + """text cut into pieces of at most chars characters and most_bytes UTF-8 bytes each, between lines where it can. + A piece that ends inside a fenced code block (``` or ~~~) closes it, and the next piece opens it again with the + same opening line (```python), so every piece reads as it should on its own.""" + text = (text or "").strip("\n") + if not text.strip(): + return [] + if _fits(text, chars, most_bytes): + return [text] + pieces: List[str] = [] + cur: List[str] = [] + size = [0, 0] # the current piece's characters and bytes, the newlines between its lines counted + fence: Optional[Tuple[str, str]] = None # (marker, opening line) while inside a code block + + def add(line: str) -> None: + sep = 1 if cur else 0 + cur.append(line) + size[0] += len(line) + sep + size[1] += len(line.encode("utf-8")) + sep + + def flush(reopen: bool) -> None: + body = list(cur) + if fence is not None: + body.append(fence[0]) # closed where the piece ends + if any(l.strip() and l != (fence or ("", ""))[1] for l in cur): + pieces.append("\n".join(body)) + del cur[:] + size[0] = size[1] = 0 + if fence is not None and reopen: + add(fence[1]) # and opened again at the start of the next + + for raw in text.split("\n"): + closing = (len(fence[0]) + 1) if fence is not None else 0 + reopen = (len(fence[1].encode("utf-8")) + 1) if fence is not None else 0 + room_chars, room_bytes = chars - 2 * closing - reopen - 1, most_bytes - 2 * closing - reopen - 1 + parts = [raw] if _fits(raw, room_chars, room_bytes) else _cut_line(raw, max(1, room_chars), max(4, room_bytes)) + for n, line in enumerate(parts): + if len(parts) > 1 and cur and (n > 0 or size[0] + 1 + len(line) > chars or + size[1] + 1 + len(line.encode("utf-8")) > most_bytes): + flush(reopen=True) # a line too long for a piece: each part of it a piece of its own, never rejoined + m = _FENCE.match(line) + after = fence + if fence is None and m: + after = (m.group(1), line.strip()) + elif fence is not None and m and m.group(1)[0] == fence[0][0] and len(m.group(1)) >= len(fence[0]) \ + and not m.group(2).strip(): + after = None + need_close = (len(after[0]) + 1) if after is not None else 0 # a piece still in a block after it closes it + sep = 1 if cur else 0 + over = cur and (size[0] + sep + len(line) + need_close > chars or + size[1] + sep + len(line.encode("utf-8")) + need_close > most_bytes) + if over: + if fence is not None and after is None: + flush(reopen=False) # the block's own closing line: the cut closes it already + fence = None + continue + flush(reopen=True) + add(line) + fence = after + if cur: + flush(reopen=False) + return pieces + + +# ---------------------------------------------------------------- the hub's question, as Persona words it + +def go_json(value) -> str: + """value as Go's encoding/json Marshal writes it (the hub hashes that): compact, <, > and & escaped, U+2028 and + U+2029 escaped, the rest of Unicode as it is.""" + out = json.dumps(value, ensure_ascii=False, separators=(",", ":")) + return (out.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026") + .replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")) + + +def ask_rev(question: str, labels: List[str], multi: bool) -> str: + """The rev a one-tap answer names its question by: the hub's askRev, sha256 of the JSON of the question, its + options' labels in order and whether several may be chosen, the first 12 hex digits. + From Persona (github.com/nwverse/persona, server/internal/hub/push_payload.go askRev, commit + 678adc29dc6510855760e3640e38726ebb848c15).""" + doc = go_json({"question": question, "options": list(labels), "multi_select": bool(multi)}) + return hashlib.sha256(doc.encode("utf-8")).hexdigest()[:12] + + +def _options(q: dict) -> List[dict]: + return [o for o in (q.get("options") or []) if isinstance(o, dict)] + + +def ask_view(ix: dict) -> Tuple[str, dict]: + """A waiting card as the words put in the topic, and how a reply answers it: data["how"] is "choose" (an option's + number), "text" (words), "allow" (y / n), "approve" (y / n), "dialog" (a terminal dialog's option) or "app" (only + in the app: several questions, fields to fill in, a secret, a form).""" + kind = str(ix.get("kind") or "") + lines = ["🟠 等你确认 · " + ASK_KINDS.get(kind, "等你处理")] + data: Dict[str, object] = {"kind": kind, "how": "app"} + qs = [q for q in (ix.get("questions") or []) if isinstance(q, dict)] + app_only = bool(ix.get("fields") or ix.get("secret") or ix.get("elicitation")) + if kind == "question" and len(qs) == 1 and not app_only: + q = qs[0] + words = str(q.get("question") or "").strip() + if q.get("header"): + lines.append("【%s】" % one_line(str(q["header"]), 40)) + lines.append(clip(words, ASK_TEXT_MOST)) + opts = _options(q) + if opts: + for i, o in enumerate(opts, 1): + desc = str(o.get("description") or "").strip() + lines.append("%d. %s%s" % (i, one_line(str(o.get("label") or ""), 80), + ":" + one_line(desc, 80) if desc else "")) + multi = bool(q.get("multi_select")) + lines.append("回复编号作答%s,也可以直接写你的回答。" % ("(可以多选,用逗号隔开,如 1,3)" if multi else "")) + data.update(how="choose", question=words, labels=[str(o.get("label") or "") for o in opts], multi=multi) + else: + lines.append("直接回复你的回答。") + data.update(how="text", question=words) + elif kind == "question": + for q in qs[:5]: + lines.append("· " + one_line(str(q.get("question") or ""), 120)) + lines.append("这个问题要填的不止一项,请在 Persona App 里回答。") + elif kind == "permission" and not app_only: + title = str(ix.get("tool_title") or ix.get("tool_name_title") or ix.get("tool_name") or "一个操作") + lines.append("它想:" + one_line(title, 80)) + summary = str(ix.get("summary") or "").strip() + command = "" + tin = ix.get("tool_input") + if isinstance(tin, dict): + command = str(tin.get("command") or "").strip() + summary = summary or str(tin.get("description") or "").strip() + if summary: + lines.append(clip(summary, ASK_TEXT_MOST)) + if command: + lines.append("```\n%s\n```" % clip(command, ASK_TEXT_MOST)) + if ix.get("reason"): + lines.append("原因:" + one_line(str(ix["reason"]), 200)) + lines.append("回复 y(或 1)允许,n(或 2)拒绝;拒绝时可以在 n 后面写原因。") + data.update(how="allow") + elif kind == "plan" and not app_only: + lines.append(clip(str(ix.get("plan") or ix.get("summary") or "").strip(), ASK_TEXT_MOST)) + lines.append("回复 y 批准这个计划,n 不批准;不批准时可以在 n 后面写修改意见。") + data.update(how="approve") + elif kind == "screen" and isinstance(ix.get("dialog"), dict) and not app_only: + d = ix["dialog"] + opts = _options(d) + lines.append(clip(str(d.get("question") or ix.get("summary") or "").strip(), ASK_TEXT_MOST)) + if d.get("command"): + lines.append("```\n%s\n```" % clip(str(d["command"]), ASK_TEXT_MOST)) + usable = [o for o in opts if not o.get("kind")] # an option that wants typed words is the app's + if opts and not d.get("multi") and usable: + for i, o in enumerate(opts, 1): + lines.append("%d. %s" % (i, one_line(str(o.get("label") or ""), 80))) + lines.append("回复编号选择。") + data.update(how="dialog", keys=[str(o.get("key") or "") if not o.get("kind") else "" for o in opts]) + else: + lines.append("这个要在 Persona App 里处理。") + else: + text = str(ix.get("summary") or (ix.get("elicitation") or {}).get("message") or "").strip() \ + if isinstance(ix.get("elicitation") or {}, dict) else str(ix.get("summary") or "") + if text: + lines.append(clip(text, ASK_TEXT_MOST)) + lines.append("这个要在 Persona App 里处理。") + return "\n".join(l for l in lines if l is not None), data + + +def parse_answer(text: str, data: dict) -> Optional[dict]: + """How a reply answers the question (ask_view's data): {"choose": [indexes]} or {"resolve": Resolution}; None when + it is no answer to it.""" + t = (text or "").strip() + how = data.get("how") + if not t or how == "app": + return None + first, _, rest = t.partition(" ") + word = first.strip().lower().rstrip("。.!!") + if how == "choose": + labels = list(data.get("labels") or []) + if _DIGITS.match(t): + picks = [int(x) - 1 for x in re.split(r"[,,、\s]+", t) if x] + if picks and all(0 <= p < len(labels) for p in picks) and len(set(picks)) == len(picks) and \ + (len(picks) == 1 or data.get("multi")): + return {"choose": picks} + return None + return {"resolve": {"answers": {str(data.get("question") or ""): t}}} + if how == "text": + return {"resolve": {"answers": {str(data.get("question") or ""): t}}} + if how in ("allow", "approve"): + if word in YES and not rest.strip(): + return {"resolve": {"allow": True} if how == "allow" else {"approve": True}} + if word in NO: + why = rest.strip() + if how == "allow": + return {"resolve": dict({"allow": False}, **({"message": why} if why else {}))} + return {"resolve": dict({"approve": False}, **({"feedback": why} if why else {}))} + return None + if how == "dialog" and t.isdigit(): + keys = list(data.get("keys") or []) + i = int(t) - 1 + if 0 <= i < len(keys) and keys[i]: + return {"resolve": {"option": keys[i]}} + return None + + +def answer_words(ans: dict, data: dict) -> str: + """What an answer was, in a few words (the question's message says so once it went in).""" + if "choose" in ans: + labels = list(data.get("labels") or []) + return "、".join(labels[i] for i in ans["choose"] if 0 <= i < len(labels)) + r = ans.get("resolve") or {} + if "allow" in r: + return "允许" if r["allow"] else "拒绝" + ("(%s)" % one_line(r["message"], 60) if r.get("message") else "") + if "approve" in r: + return "批准" if r["approve"] else "不批准" + ("(%s)" % one_line(r["feedback"], 60) if r.get("feedback") else "") + if "answers" in r: + return one_line(next(iter(r["answers"].values()), ""), 80) + if "option" in r: + keys = list(data.get("keys") or []) + return "选项 %d" % (keys.index(r["option"]) + 1) if r["option"] in keys else "已选择" + return "已作答" + + +# ---------------------------------------------------------------- the desk + +def state_of(s: Optional[dict], now: float, today_start: float) -> str: + if s is None: + return "ended" + k = kind_of(s, now, today_start) + if k in ("needs", "working", "stuck"): + return k + if str(s.get("state") or "") == "offline" or str(s.get("status") or "") in ("offline", "closed", "exited"): + return "ended" + return "idle" + + +class Workbench: + def __init__(self, app): + self.app = app + cfg = app.config + self.enabled = bool(cfg.get("workbench", False)) + self.setting = str(cfg.get("workbench_chat") or "").strip() + self.asks = bool(cfg.get("workbench_asks", False)) + self.commands = bool(cfg.get("workbench_commands", False)) + self._stop = threading.Event() + self._wake = threading.Event() + self._thread: Optional[threading.Thread] = None + self._round_mu = threading.Lock() + self._topic_locks: Dict[str, threading.Lock] = {} + self._mu = threading.Lock() + self._sessions: List[dict] = [] # the last read of the Agents + self._sessions_at = 0.0 + self._machines: Dict[str, str] = {} + self._machines_at = 0.0 + self._history: Dict[tuple, dict] = {} # the question history read so far (channel.ended_for_good) + self._last_prune = 0.0 + + # ---------------------------------------------------------------- which group + + def declared(self) -> bool: + """The extension offers the desk (its manifest has the setting): only Feishu's does.""" + props = ((self.app.manifest.get("configuration") or {}).get("properties") or {}) + return "workbench" in props + + def on(self) -> bool: + app = self.app + return (self.enabled and bool(self.setting) and app.connector_on and app.hub_role != "member" + and getattr(app.hub, "available", False)) + + def chat(self) -> str: + """The desk's group: the setting, when it is a chat this extension stored, the account is still in, and it is + not the 「Persona 渠道会话」 (whose every line is Persona's): "" else.""" + store = self.app.store + if not self.on() or store is None: + return "" + s = self.setting + if store.get_chat(s) is None or store.is_gone(s): + return "" + channel = getattr(self.app, "channel", None) + if channel is not None and s == getattr(channel, "setting", ""): + return "" + return s + + def status_line(self) -> str: + if not self.enabled: + return "没有开启" + if not self.setting: + return "已打开,但还没有填「工作台话题群」" + chat = self.chat() + if not chat: + channel = getattr(self.app, "channel", None) + if channel is not None and self.setting == getattr(channel, "setting", ""): + return "没有生效:「工作台话题群」和「Persona 渠道会话」是同一个会话" + if not self.on(): + return "没有生效(连接器关着、不是主 hub,或拿不到 Persona hub)" + return "没有生效:找不到「工作台话题群」这个会话(要是这个扩展收到过消息的会话)" + n = len(self.app.store.wb_topics(chat)) + return "已开启(%d 个话题;话题里作答:%s;工作台指令:%s)" % ( + n, "开" if self.asks else "关", "开" if self.commands else "关") + + # ---------------------------------------------------------------- lifecycle + + def start(self) -> None: + if not (self.enabled and self.setting): + return # off: nothing reads the hub or the group + if self.app.store is not None: + self.app.store.wb_restart() # a question cut off while it was being taken back: looked at again + self._thread = threading.Thread(target=self._loop, name="openmate-workbench", daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + self._wake.set() + th = self._thread + if th is not None and th is not threading.current_thread(): + th.join(3.0) + + def _loop(self) -> None: + first = True + while not self._stop.is_set(): + self._wake.wait(min(1.0, self.app.timing.workbench_poll) if first else self.app.timing.workbench_poll) + first = False + self._wake.clear() + if self._stop.is_set() or self.app.closing.is_set(): + return + try: + self.round() + except Exception: + if not self.app.closing.is_set(): + log.exception("Agent 工作台: a round failed") + + def _ready(self) -> bool: + app = self.app + return (app.store is not None and app.backend is not None and app.signed_in and app.link == "up" + and not app.handing_off()) + + def round(self) -> None: + """Read the Agents (and what they wait on), open and refresh their topics, follow the lines handed over.""" + with self._round_mu: + if not self._ready(): + return + chat = self.chat() + if not chat: + return + app, store = self.app, self.app.store + epoch = app.account_epoch() + now = time.time() + if now - self._last_prune > 3600: + self._last_prune = now + store.wb_prune(now - KEEP) + since_key = "workbench_since:" + chat + since = float(store.meta_get(since_key) or 0) + if not since: + since = now + store.meta_set(since_key, repr(now)) + try: + sessions = app.hub.agent_sessions() + except HubError as e: + log.info("Agent 工作台: the Agents could not be read (%s)", e.code or e.status) + return + with self._mu: + self._sessions, self._sessions_at = sessions, now + waiting: Optional[List[dict]] = None + if self.asks: + try: + waiting = app.hub.pending_interactions() + except HubError as e: + log.info("Agent 工作台: the waiting questions could not be read (%s)", e.code or e.status) + self._topics(chat, sessions, since, epoch) + if waiting is not None: + self._post_asks(chat, waiting, epoch) + self._end_asks(chat, waiting, epoch) + self._follow_turns(epoch) + + # ---------------------------------------------------------------- topics + + def _machine_name(self, mid: str) -> str: + now = time.time() + if now - self._machines_at > MACHINES_EVERY: + self._machines_at = now + try: + self._machines = {str(m["id"]): str(m.get("name") or m["id"]) for m in self.app.hub.machines()} + except HubError: + pass + return self._machines.get(mid, mid) + + def _snap(self, s: dict) -> dict: + """What the status shows of a session, kept with its topic (an Agent gone from the list still shows it).""" + return {"title": one_line(str(s.get("title") or project(s) or "Agent"), 40), "project": project(s), + "branch": str(s.get("branch") or ""), "agent": str(s.get("agent") or ""), + "model": model_label(str(s.get("model") or "")), "machine": self._machine_name(str(s.get("machine_id") or "")), + "activity": one_line(str(s.get("activity") or ""), 60), "moved": last_moved(s)} + + def render(self, state: str, snap: dict, data: dict) -> str: + emoji, word = STATES[state] + lines = ["%s %s|%s" % (emoji, word, snap.get("title") or "Agent")] + where = [b for b in ("项目 " + snap["project"] if snap.get("project") else "", + "分支 " + snap["branch"] if snap.get("branch") else "") if b] + if where: + lines.append(" · ".join(where)) + who = [] + label = agent_label(snap.get("agent") or "") + if snap.get("agent") and "🤖" not in label: + who.append(label) + if snap.get("model"): + who.append(snap["model"]) + if snap.get("machine"): + who.append("电脑 " + snap["machine"]) + if who: + lines.append(" · ".join(who)) + if state in ("working", "stuck") and snap.get("activity"): + lines.append("在做:" + snap["activity"]) + if data.get("last_cmd"): + lines.append("最近指令:" + one_line(data["last_cmd"], 80)) + moved = float(snap.get("moved") or 0) + if moved: + lines.append("更新于 " + local_stamp(moved, self.app.tz)) + lines.append("在这个话题里回复,就是发给这个 Agent。") + return "\n".join(lines) + + def _topics(self, chat: str, sessions: List[dict], since: float, epoch: int) -> None: + store = self.app.store + now = time.time() + start = day_start(self.app.tz, now) + topics = store.wb_topics(chat) + live = {(str(s.get("machine_id") or ""), str(s.get("session_id") or "")): s for s in sessions} + order = {"needs": 0, "stuck": 1, "working": 2, "idle": 3, "ended": 4} + opened = 0 + for key, s in sorted(live.items(), key=lambda kv: (order[state_of(kv[1], now, start)], -last_moved(kv[1]))): + if self._stop.is_set() or not self.app.owns(epoch): + return + row = topics.get(key) + state = state_of(s, now, start) + if row is None: + if s.get("archived") or opened >= NEW_TOPICS_MOST: + continue + if state not in ("needs", "working", "stuck") and last_moved(s) < since: + continue # quiet since before the desk was turned on: no topic of its own yet + if self._open(chat, key, s, state, epoch): + opened += 1 + continue + if not row.get("root_id"): + if (row.get("data") or {}).get("unsure"): + self._adopt(chat, row, epoch) + continue + self._refresh(chat, row, s, state, epoch) + for key, row in topics.items(): + if key not in live and row.get("root_id") and row.get("state") != "ended": + self._refresh(chat, row, None, "ended", epoch) + + def _open(self, chat: str, key: Tuple[str, str], s: dict, state: str, epoch: int) -> bool: + store = self.app.store + snap = self._snap(s) + data = {"snap": snap} + if state in ("working", "stuck", "needs"): + data["last_cmd"] = self._last_instruction(*key) + text = self.render(state, snap, data) + row = {"chat_id": chat, "machine_id": key[0], "session_id": key[1], "root_id": "", "text": text, + "state": state, "data": data} + at = time.time() + try: + res = self._deliver(chat, "workbench:topic:%s:%s:%s" % (chat, key[0], key[1]), text, epoch=epoch, + summary="Agent 工作台为一个 Agent 开了话题,以你的身份发到") + except RPCError as e: + if "不确定" not in str(e): + log.info("Agent 工作台: a topic was not opened (%s)", e.code or "error") + return False # surely not sent: opened again next round + # it may be in the group: never sent again; its echo is looked for (_adopt), else it has no topic + data["unsure"] = at + with self.app.owned(epoch) as ok: + if ok: + store.wb_topic_put(row) + log.info("Agent 工作台: whether a topic was opened is not known: looked for, not sent again") + return True + root = str(res.get("message_ref") or "") + if not root: + return False + with self.app.owned(epoch) as ok: + if not ok: + return False + store.wb_topic_put(dict(row, root_id=root)) + log.info("Agent 工作台: a topic was opened for an Agent (%s)", state) + return True + + def _adopt(self, chat: str, row: dict, epoch: int) -> None: + """A topic whose opening send is not known: its status, when the group's last messages have it as the user's + own (the send's echo), is its root from now on.""" + sent = float((row.get("data") or {}).get("unsure") or 0) + for m in self.app.store.messages_before(chat, None, UNSURE_LOOK): # the oldest first: the echo comes at once + at = float(m.get("at") or m.get("received") or 0) + if m.get("mine") and not m.get("root_id") and (m.get("text") or "").strip() == (row.get("text") or "").strip() \ + and sent - 60 <= at <= sent + 300: + with self.app.owned(epoch) as ok: + if ok and self.app.store.wb_topic_by_root(chat, m["id"]) is None: + data = dict(row.get("data") or {}) + data.pop("unsure", None) + self.app.store.wb_topic_put(dict(row, root_id=m["id"], data=data)) + self.app.store.wb_msg_add(chat, m["id"]) + log.info("Agent 工作台: a topic whose opening was not known was found in the group") + return + + def _refresh(self, chat: str, row: dict, s: Optional[dict], state: str, epoch: int) -> None: + """The topic's status edited when it reads differently: at once when the state changed, else at most every + EDIT_EVERY (a failed edit is tried again a minute later at the soonest).""" + if not row.get("root_id"): + return + old = dict(row.get("data") or {}) + data = dict(old) + was = row.get("state") or "" + if s is not None and state in ("working", "stuck", "needs") and was not in ("working", "stuck", "needs"): + cmd = self._last_instruction(row["machine_id"], row["session_id"]) + if cmd: + data["last_cmd"] = cmd + data["snap"] = self._snap(s) if s is not None else dict(old.get("snap") or {}) + text = self.render(state, data["snap"], data) + if text == row.get("text"): + return + now = time.time() + if now - float(old.get("edit_failed") or 0) < 60: + return + if state == was and now - float(old.get("edited") or row.get("created") or 0) < EDIT_EVERY: + return # the same state: at most every EDIT_EVERY + if self._edit(chat, row["root_id"], text, "Agent 工作台更新了一个 Agent 的状态", epoch): + data["edited"] = now + data.pop("edit_failed", None) + put = dict(row, text=text, state=state, data=data) + else: + put = dict(row, data=dict(old, edit_failed=now)) # the state stays as shown: tried again + with self.app.owned(epoch) as ok: + if ok: + self.app.store.wb_topic_put(put) + + def _last_instruction(self, mid: str, sid: str) -> str: + """The last thing the Agent was asked (its last line of the user's), "" when it cannot be read.""" + try: + res = self.app.hub.items(mid, sid) or {} + except HubError: + return "" + for it in reversed(res.get("items") or []): + if isinstance(it, dict) and it.get("role") == "user" and (it.get("kind") or "text") == "text" and \ + str(it.get("text") or "").strip(): + return one_line(str(it["text"]), 200) + return "" + + # ---------------------------------------------------------------- sending + + def _deliver(self, chat: str, key: str, text: str, reply_to: str = "", root: str = "", rich: bool = False, + summary: str = "", epoch: Optional[int] = None, session: Tuple[str, str] = ("", "")) -> dict: + """text into the desk's group as the user, once per key (the send journal), only while the account of epoch is + the one signed in; formatted when rich (plain when the service refuses the format); told to the ledger.""" + app = self.app + epoch = app.account_epoch() if epoch is None else epoch + owner = getattr(app, "_owner", "") + key = "%s@%s" % (key, owner) # each account's own: the journal outlives an account switch + + def go() -> dict: + if not app.owns(epoch, owner=owner): + raise RPCError("换了%s账号,这条不再以你的身份发出" % app.platform.name, "cannot_send") + if self.chat() != chat: + raise RPCError("Agent 工作台已经关了,或者换了群", "cannot_send") + try: + mid = app.send_as_user(chat, text, reply_to or None, root or None, rich=rich) + except SendRejected: + if not rich: + raise + mid = app.send_as_user(chat, text, reply_to or None, root or None) # the format refused: plain + app.store.wb_msg_add(chat, str(mid or "")) + app.record_sent(chat, text, str(mid or ""), reply_to=reply_to, root=root, setting="workbench", + session_id=session[1], machine_id=session[0], + summary=summary + views.where(app.platform.name, app.store.get_chat(chat), chat)) + return {"text": "已发送", "message_ref": mid, "chat": chat} + + return app.send_once(key, "workbench", go) + + def _edit(self, chat: str, mid: str, text: str, summary: str, epoch: int) -> bool: + app = self.app + if not app.owns(epoch) or app.backend is None: + return False + try: + app.backend.edit(chat, mid, text) + except BackendError as e: + log.info("Agent 工作台: a message was not edited (%s)", e.kind) + return False + app.record_sent(chat, text, mid, setting="workbench", + summary=summary + "(" + views.where(app.platform.name, app.store.get_chat(chat), chat) + ")") + return True + + def _note(self, chat: str, row: dict, key: str, text: str, epoch: Optional[int]) -> None: + """A short line under the user's line, in its topic.""" + root = row.get("root_id") or row.get("id") or "" + try: + self._deliver(chat, key, text, reply_to=row.get("id") or "", root=root, + summary="Agent 工作台把一句提示以你的身份发到", epoch=epoch) + except RPCError as e: + log.info("Agent 工作台: a note was not sent (%s)", e.code or "error") + + def _react(self, chat: str, mid: str, reaction: str, off: str = "", epoch: Optional[int] = None) -> None: + backend = self.app.backend + if backend is None or not self.app.owns(epoch): + return + try: + if off: + backend.unreact(chat, mid, off) + if reaction: + backend.react(chat, mid, reaction) + except BackendError as e: + log.info("Agent 工作台: a reaction was not set (%s)", e.kind) + + # ---------------------------------------------------------------- the user's lines + + def _ours(self, chat: str, row: dict) -> bool: + store = self.app.store + mid = str(row.get("id") or "") + if store.wb_msg_has(chat, mid) or store.wb_topic_by_root(chat, mid) is not None: + return True + agent = self.app.agent + return agent is not None and agent._own_echo(row, all_sends=True) + + def take(self, row: dict, body: str, epoch: Optional[int] = None) -> bool: + """A fresh line of the user's own (as /agent reads it): True when it is the desk's (an Agent's topic, or a + command in the group); False leaves it to /agent as before (also when the desk itself fails on it).""" + if not self.enabled: + return False + try: + return self._take(row, body, epoch) + except Exception: + log.exception("Agent 工作台: a line could not be looked at (left to /agent)") + return False + + def _take(self, row: dict, body: str, epoch: Optional[int]) -> bool: + chat = self.chat() + if not chat or row.get("chat_id") != chat or not self._ready(): + return False + if self._ours(chat, row): + return True + app = self.app + said = (body or row.get("text") or "").strip() + if app.agent is not None and app.agent._other_ai(said): + return True # an AI's line: never handed to an Agent + root = str(row.get("root_id") or row.get("thread_id") or "") + topic = app.store.wb_topic_by_root(chat, root) if root else None + req = match_prefix(said, app.agent.prefix) if app.agent is not None else None + text = (req if req is not None else said).strip() + name = text.split(None, 1)[0].lower() if text else "" + if topic is None: + if self.commands and COMMANDS.get(name) in ("ls", "help"): + self._spawn(self._command, chat, row, None, text, epoch) + return True + if self.commands and COMMANDS.get(name) in ("tail", "stop"): + self._spawn(self._hint, chat, row, "在某个 Agent 的话题里发 %s。" % name, epoch) + return True + return False # the group's main stream (or a topic not an Agent's): /agent's, as before + if text.lower() in STOP_WORDS and not self.commands: + return False # /stop is /agent's unless the commands are on + if self.commands and (name in COMMANDS or text.lower() in STOP_WORDS): + self._spawn(self._command, chat, row, topic, text, epoch) + return True + if self.asks and app.store.wb_asks_open(chat, topic["root_id"]): + self._spawn(self._answer, chat, row, topic, text, epoch) + return True + if not text: + self._spawn(self._hint, chat, row, "Agent 工作台现在只转发文字。", epoch) + return True + self._spawn(self._forward, chat, row, topic, text, epoch) + return True + + def _spawn(self, fn, *args) -> None: + def run(): + topic = args[2] if len(args) > 2 and isinstance(args[2], dict) else None + lock = self._lock_for(topic["root_id"] if topic else "main") + with lock: # one line of a topic at a time, in the order they came + try: + fn(*args) + except Exception: + if not self.app.closing.is_set(): + log.exception("Agent 工作台: a line could not be handled") + + threading.Thread(target=run, name="openmate-workbench-line", daemon=True).start() + + def _lock_for(self, key: str) -> threading.Lock: + with self._mu: + lk = self._topic_locks.get(key) + if lk is None: + lk = self._topic_locks[key] = threading.Lock() + return lk + + def _still(self, epoch: Optional[int]) -> bool: + """Right before the hub is asked to act on a line: it is still the account's that heard it (another account's + sign-in since: nothing of the one before is done).""" + if self.app.owns(epoch): + return True + log.info("Agent 工作台: a line of the account signed in before was not acted on") + return False + + def _hint(self, chat: str, row: dict, text: str, epoch: Optional[int]) -> None: + self._note(chat, row, "workbench:hint:%s:%s" % (chat, row["id"]), text, epoch) + + # ---------------------------------------------------------------- handing a line to its Agent + + def _forward(self, chat: str, row: dict, topic: dict, text: str, epoch: Optional[int]) -> None: + app, store, hub = self.app, self.app.store, self.app.hub + mid, sid = topic["machine_id"], topic["session_id"] + after = app.agent._latest_seq(mid, sid) if app.agent is not None else 0 + cmid = "openmate-wb-" + hashlib.sha256(("%s:%s" % (chat, row["id"])).encode("utf-8")).hexdigest()[:24] + with app.owned(epoch) as ok: + if not ok or not store.wb_turn_put({"chat_id": chat, "id": row["id"], "root_id": topic["root_id"], + "machine_id": mid, "session_id": sid, "state": "waiting", + "data": {"text": text, "seq": after, "cmid": cmid}}): + return # another account's by now, or taken already (delivered again) + agent = app.agent + ack = agent.ack if agent is not None else "" + self._react(chat, row["id"], ack, epoch=epoch) + deadline = time.time() + app.timing.agent_hub_wait + while True: + if not self._still(epoch): + store.wb_turn_set(chat, row["id"], "gone") + return + try: + hub.send_message(mid, sid, text, cmid) + break + except HubError as e: + if e.code == "peer_held": + break # in, held at its computer till something there is answered + refused = not e.unsent and not e.unreachable and 400 <= e.status < 500 and e.status not in (408, 429) + if refused or time.time() >= deadline: + store.wb_turn_set(chat, row["id"], "failed") + self._react(chat, row["id"], agent.fail_reaction if agent is not None else "", off=ack, epoch=epoch) + why = e.message or "hub 拒绝了" + if not refused and not e.unsent: + why += "(可能已经发到了,请在 Persona 里看一下)" + self._note(chat, row, "workbench:fail:%s:%s" % (chat, row["id"]), FAIL_NOTE % why, epoch) + return + # the same client_msg_id again: the hub takes each once + if self._stop.wait(min(app.timing.agent_hub_probe, max(0.0, deadline - time.time()))): + return + with app.owned(epoch) as ok: + if ok: + cur = store.wb_topics(chat).get((mid, sid)) + if cur is not None: + data = dict(cur.get("data") or {}, last_cmd=one_line(text, 200)) + store.wb_topic_put(dict(cur, data=data)) + log.info("Agent 工作台: a line was handed to its Agent") + self._wake.set() + + def _follow_turns(self, epoch: int) -> None: + for t in self.app.store.wb_turns_waiting(): + if self._stop.is_set() or not self.app.owns(epoch): + return + try: + if t["state"] == "posting": + self._finish(t, epoch) # its answer did not all go out (or a restart cut it off): again + else: + self._follow(t, epoch) + except HubError as e: + log.info("Agent 工作台: an Agent's answer could not be read (%s)", e.code or e.status) + + def _follow(self, t: dict, epoch: int) -> None: + app, store, hub = self.app, self.app.store, self.app.hub + chat, mid, sid = t["chat_id"], t["machine_id"], t["session_id"] + data = dict(t.get("data") or {}) + agent = app.agent + if time.time() - float(t["at"]) > app.timing.agent_timeout: + if store.wb_turn_set(chat, t["id"], "gone"): + self._react(chat, t["id"], agent.fail_reaction if agent is not None else "", + off=agent.ack if agent is not None else "", epoch=epoch) + return + after = int(data.get("seq") or 0) + items: List[dict] = [] + for _ in range(20): + res = hub.items(mid, sid, after_seq=after) or {} + page = [it for it in (res.get("items") or []) if isinstance(it, dict)] + items += page + if page: + after = max(after, max(int(it.get("seq") or 0) for it in page)) + if not page or not res.get("more_after"): + break + ours, last = bool(data.get("ours")), data.get("last") + ended = interrupted = False + for it in items: + if not ours: + if it.get("client_msg_id") == data.get("cmid") or ( + it.get("role") == "user" and str(it.get("text") or "").strip() == data.get("text")): + ours = True + continue + kind, role = it.get("kind") or "", it.get("role") or "" + if role == "assistant" and kind == "text" and str(it.get("text") or "").strip(): + last = {"id": it.get("id") or "", "text": it.get("text") or "", "full": int(it.get("full_size") or 0)} + elif kind == "turn_duration" or it.get("turn_duration"): + ended = True + elif kind == "notice" and _interrupted(str(it.get("text") or "")): + interrupted = True + if items: + data.update(seq=after, ours=ours, last=last, quiet=time.time()) + with app.owned(epoch) as ok: + if not ok or not store.wb_turn_set(chat, t["id"], "waiting", data): + return + elif ours and last and time.time() - float(data.get("quiet") or t["at"]) >= app.timing.agent_settle: + try: + srow = hub.session_row(mid, sid) or {} + except HubError: + srow = {} + ended = srow.get("status") in ("done", "idle") or srow.get("state") in ("unread", "idle") + if not (ended or interrupted): + return + data.update(interrupted=interrupted and not last) + if not store.wb_turn_set(chat, t["id"], "posting", data): + return # claimed once: its answer goes out once (each piece once more by the send journal) + self._finish(dict(t, state="posting", data=data), epoch) + + def _finish(self, t: dict, epoch: int) -> None: + """A turn ended: its answer into the topic (the pieces not yet out; each goes once by the send journal), then + the done mark. One that did not all go out is tried again the next rounds, POST_TRIES at most.""" + store, agent, chat = self.app.store, self.app.agent, t["chat_id"] + data = dict(t.get("data") or {}) + row = {"id": t["id"], "root_id": t["root_id"]} + if data.get("interrupted"): + self._note(chat, row, "workbench:stopped:%s:%s" % (chat, t["id"]), "这一轮被停下了。", epoch) + whole = True + else: + whole = self._post_answer(chat, t, data.get("last"), epoch) + if not whole: + tries = int(data.get("post_tries") or 0) + 1 + if tries < POST_TRIES: + store.wb_turn_data(chat, t["id"], dict(data, post_tries=tries)) + return + store.wb_turn_state(chat, t["id"], "failed") + self._react(chat, t["id"], agent.fail_reaction if agent is not None else "", + off=agent.ack if agent is not None else "", epoch=epoch) + return + store.wb_turn_state(chat, t["id"], "posted") + self._react(chat, t["id"], agent.done_reaction if agent is not None else "", + off=agent.ack if agent is not None else "", epoch=epoch) + + def _post_answer(self, chat: str, t: dict, last: Optional[dict], epoch: int) -> bool: + app, hub = self.app, self.app.hub + mid, sid = t["machine_id"], t["session_id"] + text = str((last or {}).get("text") or "") + if last and int(last.get("full") or 0) > len(text) and last.get("id"): + try: + text = str((hub.item_full(mid, sid, last["id"]) or {}).get("text") or text) + except HubError: + pass + if not text.strip(): + text = "(这一轮没有文字回复)" + model = effort = kind = "" + for s in self._sessions: + if s.get("machine_id") == mid and s.get("session_id") == sid: + model, effort, kind = str(s.get("model") or ""), str(s.get("effort") or ""), str(s.get("agent") or "") + agent = app.agent + margin_chars, margin_bytes = 300, 900 # the AI mark and the piece number go on top of a piece + pieces = split_reply(agent._clean_answer(text, None, (model, effort)) if agent is not None else text, + REPLY_CHARS - margin_chars, REPLY_BYTES - margin_bytes) + if len(pieces) > REPLY_PIECES_MOST: + rest = sum(len(p) for p in pieces[REPLY_PIECES_MOST - 1:]) + pieces = pieces[:REPLY_PIECES_MOST - 1] + ["……后面还有约 %d 字,请在 Persona App 里看全文。" % rest] + n = len(pieces) + for i, piece in enumerate(pieces): + body = piece + ("\n\n(%d/%d)" % (i + 1, n) if n > 1 else "") + if agent is not None: + body = agent.with_suffix(body, {"agent": kind}, (model, effort)) + try: + self._deliver(chat, "workbench:answer:%s:%s:%d" % (chat, t["id"], i), body, reply_to=t["root_id"], + root=t["root_id"], rich=True, summary="Agent 工作台把 Agent 的回复以你的身份发到", + epoch=epoch, session=(mid, sid)) + except RPCError as e: + log.info("Agent 工作台: a piece of an answer was not sent (%s)", e.code or "error") + return False + return True + + # ---------------------------------------------------------------- questions + + def _post_asks(self, chat: str, waiting: List[dict], epoch: int) -> None: + store = self.app.store + topics = store.wb_topics(chat) + for ix in waiting: + if self._stop.is_set() or not self.app.owns(epoch): + return + key = (str(ix.get("machine_id") or ""), str(ix.get("session_id") or "")) + topic = topics.get(key) + iid = str(ix.get("id") or "") + if topic is None or not topic.get("root_id") or not iid or store.wb_ask(chat, iid) is not None: + continue # its topic opens first (the next round puts it there) + text, data = ask_view(ix) + data.update(raised=str(ix.get("created_at") or ""), machine_id=key[0], session_id=key[1]) + try: + res = self._deliver(chat, "workbench:ask:%s:%s" % (chat, iid), text, reply_to=topic["root_id"], + root=topic["root_id"], rich=True, epoch=epoch, session=key, + summary="Agent 工作台把 Agent 等你确认的问题以你的身份发到") + except RPCError as e: + log.info("Agent 工作台: a question was not put in its topic (%s)", e.code or "error") + continue + with self.app.owned(epoch) as ok: + if ok: + store.wb_ask_put(chat, iid, topic["root_id"], str(res.get("message_ref") or ""), data) + + def _end_asks(self, chat: str, waiting: List[dict], epoch: int) -> None: + """A question no longer waiting, that its history says ended for good, and not answered here: taken back.""" + store = self.app.store + now_waiting = {str(i.get("id") or "") for i in waiting} + open_ = store.wb_asks_open(chat) + wanted = set() + for h in self._history.values(): + h["failed"] = False # read again (from where it stopped) this round + for a in open_: + if a["ix"] in now_waiting: + continue + d = a.get("data") or {} + view = {"ix": a["ix"], "machine_id": d.get("machine_id") or "", "session_id": d.get("session_id") or "", + "raised": d.get("raised") or "", "at": a["at"]} + wanted.add((view["machine_id"], view["session_id"], view["raised"] or rfc3339(float(a["at"]) - 86400))) + if not ended_for_good(self.app.hub, view, self._history): + continue + if not self.app.owns(epoch) or not store.wb_ask_end(chat, a["ix"], "recalling"): + continue # another account's by now, or answered here meanwhile: never taken back twice + if not self.app.owns(epoch): + store.wb_ask_state(chat, a["ix"], "open") + continue + how = take_back(self.app, chat, a["message_id"], epoch, "Agent 工作台: a question") \ + if a.get("message_id") else "ended" + tries = int(d.get("tries") or 0) + 1 + if how == "failed" and tries < TAKE_BACK_TRIES: + store.wb_ask_reopen(chat, a["ix"], dict(d, tries=tries)) # the service away: again next round + continue + store.wb_ask_state(chat, a["ix"], how) + log.info("Agent 工作台: a question answered elsewhere (%s)", how) + for k in [k for k in self._history if k not in wanted]: + del self._history[k] + + def _answer(self, chat: str, row: dict, topic: dict, text: str, epoch: Optional[int]) -> None: + app, store, hub = self.app, self.app.store, self.app.hub + asks = store.wb_asks_open(chat, topic["root_id"]) + if not asks: + return self._forward(chat, row, topic, text, epoch) + parent = str(row.get("parent_id") or "") + quoted = [x for x in asks if parent and x.get("message_id") == parent] + a = quoted[0] if quoted else asks[0] # the one the reply quotes, else the newest one waiting in this topic + data = a.get("data") or {} + ans = parse_answer(text, data) + key = "workbench:answer-note:%s:%s" % (chat, row["id"]) + if ans is None: + how = data.get("how") + if how == "app": + words = "这个话题里有一个要在 Persona App 里处理的问题,这句没有发给 Agent;处理完再发。" + else: + words = "这个话题里有一个等你确认的问题,请按上面说的回复;这句没有发给 Agent。" + self._note(chat, row, key, words, epoch) + return + try: + pending = {str(i.get("id") or ""): i for i in hub.pending_interactions()} + except HubError as e: + self._note(chat, row, key, "现在读不到 Persona 里等你确认的问题(%s),请稍后再回复。" % (e.message or e.code), epoch) + return + ix = pending.get(a["ix"]) + if ix is None: + store.wb_ask_end(chat, a["ix"], "ended") + self._note(chat, row, key, "这个问题已经结束了(在别处答了、撤了或者过期了),这句没有发出。", epoch) + return + cid = "openmate-wb-" + hashlib.sha256(("%s:%s" % (chat, row["id"])).encode("utf-8")).hexdigest()[:24] + if not self._still(epoch): + return + try: + if "choose" in ans: + _, now_data = ask_view(ix) + if now_data.get("how") != "choose" or now_data.get("labels") != data.get("labels") or \ + now_data.get("question") != data.get("question"): + self._note(chat, row, key, "这个问题刚刚变了,这句没有发出;请看新的问题再回复。", epoch) + return + picks = ans["choose"] + rev = ask_rev(str(data.get("question") or ""), list(data.get("labels") or []), bool(data.get("multi"))) + try: + if len(picks) == 1: + hub.choose(a["ix"], rev, option=picks[0], client_id=cid) + else: + hub.choose(a["ix"], rev, options=picks, client_id=cid) + except HubError as e: + if e.status == 409 and e.code == "ask_changed": + # the question, as read just now, is the one shown: answered by its labels instead + labels = list(data.get("labels") or []) + hub.resolve(a["ix"], {"answers": {str(data.get("question") or ""): + ", ".join(labels[i] for i in picks)}}) + else: + raise + else: + hub.resolve(a["ix"], ans["resolve"]) + except HubError as e: + if e.status in (409, 410) or e.code in ("not_pending",): + store.wb_ask_end(chat, a["ix"], "ended") + self._note(chat, row, key, "这个问题已经结束了(在别处答了、撤了或者过期了),这句没有发出。", epoch) + elif e.status == 400 and e.code == "not_choosable": + self._note(chat, row, key, "这个问题 Persona 要求在 App 里看过再答,这句没有发出。", epoch) + elif e.status == 403: + self._note(chat, row, key, "Persona 不让扩展替你做这个决定(%s),请在 Persona App 里处理。" % (e.message or "无权限"), + epoch) + else: + self._note(chat, row, key, "没能作答:%s" % (e.message or e.code or "hub 出错了"), epoch) + return + with app.owned(epoch) as ok: + if ok: + store.wb_ask_end(chat, a["ix"], "answered") + agent = app.agent + self._react(chat, row["id"], agent.done_reaction if agent is not None else "", epoch=epoch) + if a.get("message_id"): + body = "✅ 已作答:" + answer_words(ans, data) + self._edit(chat, a["message_id"], body, "Agent 工作台把问题标成已作答", epoch if epoch is not None else + app.account_epoch()) + log.info("Agent 工作台: a question was answered in its topic (%s)", data.get("how")) + + # ---------------------------------------------------------------- commands + + def _command(self, chat: str, row: dict, topic: Optional[dict], text: str, epoch: Optional[int]) -> None: + name, _, arg = text.partition(" ") + what = COMMANDS.get(name.lower(), "stop" if text.lower() in STOP_WORDS else "") + key = "workbench:cmd:%s:%s" % (chat, row["id"]) + root = row.get("root_id") or row.get("id") or "" + if what == "help": + words, rich = HELP, False + elif what == "ls": + words, rich = self._ls(), False + elif what == "tail" and topic is not None: + words, rich = self._tail(topic, arg), True + elif what == "stop" and topic is not None: + if not self._still(epoch): + return + try: + self.app.hub.interrupt(topic["machine_id"], topic["session_id"]) + words = "已经让它停下这一轮。" + except HubError as e: + words = "没能让它停下:%s" % (e.message or e.code) + rich = False + else: + return + try: + self._deliver(chat, key, words, reply_to=row["id"], root=root, rich=rich, epoch=epoch, + summary="Agent 工作台回答了一条指令,以你的身份发到") + except RPCError as e: + log.info("Agent 工作台: a command's answer was not sent (%s)", e.code or "error") + + def _fresh_sessions(self) -> List[dict]: + with self._mu: + fresh = time.time() - self._sessions_at < self.app.timing.workbench_poll * 2 + sessions = list(self._sessions) + if fresh: + return sessions + try: + sessions = self.app.hub.agent_sessions() + except HubError: + return sessions + with self._mu: + self._sessions, self._sessions_at = sessions, time.time() + return sessions + + def _ls(self) -> str: + now = time.time() + start = day_start(self.app.tz, now) + sessions = self._fresh_sessions() + if not sessions and not self._sessions_at: + return "现在读不到 Agent 列表,请稍后再试。" + order = {"needs": 0, "stuck": 1, "working": 2, "idle": 3, "ended": 4} + rows = [] + counts: Dict[str, int] = {} + for s in sessions: + st = state_of(s, now, start) + counts[st] = counts.get(st, 0) + 1 + if st in ("needs", "stuck", "working") or last_moved(s) >= start: + rows.append((order[st], -last_moved(s), st, s)) + rows.sort(key=lambda r: (r[0], r[1])) + head = "Agent 工作台:等你确认 %d · 执行中 %d · 待命 %d" % ( + counts.get("needs", 0), counts.get("working", 0) + counts.get("stuck", 0), counts.get("idle", 0)) + lines = [head] + for _, _, st, s in rows[:LS_MOST]: + snap = self._snap(s) + bits = [b for b in (snap["project"], snap["branch"], snap["machine"], + local_stamp(snap["moved"], self.app.tz) if snap["moved"] else "") if b] + lines.append("%s %s — %s" % (STATES[st][0], snap["title"], " · ".join(bits))) + if len(rows) > LS_MOST: + lines.append("还有 %d 个没列出" % (len(rows) - LS_MOST)) + if len(lines) == 1: + lines.append("今天还没有 Agent 做过事。") + return "\n".join(lines) + + def _tail(self, topic: dict, arg: str) -> str: + try: + n = int(arg.strip()) if arg.strip() else TAIL_LINES + except ValueError: + n = TAIL_LINES + n = max(1, min(TAIL_MOST, n)) + mid, sid = topic["machine_id"], topic["session_id"] + why = "" + try: + got = self.app.hub.screen(mid, sid, n) + screen = str(got.get("text") or "").rstrip() + if screen.strip(): + lines = screen.split("\n")[-n:] + body = "\n".join(lines) + while len(body) > TAIL_CHARS and "\n" in body: + body = body.split("\n", 1)[1] + return "终端最后 %d 行(%s):\n```\n%s\n```" % (len(body.split("\n")), local_stamp(time.time(), self.app.tz), + body.replace("```", "ˋˋˋ")) + why = "终端是空的" + except HubError as e: + why = e.message or e.code or "hub 出错了" + # no screen (an Agent with no terminal, a hub that keeps it from extensions): its last items + try: + res = self.app.hub.items(mid, sid) or {} + except HubError as e: + return "读不到终端画面(%s),也读不到它最近的记录(%s)。" % (why, e.message or e.code) + lines = [] + for it in (res.get("items") or [])[-8:]: + if not isinstance(it, dict): + continue + t = one_line(str(it.get("text") or ""), 200) + if not t: + continue + who = {"user": "你", "assistant": "Agent"}.get(str(it.get("role") or ""), str(it.get("kind") or "记录")) + lines.append("%s:%s" % (who, t)) + return "读不到终端画面(%s),这是它最近的记录:\n%s" % (why, "\n".join(lines) or "(没有记录)") diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index e222d15..b1dc11c 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.78", + "version": "0.11.79", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -142,6 +142,31 @@ "description": "「设置 › 渠道」里的飞书(OpenMate)只在这个会话里收发:填会话 id(问 Persona 助手「飞书里 xx 群的 chat id」,它会用 matefeishu_chats 查出 chat=… 那一串),要是这个扩展收到过消息的会话。在这里你自己说的每一句都交给 Persona 的渠道流程(开头的 /agent 可写可不写;默认进主对话,可在「设置 › 渠道」改),回答以你的身份回到提问处;Agent 要你回答或批准的问题也以你的身份发到这里,直接回复就是作答,在 App 里答了会自动撤回。这个会话里别人能看到这些消息,请用只有你自己的群。留空就不用(默认),渠道什么都不收也不发,/agent 照旧。", "maxLength": 256 }, + "workbench": { + "type": "boolean", + "title": "Agent 工作台", + "description": "把「工作台话题群」当成 Agent 工作台:Persona 管着的每个 Agent(各台电脑上的 Claude Code、Codex 等)在群里有自己的一个话题,第一条消息原地显示它的状态(🟡 执行中、🟠 等你确认、🟢 待命、⚫ 已结束)、项目、分支、电脑、最近指令和更新时间;你在话题里回复的话直接发给这个 Agent,它这一轮的回复回到话题里(长回复分成几条,代码块不会被切坏)。这些消息都以你的身份发在这个群里。关掉(默认)时什么都不读也不发,/agent、自动代答、收件箱、渠道都和原来一样。", + "default": false, + "x-confirm": "打开后,扩展会以你的身份在「工作台话题群」里为 Agent 开话题、更新状态,并把你在这些话题里说的话直接发给对应的 Agent(它会用自己的全部权限去做)。请用只有你自己的群。确定打开吗?" + }, + "workbench_chat": { + "type": "string", + "title": "工作台话题群", + "description": "Agent 工作台用的群:填会话 id(问 Persona 助手「飞书里 xx 群的 chat id」,它会用 matefeishu_chats 查出 chat=… 那一串),要是这个扩展收到过消息的会话。建议新建一个只有你自己的话题群;不能和「Persona 渠道会话」是同一个。群里不在 Agent 话题里的消息照旧按 /agent 处理。", + "maxLength": 256 + }, + "workbench_asks": { + "type": "boolean", + "title": "工作台:话题里作答", + "description": "要先打开 Agent 工作台。Agent 等你回答或批准时,把问题和选项发到它的话题里:回复编号作答,y / n 允许或拒绝(n 后面可以写原因),也可以直接写回答;在别处答了会自动撤回。Persona 不让扩展替你批准的卡片(付款、删除、以你的名义发送、表单和密码等),话题里会提示你去 App 里处理。", + "default": false + }, + "workbench_commands": { + "type": "boolean", + "title": "工作台:指令不过模型", + "description": "要先打开 Agent 工作台。在工作台群里发 /ls 列出各个 Agent 的状态;在某个 Agent 的话题里发 /tail [行数] 看它终端的最后几行(读不到终端时给它最近几条记录)、/stop 让它停下这一轮;/help 看说明。都由扩展直接回答,不经过模型。关掉时这些话和别的话一样发给 Agent。", + "default": false + }, "agent_reply_header": { "type": "string", "title": "AI 回复标记", diff --git a/extensions/openmate-feishu/tests/test_feishu.py b/extensions/openmate-feishu/tests/test_feishu.py index fcef070..bcaf09d 100644 --- a/extensions/openmate-feishu/tests/test_feishu.py +++ b/extensions/openmate-feishu/tests/test_feishu.py @@ -90,7 +90,9 @@ def test_configuration(self): props = MANIFEST["configuration"]["properties"] self.assertEqual(list(props), ["larkx_python", "larkx_commit", "region", "http_proxy", "agent", "agent_prefix", "agent_self_mention", - "agent_machine", "agent_balance", "agent_launcher", "agent_forward", "channel_chat", "agent_reply_header", "agent_mark_position", + "agent_machine", "agent_balance", "agent_launcher", "agent_forward", "channel_chat", + "workbench", "workbench_chat", "workbench_asks", "workbench_commands", + "agent_reply_header", "agent_mark_position", "agent_mark_effort", "agent_ack_reaction", "agent_done_reaction", "agent_fail_reaction", @@ -123,6 +125,9 @@ def test_configuration(self): self.assertTrue(re.match(props["larkx_commit"]["pattern"], d["larkx_commit"])) self.assertEqual([c["const"] for c in props["region"]["oneOf"]], ["feishu", "lark"]) self.assertIs(d["agent"], False) + # Agent 工作台 and its two parts: off until the user turns them on, the group named by the user only + self.assertEqual((d["workbench"], d["workbench_asks"], d["workbench_commands"]), (False, False, False)) + self.assertNotIn("workbench_chat", d) self.assertIs(d["agent_forward"], True, "a follow-up goes to the task's Agent unless switched off") self.assertEqual(props["agent_machine"]["format"], "machine") self.assertEqual(props["agent_launcher"]["format"], "launcher") diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index c138773..1a63a91 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.71", + "version": "0.1.72", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.79/openmate-feishu-0.11.79.tar.gz b/packages/openmate-feishu/0.11.79/openmate-feishu-0.11.79.tar.gz new file mode 100644 index 0000000..3ff7a90 Binary files /dev/null and b/packages/openmate-feishu/0.11.79/openmate-feishu-0.11.79.tar.gz differ diff --git a/packages/openmate-wechat/0.1.72/openmate-wechat-0.1.72.tar.gz b/packages/openmate-wechat/0.1.72/openmate-wechat-0.1.72.tar.gz new file mode 100644 index 0000000..48c0f36 Binary files /dev/null and b/packages/openmate-wechat/0.1.72/openmate-wechat-0.1.72.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index eb27e88..27550db 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.78", + "version": "0.11.79", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -249,6 +249,31 @@ "description": "「设置 › 渠道」里的飞书(OpenMate)只在这个会话里收发:填会话 id(问 Persona 助手「飞书里 xx 群的 chat id」,它会用 matefeishu_chats 查出 chat=… 那一串),要是这个扩展收到过消息的会话。在这里你自己说的每一句都交给 Persona 的渠道流程(开头的 /agent 可写可不写;默认进主对话,可在「设置 › 渠道」改),回答以你的身份回到提问处;Agent 要你回答或批准的问题也以你的身份发到这里,直接回复就是作答,在 App 里答了会自动撤回。这个会话里别人能看到这些消息,请用只有你自己的群。留空就不用(默认),渠道什么都不收也不发,/agent 照旧。", "maxLength": 256 }, + "workbench": { + "type": "boolean", + "title": "Agent 工作台", + "description": "把「工作台话题群」当成 Agent 工作台:Persona 管着的每个 Agent(各台电脑上的 Claude Code、Codex 等)在群里有自己的一个话题,第一条消息原地显示它的状态(🟡 执行中、🟠 等你确认、🟢 待命、⚫ 已结束)、项目、分支、电脑、最近指令和更新时间;你在话题里回复的话直接发给这个 Agent,它这一轮的回复回到话题里(长回复分成几条,代码块不会被切坏)。这些消息都以你的身份发在这个群里。关掉(默认)时什么都不读也不发,/agent、自动代答、收件箱、渠道都和原来一样。", + "default": false, + "x-confirm": "打开后,扩展会以你的身份在「工作台话题群」里为 Agent 开话题、更新状态,并把你在这些话题里说的话直接发给对应的 Agent(它会用自己的全部权限去做)。请用只有你自己的群。确定打开吗?" + }, + "workbench_chat": { + "type": "string", + "title": "工作台话题群", + "description": "Agent 工作台用的群:填会话 id(问 Persona 助手「飞书里 xx 群的 chat id」,它会用 matefeishu_chats 查出 chat=… 那一串),要是这个扩展收到过消息的会话。建议新建一个只有你自己的话题群;不能和「Persona 渠道会话」是同一个。群里不在 Agent 话题里的消息照旧按 /agent 处理。", + "maxLength": 256 + }, + "workbench_asks": { + "type": "boolean", + "title": "工作台:话题里作答", + "description": "要先打开 Agent 工作台。Agent 等你回答或批准时,把问题和选项发到它的话题里:回复编号作答,y / n 允许或拒绝(n 后面可以写原因),也可以直接写回答;在别处答了会自动撤回。Persona 不让扩展替你批准的卡片(付款、删除、以你的名义发送、表单和密码等),话题里会提示你去 App 里处理。", + "default": false + }, + "workbench_commands": { + "type": "boolean", + "title": "工作台:指令不过模型", + "description": "要先打开 Agent 工作台。在工作台群里发 /ls 列出各个 Agent 的状态;在某个 Agent 的话题里发 /tail [行数] 看它终端的最后几行(读不到终端时给它最近几条记录)、/stop 让它停下这一轮;/help 看说明。都由扩展直接回答,不经过模型。关掉时这些话和别的话一样发给 Agent。", + "default": false + }, "agent_reply_header": { "type": "string", "title": "AI 回复标记", @@ -540,9 +565,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.78/openmate-feishu-0.11.78.tar.gz", - "sha256": "2bf0214371c7d1745fa293c49ff38a99771f563948cd68e1afc0dbddf48e0866", - "size": 415117 + "url": "packages/openmate-feishu/0.11.79/openmate-feishu-0.11.79.tar.gz", + "sha256": "7fe18ce92b7dfdc213885f711afdd1c549141b926fe20a462d8fa23ed9708880", + "size": 436099 } ] }, @@ -551,7 +576,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.71", + "version": "0.1.72", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -848,9 +873,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.71/openmate-wechat-0.1.71.tar.gz", - "sha256": "dad07dc9350adb22378693049c8bd04e422108d0bb4d4305dbbf2fe62b5daa00", - "size": 311944 + "url": "packages/openmate-wechat/0.1.72/openmate-wechat-0.1.72.tar.gz", + "sha256": "d4132bf6bee520c67e58f82378460ff065521dd10d95f359688f2f3b3098b05e", + "size": 332063 } ] } diff --git a/tests/harness.py b/tests/harness.py index f71b217..6bc5370 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -39,6 +39,8 @@ def fast(**kw) -> Timing: sent_retry=(0.05, 0.05, 0.05), warm_pages=False, agent_model_wait=1.0) if "channel_poll" in Timing.__dataclass_fields__: # the channel's (older code has none: its tests fail elsewhere) base.update(channel_poll=0.05, channel_retry=(0.05, 0.05), channel_unseen=0.3) + if "workbench_poll" in Timing.__dataclass_fields__: # Agent 工作台's (older code has none) + base.update(workbench_poll=0.05) base.update(kw) return Timing(**base) @@ -243,6 +245,10 @@ def __init__(self, token: str = TOKEN): self.interactions: List[dict] = [] # GET /api/v1/interactions (agents.read): the cards waiting for an answer self.interactions_status: Optional[int] = None # an HTTP status that route answers instead self.history: List[dict] = [] # GET /api/v1/interactions/history: [{interaction: {id, machine_id, …}, status}] + self.agent_list: List[dict] = [] # GET /api/v1/sessions?agents_only=1 (the Agents page, Agent 工作台): summary rows + self.screens: Dict[str, Any] = {} # session id → GET …/screen's answer ({text, status}), or an HTTP status + self.answers: List[dict] = [] # POST /api/v1/interactions/{id}/choose and …/resolve: {id, how, body} + self.answer_status: Dict[str, tuple] = {} # interaction id → (status, code) its answers get instead # placement (machines.read, assistant.ask): None leaves the route out (an older hub, or no permission: 404) self.assistant_mid: Optional[str] = None # GET /api/v1/assistant's machine_id self.machine_list: Optional[List[dict]] = None # GET /api/v1/machines: [{id, online}] @@ -493,6 +499,21 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = rows.append({"session_id": "%s-done" % wmid, "machine_id": wmid, "status": "done", "state": "working"}) return 200, {"sessions": rows, "total": len(rows), "has_more": self.working_more} + if method == "GET" and p == "/api/v1/sessions" and query.get("agents_only"): + return 200, {"sessions": [dict(r) for r in self.agent_list], "total": len(self.agent_list), + "has_more": False} + if method == "POST" and len(parts) == 5 and parts[:3] == ["api", "v1", "interactions"] \ + and parts[4] in ("choose", "resolve"): + ix = parts[3] + self.answers.append({"id": ix, "how": parts[4], "body": body}) + if ix in self.answer_status: + status, code = self.answer_status[ix] + return status, {"error": "refused (%s)" % code, "code": code} + if not any(i.get("id") == ix for i in self.interactions): + return (409, {"error": "not pending", "code": "not_pending"}) if parts[4] == "choose" else \ + (410, {"error": "ended", "status": "resolved"}) + self.interactions = [i for i in self.interactions if i.get("id") != ix] + return 200, {"ok": True} if method == "GET" and p == "/api/v1/sessions": sid, mid = query.get("session_id"), query.get("machine_id") s = self.sessions.get(sid or "") @@ -548,6 +569,11 @@ def route(self, method: str, parts: List[str], query: dict, body: Any, op: str = status, code = self.lost_send_status return status, {"error": "the answer was lost", "code": code} return 200, {"ok": True} + if method == "GET" and rest == ["screen"]: + got = self.screens.get(sid) + if got is None or isinstance(got, int): + return got or 404, {"error": "no terminal", "code": "no_terminal"} + return 200, dict(got, lines=query.get("lines")) if method == "POST" and rest == ["interrupt"]: s["working"] = False s["interrupted"] = True diff --git a/tests/test_workbench.py b/tests/test_workbench.py new file mode 100644 index 0000000..55d541f --- /dev/null +++ b/tests/test_workbench.py @@ -0,0 +1,509 @@ +"""Agent 工作台 (workbench.py): the user's own group, one topic per Agent the hub lists. Off by default; while off (or +pointed nowhere) /agent, Persona's 渠道 and the rest go on exactly as before. On: a status topic per Agent, edited in +place; the user's lines in a topic go to its Agent and the answer comes back there in pieces; with 话题里作答 a +question the Agent waits on is put in the topic and a reply answers it; with 工作台指令 /ls, /tail and /stop are +answered without a model.""" + +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 datetime as dt +import json +import os +import time +import unittest + +from harness import CID, ROOT, Harness, wait_until +from openmate_core import workbench as wbmod +from openmate_core.backend import Chat +from openmate_core.fixture import FixtureWorld + +DESK = "chat_example_desk" +SOLO = "chat_example_solo" +TEAM = "chat_example_team" +MID, SID = "mac-a", "sess-a" + + +def iso(seconds_ago: float) -> str: + return dt.datetime.fromtimestamp(time.time() - seconds_ago, dt.timezone.utc).isoformat().replace("+00:00", "Z") + + +def agent_row(sid=SID, mid=MID, **kw) -> dict: + row = {"session_id": sid, "machine_id": mid, "title": "修复登录", "space_name": "persona", "branch": "fix/login", + "state": "working", "status": "working", "state_since": iso(60), "updated_at": iso(30), + "activity": "在跑测试", "agent": "claude", "model": "claude-opus-5-5", "effort": "xhigh"} + row.update(kw) + return row + + +def manifest(): + with open(os.path.join(ROOT, "extensions", "openmate-feishu", "persona-extension.json"), encoding="utf-8") as f: + return json.load(f) + + +def world_with_desk() -> FixtureWorld: + world = FixtureWorld() + world.add_chat(Chat(DESK, "group", "示例工作台", members=1)) + world.make(DESK, "me", "这个群只有我自己", ago=3000) + world.add_chat(Chat(SOLO, "group", "示例渠道群", members=1)) + world.make(SOLO, "me", "渠道", ago=3000) + return world + + +def desk(test, rows=None, **cfg) -> Harness: + """A signed-in run with the desk on (its group: DESK) and one working Agent listed.""" + world = world_with_desk() + config = {"agent": True, "workbench": True, "workbench_chat": DESK} + config.update(cfg) + h = Harness(test, config=config, world=world, initialize=False) + h.http.add_agent(SID, machine=MID, working=True) + h.http.add(SID, "user", "text", "帮我修一下登录") + h.http.agent_list = list(rows) if rows is not None else [agent_row()] + h.initialize() + h.sign_in() + wait_until(lambda: h.app._catchup_done.is_set(), what="catch-up") + return h + + +def topic(h, sid=SID, mid=MID) -> dict: + return wait_until(lambda: (lambda t: t if t and t.get("root_id") else None)( + h.app.store.wb_topics(DESK).get((mid, sid))), what="the Agent's topic") + + +def sent_in(h, root) -> list: + return [s for s in h.sent() if s["chat"] == DESK and s["root"] == root] + + +def text_of(h, mid) -> str: + return [s for s in h.sent() if s["id"] == mid][-1]["text"] + + +def say(h, text, root=None, chat=DESK): + if root: + return h.world.push(chat, "me", text, root_id=root, parent_id=root, placement="thread") + return h.world.push(chat, "me", text) + + +def agents_reads(h) -> int: + with h.http.lock: + return sum(1 for r in h.http.requests if r["path"] == "/api/v1/sessions" and r["query"].get("agents_only")) + + +# ---------------------------------------------------------------- pieces of an answer + +class SplitTest(unittest.TestCase): + def test_short_is_one_piece(self): + self.assertEqual(wbmod.split_reply("你好\n世界"), ["你好\n世界"]) + self.assertEqual(wbmod.split_reply(" \n"), []) + + def test_each_piece_within_both_budgets(self): + text = "\n".join("第 %d 行:%s" % (i, "汉字" * (i % 40)) for i in range(400)) + pieces = wbmod.split_reply(text, 500, 900) + self.assertGreater(len(pieces), 3) + for p in pieces: + self.assertLessEqual(len(p), 500) + self.assertLessEqual(len(p.encode("utf-8")), 900, "UTF-8 bytes too: Chinese is 3 bytes a character") + self.assertEqual("\n".join(pieces), text, "cut between lines, nothing lost or doubled") + + def test_code_block_closed_and_opened_again(self): + code = "\n".join("x_%d = compute(%d)" % (i, i) for i in range(60)) + text = "前面的说明\n```python\n%s\n```\n后面的结论" % code + pieces = wbmod.split_reply(text, 300, 3000) + self.assertGreater(len(pieces), 2) + for p in pieces: + fences = [l for l in p.split("\n") if l.startswith("```")] + self.assertEqual(len(fences) % 2, 0, "every piece closes the blocks it opens: %r" % p) + for p in pieces[1:-1]: + self.assertTrue(p.startswith("```python\n"), "a piece in the block opens it again with its language") + self.assertTrue(pieces[-1].endswith("后面的结论")) + body = [l for p in pieces for l in p.split("\n") if l.startswith("x_")] + self.assertEqual(body, code.split("\n"), "every code line once, in order") + + def test_a_line_longer_than_a_piece(self): + pieces = wbmod.split_reply("开头\n" + "长" * 25 + "\n结尾", 10, 1000) + self.assertEqual("".join(p.replace("\n", "") for p in pieces), "开头" + "长" * 25 + "结尾") + self.assertTrue(all(len(p) <= 10 for p in pieces)) + + +class AskTest(unittest.TestCase): + def test_rev_is_the_hubs(self): + # computed with Go's encoding/json (go1.21.4) as Persona's askRev does (server/internal/hub/push_payload.go) + self.assertEqual(wbmod.ask_rev("要不要合并 & 发版?", ["合并", '先不合"等等"', "a\nb\tc"], False), "468455f884b9") + self.assertEqual(wbmod.ask_rev("Pick one
line", ["x/y", "😀 emoji", ""], True), "1539d074327d") + self.assertEqual(wbmod.ask_rev("", [], False), "30225f243c85") + + def test_how_each_kind_is_answered(self): + q = {"id": "i", "kind": "question", "questions": [{"question": "用哪个?", "options": [{"label": "甲"}, {"label": "乙"}]}]} + text, data = wbmod.ask_view(q) + self.assertIn("1. 甲", text) + self.assertEqual(wbmod.parse_answer("2", data), {"choose": [1]}) + self.assertIsNone(wbmod.parse_answer("1,2", data), "one choice only") + self.assertIsNone(wbmod.parse_answer("3", data), "no such option") + self.assertEqual(wbmod.parse_answer("都不要", data), {"resolve": {"answers": {"用哪个?": "都不要"}}}) + _, multi = wbmod.ask_view({"kind": "question", "questions": [{"question": "选", "multi_select": True, + "options": [{"label": "a"}, {"label": "b"}]}]}) + self.assertEqual(wbmod.parse_answer("1,2", multi), {"choose": [0, 1]}) + _, perm = wbmod.ask_view({"kind": "permission", "tool_name": "Bash", "tool_input": {"command": "rm -rf build"}}) + self.assertEqual(wbmod.parse_answer("y", perm), {"resolve": {"allow": True}}) + self.assertEqual(wbmod.parse_answer("n 先别删", perm), {"resolve": {"allow": False, "message": "先别删"}}) + self.assertIsNone(wbmod.parse_answer("等一下", perm)) + _, plan = wbmod.ask_view({"kind": "plan", "plan": "1. 改代码"}) + self.assertEqual(wbmod.parse_answer("同意", plan), {"resolve": {"approve": True}}) + self.assertEqual(wbmod.parse_answer("n 再细一点", plan), {"resolve": {"approve": False, "feedback": "再细一点"}}) + _, form = wbmod.ask_view({"kind": "question", "fields": [{"key": "pw", "label": "密码", "secret": True}], + "questions": [{"question": "登录", "options": [{"label": "好"}]}]}) + self.assertEqual(form["how"], "app") + self.assertIsNone(wbmod.parse_answer("1", form), "a card with fields is the app's") + + +# ---------------------------------------------------------------- off: as before + +class OffByDefaultTest(unittest.TestCase): + def test_manifest_switches_default_off(self): + props = manifest()["configuration"]["properties"] + for key in ("workbench", "workbench_asks", "workbench_commands"): + self.assertIs(props[key]["default"], False, key) + self.assertNotIn("default", props["workbench_chat"]) + self.assertIn("x-confirm", props["workbench"]) + wechat = os.path.join(ROOT, "extensions", "openmate-wechat", "persona-extension.json") + with open(wechat, encoding="utf-8") as f: + self.assertFalse([k for k in json.load(f)["configuration"]["properties"] if k.startswith("workbench")]) + + def test_off_nothing_read_and_agent_as_before(self): + """Off (the group even named): no Agents read, no topic, and /agent in that group starts its run as before.""" + world = world_with_desk() + h = Harness(self, config={"agent": True, "workbench_chat": DESK, "agent_ack_reaction": ""}, world=world) + h.http.agent_list = [agent_row()] + h.sign_in() + wait_until(lambda: h.app._catchup_done.is_set(), what="catch-up") + self.assertIsNone(h.app.workbench._thread, "no loop while off") + m = say(h, "/agent 看看登录为什么失败") + wait_until(lambda: h.http.starts(), what="the /agent conversation started") + time.sleep(0.3) + self.assertEqual(agents_reads(h), 0) + self.assertEqual(h.http.interactions_asked(), 0) + self.assertEqual(h.app.store.wb_topics(DESK), {}) + self.assertEqual([s for s in h.sent() if s["chat"] == DESK and s["text"].startswith("🟡")], []) + self.assertIn("Agent 工作台:没有开启", h.tool("status")) + self.assertEqual(len(h.http.starts()), 1) + self.assertIn("看看登录为什么失败", h.http.starts()[0]["body"]["prompt"]) + self.assertTrue(m.id) + + def test_on_without_a_group_does_nothing(self): + h = Harness(self, config={"agent": True, "workbench": True}, world=world_with_desk()) + h.sign_in() + time.sleep(0.3) + self.assertIsNone(h.app.workbench._thread) + self.assertEqual(agents_reads(h), 0) + self.assertIn("还没有填「工作台话题群」", h.tool("status")) + + def test_the_channel_chat_is_never_the_desk(self): + """The desk pointed at the 「Persona 渠道会话」: the channel keeps every line there, no topic is opened.""" + h = desk(self, channel_chat=SOLO, workbench_chat=SOLO) + say(h, "/agent 你好", chat=SOLO) + wait_until(lambda: h.hub.received, what="handed to Persona's channel") + time.sleep(0.3) + self.assertEqual(h.app.store.wb_topics(SOLO), {}) + self.assertEqual(agents_reads(h), 0) + self.assertIn("同一个会话", h.tool("status")) + + def test_on_other_chats_and_the_desks_main_stream_stay_agents(self): + h = desk(self, agent_ack_reaction="") + topic(h) + say(h, "/agent 查一下周报", chat=TEAM) + say(h, "/agent 群里主消息也照旧") + wait_until(lambda: len(h.http.starts()) >= 2, what="both /agent conversations started") + self.assertEqual(h.http.messages_to(MID, SID), [], "nothing handed to the Agent") + + +# ---------------------------------------------------------------- on + +class DeskTest(unittest.TestCase): + def test_topic_status_opened_and_edited_in_place(self): + h = desk(self) + t = topic(h) + first = text_of(h, t["root_id"]) + self.assertTrue(first.startswith("🟡 执行中|修复登录"), first) + for words in ("项目 persona", "分支 fix/login", "claude code", "Opus 5.5", "电脑 mac-a", "最近指令:帮我修一下登录", + "在这个话题里回复,就是发给这个 Agent"): + self.assertIn(words, first) + h.http.agent_list = [agent_row(state="needs_you", pending_interactions=1)] + wait_until(lambda: text_of(h, t["root_id"]).startswith("🟠 等你确认"), what="edited to 等你确认") + h.http.agent_list = [agent_row(state="idle", status="done")] + wait_until(lambda: text_of(h, t["root_id"]).startswith("🟢 待命"), what="edited to 待命") + h.http.agent_list = [] + wait_until(lambda: text_of(h, t["root_id"]).startswith("⚫ 已结束|修复登录"), what="edited to 已结束") + roots = [s for s in h.sent() if s["chat"] == DESK and not s["root"]] + self.assertEqual(len(roots), 1, "one topic, edited in place") + self.assertEqual(h.http.messages_to(MID, SID), [], "its own messages are never handed to the Agent") + self.assertTrue([r for r in h.hub.sent_records if r.get("setting") == "workbench"], "told to the ledger") + + def test_the_same_state_is_edited_at_most_every_few_minutes(self): + h = desk(self) + t = topic(h) + edits = len(h.world.edits) + h.http.agent_list = [agent_row(activity="在改另一个文件", updated_at=iso(1))] + time.sleep(0.4) + self.assertEqual(len(h.world.edits), edits, "only the activity changed: not edited yet") + h.http.agent_list = [agent_row(state="idle", status="done", updated_at=iso(1))] + wait_until(lambda: text_of(h, t["root_id"]).startswith("🟢 待命"), what="a new state: edited at once") + + def test_quiet_agents_from_before_get_no_topic(self): + old = agent_row("sess-old", state="idle", status="done", state_since=iso(86400), updated_at=iso(86400)) + h = desk(self, rows=[agent_row(), old]) + topic(h) + time.sleep(0.3) + self.assertNotIn((MID, "sess-old"), h.app.store.wb_topics(DESK)) + h.http.agent_list = [agent_row(), dict(old, state="working", status="working", updated_at=iso(1))] + h.http.add_agent("sess-old", machine=MID) + topic(h, sid="sess-old") + + def test_a_line_goes_to_the_agent_and_its_answer_comes_back(self): + h = desk(self) + root = topic(h)["root_id"] + m = say(h, "把测试也跑一遍", root=root) + msgs = wait_until(lambda: h.http.messages_to(MID, SID), what="handed to the Agent") + self.assertEqual(msgs[0]["body"]["text"], "把测试也跑一遍") + self.assertTrue(msgs[0]["body"]["client_msg_id"].startswith("openmate-wb-")) + wait_until(lambda: (DESK, m.id, "THINKING") in h.world.reactions, what="the ack") + h.http.add(SID, "assistant", "text", "**测试都过了**,一共 12 个。") + h.http.end_turn(SID) + reply = wait_until(lambda: [s for s in sent_in(h, root) if "测试都过了" in s["text"]], what="the answer") + self.assertIn("🤖 AI 回复", reply[0]["text"]) + self.assertIn("Opus 5.5", reply[0]["text"]) + self.assertTrue(reply[0]["rich"], "formatted") + self.assertEqual(reply[0]["reply_to"], root) + wait_until(lambda: (DESK, m.id, "DONE") in h.world.reactions, what="the done mark") + self.assertNotIn((DESK, m.id, "THINKING"), h.world.reactions) + time.sleep(0.3) + self.assertEqual(len(h.http.messages_to(MID, SID)), 1, "the answer's echo is not handed back") + self.assertEqual(len([s for s in sent_in(h, root) if "测试都过了" in s["text"]]), 1, "once") + + def test_a_long_answer_in_pieces_plain_when_the_format_is_refused(self): + h = desk(self) + root = topic(h)["root_id"] + say(h, "给我完整的代码", root=root) + wait_until(lambda: h.http.messages_to(MID, SID), what="handed over") + code = "\n".join("line_%04d = %d # 中文注释" % (i, i) for i in range(900)) + h.http.add(SID, "assistant", "text", "代码如下:\n```python\n%s\n```\n完。" % code) + h.world.format_ok = False + h.http.end_turn(SID) + pieces = wait_until(lambda: (lambda ps: ps if ps and "完。" in ps[-1]["text"] else None)( + [s for s in sent_in(h, root) if "🤖 AI 回复" in s["text"]]), timeout=8, what="every piece") + n = len(pieces) + self.assertGreater(n, 2) + for i, p in enumerate(pieces, 1): + self.assertIn("(%d/%d)" % (i, n), p["text"]) + self.assertLessEqual(len(p["text"]), wbmod.REPLY_CHARS) + self.assertLessEqual(len(p["text"].encode("utf-8")), wbmod.REPLY_BYTES) + self.assertEqual(len([l for l in p["text"].split("\n") if l.startswith("```")]) % 2, 0) + self.assertFalse(p["rich"], "the format refused: plain text") + got = [l for p in pieces for l in p["text"].split("\n") if l.startswith("line_")] + self.assertEqual(got, code.split("\n")) + + +class AsksTest(unittest.TestCase): + def question(self=None, **kw): + ix = {"id": "ix-q", "kind": "question", "machine_id": MID, "session_id": SID, "created_at": iso(5), + "questions": [{"question": "用哪个方案?", "options": [{"label": "方案甲"}, + {"label": "方案乙", "description": "改动小"}]}]} + ix.update(kw) + return ix + + def test_off_no_question_is_put_and_lines_go_to_the_agent(self): + h = desk(self) + root = topic(h)["root_id"] + h.http.interactions = [self.question()] + say(h, "2", root=root) + wait_until(lambda: h.http.messages_to(MID, SID), what="handed to the Agent as a line") + self.assertEqual(h.http.interactions_asked(), 0) + self.assertEqual(h.http.answers, []) + + def test_a_number_chooses_with_the_questions_rev(self): + h = desk(self, workbench_asks=True) + root = topic(h)["root_id"] + h.http.interactions = [self.question()] + ask = wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q"), what="the question in its topic") + card = text_of(h, ask["message_id"]) + self.assertIn("用哪个方案?", card) + self.assertIn("1. 方案甲", card) + self.assertIn("2. 方案乙:改动小", card) + m = say(h, "2", root=root) + ans = wait_until(lambda: h.http.answers, what="answered") + self.assertEqual(ans[0]["how"], "choose") + body = ans[0]["body"] + self.assertEqual((body["option"], body["rev"]), (1, wbmod.ask_rev("用哪个方案?", ["方案甲", "方案乙"], False))) + wait_until(lambda: text_of(h, ask["message_id"]) == "✅ 已作答:方案乙", what="the question marked answered") + wait_until(lambda: (DESK, m.id, "DONE") in h.world.reactions, what="the done mark") + self.assertEqual(h.http.messages_to(MID, SID), [], "an answer is not a line for the Agent") + self.assertEqual(h.app.store.wb_ask(DESK, "ix-q")["state"], "answered") + time.sleep(0.3) + self.assertNotIn((DESK, ask["message_id"]), h.world.recalls, "answered here: not taken back") + + def test_ask_changed_answers_by_label_when_the_question_is_the_same(self): + h = desk(self, workbench_asks=True) + root = topic(h)["root_id"] + h.http.interactions = [self.question()] + wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q"), what="the question") + h.http.answer_status["ix-q"] = (409, "ask_changed") + say(h, "1", root=root) + wait_until(lambda: len(h.http.answers) >= 2, what="answered again by label") + h.http.answer_status.clear() + self.assertEqual(h.http.answers[1]["how"], "resolve") + + def test_approval_y_n_and_a_refusal(self): + h = desk(self, workbench_asks=True) + root = topic(h)["root_id"] + perm = {"id": "ix-p", "kind": "permission", "machine_id": MID, "session_id": SID, "created_at": iso(5), + "tool_name": "Bash", "tool_input": {"command": "rm -rf build"}} + h.http.interactions = [perm] + ask = wait_until(lambda: h.app.store.wb_ask(DESK, "ix-p"), what="the approval in its topic") + self.assertIn("rm -rf build", text_of(h, ask["message_id"])) + say(h, "随便说点", root=root) + wait_until(lambda: [s for s in sent_in(h, root) if "等你确认的问题" in s["text"]], what="told how to answer") + self.assertEqual(h.http.answers, []) + self.assertEqual(h.http.messages_to(MID, SID), []) + h.http.answer_status["ix-p"] = (403, "owner_only") + say(h, "y", root=root) + wait_until(lambda: [s for s in sent_in(h, root) if "Persona 不让扩展替你做这个决定" in s["text"]], what="refused") + h.http.answer_status.clear() + say(h, "n 先别删", root=root) + wait_until(lambda: len(h.http.answers) >= 2, what="declined") + self.assertEqual(h.http.answers[-1]["body"], {"allow": False, "message": "先别删"}) + + def test_answered_elsewhere_is_taken_back(self): + h = desk(self, workbench_asks=True) + topic(h) + h.http.interactions = [self.question()] + ask = wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q"), what="the question") + h.http.history.append({"interaction": self.question(), "status": "resolved"}) + h.http.interactions = [] + wait_until(lambda: (DESK, ask["message_id"]) in h.world.recalls, what="taken back") + wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q")["state"] == "recalled", what="marked taken back") + self.assertEqual(h.http.answers, [], "nothing answered from here") + + +class CommandsTest(unittest.TestCase): + def test_off_commands_are_lines(self): + h = desk(self) + root = topic(h)["root_id"] + say(h, "/tail", root=root) + msgs = wait_until(lambda: h.http.messages_to(MID, SID), what="handed over") + self.assertEqual(msgs[0]["body"]["text"], "/tail") + + def test_ls_tail_stop_without_a_model(self): + h = desk(self, workbench_commands=True) + root = topic(h)["root_id"] + ls = say(h, "/ls") + out = wait_until(lambda: [s for s in h.sent() if s["chat"] == DESK and s["reply_to"] == ls.id], what="/ls") + self.assertIn("执行中 1", out[0]["text"]) + self.assertIn("🟡 修复登录 — persona · fix/login", out[0]["text"]) + h.http.screens[SID] = {"text": "$ make test\nok 12 passed", "status": "working"} + tail = say(h, "/tail 5", root=root) + out = wait_until(lambda: [s for s in h.sent() if s["reply_to"] == tail.id], what="/tail") + self.assertIn("```\n$ make test\nok 12 passed\n```", out[0]["text"]) + self.assertTrue(out[0]["rich"]) + with h.http.lock: + self.assertEqual([r["query"].get("lines") for r in h.http.requests if r["path"].endswith("/screen")], ["5"]) + h.http.screens.pop(SID) + h.http.add(SID, "assistant", "text", "正在看日志") + tail2 = say(h, "/tail", root=root) + out = wait_until(lambda: [s for s in h.sent() if s["reply_to"] == tail2.id], what="/tail without a screen") + self.assertIn("读不到终端画面", out[0]["text"]) + self.assertIn("Agent:正在看日志", out[0]["text"]) + stop = say(h, "/stop", root=root) + wait_until(lambda: h.http.posts("/api/v1/sessions/%s/%s/interrupt" % (MID, SID)), what="interrupted") + wait_until(lambda: [s for s in h.sent() if s["reply_to"] == stop.id], what="told") + self.assertEqual(h.http.messages_to(MID, SID), [], "commands never go to the Agent") + self.assertEqual(h.http.starts(), [], "nor to a model") + + +class RobustnessTest(unittest.TestCase): + """What the first review found: nothing done for an account signed out since, no second topic for a send whose + outcome is not known, an answer that did not all go out sent again, a take-back tried again.""" + + def test_nothing_acted_on_for_the_account_before(self): + h = desk(self, workbench_asks=True, workbench_commands=True) + t = topic(h) + h.http.interactions = [AsksTest.question(None)] + wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q"), what="the question") + old = h.app.account_epoch() - 1 # as if another account signed in after the line was heard + row = {"id": "msg_example_old", "chat_id": DESK, "root_id": t["root_id"], "parent_id": t["root_id"]} + wb = h.app.workbench + wb._answer(DESK, row, t, "1", old) + wb._command(DESK, row, t, "/stop", old) + self.assertEqual(h.http.answers, []) + self.assertEqual(h.http.posts("/interrupt"), []) + self.assertEqual(h.http.messages_to(MID, SID), []) + + def test_a_topic_whose_send_is_not_known_is_not_sent_again(self): + world = world_with_desk() + world.send_fail_always = "uncertain" + h = Harness(self, config={"agent": True, "workbench": True, "workbench_chat": DESK}, world=world, + initialize=False) + h.http.add_agent(SID, machine=MID) + h.http.agent_list = [agent_row()] + h.initialize() + h.sign_in() + row = wait_until(lambda: h.app.store.wb_topics(DESK).get((MID, SID)), what="the topic noted as unsure") + self.assertEqual(row["root_id"], "") + self.assertTrue(row["data"].get("unsure")) + time.sleep(0.4) + world.send_fail_always = None + time.sleep(0.3) + self.assertEqual([s for s in h.sent() if s["text"].startswith("🟡")], [], "never sent again") + echo = world.push(DESK, "me", row["text"]) # the first one did go out after all: its echo + got = wait_until(lambda: h.app.store.wb_topics(DESK)[(MID, SID)]["root_id"], what="adopted") + self.assertEqual(got, echo.id) + self.assertEqual(h.http.messages_to(MID, SID), [], "its echo is not a line for the Agent") + owner = h.app._owner + self.assertIsNotNone(h.app.store.send_get("workbench:topic:%s:%s:%s@%s" % (DESK, MID, SID, owner)), + "the journal's key is the account's own") + + def test_an_answer_that_did_not_go_out_is_sent_again(self): + h = desk(self) + root = topic(h)["root_id"] + m = say(h, "再看一眼", root=root) + wait_until(lambda: h.http.messages_to(MID, SID), what="handed over") + h.world.send_fail_always = "rejected" + h.http.add(SID, "assistant", "text", "看过了,没问题") + h.http.end_turn(SID) + wait_until(lambda: (h.app.store.wb_turn(DESK, m.id) or {}).get("data", {}).get("post_tries"), + what="the first try failed") + h.world.send_fail_always = None + reply = wait_until(lambda: [s for s in sent_in(h, root) if "看过了,没问题" in s["text"]], what="sent again") + self.assertEqual(len(reply), 1) + wait_until(lambda: h.app.store.wb_turn(DESK, m.id)["state"] == "posted", what="posted") + wait_until(lambda: (DESK, m.id, "DONE") in h.world.reactions, what="the done mark") + + def test_a_take_back_that_failed_is_tried_again(self): + h = desk(self, workbench_asks=True) + topic(h) + h.http.interactions = [AsksTest.question(None)] + ask = wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q"), what="the question") + h.world.recall_fail = h.world.edit_fail = True + h.http.history.append({"interaction": AsksTest.question(None), "status": "resolved"}) + h.http.interactions = [] + wait_until(lambda: (h.app.store.wb_ask(DESK, "ix-q")["data"] or {}).get("tries"), what="a failed try") + self.assertEqual(h.app.store.wb_ask(DESK, "ix-q")["state"], "open") + h.world.recall_fail = h.world.edit_fail = False + wait_until(lambda: (DESK, ask["message_id"]) in h.world.recalls, what="taken back at last") + wait_until(lambda: h.app.store.wb_ask(DESK, "ix-q")["state"] == "recalled", what="marked") + + def test_a_reply_answers_the_question_it_quotes(self): + h = desk(self, workbench_asks=True) + root = topic(h)["root_id"] + first = AsksTest.question(None, id="ix-1") + h.http.interactions = [first] + a1 = wait_until(lambda: h.app.store.wb_ask(DESK, "ix-1"), what="the first question") + second = AsksTest.question(None, id="ix-2", created_at=iso(1)) + h.http.interactions = [first, second] + wait_until(lambda: h.app.store.wb_ask(DESK, "ix-2"), what="the second question") + h.world.push(DESK, "me", "1", root_id=root, parent_id=a1["message_id"], placement="thread") + ans = wait_until(lambda: h.http.answers, what="answered") + self.assertEqual(ans[0]["id"], "ix-1", "the one quoted, not the newest") + + +if __name__ == "__main__": + unittest.main()