@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.
@@ -0,0 +1,106 @@
1
+ """Where the bus daemon listens, and this process's start time.
2
+
3
+ Port of the socket-path block in the Pi extension (a test holds the two to the
4
+ same answers). The Pi extension's `procStart` is `ps -o lstart=` in UTC.
5
+ """
6
+
7
+ import hashlib
8
+ import os
9
+ import stat
10
+ import subprocess
11
+ import sys
12
+
13
+ # sun_path holds 104 bytes on macOS and 108 on Linux, NUL included.
14
+ MAX_SOCKET_PATH = 107 if sys.platform.startswith("linux") else 103
15
+
16
+
17
+ def canonical_home(p):
18
+ """The deepest existing ancestor through realpath, the rest appended as is."""
19
+ rest = []
20
+ cur = p
21
+ while True:
22
+ try:
23
+ real = os.path.realpath(cur, strict=True)
24
+ return os.path.join(real, *rest) if rest else real
25
+ except OSError:
26
+ parent = os.path.dirname(cur)
27
+ if parent == cur:
28
+ return p
29
+ rest.insert(0, os.path.basename(cur))
30
+ cur = parent
31
+
32
+
33
+ def unsafe_socket_dir(d):
34
+ """Why a socket folder must not be used, or None when it is safe."""
35
+ try:
36
+ st = os.lstat(d)
37
+ except OSError:
38
+ return None
39
+ if st.st_uid != os.getuid():
40
+ return "belongs to another user"
41
+ if stat.S_ISLNK(st.st_mode):
42
+ return "is a symlink"
43
+ if not stat.S_ISDIR(st.st_mode):
44
+ return "is not a folder"
45
+ mode = stat.S_IMODE(st.st_mode)
46
+ if mode != 0o700:
47
+ return f"is open to other users (mode {mode:o})"
48
+ return None
49
+
50
+
51
+ def socket_base(platform=None, run_dir=None):
52
+ plat = sys.platform if platform is None else platform
53
+ if not plat.startswith("linux"):
54
+ return "/tmp"
55
+ run = run_dir if run_dir is not None else f"/run/user/{os.getuid()}"
56
+ try:
57
+ if stat.S_ISDIR(os.lstat(run).st_mode) and not unsafe_socket_dir(run):
58
+ return run
59
+ except OSError:
60
+ pass
61
+ return "/tmp"
62
+
63
+
64
+ def short_socket_dir(home):
65
+ digest = hashlib.sha256(canonical_home(home).encode("utf-8")).hexdigest()
66
+ return os.path.join(socket_base(), f"oa-bus-{os.getuid()}-{digest[:8]}")
67
+
68
+
69
+ def _fits(p):
70
+ return len(p.encode("utf-8")) <= MAX_SOCKET_PATH
71
+
72
+
73
+ def daemon_socket_path(home):
74
+ plain = os.path.join(canonical_home(home), "daemon.sock")
75
+ return plain if _fits(plain) else os.path.join(short_socket_dir(home), "daemon.sock")
76
+
77
+
78
+ def socket_dir_problem(home):
79
+ """Why the daemon socket for `home` must not be dialed, or None."""
80
+ d = short_socket_dir(home)
81
+ if os.path.dirname(daemon_socket_path(home)) != d:
82
+ return None
83
+ why = unsafe_socket_dir(d)
84
+ return f"{d} {why}" if why else None
85
+
86
+
87
+ def bus_home():
88
+ env = os.environ.get("OA_BUS_HOME")
89
+ return os.path.abspath(env or os.path.join(os.path.expanduser("~"), ".oa-bus"))
90
+
91
+
92
+ def proc_start(pid=None):
93
+ """`TZ=UTC LC_ALL=C ps -o lstart=` for this process: the form the daemon re-reads to attest it."""
94
+ env = {**os.environ, "TZ": "UTC", "LC_ALL": "C"}
95
+ try:
96
+ out = subprocess.run(
97
+ ["ps", "-o", "lstart=", "-p", str(os.getpid() if pid is None else pid)],
98
+ capture_output=True,
99
+ text=True,
100
+ env=env,
101
+ timeout=5,
102
+ check=False,
103
+ ).stdout.strip()
104
+ except (OSError, subprocess.SubprocessError):
105
+ return None
106
+ return out or None
@@ -0,0 +1,235 @@
1
+ """The bus tools: the MCP tools' descriptions and JSON Schemas, named as Pi names them.
2
+
3
+ Names carry an `oabus_` prefix (#1448). Hermes passes each handler the calling
4
+ session as `session_id`; it is resolved to its root, and a subagent is refused.
5
+ """
6
+
7
+ import json
8
+ import time
9
+
10
+ from . import copy
11
+ from .link import LinkError
12
+ from .roots import NotOnBus
13
+
14
+ STATES = ["working", "idle", "blocked", "waiting_on_owner"]
15
+
16
+ _NONE = {"type": "object", "properties": {}, "additionalProperties": False}
17
+
18
+ TOOLS = [
19
+ {
20
+ "name": "oabus_list_agents",
21
+ "description": "List the agents you can message, in your Open Artifacts bus namespace and linked ones.",
22
+ "parameters": _NONE,
23
+ },
24
+ {
25
+ "name": "oabus_send_message",
26
+ "description": "Send a message to another agent by name.",
27
+ "parameters": {
28
+ "type": "object",
29
+ "properties": {
30
+ "to": {"type": "string"},
31
+ "text": {"type": "string"},
32
+ "to_namespace": {
33
+ "type": "string",
34
+ "description": "The recipient's namespace, when the target name exists in several: a global agent's, or a linked project's.",
35
+ },
36
+ },
37
+ "required": ["to", "text"],
38
+ "additionalProperties": False,
39
+ },
40
+ },
41
+ {
42
+ "name": "oabus_fetch",
43
+ "description": "Fetch the full body of an oversized message by id.",
44
+ "parameters": {
45
+ "type": "object",
46
+ "properties": {"msg_id": {"type": "string"}},
47
+ "required": ["msg_id"],
48
+ "additionalProperties": False,
49
+ },
50
+ },
51
+ {
52
+ "name": "oabus_self",
53
+ "description": "Your own Open Artifacts bus agent entry and bus name. To become global, ask the user to approve running `npx @open-artifacts/bus global add <your start dir>`, then restart.",
54
+ "parameters": _NONE,
55
+ },
56
+ {
57
+ "name": "oabus_set_status",
58
+ "description": "Tell the user what you are doing: working, idle, blocked, or waiting_on_owner (waiting on the user), with an optional short label. The user sees it labelled as your own report.",
59
+ "parameters": {
60
+ "type": "object",
61
+ "properties": {
62
+ "state": {"type": "string", "enum": STATES},
63
+ "label": {
64
+ "type": "string",
65
+ "maxLength": 64,
66
+ "description": "What you are on, in a few words.",
67
+ },
68
+ },
69
+ "required": ["state"],
70
+ "additionalProperties": False,
71
+ },
72
+ },
73
+ ]
74
+
75
+
76
+ class ToolError(Exception):
77
+ pass
78
+
79
+
80
+ def _failed(f):
81
+ raise ToolError(f"oa-bus: {f.get('message') if f['type'] == 'error' else f['type']}")
82
+
83
+
84
+ def _roster(link):
85
+ try:
86
+ r = link.request({"type": "list"})
87
+ except LinkError:
88
+ return None
89
+ return r.get("agents", []) if r["type"] == "roster" else None
90
+
91
+
92
+ def run(name, args, link):
93
+ """One tool call on the session's attested link; a `from` argument is never read."""
94
+ if name == "oabus_list_agents":
95
+ r = link.request({"type": "list"})
96
+ if r["type"] != "roster":
97
+ _failed(r)
98
+ agents = r.get("agents", [])
99
+ if not agents:
100
+ return "No agents in your namespace and linked ones."
101
+ now = int(time.time() * 1000)
102
+ return "\n".join(
103
+ copy.roster_line(
104
+ {
105
+ **a,
106
+ "queued": (a.get("state") or ("live" if a.get("live") else "queued")) == "queued",
107
+ "away": str(a.get("since", "")) if a.get("state") == "away" else None,
108
+ },
109
+ now,
110
+ )
111
+ for a in agents
112
+ )
113
+ if name == "oabus_send_message":
114
+ to = str(args.get("to") or "")
115
+ body = str(args.get("text") or "")
116
+ if not to or not body:
117
+ raise ToolError("oa-bus: to and text are required")
118
+ ns = args.get("to_namespace")
119
+ namespace = ns if isinstance(ns, str) and ns else None
120
+ frame = {"type": "send", "to": to, "body": body}
121
+ if namespace:
122
+ frame["namespace"] = namespace
123
+ r = link.request(frame)
124
+ if r["type"] != "receipt":
125
+ _failed(r)
126
+ # The daemon's copy for a send it gave up on (C16): verbatim, not an error.
127
+ if isinstance(r.get("text"), str) and r["text"]:
128
+ return r["text"]
129
+ receipt = {"state": str(r["state"]), "reason": r.get("reason")}
130
+ reason = receipt["reason"]
131
+ n = moved = linked = None
132
+ if reason == "ambiguous":
133
+ agents = _roster(link)
134
+ if agents is not None:
135
+ n = len({a["namespace"] for a in agents if a["name"] == to})
136
+ if reason == "revoked":
137
+ agents = _roster(link)
138
+ if agents is not None:
139
+ moved = copy.moved_name(
140
+ to, [a["name"] for a in agents if namespace is None or a["namespace"] == namespace]
141
+ )
142
+ if reason in ("closed", "revoked") and not namespace:
143
+ agents = _roster(link)
144
+ if agents is not None:
145
+ linked = copy.linked_live_namespace(to, agents)
146
+ out = copy.receipt_text(receipt, to, n, copy.excerpt_of(body), moved, linked)
147
+ if receipt["state"] in ("refused", "expired"):
148
+ raise ToolError(out)
149
+ return out
150
+ if name == "oabus_fetch":
151
+ r = link.request({"type": "fetch", "msg_id": str(args.get("msg_id") or "")})
152
+ if r["type"] != "body":
153
+ _failed(r)
154
+ # A peer's text, like a delivered body; the daemon strips it too.
155
+ return copy.strip_terminal_controls(str(r["body"]))
156
+ if name == "oabus_set_status":
157
+ return _status(args, link)
158
+ r = link.request({"type": "self", "row": True})
159
+ if r["type"] != "agent":
160
+ _failed(r)
161
+ return copy.self_text(r.get("agent"))
162
+
163
+
164
+ def _status(args, link):
165
+ """set_status. Arguments are checked first. Refusals are the daemon's copy, as-is."""
166
+ state = str(args.get("state") or "")
167
+ if state not in STATES:
168
+ raise ToolError(f"oa-bus: state: must be one of {', '.join(STATES)}")
169
+ label = None
170
+ if isinstance(args.get("label"), str):
171
+ label = copy.clean_status_label(args["label"]) or None
172
+ chars = len([*label]) if label else 0
173
+ if chars > 64:
174
+ raise ToolError(copy.status_label_too_long(chars))
175
+ frame = {"type": "set_status", "state": state}
176
+ if label:
177
+ frame["label"] = label
178
+ r = link.request(frame)
179
+ if r["type"] == "error":
180
+ bad = r.get("code") == "bad_frame" and r.get("message") != copy.STATUS_COPY["bad_frame"]
181
+ raise ToolError(copy.STATUS_COPY["bad_frame"] if bad else str(r["message"]))
182
+ if r["type"] == "status_set":
183
+ done = copy.status_set_text(state, label)
184
+ earlier = r.get("earlier")
185
+ return f"{done}\n\n{copy.earlier_status_text(str(earlier['message']))}" if earlier else done
186
+ _failed(r)
187
+
188
+
189
+ class Tools:
190
+ """The handlers Hermes calls: `handler(args, task_id=, session_id=, user_task=)`."""
191
+
192
+ def __init__(self, bus):
193
+ self.bus = bus
194
+
195
+ def call(self, name, args, session_id=None, **_kw):
196
+ try:
197
+ ref = self.bus.roots.resolve(session_id)
198
+ # A failed link is retried in the background as well (ensure schedules it).
199
+ link = self.bus.ensure(ref)
200
+ # Late deliveries the daemon hands back ride after the result, each after a blank line.
201
+ late = []
202
+ tracked = _Tracked(link, late)
203
+ try:
204
+ out = run(name, args if isinstance(args, dict) else {}, tracked)
205
+ except (ToolError, LinkError) as e:
206
+ if not late:
207
+ raise
208
+ raise ToolError("\n\n".join([str(e), *late])) from None
209
+ return "\n\n".join([out, *late])
210
+ except NotOnBus as e:
211
+ return json.dumps({"error": str(e)})
212
+ except (ToolError, LinkError) as e:
213
+ return json.dumps({"error": f"oa-bus: {e}" if isinstance(e, LinkError) else str(e)})
214
+
215
+ def handler(self, name):
216
+ def handle(args, **kw):
217
+ return self.call(name, args, **kw)
218
+
219
+ return handle
220
+
221
+
222
+ class _Tracked:
223
+ """A link whose requests ask for late-delivery notices."""
224
+
225
+ def __init__(self, link, late):
226
+ self._link = link
227
+ self._late = late
228
+ self.welcome = link.welcome
229
+
230
+ def request(self, frame, timeout=None):
231
+ extra = {} if timeout is None else {"timeout": timeout}
232
+ r = self._link.request({**frame, "late": True}, **extra)
233
+ if isinstance(r.get("late"), list):
234
+ self._late.extend(t for t in r["late"] if isinstance(t, str))
235
+ return r
@@ -0,0 +1,29 @@
1
+ """The frame a peer's message reaches Hermes in.
2
+
3
+ The same `<cross-session-message>` wrapper Claude Code gets
4
+ (bus-adapter-claude-code/src/inject.ts): a body can neither close it nor open
5
+ a second one with a forged sender.
6
+ """
7
+
8
+ import re
9
+
10
+ from .copy import WS
11
+
12
+ # JavaScript's /i is ASCII-only here, and its \s is the WS class.
13
+ _NESTED = re.compile(rf"<([{WS}]*/?[{WS}]*cross-session-message)", re.IGNORECASE | re.ASCII)
14
+
15
+
16
+ def attr(s):
17
+ return s.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")
18
+
19
+
20
+ def neutralize(s):
21
+ return _NESTED.sub(lambda m: "&lt;" + m.group(1), s)
22
+
23
+
24
+ def wrap(from_name, text, source="oa-bus"):
25
+ """`text` inside the wrapper, a sender that is the bus's own word for it."""
26
+ return (
27
+ f'<cross-session-message from="{attr(source)}" from-name="{attr(from_name)}" '
28
+ f'from-mode="prompting">\n{neutralize(text)}\n</cross-session-message>'
29
+ )