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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion core/openmate_core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
answered and then stayed quiet for `agent_settle` has ended its turn too when its status says done or idle. A turn that
ends while a card the request raised waits for the owner (a command held for approval: Persona tells the tool call to
end the turn, and the card's outcome later starts the next one) answers nothing: nothing is posted, the one reply stays
free, and the turn after the outcome answers as usual (_card_waits). /stop, /停止 or /停 in the thread (or quoting the
free, and the turn after the outcome answers as usual (_card_waits; a card answered just before the turn ended still
owes that outcome, which the tool call's result says: card_owed). /stop, /停止 or /停 in the thread (or quoting the
request) stops it. Runs are kept in the store, so a restart goes on waiting for the running ones.

A follow-up in a thread whose conversation handed its work to a task (a to-do it opened, still open, with an Agent on
Expand Down Expand Up @@ -2828,6 +2829,16 @@ def _poll(self, run: dict) -> None:
cur.pop("card_unsure_since", None)
last_text = None
log.info("/agent %s: the conversation went on while its turn's end was put off", cur["id"])
if _card_left_waiting(it):
# Persona let a tool call of this request go while its card waits for the owner: the card's
# outcome is owed, as a later message that starts the turn that answers (_turn_ended)
cur["card_owed"] = time.time()
elif cur.get("card_owed") and _card_outcome(it):
# that message: the words before it only said the card waits, and the turn it starts (still
# under way, though the one before may have ended in this same read) is the one that answers
del cur["card_owed"]
last_text, answered, ended = None, False, False
log.info("/agent %s: the outcome of the card it waited on came", cur["id"])
if role == "assistant":
answered = True
if cur.get("card_hold"): # the next turn (the card's outcome came): its end is the answer's
Expand Down Expand Up @@ -3025,6 +3036,11 @@ def _turn_ended(self, run_id: str) -> None:
if first is not None and self._unanswered(first): # a card waiting comes first: the run is not over
unsure = float(first.get("card_unsure_since") or 0)
card = self._card_waits(first, bool(unsure) and time.time() - unsure > self.app.timing.agent_hub_wait)
if card is False and first.get("card_owed"):
# no card waits now, but one this request's tool call was let go for has not told its outcome: the
# owner answered it after that (before or as the turn ended); the outcome waits for this turn's end,
# then starts the next turn, which answers
card = True
tasks = self._open_tasks(first) if card is False and first is not None and self._may_await(first) else "none"
with self._lock(run_id):
cur = self.store.run_get(run_id)
Expand Down Expand Up @@ -4040,3 +4056,59 @@ def _item_time(it: dict) -> float:
def _interrupted(text: str) -> bool:
"""The notice Persona's transcript writes for a stopped turn (transcript.InterruptedNotice)."""
return (text or "").strip() == "已中断"


# What Persona gives a tool call its approval card holds when the card outlives the call: the card stays waiting for the
# owner, and a later message tells the conversation its outcome. Persona's approval.WaitingText and
# approval.ClarifyingText (github.com/nwverse/persona, server/internal/approval/approval.go, commit 926e3861a5).
_CARD_WAITING = ("The owner has not answered this approval yet. Nothing changed. End this turn now. The card stays "
"pending in the Persona app and web, where the owner can still allow or deny it, even without a "
"notification; do not retry the tool or create another approval. A later message will report its "
"outcome.")
_CARD_CLARIFYING = ("The owner asked a question about this approval. It is not an approval decision and nothing changed. "
"The question arrives as a separate owner message; answer it then. The original approval card "
"remains valid and is still pending; do not retry the tool or create another approval. A later "
"message reports its outcome.")
# The message with a card's outcome when the hub has not marked it: Persona's marker on its first line
# (prompts.ApprovalResultMarker) or its older wording (parseLegacyApprovalResult), server/internal/prompts/
# approval_result.go, same commit
_CARD_MARK = ("<persona-approval-result>", "</persona-approval-result>")
_CARD_OUTCOME = re.compile(r"^Approval [A-Za-z0-9_.:-]+ is (?:[^.\n]+ and is no longer pending\.|no longer pending\. "
r"Its one-time continuation was already consumed or is no longer available\.)(?:\s|$)")


def _card_left_waiting(it: dict) -> bool:
"""A tool call's result that is not its outcome: Persona let the call go while its card still waits, and the card's
outcome comes as a later message. The same test as Persona's nonFinalApprovalResult (server/internal/assistant/
fleet_ix_terminal.go, commit 926e3861a5): the very words, or a PreToolUse hook's error around them."""
if it.get("role") != "user" or it.get("kind") != "tool_result":
return False
text = (it.get("text") or "").strip()
if text.startswith("PreToolUse:"):
i = text.find("hook error:")
if not it.get("is_error") or i < 0:
return False
text = text[i + len("hook error:"):].strip()
return any(text == w or text.startswith(w + " ") for w in (_CARD_WAITING, _CARD_CLARIFYING))


def _card_outcome(it: dict) -> bool:
"""The message Persona sends into a conversation with the outcome of a card that outlived its tool call (approved,
denied, expired…). The hub marks it (prompts.IsApprovalResult: injected, kind system, state approval_*); the text
is read only when it does not: Persona's marker on its first line, or its older wording. A question card's (a
question that a restart cancelled: approval_question_*) is not an approval's."""
if it.get("role") != "user" or it.get("kind") != "text":
return False
inj = it.get("injected")
if isinstance(inj, dict) and inj:
state = str(inj.get("state") or "")
return inj.get("kind") == "system" and state.startswith("approval_") and not state.startswith("approval_question")
text = (it.get("text") or "").lstrip()
head = text.split("\n", 1)[0].strip()
if head.startswith(_CARD_MARK[0]) and head.endswith(_CARD_MARK[1]):
try:
meta = json.loads(head[len(_CARD_MARK[0]):-len(_CARD_MARK[1])])
except ValueError:
return False
return isinstance(meta, dict) and meta.get("kind") == "approval"
return bool(_CARD_OUTCOME.match(text))
2 changes: 1 addition & 1 deletion extensions/openmate-feishu/persona-extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": 1,
"id": "openmate-feishu",
"name": "飞书(OpenMate)",
"version": "0.11.82",
"version": "0.11.83",
"description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down
2 changes: 1 addition & 1 deletion extensions/openmate-wechat/persona-extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
"version": "0.1.77",
"version": "0.1.78",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down
Binary file not shown.
Binary file not shown.
16 changes: 8 additions & 8 deletions persona-extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"manifest_version": 1,
"id": "openmate-feishu",
"name": "飞书(OpenMate)",
"version": "0.11.82",
"version": "0.11.83",
"description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down Expand Up @@ -540,9 +540,9 @@
"icon": "assets/icon.png",
"packages": [
{
"url": "packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz",
"sha256": "226c6e064c8caae7b1d60410119472939d14253a8b6f934fe33dc649389b4302",
"size": 421476
"url": "packages/openmate-feishu/0.11.83/openmate-feishu-0.11.83.tar.gz",
"sha256": "4ed90e9b9d0cd0cd916d854bb8f4bbd8cf7644b09aabc0ffb41ba6bb89b6f3c9",
"size": 423002
}
]
},
Expand All @@ -551,7 +551,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
"version": "0.1.77",
"version": "0.1.78",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down Expand Up @@ -849,9 +849,9 @@
"icon": "assets/icon.png",
"packages": [
{
"url": "packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz",
"sha256": "871d635387716cdb1dbb69c38d80600ea2de758bf7b65815fbe04d64556e56c1",
"size": 320434
"url": "packages/openmate-wechat/0.1.78/openmate-wechat-0.1.78.tar.gz",
"sha256": "edf834f9404f53a2db2dc30e9d53c5c82b436c492dd8ccfc491fe45143d57fa7",
"size": 321965
}
]
}
Expand Down
Loading
Loading