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
111 changes: 105 additions & 6 deletions core/openmate_core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
and answers with <connector>_agent_reply, bound to this request by its id. A request in the thread of an earlier one
goes on in that conversation. If the turn ends without a reply through the tool, the latest answer is posted once
instead (never both). A turn ends at its turn_duration item; Claude Code does not always write one, so a session that
answered and then stayed quiet for `agent_settle` has ended its turn too when its status says done or idle. /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.
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
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
it) goes straight to that Agent (`agent_forward`, on by default): the thread is told it was handed on, and the task's
Expand Down Expand Up @@ -50,6 +53,7 @@
from .wire import RPCError

START_REPLAY_MOST = 25 * 86400.0 # a start older than this is not asked again (the hub keeps receipts 30 days)
CARD_SKEW = 30.0 # a card raised this long before its request (the hub's clock against this one's) is still the request's
CHECK = "请先在 Persona 里看看有没有新开的会话;没有的话再重新发送。"

log = logging.getLogger("openmate.agent")
Expand Down Expand Up @@ -384,6 +388,7 @@ def __init__(self, app):
self._own: Dict[tuple, List[float]] = {} # a tool's formatted sends (own_send): their echoes are none either
self._own_gen = 0 # one more at each forget: a send's end from the account before is none of the next one's
self._asked: Dict[str, float] = {} # run id → when its session's status was last asked
self._held_read: Dict[str, float] = {} # run id → when the conversation of a run held for a card was last read
self._handing: Dict[str, tuple] = {} # run id → (chat, thread, asked at) of a follow-up being handed to an Agent
self._handed = threading.Condition(self._mu)

Expand Down Expand Up @@ -2772,9 +2777,23 @@ def _transcript(self, mid: str, sid: str, after: int, deadline: Optional[float]
return items, after

def _poll(self, run: dict) -> None:
t = self.app.timing
now = time.time()
send_until = run.get("send_wait_until") or 0
if not send_until and time.time() - (run.get("reconciled_at") or run["created"]) > self.app.timing.agent_timeout:
self._timeout(run["id"])
held = float(run.get("card_hold") or 0) # its turn ended on a card that waits for the owner (_turn_ended)
if held:
if now - held > t.agent_approval_wait:
self._timeout(run["id"])
return
with self._mu:
if now - self._held_read.get(run["id"], 0.0) < t.agent_hold_poll:
return # nothing goes on before the card's outcome starts the next turn: read now and then
self._held_read[run["id"]] = now
for k in [k for k, at in self._held_read.items() if now - at > 3600]:
del self._held_read[k]
elif not send_until and now - max(float(run.get("reconciled_at") or run["created"]),
float(run.get("card_resumed") or 0)) > t.agent_timeout:
self._timeout(run["id"]) # (the turn after a card's outcome has its own agent_timeout)
return
mid, sid = run["machine_id"], run["session_id"]
try:
Expand Down Expand Up @@ -2803,8 +2822,17 @@ def _poll(self, run: dict) -> None:
log.info("/agent send reconciliation %s: found", cur["id"])
continue
kind, role = it.get("kind") or "", it.get("role") or ""
if cur.pop("card_unsure", None):
# the conversation went on before the hub said whether a card waited when that turn ended
# (a card's outcome, say): its words are not posted; the turn now under way ends as usual
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 role == "assistant":
answered = True
if cur.get("card_hold"): # the next turn (the card's outcome came): its end is the answer's
cur["card_hold"], cur["card_resumed"] = 0, time.time()
log.info("/agent %s: the conversation goes on after the card it waited on", cur["id"])
if role == "assistant" and kind == "text" and (it.get("text") or "").strip():
last_text = {"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"):
Expand All @@ -2822,6 +2850,8 @@ def _poll(self, run: dict) -> None:
if send_until and not run.get("ours_seen") and time.time() >= send_until:
self._send_unseen(run)
return
if not ended and not interrupted and run.get("card_unsure"):
ended = True # its turn ended when the hub could not say whether a card waits there: asked again
if not ended and not interrupted and self._settled(run):
ended = True
if interrupted:
Expand Down Expand Up @@ -2945,14 +2975,80 @@ def _end_awaiting(self, run_id: str, outcome: str = "done") -> None:
cur["awaiting"] = ""
self.store.run_put(cur)

@staticmethod
def _unanswered(run: dict) -> bool:
"""Nothing answered the request yet: its turn's end would post the turn's last words as the answer."""
return run.get("kind") not in QUIET_KINDS and not int(run.get("replies") or 0) \
and not int(run.get("reply_inflight") or 0) and not run.get("fallback")

def _card_waits(self, run: dict, last: bool = False) -> Optional[bool]:
"""Whether a card raised for this request in its conversation still waits for the owner; None when the hub
cannot say now. Such a card is a command Persona holds for the owner's approval (or a question): when nobody
answered it in time, Persona gives the tool call a non-final result ("The owner has not answered this approval
yet … End this turn now … A later message will report its outcome"), keeps the card waiting (24 h) and tells
the conversation its outcome in a later message, which starts the next turn. So a turn that ends meanwhile has
no answer in its last words. The session's row counts the cards waiting there (pending_interactions); the cards
the hub shows say whether one was raised since this request was asked (an earlier request's card still waiting
is not this one's). One the hub does not show extensions (a private card) may be this one's: it counts.
last: the hub could not say for agent_hub_wait already; a read that fails now is taken as its answer was."""
mid, sid = run.get("machine_id") or "", run.get("session_id") or ""
if not (mid and sid and self.hub.available):
return False
try:
row = self.hub.session_row(mid, sid) or {}
except HubError as e:
return self._card_unknown(e, False, last) # no row: as before, the last words are the answer
n = int(row.get("pending_interactions") or 0)
if n <= 0 and row.get("state") != "needs_you":
return False
try:
cards = [i for i in self.hub.pending_interactions()
if i.get("machine_id") == mid and i.get("session_id") == sid]
except HubError as e:
return self._card_unknown(e, n > 0, last) # a card waits there, whose cannot be told
since = float(run.get("created") or 0) - CARD_SKEW
if any(not hub_time(i.get("created_at")) or hub_time(i.get("created_at")) >= since for i in cards):
return True # (one with no time known: taken as this request's)
return len(cards) < n

@staticmethod
def _card_unknown(e: HubError, refused: bool, last: bool) -> Optional[bool]:
"""_card_waits when a read failed: asked again at the next read (None), unless the hub refuses it for good
(403, 404: no such route or scope) or could not say for agent_hub_wait already (last): then `refused`."""
log.info("/agent: whether a card waits in the conversation could not be read (%s)", e.code or e.status)
return refused if last or e.status in (403, 404) else None

def _turn_ended(self, run_id: str) -> None:
first = self.store.run_get(run_id)
# (the hub asked before the run's lock is taken: its answer may take a while)
tasks = self._open_tasks(first) if first is not None and self._may_await(first) else "none"
card: Optional[bool] = False
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"
with self._lock(run_id):
cur = self.store.run_get(run_id)
if cur is None or cur["state"] != "running":
return
if card is not False and self._unanswered(cur):
if card is None:
# whether its last words are an answer cannot be told now: nothing is posted, asked again (at
# most agent_hub_wait), unless the conversation goes on meanwhile (_poll)
cur["card_unsure"] = True
cur.setdefault("card_unsure_since", time.time())
else:
# a card it raised waits for the owner: its last words only say so. Nothing is posted and nothing
# takes the one reply; the turn after the card's outcome (approved, denied, expired) answers it,
# through the tool or its last words, as usual. Its 🤔 stays meanwhile
cur.pop("card_unsure", None)
cur.pop("card_unsure_since", None)
cur["card_hold"], cur["answered"], cur["last_text"] = time.time(), False, None
log.info("/agent %s: the turn ended while a card it raised waits for the owner: no answer yet",
run_id)
self.store.run_put(cur)
return
cur.pop("card_unsure", None)
cur.pop("card_unsure_since", None)
post = None
awaiting = tasks != "none" and self._may_await(cur)
if awaiting:
Expand Down Expand Up @@ -3044,8 +3140,11 @@ def _timeout(self, run_id: str) -> None:
self.store.run_put(cur)
self._end_reaction(run_id, "failed")
if notice:
t = self.app.timing
waited = ("要你处理的卡片等了 %s" % _span(t.agent_approval_wait)) if cur.get("card_hold") \
else ("等了 %s" % _span(t.agent_timeout))
mid = self._post_once(cur, "agent:%s:timeout" % run_id,
"等了 %s 还没有结果,不再等待。可以在 Persona 里打开这个会话看进度。" % _span(self.app.timing.agent_timeout),
"%s还没有结果,不再等待。可以在 Persona 里打开这个会话看进度。" % waited,
**self._where(cur))
with self._lock(run_id):
cur = self.store.run_get(run_id)
Expand Down
4 changes: 4 additions & 0 deletions core/openmate_core/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,8 @@ class Timing:
agent_task_wait_most: float = 86400.0 # a request waiting on its to-dos (agent_task_wait) times out this late…
agent_task_recheck: float = 60.0 # …and asks the hub about them at most this often
mute_batch: int = 10 # …at most this many groups per round, in the background (an Inbox read never waits for it)
# A request whose turn ended while a card it raised waits for the owner (Persona's approval cards stay 24 h after
# the tool call gave up waiting, then say they expired) waits this long for the turn after the card's outcome…
agent_approval_wait: float = 25 * 3600.0
agent_hold_poll: float = 30.0 # …and its conversation is read this often meanwhile
extra: Dict[str, float] = field(default_factory=dict)
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.81",
"version": "0.11.82",
"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.76",
"version": "0.1.77",
"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.81",
"version": "0.11.82",
"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.81/openmate-feishu-0.11.81.tar.gz",
"sha256": "851f0d2b8803408bda48551e38d699c766aa6fc74bc1408fa7d18738dec1d8c6",
"size": 419375
"url": "packages/openmate-feishu/0.11.82/openmate-feishu-0.11.82.tar.gz",
"sha256": "226c6e064c8caae7b1d60410119472939d14253a8b6f934fe33dc649389b4302",
"size": 421476
}
]
},
Expand All @@ -551,7 +551,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
"version": "0.1.76",
"version": "0.1.77",
"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.76/openmate-wechat-0.1.76.tar.gz",
"sha256": "832c3d2ed643afe6ec7ca291cdd311570db763a72f0ebc5b020a333f96629807",
"size": 318320
"url": "packages/openmate-wechat/0.1.77/openmate-wechat-0.1.77.tar.gz",
"sha256": "871d635387716cdb1dbb69c38d80600ea2de758bf7b65815fbe04d64556e56c1",
"size": 320434
}
]
}
Expand Down
2 changes: 2 additions & 0 deletions tests/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,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 "agent_hold_poll" in Timing.__dataclass_fields__: # a run held for a card (older code has none)
base.update(agent_hold_poll=0.05)
base.update(kw)
return Timing(**base)

Expand Down
Loading
Loading