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
165 changes: 149 additions & 16 deletions core/openmate_core/agent.py

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions core/openmate_core/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,25 @@ def start_conversation(self, prompt: str, purpose: str, report_tasks: bool, mach
raise HubError(0, "hub 没有给出会话 id")
return sess

def assistant_machine(self, timeout: float = 10.0) -> str:
"""The computer the assistant runs on (assistant.ask): where a conversation started without a machine goes."""
doc = self.request("GET", "/api/v1/assistant", timeout=timeout)
a = (doc.get("assistant") if isinstance(doc, dict) and isinstance(doc.get("assistant"), dict) else doc) or {}
return str(a.get("machine_id") or "") if isinstance(a, dict) else ""

def machines(self, timeout: float = 10.0) -> List[dict]:
"""The user's computers (machines.read), in their configured order."""
doc = self.request("GET", "/api/v1/machines", timeout=timeout)
items = doc.get("machines") if isinstance(doc, dict) else None
return [m for m in items if isinstance(m, dict) and m.get("id")] if isinstance(items, list) else []

def machine_metrics(self, machine_id: str, timeout: float = 10.0) -> dict:
"""One computer's readings (machines.read): {system: {cores, …}, latest: {t, load, mem_used, mem_total, …}};
the hub leaves `latest` out when no sample arrived in the last 30 seconds."""
doc = self.request("GET", "/api/v1/machines/%s/metrics" % _seg(machine_id), query={"range": "1h"}, timeout=timeout)
m = doc.get("metrics") if isinstance(doc, dict) else None
return m if isinstance(m, dict) else {}

def send_message(self, machine_id: str, session_id: str, text: str, client_msg_id: str = "") -> dict:
body: Dict[str, Any] = {"text": text}
if client_msg_id:
Expand Down
146 changes: 146 additions & 0 deletions core/openmate_core/placement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""Where a new /agent conversation starts when no computer is set (agent_machine empty) and agent_balance is on.

The assistant's own computer stays home: a new conversation starts there, exactly as before (no machine in the start),
unless that computer is busy right now. Then it goes to the least loaded other computer that is online and not busy
itself. Only a NEW conversation is placed: a follow-up goes to its conversation where it runs, and a new conversation
in a thread that already had one starts on that thread's computer again (its files and context are there), as long
as the thread's runs are kept (store.prune_runs: 3 days, 200 runs).

Busy: the 1-minute load is over BUSY_LOAD_PER_CORE times the computer's cores, or less than MIN_FREE_BYTES of memory is
free. Another computer is chosen only with both readings fresh and neither busy; home without any reading stays home.
Nothing here ever stops a start, it only picks where: any error, and a hub too slow (BUDGET), is the old behaviour.
Pictures an Agent leaves are read on the extension's computer, taken to be the assistant's (as before placement): a
conversation placed elsewhere is told it cannot attach one. The launcher Persona gives `/agent` (its "Lark /agent"
setting) has to run on the chosen computer too: the built-in claude does everywhere.
A computer that cannot take an assistant conversation is never chosen: one without Claude Code, or one the list marks
(trust work or pending, an incompatible node); a work computer the list does not mark is not known here: with one,
set agent_machine or switch agent_balance off. A start that still fails there fails as any start does (never started
again elsewhere: an answer may be lost, and the request must not run twice). BUDGET bounds each request's waiting, not
a hub that answers in slow trickles.
"""

from __future__ import annotations

import logging
import time
from typing import List, Optional, Tuple

log = logging.getLogger("openmate.placement")

BUSY_LOAD_PER_CORE = 0.75
MIN_FREE_BYTES = 2 << 30
FRESH_SECONDS = 120.0 # a reading older than this (by its own time) is no reading
BUDGET = 8.0 # seconds placement may take in all: the request waits for it, and a restart meanwhile loses it
ASK_TIMEOUT = 4.0 # one hub request

Reading = Tuple[Optional[float], Optional[int]] # (load per core, free memory bytes); either may be unknown


def reading(metrics: dict, now: Optional[float] = None) -> Optional[Reading]:
"""(load per core, free bytes) from a computer's metrics, either None when not read (Windows sends no load; a Mac
sends its total before its first used-memory reading); None when the computer is offline, the sample is missing
or stale, or neither is known."""
if not isinstance(metrics, dict) or metrics.get("online") is False:
return None
latest, system = metrics.get("latest"), metrics.get("system")
if not isinstance(latest, dict):
return None
try:
t = float(latest.get("t") or 0)
except (TypeError, ValueError):
return None
if t and abs((now or time.time()) - t) > FRESH_SECONDS:
return None
lpc: Optional[float] = None
try:
cores = int((system or {}).get("cores") or 0) if isinstance(system, dict) else 0
load = latest.get("load")
if cores > 0 and load is not None and float(load) >= 0:
lpc = float(load) / cores
except (TypeError, ValueError):
lpc = None
free: Optional[int] = None
try:
total, used = int(latest.get("mem_total") or 0), int(latest.get("mem_used") or 0)
if total > 0 and used > 0:
free = max(0, total - used)
except (TypeError, ValueError):
free = None
if lpc is None and free is None:
return None
return lpc, free


def eligible(machine: dict) -> bool:
"""A listed computer the hub may start an assistant conversation on: with Claude Code (its node reported a
version), and not one it says is a work computer, still pending, or running a node too old for it."""
return (bool(machine.get("claude_version")) and str(machine.get("trust") or "personal") == "personal"
and not machine.get("node_incompatible"))


def busy(r: Reading) -> bool:
lpc, free = r
return (lpc is not None and lpc > BUSY_LOAD_PER_CORE) or (free is not None and free < MIN_FREE_BYTES)


def _words(r: Reading) -> str:
lpc, free = r
return "负载 %s/核,可用内存 %s" % ("%.2f" % lpc if lpc is not None else "未知",
"%.1f GiB" % (free / float(1 << 30)) if free is not None else "未知")


def choose(hub, sticky: str = "", clock=time.monotonic) -> Tuple[str, str]:
"""(machine id to start on, "" for the assistant's own computer as before; why, for the log)."""
deadline = clock() + BUDGET
try:
home = hub.assistant_machine(timeout=ASK_TIMEOUT)
machines: List[dict] = hub.machines(timeout=ASK_TIMEOUT)
except Exception as e: # an older hub, or the extension without machines.read: where it always went
return "", "读不到电脑列表(%s):用助手所在的电脑" % (getattr(e, "code", "") or e.__class__.__name__)
online = [str(m["id"]) for m in machines if m.get("online") and eligible(m)]

def metrics(mid: str) -> Optional[dict]:
left = deadline - clock()
if left < 0.5: # not worth asking: the budget is spent
return None
try:
return hub.machine_metrics(mid, timeout=min(ASK_TIMEOUT, left))
except Exception:
return None

def read(mid: str) -> Optional[Reading]:
m = metrics(mid)
return reading(m) if m is not None else None

if not home:
return "", "不知道助手在哪台电脑上:照旧交给 Persona"
home_m = metrics(home) # (home by any id the hub knows it by: an id kept after two entries were merged is unlisted)
home_now = str((home_m or {}).get("machine_id") or "") # its current id, when the setting names an older one
if sticky:
if sticky in (home, home_now):
return "", "这个话题之前就在助手所在的电脑上:还开在那里"
if sticky in online:
return sticky, "这个话题之前就在 %s 上:还开在那台电脑上" % sticky
m = metrics(sticky) or {} # an id kept after two entries were merged: the hub answers for its current id
now_id = str(m.get("machine_id") or "")
if m.get("online") is True and now_id and now_id != sticky and now_id in online:
return ("" if now_id in (home, home_now) else now_id), \
"这个话题之前就在 %s(现在叫 %s)上:还开在那台电脑上" % (sticky, now_id)
log.info("/agent: the thread's computer %s is offline: placed anew", sticky)
here = reading(home_m) if home_m is not None else None
if here is None:
return "", "%s 没有最近的负载读数(或不在线):照旧用它" % home
if not busy(here):
return "", "%s 不忙(%s)" % (home, _words(here))
best: Optional[Tuple[float, str, Reading]] = None
for mid in online:
if mid in (home, home_now):
continue
r = read(mid)
if r is None or r[0] is None or r[1] is None or busy(r):
continue # another computer only with both readings, neither busy
if best is None or r[0] < best[0]:
best = (r[0], mid, r)
if best is None:
return "", "%s 忙(%s),别的电脑也都忙、没有读数或来不及读:还用它" % (home, _words(here))
return best[1], "%s 忙(%s):开到 %s(%s)" % (home, _words(here), best[1], _words(best[2]))
12 changes: 9 additions & 3 deletions 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.52",
"version": "0.11.53",
"description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down Expand Up @@ -112,7 +112,13 @@
"type": "string",
"format": "machine",
"title": "/agent 在哪台电脑上跑",
"description": "不设置就用助手所在的电脑。"
"description": "不设置就用助手所在的电脑;它忙时按负载开到别的电脑上(见「忙时分到空闲的电脑」)。设置了就总在这台电脑上跑。"
},
"agent_balance": {
"type": "boolean",
"title": "忙时分到空闲的电脑",
"description": "没设置「/agent 在哪台电脑上跑」时:新的 /agent 照旧开在助手所在的电脑上;那台电脑忙(1 分钟负载超过 CPU 核数的 75%,或可用内存不到 2 GiB)时,开到负载最低、也不忙的另一台在线电脑上。已经开着的会话不会换电脑:话题里接着问的,照旧交给原来的会话(或它派出去做事的 Agent);话题里再开新会话,也回到这个话题之前用的电脑。设置了「/agent 用哪个启动器」时不分流;Persona 里「Lark /agent」用的启动器要在别的电脑上也能用(内置的 claude 哪台都有)。",
"default": true
},
"agent_launcher": {
"type": "string",
Expand Down Expand Up @@ -275,7 +281,7 @@
"permissions": {
"network": ["feishu.cn", "*.feishu.cn", "larksuite.com", "*.larksuite.com", "larkoffice.com", "*.larkoffice.com",
"config:starkmesh_url:http"],
"hub": ["agents.control", "agents.read", "assistant.ask", "extensions.call:openmate-wechat", "inbox.read", "kb.read", "todos.read"]
"hub": ["agents.control", "agents.read", "assistant.ask", "extensions.call:openmate-wechat", "inbox.read", "kb.read", "machines.read", "todos.read"]
},
"host_integrations": [{"id": "lark-cli", "version": ">=1.0.72 <2.0.0"}]
}
5 changes: 3 additions & 2 deletions extensions/openmate-feishu/tests/test_feishu.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ def test_connector(self):
def test_permissions(self):
perms = MANIFEST["permissions"]
self.assertEqual(sorted(perms["hub"]), ["agents.control", "agents.read", "assistant.ask",
"extensions.call:openmate-wechat", "inbox.read", "kb.read", "todos.read"])
"extensions.call:openmate-wechat", "inbox.read", "kb.read", "machines.read",
"todos.read"]) # machines.read: /agent's placement by load
self.assertEqual(perms["network"], ["feishu.cn", "*.feishu.cn", "larksuite.com", "*.larksuite.com",
"larkoffice.com", "*.larkoffice.com", "config:starkmesh_url:http"])
props = MANIFEST["configuration"]["properties"]
Expand All @@ -81,7 +82,7 @@ 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_launcher", "agent_forward", "channel_chat", "agent_reply_header", "agent_mark_position",
"agent_machine", "agent_balance", "agent_launcher", "agent_forward", "channel_chat", "agent_reply_header", "agent_mark_position",
"agent_mark_effort",
"agent_ack_reaction",
"agent_done_reaction", "agent_fail_reaction",
Expand Down
13 changes: 10 additions & 3 deletions 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.49",
"version": "0.1.50",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down Expand Up @@ -124,7 +124,13 @@
"type": "string",
"format": "machine",
"title": "/agent 在哪台电脑上跑",
"description": "不设置就用助手所在的电脑。"
"description": "不设置就用助手所在的电脑;它忙时按负载开到别的电脑上(见「忙时分到空闲的电脑」)。设置了就总在这台电脑上跑。"
},
"agent_balance": {
"type": "boolean",
"title": "忙时分到空闲的电脑",
"description": "没设置「/agent 在哪台电脑上跑」时:新的 /agent 照旧开在助手所在的电脑上;那台电脑忙(1 分钟负载超过 CPU 核数的 75%,或可用内存不到 2 GiB)时,开到负载最低、也不忙的另一台在线电脑上。已经开着的 /agent 会话不会换电脑;每条新的 /agent 按当时的负载选电脑。设置了「/agent 用哪个启动器」时不分流;Persona 里「Lark /agent」用的启动器要在别的电脑上也能用(内置的 claude 哪台都有)。",
"default": true
},
"agent_launcher": {
"type": "string",
Expand Down Expand Up @@ -280,7 +286,8 @@
"agents.control",
"agents.read",
"assistant.ask",
"kb.read"
"kb.read",
"machines.read"
]
}
}
Binary file not shown.
Binary file not shown.
Loading
Loading