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
11 changes: 7 additions & 4 deletions core/openmate_core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2199,16 +2199,18 @@ def _reply_tool(self, request: str, text: str, progress: bool = False, image: st
self.store.run_put(cur)
if cur.get("progress_id") and cur.get("kind") != "doc":
self._progress_done(cur)
note = self._send_image(cur, pic) if pic is not None else ""
note = self._send_image(cur, pic, named_key) if pic is not None else ""
return "已回复到%s(消息 id=%s)%s" % (self.app.platform.name, sent_id or "未知", note)

def _send_image(self, run: dict, pic: tuple) -> str:
def _send_image(self, run: dict, pic: tuple, reply_key: str = "") -> str:
"""The answer's picture, once (its own key in the send journal: by its bytes), right after the answer's text;
what became of it, for the Agent (kept with the run: the same answer asked again tells it again). Its failure
leaves the answer as it is (one reply: never tried again). A /stop that landed first keeps it from going: the
run's lock orders the two (a /stop after it began is like one after the text began)."""
path, sha, name = pic
key = "agent:%s:image:%s" % (run["id"], sha[:32])
# keyed by its reply (the request it names and its text) and its bytes: that reply asked again sends it never a
# second time, wherever the reply went; another reply's picture is its own
key = ("%s:image:%s" % (reply_key, sha[:32])) if reply_key else "agent:%s:image:%s" % (run["id"], sha[:32])
with self._lock(run["id"]):
cur = self.store.run_get(run["id"])
if cur is None:
Expand All @@ -2222,7 +2224,8 @@ def _send_image(self, run: dict, pic: tuple) -> str:

def go() -> dict:
self._still_ours(run)
mid = self.app.send_image_as_user(run["chat_id"], path)
w = self._where(run) # where its text went (a backend that cannot place a picture: into the chat)
mid = self.app.send_image_as_user(run["chat_id"], path, w["reply_to"], w["root"], w["to_chat"])
chat = self.store.get_chat(run["chat_id"])
self.app.record_sent(run["chat_id"], "[图片] %s" % name, str(mid or ""),
session_id=run.get("session_id") or "", machine_id=run.get("machine_id") or "",
Expand Down
95 changes: 91 additions & 4 deletions core/openmate_core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ def __init__(self, platform: Platform, timing: Optional[Timing] = None, backend_
self.agent: Optional[AgentRunner] = None
self.channel: Optional[ChannelBridge] = None # Persona's 渠道 (channel.py), made at the start with the agent
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)
self._methods = {
"status": self.m_status,
"tools.list": lambda p: {"tools": toolmod.read_tools(self)},
Expand All @@ -186,6 +188,7 @@ def __init__(self, platform: Platform, timing: Optional[Timing] = None, backend_
self.today_api = None # todayapi.TodayAPI, for a platform with today_api_callers and a socket from the host
self.connector_on = True # initialize's active.connectors names this connector (off: no link, no /agent)
self.hub_role = "center" # "member": another hub is primary, the chat-driven work (/agent, 代答) is its own
self.hub_capabilities: frozenset = frozenset() # initialize's hub.capabilities

# ------------------------------------------------------------------ the protocol

Expand Down Expand Up @@ -260,6 +263,8 @@ def _initialize(self, params: dict) -> dict:
# its own is: no "connectors" key is this connector off. Only an older hub sends no active (on).
self.connector_on = self.cid in [str(c) for c in active.get("connectors") or []]
self.hub_role = str(hub.get("role") or "center")
caps = hub.get("capabilities") # what this hub can do (tool_images: pictures in a tool's answer)
self.hub_capabilities = frozenset(str(c) for c in caps) if isinstance(caps, list) else frozenset()
self.initialized = True
self._start_today_api() # /health answers from now on: the host checks it as soon as this returns
out = {"protocol": PROTOCOL, "id": self.manifest["id"], "version": self.manifest["version"]}
Expand Down Expand Up @@ -1617,18 +1622,32 @@ def send_as_user(self, chat_id: str, text: str, reply_to: Optional[str] = None,
self.channel.outgoing(chat_id, text, str(mid or "")) # known by its id from now on
return mid

def send_image_as_user(self, chat_id: str, path: str) -> str:
"""A picture (an /agent reply's, checked and copied by images.take) into the chat as the user."""
def send_image_as_user(self, chat_id: str, path: str, reply_to: str = "", root: str = "",
to_chat: bool = False) -> str:
"""A picture (checked and copied by images.take) into the chat as the user; where its text went (reply_to,
root) when the backend can place a picture so (image_threads), else into the chat."""
if not self.signed_in:
raise SendRejected("还没有登录%s" % self.platform.name)
self._not_handing_off()
if self.link == "expired":
raise SendRejected("%s登录已失效,请重新扫码登录" % self.platform.name)
if not getattr(self.backend, "can_send_images", False):
raise SendRejected("%s这里现在不能发图片" % self.platform.name)
mid = self.backend.send_image(chat_id, path)
if self.channel is not None:
self.channel.outgoing(chat_id, "", str(mid or "")) # its echo in the 渠道's chat is no line of the user's
# its echo in the 渠道's chat (it may come before its id is known) is no line of the user's
self.channel.outgoing(chat_id, "", picture=True)
try:
if (reply_to or root) and getattr(self.backend, "image_threads", False):
mid = self.backend.send_image(chat_id, path, reply_to=reply_to or None, root=root or None,
to_chat=bool(to_chat))
else:
mid = self.backend.send_image(chat_id, path)
except SendRejected:
if self.channel is not None:
self.channel.outgoing(chat_id, "", failed=True, picture=True) # surely not sent: no picture stands
raise
if self.channel is not None:
self.channel.outgoing(chat_id, "", str(mid or ""), picture=True) # known by its id from now on
return mid

# ------------------------------------------------------------------ inbox
Expand All @@ -1646,8 +1665,70 @@ def m_inbox_collect(self, params: dict) -> dict:
can_reply=self.signed_in)
if thing is not None:
things.append(thing)
if things and self.backend is not None and getattr(self.backend, "has_avatars", False):
known = self.store.avatars(th["thread"] for th in things)
for th in things:
value = known.get(th["thread"], ("", 0.0))[0]
if value:
th["avatar"] = value
now = time.time()
self._ask_avatars([th["thread"] for th in things
if th["thread"] not in known or known[th["thread"]][1] < now - t.avatar_ttl])
return {"things": things}

def _ask_avatars(self, chat_ids: List[str]) -> None:
"""Ask the service, in the background, for the pictures of these chats (none, or a day old), each at most once
per avatar_retry; when one changed, the Inbox is told (connector.changed) to read the rows again."""
t = self.timing
now = time.monotonic()
with self.lock:
if not chat_ids or self._avatars_by is not None or not self.signed_in or self.link != "up":
return
due = [c for c in chat_ids if self._avatars_tried.get(c, -1e18) <= now - t.avatar_retry][:t.avatar_batch]
if not due:
return
for c in due:
self._avatars_tried[c] = now
if len(self._avatars_tried) > 4 * t.inbox_most: # the ones asked about longest ago go first
for c, _ in sorted(self._avatars_tried.items(), key=lambda kv: kv[1])[:len(self._avatars_tried) // 2]:
del self._avatars_tried[c]
epoch = self.account_epoch()
self._avatars_by = threading.Thread(target=self._avatars_round, args=(due, epoch), name="openmate-avatars",
daemon=True)
self._avatars_by.start()

def _avatars_round(self, due: List[str], epoch: int) -> None:
changed = False
try:
before = self.store.avatars(due)
for chat_id in due:
if self.closing.is_set() or not self.owns(epoch):
return
try:
fresh = getattr(self.backend, "chat_picture", None) # the service asked now, not a kept row
info = fresh(chat_id) if callable(fresh) else self.backend.chat_info(chat_id)
except BackendError as e:
log.info("a chat's picture was not read: %s", e.kind)
continue
except Exception:
log.exception("chat_info failed (a chat's picture)")
continue
if getattr(info, "avatar", None) is None or info.id != chat_id:
continue
with self.owned(epoch) as ok: # another account's sign-in meanwhile: its store is not written
if not ok:
return
if self.store.get_chat(chat_id) is None:
continue # (gone meanwhile: nothing to draw it for)
self.store.set_avatar(chat_id, info.avatar) # only the picture: the rest is the chat's own
if info.avatar != before.get(chat_id, ("", 0.0))[0]:
changed = True
finally:
with self.lock:
self._avatars_by = None
if changed and self.changed is not None:
self.changed.mark("inbox")

def m_inbox_reply(self, params: dict) -> dict:
if params.get("changes"):
raise RPCError("%s会话不支持修改状态,只能回复文字" % self.platform.name)
Expand Down Expand Up @@ -1756,6 +1837,12 @@ def m_thread_page(self, params: dict) -> dict:
}
if chat.get("members"):
page["chat"]["members"] = int(chat["members"])
if getattr(self.backend, "has_avatars", False):
known = self.store.avatars([chat_id]).get(chat_id)
if known is not None and known[0]:
page["chat"]["avatar"] = known[0]
if known is None or known[1] < time.time() - self.timing.avatar_ttl:
self._ask_avatars([chat_id]) # (a chat outside the Inbox's days too: in the background)
if rows and not (len(rows) < limit and at_start):
page["before"] = str(min(r["position"] for r in rows))
if epoch != self.account_epoch():
Expand Down
15 changes: 14 additions & 1 deletion core/openmate_core/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ class Chat:
topic: bool = False
members: int = 0
muted: bool = False
#: the chat's picture for Persona's Inbox (InboxThing.avatar, #10923): an https address that always names the same
#: bytes (a changed picture gets a new one), the other person's in a dm, the group's own in a group. "" when the
#: service says there is none, None when this Chat does not say (a backend without has_avatars, a list's row)
avatar: Optional[str] = None


@dataclass
Expand Down Expand Up @@ -408,13 +412,22 @@ def send(self, chat_id: str, text: str, reply_to: Optional[str] = None, root: Op
def create_chat(self, user_id: str) -> str:
"""The direct chat with a person (created when there is none yet, without sending anything); its chat id."""

#: Whether chat_info's Chat says the chat's picture (Chat.avatar): the core then asks it for the chats in the Inbox
#: that have none yet, or whose picture is a day old
has_avatars: bool = False

#: Whether send_image works now (an /agent reply may carry a picture then; the tool offers it only then)
can_send_images: bool = False

#: Whether send_image also takes reply_to, root and to_chat (the place send gives a text with them: a thread, a
#: quote, a thread and the chat); the core passes them only then
image_threads: bool = False

def send_image(self, chat_id: str, path: str) -> str:
"""Send the picture at path (a PNG or JPEG of at most 10 MB the core checked and copied into the extension's
data) into chat_id as the account; the new message's id. Raise SendRejected only when it surely did not go
out; BackendError for an unknown outcome (never sent again)."""
out; BackendError for an unknown outcome (never sent again). A backend with image_threads also takes
reply_to and root, as send does."""
raise BackendError("这个平台不支持发图片", "unsupported")

def close(self) -> None:
Expand Down
Loading
Loading