@open-artifacts/bus 0.132.0 → 0.133.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/oa-bus.ts +1 -1
- package/assets/oa_bus/__init__.py +5 -0
- package/assets/oa_bus/bus.py +372 -0
- package/assets/oa_bus/copy.py +475 -0
- package/assets/oa_bus/frames.py +316 -0
- package/assets/oa_bus/link.py +190 -0
- package/assets/oa_bus/plugin.py +42 -0
- package/assets/oa_bus/plugin.yaml +15 -0
- package/assets/oa_bus/roots.py +117 -0
- package/assets/oa_bus/sockpath.py +106 -0
- package/assets/oa_bus/tools.py +235 -0
- package/assets/oa_bus/wrap.py +29 -0
- package/dist/index.js +572 -293
- package/package.json +1 -1
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""IPC frames between this plugin and the Open Artifacts bus daemon.
|
|
2
|
+
|
|
3
|
+
Mirrors @oa/bus-ipc frames.ts for the frames this plugin sends and receives.
|
|
4
|
+
The golden fixtures in packages/bus-adapter-hermes/fixtures are generated from
|
|
5
|
+
the zod schemas, and tests hold this code to them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
V = 1
|
|
12
|
+
MAX_BODY_BYTES = 1024 * 1024
|
|
13
|
+
MAX_LINE_BYTES = 4 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
KINDS = ("claude-code", "opencode", "pi", "omp", "hermes", "codex")
|
|
16
|
+
STATUS_STATES = ("working", "idle", "blocked", "waiting_on_owner")
|
|
17
|
+
RECEIPT_STATES = ("pending", "delivered", "expired", "refused")
|
|
18
|
+
RECEIPT_REASONS = (
|
|
19
|
+
"unknown_agent",
|
|
20
|
+
"closed",
|
|
21
|
+
"inbox_full",
|
|
22
|
+
"too_large",
|
|
23
|
+
"other_namespace",
|
|
24
|
+
"revoked",
|
|
25
|
+
"ambiguous",
|
|
26
|
+
"role_vacant",
|
|
27
|
+
"agent_gone",
|
|
28
|
+
"mailbox_full",
|
|
29
|
+
"reserved_name",
|
|
30
|
+
"recipient_closed",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
_AGENT_REF = re.compile(r"[A-Za-z0-9_.:-]{1,128}")
|
|
34
|
+
_MSG_ID = re.compile(r"[1-9A-HJ-NP-Za-km-z]{16}")
|
|
35
|
+
_KIND_TOKEN = re.compile(r"[a-z][a-z0-9-]{0,31}")
|
|
36
|
+
_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9 ._-]{0,62}[A-Za-z0-9_-])?")
|
|
37
|
+
_IPV4 = re.compile(r"\d{1,3}(?:\.\d{1,3}){3}")
|
|
38
|
+
_NAMESPACE = re.compile(r"[a-z0-9._~/-]+")
|
|
39
|
+
_ISO = re.compile(
|
|
40
|
+
r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)"
|
|
41
|
+
)
|
|
42
|
+
_FORBIDDEN_REFS = ("__proto__", "constructor", "prototype")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class FrameError(ValueError):
|
|
46
|
+
"""A frame that does not match the protocol."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _fail(msg):
|
|
50
|
+
raise FrameError(msg)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_str(v, lo=0, hi=None):
|
|
54
|
+
return isinstance(v, str) and len(v) >= lo and (hi is None or len(v) <= hi)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_int(v):
|
|
58
|
+
return isinstance(v, int) and not isinstance(v, bool)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _is_num(v):
|
|
62
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def well_formed(s):
|
|
66
|
+
"""No lone surrogates (JSON can carry them; a WebSocket cannot)."""
|
|
67
|
+
try:
|
|
68
|
+
s.encode("utf-8")
|
|
69
|
+
except UnicodeEncodeError:
|
|
70
|
+
return False
|
|
71
|
+
return True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _need(frame, key, ok, what):
|
|
75
|
+
if key not in frame or not ok(frame[key]):
|
|
76
|
+
_fail(f"{key}: expected {what}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _opt(frame, key, ok, what):
|
|
80
|
+
if key in frame and not ok(frame[key]):
|
|
81
|
+
_fail(f"{key}: expected {what}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _agent_ref(v):
|
|
85
|
+
return (
|
|
86
|
+
isinstance(v, str)
|
|
87
|
+
and _AGENT_REF.fullmatch(v) is not None
|
|
88
|
+
and v not in _FORBIDDEN_REFS
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _msg_id(v):
|
|
93
|
+
return isinstance(v, str) and _MSG_ID.fullmatch(v) is not None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _bus_name(v):
|
|
97
|
+
return (
|
|
98
|
+
isinstance(v, str)
|
|
99
|
+
and len(v) <= 64
|
|
100
|
+
and _NAME.fullmatch(v) is not None
|
|
101
|
+
and _IPV4.fullmatch(v) is None
|
|
102
|
+
and well_formed(v)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _namespace(v):
|
|
107
|
+
return (
|
|
108
|
+
isinstance(v, str)
|
|
109
|
+
and 1 <= len(v) <= 128
|
|
110
|
+
and _NAMESPACE.fullmatch(v) is not None
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _iso(v):
|
|
115
|
+
return isinstance(v, str) and _ISO.fullmatch(v) is not None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _base(frame, types):
|
|
119
|
+
if not isinstance(frame, dict):
|
|
120
|
+
_fail("a frame is an object")
|
|
121
|
+
if frame.get("v") != V or isinstance(frame.get("v"), bool):
|
|
122
|
+
_fail("v must be 1")
|
|
123
|
+
if not _is_str(frame.get("id"), 1, 64):
|
|
124
|
+
_fail("id: expected a string of 1 to 64 characters")
|
|
125
|
+
t = frame.get("type")
|
|
126
|
+
if t not in types:
|
|
127
|
+
_fail(f"unknown frame type: {t!r}")
|
|
128
|
+
return t
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# --- Frames the plugin sends.
|
|
132
|
+
|
|
133
|
+
ADAPTER_TYPES = ("hello", "send", "list", "self", "fetch", "ack", "set_status")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def check_adapter_frame(frame):
|
|
137
|
+
"""Raises FrameError unless `frame` is one the daemon accepts from an adapter."""
|
|
138
|
+
t = _base(frame, ADAPTER_TYPES)
|
|
139
|
+
if t == "hello":
|
|
140
|
+
_need(frame, "kind", lambda v: v in KINDS, "a known agent kind")
|
|
141
|
+
_need(frame, "agent_ref", _agent_ref, "an agent ref")
|
|
142
|
+
_need(frame, "pid", lambda v: _is_int(v) and v > 0, "a positive integer")
|
|
143
|
+
_opt(frame, "client_version", lambda v: _is_str(v, 1, 64), "1 to 64 chars")
|
|
144
|
+
_opt(frame, "cwd", lambda v: _is_str(v, 1, 4096), "1 to 4096 chars")
|
|
145
|
+
_opt(
|
|
146
|
+
frame,
|
|
147
|
+
"proposed_name",
|
|
148
|
+
lambda v: _is_str(v, 1, 64) and well_formed(v),
|
|
149
|
+
"1 to 64 well-formed chars",
|
|
150
|
+
)
|
|
151
|
+
_opt(
|
|
152
|
+
frame,
|
|
153
|
+
"caps",
|
|
154
|
+
lambda v: isinstance(v, list)
|
|
155
|
+
and len(v) <= 16
|
|
156
|
+
and all(_is_str(c, 0, 32) for c in v),
|
|
157
|
+
"up to 16 short strings",
|
|
158
|
+
)
|
|
159
|
+
if "attest" in frame:
|
|
160
|
+
a = frame["attest"]
|
|
161
|
+
if not isinstance(a, dict):
|
|
162
|
+
_fail("attest: expected an object")
|
|
163
|
+
for k in ("session_id", "socket_path", "proc_start"):
|
|
164
|
+
if k in a and not isinstance(a[k], str):
|
|
165
|
+
_fail(f"attest.{k}: expected a string")
|
|
166
|
+
elif t == "send":
|
|
167
|
+
_need(frame, "to", _bus_name, "a bus name")
|
|
168
|
+
_opt(frame, "namespace", lambda v: _namespace(v) and well_formed(v), "a namespace")
|
|
169
|
+
_need(
|
|
170
|
+
frame,
|
|
171
|
+
"body",
|
|
172
|
+
lambda v: _is_str(v, 1)
|
|
173
|
+
and well_formed(v)
|
|
174
|
+
and len(v.encode("utf-8")) <= MAX_BODY_BYTES,
|
|
175
|
+
"a well-formed body of 1 byte to 1 MB",
|
|
176
|
+
)
|
|
177
|
+
elif t == "fetch" or t == "ack":
|
|
178
|
+
_need(frame, "msg_id", _msg_id, "a message id")
|
|
179
|
+
elif t == "set_status":
|
|
180
|
+
_need(frame, "state", lambda v: v in STATUS_STATES, "a status state")
|
|
181
|
+
_opt(
|
|
182
|
+
frame,
|
|
183
|
+
"label",
|
|
184
|
+
lambda v: _is_str(v, 1, 128) and len([*v]) <= 64 and v == v.strip(),
|
|
185
|
+
"a label of 1 to 64 characters",
|
|
186
|
+
)
|
|
187
|
+
elif t == "self":
|
|
188
|
+
if "row" in frame and frame["row"] is not True:
|
|
189
|
+
_fail("row: expected true")
|
|
190
|
+
if t in ("send", "list", "self", "fetch", "set_status"):
|
|
191
|
+
_opt(frame, "late", lambda v: v is True, "true")
|
|
192
|
+
return frame
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# --- Frames the plugin receives.
|
|
196
|
+
|
|
197
|
+
DAEMON_TYPES = (
|
|
198
|
+
"welcome",
|
|
199
|
+
"receipt",
|
|
200
|
+
"roster",
|
|
201
|
+
"agent",
|
|
202
|
+
"body",
|
|
203
|
+
"deliver",
|
|
204
|
+
"notice",
|
|
205
|
+
"error",
|
|
206
|
+
"status_set",
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _agent_info(v):
|
|
211
|
+
if not isinstance(v, dict):
|
|
212
|
+
return False
|
|
213
|
+
if not (_is_str(v.get("name")) and _is_str(v.get("namespace"))):
|
|
214
|
+
return False
|
|
215
|
+
k = v.get("kind")
|
|
216
|
+
if not (isinstance(k, str) and _KIND_TOKEN.fullmatch(k)):
|
|
217
|
+
return False
|
|
218
|
+
if not isinstance(v.get("live"), bool) or not isinstance(v.get("global"), bool):
|
|
219
|
+
return False
|
|
220
|
+
if "state" in v and v["state"] not in ("live", "queued", "away"):
|
|
221
|
+
return False
|
|
222
|
+
if "since" in v and not _iso(v["since"]):
|
|
223
|
+
return False
|
|
224
|
+
if "status" in v and v["status"] not in STATUS_STATES:
|
|
225
|
+
return False
|
|
226
|
+
if "status_at" in v and not _iso(v["status_at"]):
|
|
227
|
+
return False
|
|
228
|
+
return True
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def parse_daemon_frame(frame):
|
|
232
|
+
"""Returns `frame` when it is one the daemon sends an adapter; raises FrameError otherwise."""
|
|
233
|
+
t = _base(frame, DAEMON_TYPES)
|
|
234
|
+
if t == "welcome":
|
|
235
|
+
_need(frame, "agent_ref", _agent_ref, "an agent ref")
|
|
236
|
+
_need(frame, "bus_name", _is_str, "a string")
|
|
237
|
+
_need(frame, "namespace", _is_str, "a string")
|
|
238
|
+
_need(frame, "global", lambda v: isinstance(v, bool), "a boolean")
|
|
239
|
+
elif t == "receipt":
|
|
240
|
+
_need(frame, "msg_id", _is_str, "a string")
|
|
241
|
+
_need(frame, "state", lambda v: v in RECEIPT_STATES, "a receipt state")
|
|
242
|
+
_opt(frame, "reason", lambda v: v in RECEIPT_REASONS, "a receipt reason")
|
|
243
|
+
_opt(frame, "held", lambda v: v is True, "true")
|
|
244
|
+
_opt(frame, "text", lambda v: _is_str(v, 1), "a non-empty string")
|
|
245
|
+
elif t == "roster":
|
|
246
|
+
_need(
|
|
247
|
+
frame,
|
|
248
|
+
"agents",
|
|
249
|
+
lambda v: isinstance(v, list) and all(_agent_info(a) for a in v),
|
|
250
|
+
"a list of agents",
|
|
251
|
+
)
|
|
252
|
+
elif t == "agent":
|
|
253
|
+
_need(
|
|
254
|
+
frame,
|
|
255
|
+
"agent",
|
|
256
|
+
lambda v: v is None or _agent_info(v),
|
|
257
|
+
"an agent or null",
|
|
258
|
+
)
|
|
259
|
+
elif t == "body":
|
|
260
|
+
_need(frame, "msg_id", _is_str, "a string")
|
|
261
|
+
_need(frame, "body", _is_str, "a string")
|
|
262
|
+
elif t == "deliver":
|
|
263
|
+
_need(frame, "msg_id", _is_str, "a string")
|
|
264
|
+
_need(frame, "from_name", _is_str, "a string")
|
|
265
|
+
_need(frame, "namespace", _is_str, "a string")
|
|
266
|
+
_opt(frame, "body", _is_str, "a string")
|
|
267
|
+
_opt(
|
|
268
|
+
frame,
|
|
269
|
+
"notice",
|
|
270
|
+
lambda v: isinstance(v, dict)
|
|
271
|
+
and _is_num(v.get("size"))
|
|
272
|
+
and _is_str(v.get("msg_id")),
|
|
273
|
+
"a notice",
|
|
274
|
+
)
|
|
275
|
+
if ("body" in frame) == ("notice" in frame):
|
|
276
|
+
_fail("deliver needs exactly one of body or notice")
|
|
277
|
+
elif t == "notice":
|
|
278
|
+
_need(frame, "text", lambda v: _is_str(v, 1), "a non-empty string")
|
|
279
|
+
_opt(frame, "msg_id", _is_str, "a string")
|
|
280
|
+
elif t == "error":
|
|
281
|
+
_need(frame, "code", _is_str, "a string")
|
|
282
|
+
_need(frame, "message", _is_str, "a string")
|
|
283
|
+
elif t == "status_set":
|
|
284
|
+
_opt(
|
|
285
|
+
frame,
|
|
286
|
+
"earlier",
|
|
287
|
+
lambda v: isinstance(v, dict)
|
|
288
|
+
and _is_str(v.get("code"))
|
|
289
|
+
and _is_str(v.get("message")),
|
|
290
|
+
"an earlier status",
|
|
291
|
+
)
|
|
292
|
+
_opt(
|
|
293
|
+
frame,
|
|
294
|
+
"late",
|
|
295
|
+
lambda v: isinstance(v, list) and all(_is_str(x, 1) for x in v),
|
|
296
|
+
"a list of strings",
|
|
297
|
+
)
|
|
298
|
+
return frame
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def encode(partial):
|
|
302
|
+
"""One JSON line for the daemon: `v` first, as the other adapters write it."""
|
|
303
|
+
frame = {"v": V, **partial}
|
|
304
|
+
check_adapter_frame(frame)
|
|
305
|
+
return (json.dumps(frame, ensure_ascii=False, separators=(",", ":")) + "\n").encode(
|
|
306
|
+
"utf-8"
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def decode(line):
|
|
311
|
+
"""A received line to a validated frame; FrameError for anything else."""
|
|
312
|
+
try:
|
|
313
|
+
obj = json.loads(line.decode("utf-8") if isinstance(line, bytes) else line)
|
|
314
|
+
except (ValueError, UnicodeDecodeError) as e:
|
|
315
|
+
raise FrameError(f"not JSON: {e}") from None
|
|
316
|
+
return parse_daemon_frame(obj)
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""One connection to the bus daemon, held open for one Hermes root session."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
import threading
|
|
5
|
+
|
|
6
|
+
from . import frames
|
|
7
|
+
from .sockpath import bus_home, daemon_socket_path, socket_dir_problem
|
|
8
|
+
|
|
9
|
+
# The IPC marker (CONTRACT.md): the package version, stamped by the CLI's bundler.
|
|
10
|
+
CLIENT_VERSION = "0.0.0"
|
|
11
|
+
|
|
12
|
+
# Above the daemon's 10 s hub wait plus its 5 s wait for delivered.
|
|
13
|
+
REQUEST_TIMEOUT_S = 20.0
|
|
14
|
+
HELLO_TIMEOUT_S = 5.0
|
|
15
|
+
RECONNECT_S = 3.0
|
|
16
|
+
MAX_REFUSED_BACKOFF_S = 60.0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def retry_delay_s(refusals):
|
|
20
|
+
"""3 s while the daemon is down; after `refusals` refused hellos in a row, 3 s doubling to 60 s."""
|
|
21
|
+
if refusals <= 1:
|
|
22
|
+
return RECONNECT_S
|
|
23
|
+
return min(RECONNECT_S * 2 ** (refusals - 1), MAX_REFUSED_BACKOFF_S)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LinkError(Exception):
|
|
27
|
+
def __init__(self, message, refused=False):
|
|
28
|
+
super().__init__(message)
|
|
29
|
+
self.refused = refused
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Link:
|
|
33
|
+
"""Connects and says hello in `open`; then `deliver` and `notice` frames arrive on a reader thread."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, ref, cwd, name, proc_start, pid, on_deliver, on_notice, on_lost, home=None):
|
|
36
|
+
self.ref = ref
|
|
37
|
+
self.welcome = {}
|
|
38
|
+
self._hello = {
|
|
39
|
+
"id": "hello",
|
|
40
|
+
"type": "hello",
|
|
41
|
+
"kind": "hermes",
|
|
42
|
+
"client_version": CLIENT_VERSION,
|
|
43
|
+
"agent_ref": ref,
|
|
44
|
+
"pid": pid,
|
|
45
|
+
"cwd": cwd,
|
|
46
|
+
"proposed_name": name,
|
|
47
|
+
"caps": ["mailbox", "pending"],
|
|
48
|
+
"attest": {"proc_start": proc_start} if proc_start else {},
|
|
49
|
+
}
|
|
50
|
+
self._home = home if home is not None else bus_home()
|
|
51
|
+
self._on_deliver = on_deliver
|
|
52
|
+
self._on_notice = on_notice
|
|
53
|
+
self._on_lost = on_lost
|
|
54
|
+
self._sock = None
|
|
55
|
+
self._wlock = threading.Lock()
|
|
56
|
+
self._lock = threading.Lock()
|
|
57
|
+
self._pending = {}
|
|
58
|
+
self._seq = 0
|
|
59
|
+
self._ended = False
|
|
60
|
+
self._welcomed = threading.Event()
|
|
61
|
+
self._refusal = None
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def closed(self):
|
|
65
|
+
return self._ended
|
|
66
|
+
|
|
67
|
+
def open(self):
|
|
68
|
+
problem = socket_dir_problem(self._home)
|
|
69
|
+
if problem:
|
|
70
|
+
raise LinkError(problem)
|
|
71
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
72
|
+
sock.settimeout(HELLO_TIMEOUT_S)
|
|
73
|
+
try:
|
|
74
|
+
sock.connect(daemon_socket_path(self._home))
|
|
75
|
+
except OSError as e:
|
|
76
|
+
sock.close()
|
|
77
|
+
raise LinkError(f"the daemon is not reachable: {e}") from None
|
|
78
|
+
sock.settimeout(None)
|
|
79
|
+
self._sock = sock
|
|
80
|
+
threading.Thread(target=self._read, name="oa-bus-link", daemon=True).start()
|
|
81
|
+
self._send(self._hello)
|
|
82
|
+
if not self._welcomed.wait(HELLO_TIMEOUT_S):
|
|
83
|
+
self._end(lost=False)
|
|
84
|
+
raise LinkError(self._refusal or "the daemon did not answer hello")
|
|
85
|
+
if self._refusal:
|
|
86
|
+
self.close()
|
|
87
|
+
raise LinkError(self._refusal, refused=True)
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
def _send(self, partial):
|
|
91
|
+
data = frames.encode(partial)
|
|
92
|
+
with self._wlock:
|
|
93
|
+
if self._ended or self._sock is None:
|
|
94
|
+
raise LinkError("the daemon connection closed")
|
|
95
|
+
try:
|
|
96
|
+
self._sock.sendall(data)
|
|
97
|
+
except OSError:
|
|
98
|
+
raise LinkError("the daemon connection closed") from None
|
|
99
|
+
|
|
100
|
+
def request(self, partial, timeout=REQUEST_TIMEOUT_S):
|
|
101
|
+
"""Sends a frame and waits for the reply with its id."""
|
|
102
|
+
with self._lock:
|
|
103
|
+
if self._ended:
|
|
104
|
+
raise LinkError("the daemon connection closed")
|
|
105
|
+
self._seq += 1
|
|
106
|
+
req_id = str(self._seq)
|
|
107
|
+
slot = {"event": threading.Event(), "frame": None}
|
|
108
|
+
self._pending[req_id] = slot
|
|
109
|
+
try:
|
|
110
|
+
self._send({**partial, "id": req_id})
|
|
111
|
+
if not slot["event"].wait(timeout):
|
|
112
|
+
raise LinkError(f"the daemon did not answer {partial.get('type')}")
|
|
113
|
+
if slot["frame"] is None:
|
|
114
|
+
raise LinkError("the daemon connection closed")
|
|
115
|
+
return slot["frame"]
|
|
116
|
+
finally:
|
|
117
|
+
with self._lock:
|
|
118
|
+
self._pending.pop(req_id, None)
|
|
119
|
+
|
|
120
|
+
def ack(self, msg_id):
|
|
121
|
+
"""Fire-and-forget: the daemon answers an ack with nothing."""
|
|
122
|
+
with self._lock:
|
|
123
|
+
self._seq += 1
|
|
124
|
+
n = self._seq
|
|
125
|
+
self._send({"type": "ack", "id": f"ack-{n}", "msg_id": msg_id})
|
|
126
|
+
|
|
127
|
+
def close(self):
|
|
128
|
+
self._end(lost=False)
|
|
129
|
+
|
|
130
|
+
def _end(self, lost):
|
|
131
|
+
with self._lock:
|
|
132
|
+
was_open = not self._ended
|
|
133
|
+
self._ended = True
|
|
134
|
+
pending = list(self._pending.values())
|
|
135
|
+
sock = self._sock
|
|
136
|
+
if sock is not None:
|
|
137
|
+
try:
|
|
138
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
139
|
+
except OSError:
|
|
140
|
+
pass
|
|
141
|
+
sock.close()
|
|
142
|
+
for slot in pending:
|
|
143
|
+
slot["event"].set()
|
|
144
|
+
self._welcomed.set()
|
|
145
|
+
if lost and was_open and self.welcome:
|
|
146
|
+
self._on_lost(self)
|
|
147
|
+
|
|
148
|
+
def _read(self):
|
|
149
|
+
buf = b""
|
|
150
|
+
try:
|
|
151
|
+
while True:
|
|
152
|
+
chunk = self._sock.recv(65536)
|
|
153
|
+
if not chunk:
|
|
154
|
+
break
|
|
155
|
+
buf += chunk
|
|
156
|
+
while True:
|
|
157
|
+
i = buf.find(b"\n")
|
|
158
|
+
if i == -1:
|
|
159
|
+
break
|
|
160
|
+
line, buf = buf[:i], buf[i + 1 :]
|
|
161
|
+
self._line(line)
|
|
162
|
+
if len(buf) > frames.MAX_LINE_BYTES:
|
|
163
|
+
break
|
|
164
|
+
except OSError:
|
|
165
|
+
pass
|
|
166
|
+
self._end(lost=True)
|
|
167
|
+
|
|
168
|
+
def _line(self, line):
|
|
169
|
+
try:
|
|
170
|
+
f = frames.decode(line)
|
|
171
|
+
except frames.FrameError:
|
|
172
|
+
return
|
|
173
|
+
if not self._welcomed.is_set():
|
|
174
|
+
if f["type"] == "welcome":
|
|
175
|
+
self.welcome = f
|
|
176
|
+
else:
|
|
177
|
+
self._refusal = str(f.get("message") or "the daemon refused hello")
|
|
178
|
+
self._welcomed.set()
|
|
179
|
+
return
|
|
180
|
+
t = f["type"]
|
|
181
|
+
if t == "deliver":
|
|
182
|
+
self._on_deliver(f, self)
|
|
183
|
+
elif t == "notice":
|
|
184
|
+
self._on_notice(self, f["text"], f.get("msg_id"))
|
|
185
|
+
else:
|
|
186
|
+
with self._lock:
|
|
187
|
+
slot = self._pending.get(f["id"])
|
|
188
|
+
if slot is not None:
|
|
189
|
+
slot["frame"] = f
|
|
190
|
+
slot["event"].set()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Registers the bus tools and hooks with Hermes (a plugin's `register(ctx)`)."""
|
|
2
|
+
|
|
3
|
+
import atexit
|
|
4
|
+
|
|
5
|
+
from .bus import Bus
|
|
6
|
+
from .roots import Roots
|
|
7
|
+
from .tools import TOOLS, Tools
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def register(ctx, roots=None, bus=None):
|
|
11
|
+
roots = roots or Roots()
|
|
12
|
+
bus = bus or Bus(roots, inject=ctx.inject_message)
|
|
13
|
+
tools = Tools(bus)
|
|
14
|
+
|
|
15
|
+
for tool in TOOLS:
|
|
16
|
+
ctx.register_tool(
|
|
17
|
+
name=tool["name"],
|
|
18
|
+
toolset="oa_bus",
|
|
19
|
+
schema=tool,
|
|
20
|
+
handler=tools.handler(tool["name"]),
|
|
21
|
+
description=tool["description"],
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Hooks get keyword arguments only, and may gain more: always take **kwargs.
|
|
25
|
+
def pre_llm_call(session_id=None, platform=None, user_message=None, conversation_history=None, **_kw):
|
|
26
|
+
return bus.turn_start(session_id, platform, user_message, conversation_history)
|
|
27
|
+
|
|
28
|
+
def on_session_end(session_id=None, **_kw):
|
|
29
|
+
bus.turn_end(session_id)
|
|
30
|
+
|
|
31
|
+
def on_session_finalize(session_id=None, **_kw):
|
|
32
|
+
bus.session_finalize(session_id)
|
|
33
|
+
|
|
34
|
+
def subagent_start(parent_session_id=None, child_session_id=None, **_kw):
|
|
35
|
+
roots.note_subagent(parent_session_id, child_session_id)
|
|
36
|
+
|
|
37
|
+
ctx.register_hook("pre_llm_call", pre_llm_call)
|
|
38
|
+
ctx.register_hook("on_session_end", on_session_end)
|
|
39
|
+
ctx.register_hook("on_session_finalize", on_session_finalize)
|
|
40
|
+
ctx.register_hook("subagent_start", subagent_start)
|
|
41
|
+
atexit.register(bus.close_all)
|
|
42
|
+
return bus
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
name: oa-bus
|
|
2
|
+
version: 0.0.0
|
|
3
|
+
description: "Open Artifacts bus: message other agents, set your status, and receive their messages in this Hermes session."
|
|
4
|
+
author: "Open Artifacts"
|
|
5
|
+
provides_tools:
|
|
6
|
+
- oabus_list_agents
|
|
7
|
+
- oabus_send_message
|
|
8
|
+
- oabus_fetch
|
|
9
|
+
- oabus_self
|
|
10
|
+
- oabus_set_status
|
|
11
|
+
provides_hooks:
|
|
12
|
+
- pre_llm_call
|
|
13
|
+
- on_session_end
|
|
14
|
+
- on_session_finalize
|
|
15
|
+
- subagent_start
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Which conversation a Hermes session id belongs to.
|
|
2
|
+
|
|
3
|
+
The bus identity (`agent_ref`) is the lineage ROOT: the first session of a
|
|
4
|
+
conversation. Context compression rotates the live session id to a new row
|
|
5
|
+
that links back to its parent; subagents (`delegate_task`) run in this process
|
|
6
|
+
under ids of their own. A session whose root cannot be told is refused, never
|
|
7
|
+
guessed: a wrong root would be a second agent on the bus.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NotOnBus(Exception):
|
|
14
|
+
"""A session that cannot use the bus; the message is for the agent."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
NO_SESSION = (
|
|
18
|
+
"oa-bus: Hermes did not say which session made this call, so it cannot be "
|
|
19
|
+
"placed on the bus. Update Hermes (the oa-bus plugin needs 0.19 or newer)."
|
|
20
|
+
)
|
|
21
|
+
UNRESOLVED = (
|
|
22
|
+
"oa-bus: this session's conversation could not be found in Hermes's session "
|
|
23
|
+
"history, so it is not on the bus. Send another message in this session and "
|
|
24
|
+
"try again."
|
|
25
|
+
)
|
|
26
|
+
SUBAGENT = (
|
|
27
|
+
"oa-bus: a subagent is not on the bus; only the main Hermes session can use "
|
|
28
|
+
"Open Artifacts bus"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_dbs = {}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def hermes_lineage_root(session_id):
|
|
36
|
+
"""The root of `session_id`'s compression lineage, through Hermes's own SessionDB.
|
|
37
|
+
|
|
38
|
+
Hermes's public API (hermes_state.SessionDB.get_compression_lineage), in
|
|
39
|
+
process, on a read-only handle. The path is resolved on each call, so it
|
|
40
|
+
follows the active profile or home override. None when the history file or
|
|
41
|
+
the session does not exist.
|
|
42
|
+
"""
|
|
43
|
+
from hermes_constants import get_hermes_home # only importable inside Hermes
|
|
44
|
+
from hermes_state import SessionDB
|
|
45
|
+
|
|
46
|
+
path = get_hermes_home() / "state.db"
|
|
47
|
+
if not path.exists():
|
|
48
|
+
return None
|
|
49
|
+
db = _dbs.get(path)
|
|
50
|
+
if db is None:
|
|
51
|
+
db = _dbs[path] = SessionDB(path, read_only=True)
|
|
52
|
+
lineage = db.get_compression_lineage(session_id)
|
|
53
|
+
return lineage[0] if lineage and session_id in lineage else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Roots:
|
|
57
|
+
def __init__(self, lineage_root=hermes_lineage_root):
|
|
58
|
+
self._lineage_root = lineage_root
|
|
59
|
+
self._lock = threading.Lock()
|
|
60
|
+
self._root_of = {}
|
|
61
|
+
# child session id -> the session that delegated to it.
|
|
62
|
+
self._subagents = {}
|
|
63
|
+
|
|
64
|
+
def note_subagent(self, parent_session_id, child_session_id):
|
|
65
|
+
"""subagent_start: `child_session_id` is a subagent of `parent_session_id`."""
|
|
66
|
+
if child_session_id and child_session_id != parent_session_id:
|
|
67
|
+
with self._lock:
|
|
68
|
+
self._subagents[child_session_id] = parent_session_id
|
|
69
|
+
|
|
70
|
+
def _lineage(self, session_id):
|
|
71
|
+
with self._lock:
|
|
72
|
+
root = self._root_of.get(session_id)
|
|
73
|
+
if root is None:
|
|
74
|
+
try:
|
|
75
|
+
root = self._lineage_root(session_id)
|
|
76
|
+
except Exception:
|
|
77
|
+
root = None
|
|
78
|
+
if not isinstance(root, str) or not root:
|
|
79
|
+
raise NotOnBus(UNRESOLVED)
|
|
80
|
+
with self._lock:
|
|
81
|
+
self._root_of[session_id] = root
|
|
82
|
+
return root
|
|
83
|
+
|
|
84
|
+
def root_of(self, session_id):
|
|
85
|
+
"""The root session id of any session: a subagent maps to its delegator's root."""
|
|
86
|
+
if not isinstance(session_id, str) or not session_id:
|
|
87
|
+
raise NotOnBus(NO_SESSION)
|
|
88
|
+
for _ in range(32):
|
|
89
|
+
with self._lock:
|
|
90
|
+
parent = self._subagents.get(session_id)
|
|
91
|
+
if parent is None:
|
|
92
|
+
break
|
|
93
|
+
session_id = parent
|
|
94
|
+
root = self._lineage(session_id)
|
|
95
|
+
with self._lock:
|
|
96
|
+
parent = self._subagents.get(root)
|
|
97
|
+
return root if parent is None else self.root_of(parent)
|
|
98
|
+
|
|
99
|
+
def is_subagent(self, session_id):
|
|
100
|
+
"""Whether the session, or the lineage it rotated from, is a subagent's."""
|
|
101
|
+
with self._lock:
|
|
102
|
+
if session_id in self._subagents:
|
|
103
|
+
return True
|
|
104
|
+
try:
|
|
105
|
+
root = self._lineage(session_id)
|
|
106
|
+
except NotOnBus:
|
|
107
|
+
return False
|
|
108
|
+
with self._lock:
|
|
109
|
+
return root in self._subagents
|
|
110
|
+
|
|
111
|
+
def resolve(self, session_id):
|
|
112
|
+
"""The root session id of a main session; raises NotOnBus for a subagent or an unknown session."""
|
|
113
|
+
if not isinstance(session_id, str) or not session_id:
|
|
114
|
+
raise NotOnBus(NO_SESSION)
|
|
115
|
+
if self.is_subagent(session_id):
|
|
116
|
+
raise NotOnBus(SUBAGENT)
|
|
117
|
+
return self._lineage(session_id)
|