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
916 changes: 644 additions & 272 deletions core/openmate_core/agent.py

Large diffs are not rendered by default.

17 changes: 1 addition & 16 deletions core/openmate_core/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@

from __future__ import annotations

import datetime as _dt
import logging
import re
import time
from typing import Any, Callable, Dict, List, Optional, Tuple

from .agent import model_label
from .hub import HubError
from .hub import HubError, hub_time as ts
from .textutil import clip, one_line
from .ui import Fresh, NotYet, Page, day_start, empty, row, snapshot_notice, snapshot_source, stat, state_of, state_text, tile, when

Expand Down Expand Up @@ -44,19 +42,6 @@
TITLES = {k: t for k, t, *_ in GROUPS}


def ts(v: Any) -> float:
"""A hub time (RFC 3339, Go's zero time for none) as a timestamp; 0 when none."""
s = str(v or "").strip()
if not s or s.startswith("0001-"):
return 0.0
# Go writes 0–9 fraction digits (".49", ".123456789"); Python before 3.11 takes only 3 or 6
s = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], s.replace("Z", "+00:00"), count=1)
try:
return _dt.datetime.fromisoformat(s).timestamp()
except ValueError:
return 0.0


def span(seconds: float) -> str:
"""How long, as people say it: 3 分钟, 1 小时 20 分, 2 天."""
m = int(max(0, seconds) // 60)
Expand Down
71 changes: 58 additions & 13 deletions core/openmate_core/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
from __future__ import annotations

import http.client
import re
import json
import socket
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from typing import Any, Dict, List, Optional

_LOOPBACK = {"127.0.0.1", "localhost", "::1", "[::1]"}
Expand All @@ -45,15 +47,28 @@
MACHINE_UNSURE = ("node_unreachable", "timeout")


def hub_time(v: Any) -> float:
"""A hub time (RFC 3339, Go's zero time for none) as a timestamp; 0 when none."""
s = str(v or "").strip()
if not s or s.startswith("0001-"):
return 0.0
# Go writes 0–9 fraction digits (".49", ".123456789"); Python before 3.11 takes only 3 or 6
s = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], s.replace("Z", "+00:00"), count=1)
try:
return datetime.fromisoformat(s).timestamp()
except ValueError:
return 0.0

class HubError(Exception):
def __init__(self, status: int, message: str, code: str = "", retryable: Optional[bool] = None,
delivered: str = ""):
delivered: str = "", token_refused: bool = False):
super().__init__(message)
self.status = status
self.message = message
self.code = code
self.retryable = retryable # the hub's "retryable" and "delivered" ("none": nothing ran), when it said them
self.delivered = delivered
self.token_refused = token_refused

@property
def unreachable(self) -> bool:
Expand All @@ -72,6 +87,14 @@ def transient(self) -> bool:
Unless unsent, it may also have run."""
return self.unsent or self.unreachable or (self.code in MACHINE_UNSURE and self.status >= 500)

@property
def send_uncertain(self) -> bool:
"""The send may already be in the session or held by its manager."""
if self.token_refused or self.unsent or self.delivered == "none":
return False
return (self.delivered == "unknown" or self.status in (0, 408, 502, 504)
or self.code in ("internal", "timeout", "unknown") or self.transient)


class HubAPI:
def __init__(self, base_url: str, token: str, timeout: float = 30.0):
Expand Down Expand Up @@ -108,6 +131,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op
with self._opener.open(req, timeout=timeout or self.timeout) as resp:
raw = resp.read()
except urllib.error.HTTPError as e:
token_refused = e.code == 401 and e.headers.get("X-Persona-Auth-Refused") == "token"
raw = b""
cut = False
try:
Expand All @@ -117,7 +141,8 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op
finally:
e.close()
if cut:
raise HubError(e.code, "和 Persona hub 的连接中途断了(HTTP %d)" % e.code, NETWORK)
raise HubError(e.code, "和 Persona hub 的连接中途断了(HTTP %d)" % e.code, NETWORK,
token_refused=token_refused)
message, code, retryable, delivered = "", "", None, ""
try:
doc = json.loads(raw or b"{}")
Expand All @@ -131,7 +156,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op
code = str(doc["state"]) # a receipt the hub could not settle (503 state unknown)
except ValueError:
pass
raise HubError(e.code, message or ("hub 回答 HTTP %d" % e.code), code, retryable, delivered)
raise HubError(e.code, message or ("hub 回答 HTTP %d" % e.code), code, retryable, delivered, token_refused)
except http.client.HTTPException as e: # cut off mid-answer (IncompleteRead, a bad status line): it may have run
raise HubError(0, "和 Persona hub 的连接中途断了(%s)" % type(e).__name__, NETWORK)
except (urllib.error.URLError, OSError) as e:
Expand All @@ -143,7 +168,7 @@ def request(self, method: str, path: str, body: Optional[dict] = None, query: Op
try:
return json.loads(raw)
except ValueError:
raise HubError(0, "hub 的回答不是 JSON")
raise HubError(0, "hub 的回答不是 JSON", NETWORK)

# ---- the routes ----

Expand All @@ -162,7 +187,7 @@ def capabilities(self) -> dict:

def start_conversation(self, prompt: str, purpose: str, report_tasks: bool, machine_id: str = "", launcher: str = "",
guest_tools: Optional[List[str]] = None, op_id: str = "",
images: Optional[List[dict]] = None) -> dict:
images: Optional[List[dict]] = None, timeout: float = 120) -> dict:
"""A conversation; with guest_tools a guest one (docs/assistant/assistant.md "Guest conversations"): it answers
someone else for the user, with none of the assistant's powers but these connector tools. With op_id the hub
starts it once however often it is asked (assistant_start_ops): the same op_id and body get the first answer.
Expand All @@ -177,15 +202,24 @@ def start_conversation(self, prompt: str, purpose: str, report_tasks: bool, mach
body["machine_id"] = machine_id
if launcher:
body["launcher"] = launcher
out = self.request("POST", "/api/v1/assistant/conversations", body, timeout=120, op_id=op_id)
out = self.request("POST", "/api/v1/assistant/conversations", body, timeout=timeout, op_id=op_id)
state = str((out or {}).get("state") or "") if isinstance(out, dict) else ""
if state in ("pending", "unknown") and not (out or {}).get("session"):
raise HubError(202, "hub 还在处理这次启动" if state == "pending" else "hub 不确定这次有没有启动", state)
sess = (out or {}).get("session") or {}
if not sess.get("session_id"):
raise HubError(0, "hub 没有给出会话 id")
raise HubError(0, "hub 没有给出会话 id", NETWORK)
return sess

def assistant_probe(self, timeout: float) -> None:
self.request("GET", "/api/v1/assistant", timeout=timeout)

def start_candidates(self, timeout: float) -> dict:
doc = self.request("GET", "/api/v1/sessions", query={"include_hidden": 1, "limit": 200}, timeout=timeout)
if not isinstance(doc, dict) or not isinstance(doc.get("sessions"), list):
raise HubError(0, "hub 的会话列表不是列表")
return doc

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)
Expand Down Expand Up @@ -225,17 +259,22 @@ def working_sessions(self, timeout: float = 10.0) -> Dict[str, int]:
return out

def send_message(self, machine_id: str, session_id: str, text: str, client_msg_id: str = "",
images: Optional[List[dict]] = None) -> dict:
images: Optional[List[dict]] = None, timeout: float = 120) -> dict:
body: Dict[str, Any] = {"text": text}
if images: # [{mime, data (base64)}]: pictures with it (only when some)
body["images"] = list(images)
if client_msg_id:
body["client_msg_id"] = client_msg_id
return self.request("POST", "/api/v1/sessions/%s/%s/messages" % (_seg(machine_id), _seg(session_id)), body, timeout=120)
return self.request("POST", "/api/v1/sessions/%s/%s/messages" % (_seg(machine_id), _seg(session_id)),
body, timeout=timeout)

def items(self, machine_id: str, session_id: str, after_seq: Optional[int] = None) -> dict:
def items(self, machine_id: str, session_id: str, after_seq: Optional[int] = None, *,
timeout: Optional[float] = None, lazy_images: bool = False) -> dict:
query = {"after_seq": after_seq} if after_seq is not None else {"turns": 1}
return self.request("GET", "/api/v1/sessions/%s/%s/items" % (_seg(machine_id), _seg(session_id)), query=query)
if lazy_images:
query["lazy_images"] = 1
return self.request("GET", "/api/v1/sessions/%s/%s/items" % (_seg(machine_id), _seg(session_id)),
query=query, timeout=timeout)

def item_full(self, machine_id: str, session_id: str, item_id: str) -> dict:
return self.request("GET", "/api/v1/sessions/%s/%s/items/%s/full" % (_seg(machine_id), _seg(session_id), _seg(item_id)))
Expand All @@ -254,17 +293,23 @@ def todos(self) -> List[dict]:
res = self.request("GET", "/api/v1/todos", timeout=10) or {} # optional: a slow answer asks the conversation
return [t for t in (res.get("todos") or []) if isinstance(t, dict)] if isinstance(res, dict) else []

def reporters(self, timeout: float = 15) -> List[dict]:
doc = self.request("GET", "/api/v1/assistant/reporters", timeout=timeout)
if not isinstance(doc, dict) or not isinstance(doc.get("reporters"), list):
raise HubError(0, "hub 的汇报会话列表不是列表")
return doc["reporters"]

def reporter_state(self, session_id: str) -> str:
"""Whether the hub tells the conversation about the tasks it opened: "reporting"; "stopped" (its task notices
are dropped until it is asked again); "absent" (not, or no more, a reporting conversation: they go to the main
conversation); "unknown" from a hub without the list (404)."""
try:
res = self.request("GET", "/api/v1/assistant/reporters", timeout=15) or {}
rows = self.reporters()
except HubError as e:
if e.status == 404:
return "unknown"
raise
for r in (res.get("reporters") or []) if isinstance(res, dict) else []:
for r in rows:
if isinstance(r, dict) and r.get("session_id") == session_id:
return "stopped" if r.get("stopped_at") else "reporting"
return "absent"
Expand Down
7 changes: 6 additions & 1 deletion core/openmate_core/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,14 @@ class Timing:
agent_keep_most: int = 200
agent_hub_wait: float = 300.0 # how long a /agent request waits for the hub to be reachable before it fails
agent_hub_probe: float = 5.0 # meanwhile the hub is asked this often whether it answers
agent_doubt_lookback: float = 600.0 # include sessions listed shortly before run creation
agent_doubt_age: float = 90.0 # bus disconnect detection plus startup and transcript lag
agent_doubt_stable: float = 30.0 # successful bus probes before trusting a negative lookup
agent_doubt_lookup: float = 20.0 # minimum interval between fresh snapshots used as negative evidence
agent_doubt_cleanup: float = 300.0 # keep looking for the replaced or stopped start
agent_send_wait: float = 120.0 # time to see an uncertain or queued follow-up in the transcript
warm_pages: bool = True # the pages read what they show in the background right after the start
agent_model_wait: float = 4.0 # a reply waits this long at most for the hub to list its session's model
agent_start_tries: int = 3 # starts that may have reached the hub (each with a new request id) before it fails
agent_settle: float = 8.0 # a session quiet this long after it answered: its status says whether the turn ended
secrets_retry: float = 2.0
sent_retry: Tuple[float, ...] = (5.0, 30.0, 120.0) # waits before sent.record is tried again (the hub was busy)
Expand Down
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.80",
"version": "0.11.81",
"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.73",
"version": "0.1.74",
"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.80",
"version": "0.11.81",
"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.80/openmate-feishu-0.11.80.tar.gz",
"sha256": "85ca0b8e31a6cf6d47d87434b89360070ed2582e165b5c57e89fac8afe7a4878",
"size": 415117
"url": "packages/openmate-feishu/0.11.81/openmate-feishu-0.11.81.tar.gz",
"sha256": "851f0d2b8803408bda48551e38d699c766aa6fc74bc1408fa7d18738dec1d8c6",
"size": 419375
}
]
},
Expand All @@ -551,7 +551,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
"version": "0.1.73",
"version": "0.1.74",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
Expand Down Expand Up @@ -848,9 +848,9 @@
"icon": "assets/icon.png",
"packages": [
{
"url": "packages/openmate-wechat/0.1.73/openmate-wechat-0.1.73.tar.gz",
"sha256": "3c3db8c37498fec862f109c5e86d18c4896fa7884f4f32fa342adf0972e3cd3f",
"size": 311944
"url": "packages/openmate-wechat/0.1.74/openmate-wechat-0.1.74.tar.gz",
"sha256": "dcae7d4e7b59bc6ef6a8f4d7a9d8868578fee234a7c2eb608918f4363fe05f77",
"size": 316149
}
]
}
Expand Down
Loading
Loading