Skip to content
Open
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
65 changes: 63 additions & 2 deletions 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,7 +3036,12 @@ 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)
tasks = self._open_tasks(first) if card is False and first is not None and self._may_await(first) else "none"
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)
if cur is None or cur["state"] != "running":
Expand Down Expand Up @@ -4040,3 +4056,48 @@ 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 older wording): parseLegacyApprovalResult
# (server/internal/prompts/approval_result.go, same commit)
_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."""
if it.get("role") != "user" or it.get("kind") != "text":
return False
inj = it.get("injected")
if isinstance(inj, dict) and inj:
return inj.get("kind") == "system" and str(inj.get("state") or "").startswith("approval_")
text = (it.get("text") or "").lstrip()
return text.startswith("<persona-approval-result>") or bool(_CARD_OUTCOME.match(text))
218 changes: 218 additions & 0 deletions tests/test_agent_approval.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,225 @@ def test_a_hub_that_never_lists_the_cards_holds_while_the_row_counts_one(self):
self.assertTrue(h.sent()[-1]["text"].startswith("写好了。"))


def marked_outcome(h, run, word, ix="ix-approval-1"):
"""The card's outcome as the hub hands it out: Persona's marker on its first line (prompts.ApprovalResultMarker)
and the hub's mark on the item (hub.withInjected). It starts the next turn."""
sid = run["session_id"]
head = ('<persona-approval-result>{"id":"%s","status":"%s","kind":"approval","summary":"Bash"}'
'</persona-approval-result>' % (ix, word))
with h.http.lock:
h.http.sessions[sid]["working"] = True
h.http.add(sid, "user", "text", head + "\nApproval %s is %s and is no longer pending." % (ix, word),
injected={"kind": "system", "state": "approval_" + word, "line": "审批结果:" + word})


def held(h, run):
return wait_until(lambda: (lambda r: r if r.get("card_hold") else None)(h.app.store.run_get(run["id"])),
what="the run held for the card's outcome")


class AnsweredAsTheTurnEndsTest(unittest.TestCase):
"""The owner answers the card after Persona let its tool call go and before the extension reads the end of the
turn (a review of PR #67, P1): no card waits by then, yet its outcome is still to come, queued behind the turn,
and starts the next one. The turn's words only said the card waits: nothing is posted, the one reply stays free,
and the next turn answers."""

def setUp(self):
self.tmp = os.path.realpath(tempfile.mkdtemp(prefix="openmate-card-test-"))
self.addCleanup(shutil.rmtree, self.tmp, True)

@staticmethod
def raced(h, run, result=WAITING, outcome=None, **kw):
"""In one read: the tool call let go while its card waits, the words about it, the owner's answer, the end of
the turn (and, with `outcome`, the outcome's message right after it)."""
sid = run["session_id"]
with h.http.lock:
h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1")
CardTest.raise_card(h, run)
h.http.add(sid, "user", "tool_result", result, tool_use_id="toolu_1", **kw)
h.http.add(sid, "assistant", "text", STUCK)
CardTest.end_card(h, run) # answered now: no card waits when the extension reads the end of the turn
h.http.end_turn(sid)
if outcome:
marked_outcome(h, run, outcome)

def test_approved_then_the_answer_with_its_picture_goes(self):
h = wechat(self)
h.world.images_ok = True
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面,然后截图"))
sid = run["session_id"]
n = len(h.sent())
self.raced(h, run)
cur = held(h, run)
time.sleep(0.3)
self.assertEqual(len(h.sent()), n, "the words about the card are no answer: nothing posted")
cur = h.app.store.run_get(run["id"])
self.assertEqual(cur["state"], "running")
self.assertFalse(cur.get("fallback"), "the one reply is not taken")
self.assertTrue(cur.get("card_owed"))
marked_outcome(h, run, "approved")
h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_2")
h.http.add(sid, "user", "tool_result", "ok", tool_use_id="toolu_2")
out = h.tool("agent_reply", request=run["id"], text="接龙 25 人已写进成员名录,见截图。",
image=CardTest.picture(self))
self.assertIn("图片也发出了", out)
self.assertEqual(len(h.world.images), 1)
h.http.add(sid, "assistant", "text", "已回复。")
h.http.end_turn(sid)
wait_until(lambda: h.app.store.run_get(run["id"])["state"] == "done", what="done")
time.sleep(0.2)
texts = [s["text"] for s in h.sent()[n:]]
self.assertEqual(len(texts), 1, texts)
self.assertTrue(texts[0].startswith("接龙 25 人已写进成员名录,见截图。"), texts)
self.assertNotIn("还卡在审批卡上", "".join(texts))
self.assertFalse(h.app.store.run_get(run["id"]).get("card_owed"))

def test_denied_or_expired_the_next_turn_answers_once(self):
for word, last in (("denied", "审批被拒了:没有登录公会站,也没写入任何数据。"),
("expired", "审批卡过期了:没有登录公会站,也没写入任何数据。要做的话请再发一次。")):
with self.subTest(word):
h = wechat(self)
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面"))
sid = run["session_id"]
n = len(h.sent())
self.raced(h, run)
held(h, run)
time.sleep(0.2)
self.assertEqual(len(h.sent()), n)
marked_outcome(h, run, word)
h.http.add(sid, "assistant", "text", last)
h.http.end_turn(sid)
wait_until(lambda: len(h.sent()) > n, what="the answer")
time.sleep(0.3)
texts = [s["text"] for s in h.sent()[n:]]
self.assertEqual(len(texts), 1, texts)
self.assertTrue(texts[0].startswith(last), texts)
cur = h.app.store.run_get(run["id"])
self.assertEqual((cur["state"], cur["fallback"]), ("done", "sent"))

def test_the_outcome_read_together_with_the_end_of_the_turn(self):
"""The outcome's message already follows the end of the turn when the extension reads it: the turn under way
is the outcome's, and its end answers."""
h = wechat(self)
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面"))
sid = run["session_id"]
n = len(h.sent())
self.raced(h, run, outcome="approved")
wait_until(lambda: h.app.store.run_get(run["id"])["last_seq"] >= h.http.sessions[sid]["items"][-1]["seq"],
what="read")
time.sleep(0.3)
self.assertEqual(len(h.sent()), n)
cur = h.app.store.run_get(run["id"])
self.assertEqual(cur["state"], "running")
self.assertFalse(cur.get("last_text"), "the words before the outcome are not kept to be posted")
self.assertFalse(cur.get("card_owed"))
h.http.add(sid, "assistant", "text", "开始写名单……")
time.sleep(0.3)
self.assertEqual(len(h.sent()), n, "nor the next turn's half-written words")
h.http.add(sid, "assistant", "text", "写好了:接龙 25 人已在成员名录里。")
h.http.end_turn(sid)
wait_until(lambda: len(h.sent()) > n, what="the answer")
time.sleep(0.2)
texts = [s["text"] for s in h.sent()[n:]]
self.assertEqual(len(texts), 1, texts)
self.assertTrue(texts[0].startswith("写好了:接龙 25 人已在成员名录里。"), texts)

def test_a_hook_error_around_the_words_too(self):
"""A PreToolUse hook's error that wraps Persona's words (Persona's nonFinalApprovalResult takes it so)."""
h = wechat(self)
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面"))
sid = run["session_id"]
n = len(h.sent())
self.raced(h, run, result="PreToolUse:Bash hook error: " + WAITING, is_error=True)
held(h, run)
time.sleep(0.2)
self.assertEqual(len(h.sent()), n)
marked_outcome(h, run, "approved")
h.http.add(sid, "assistant", "text", "写好了。")
h.http.end_turn(sid)
wait_until(lambda: len(h.sent()) > n, what="the answer")
self.assertTrue(h.sent()[-1]["text"].startswith("写好了。"))

def test_the_hub_cannot_say_for_long_the_outcome_still_owed_holds(self):
"""The session's row cannot be read for agent_hub_wait: no card is known to wait, but the outcome is owed."""
from unittest.mock import patch

from openmate_core.hub import HubError

h = _wechat_with(self, fast(agent_hub_wait=0.5))
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面"))
sid = run["session_id"]
n = len(h.sent())
with patch.object(h.app.hub, "session_row", side_effect=HubError(503, "busy")):
self.raced(h, run)
wait_until(lambda: h.app.store.run_get(run["id"]).get("card_unsure"), what="put off")
held(h, run)
time.sleep(0.2)
self.assertEqual(len(h.sent()), n)
marked_outcome(h, run, "approved")
h.http.add(sid, "assistant", "text", "写好了。")
h.http.end_turn(sid)
wait_until(lambda: len(h.sent()) > n, what="the answer")
self.assertTrue(h.sent()[-1]["text"].startswith("写好了。"))

def test_feishu_held_too_then_answered_through_the_tool(self):
h = agent(self)
run = running(h, ask(h, "/agent 把名单写进成员页"))
sid = run["session_id"]
self.raced(h, run)
held(h, run)
time.sleep(0.3)
self.assertEqual(answers(h), [], "no answer posted")
self.assertFalse(any("还卡在审批卡上" in s["text"] for s in h.sent()))
marked_outcome(h, run, "approved")
h.tool("agent_reply", request=run["id"], text="名单写好了。")
h.http.add(sid, "assistant", "text", "已回复")
h.http.end_turn(sid)
wait_until(lambda: h.app.store.run_get(run["id"])["state"] == "done", what="done")
time.sleep(0.2)
self.assertEqual([s["text"] for s in answers(h)], ["名单写好了。\n\n" + SUFFIX])


class UnchangedTest(unittest.TestCase):
def test_a_card_approved_within_its_first_wait_is_no_hold(self):
"""Approved while its tool call still waited: the call has its real result, no outcome message is owed, and
the turn's last words are the answer as before."""
h = wechat(self)
run = running(h, ask(h, "/agent 把接龙成员写到群公告的成员里面"))
sid = run["session_id"]
n = len(h.sent())
with h.http.lock:
h.http.add(sid, "assistant", "tool_use", tool_name="Bash", tool_use_id="toolu_1")
CardTest.raise_card(h, run)
CardTest.end_card(h, run)
h.http.add(sid, "user", "tool_result", "群公告已更新", tool_use_id="toolu_1")
h.http.add(sid, "assistant", "text", "写好了:接龙 25 人已在成员名录里。")
h.http.end_turn(sid)
wait_until(lambda: len(h.sent()) > n, what="the fallback")
time.sleep(0.2)
texts = [s["text"] for s in h.sent()[n:]]
self.assertEqual(len(texts), 1, texts)
self.assertTrue(texts[0].startswith("写好了:接龙 25 人已在成员名录里。"))
cur = h.app.store.run_get(run["id"])
self.assertFalse(cur.get("card_hold") or cur.get("card_owed"))

def test_an_earlier_requests_outcome_does_not_drop_this_answer(self):
"""The outcome of a card an earlier request waited on comes after this request's turn: this one owes none, so
its last words are its answer as before."""
h = wechat(self)
run = running(h, ask(h, "/agent 总结一下"))
sid = run["session_id"]
n = len(h.sent())
with h.http.lock:
h.http.add(sid, "assistant", "text", "总结:周五前更新接口文档。")
h.http.end_turn(sid)
marked_outcome(h, run, "approved", "ix-old")
wait_until(lambda: len(h.sent()) > n, what="the fallback")
time.sleep(0.2)
texts = [s["text"] for s in h.sent()[n:]]
self.assertEqual(len(texts), 1, texts)
self.assertTrue(texts[0].startswith("总结:周五前更新接口文档。"))

def test_no_card_the_last_words_are_the_answer_as_before(self):
h = wechat(self)
run = running(h, ask(h, "/agent 总结一下"))
Expand Down
Loading