@open-artifacts/bus 0.144.0 → 0.146.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.
@@ -2,15 +2,26 @@
2
2
 
3
3
  import atexit
4
4
 
5
+ from . import proof as _proof
6
+
5
7
  from .bus import Bus
6
8
  from .roots import Roots
7
9
  from .tools import TOOLS, Tools
8
10
 
9
11
 
10
- def register(ctx, roots=None, bus=None):
12
+ def _servers():
13
+ return _proof.proof_servers()
14
+
15
+
16
+ def register(ctx, roots=None, bus=None, proof_servers=None, install=None):
17
+ """`proof_servers` (this instance's raw MCP server names) and `install` (what puts the proof
18
+ argument on the wire, see proof.py) are replaced in tests."""
11
19
  roots = roots or Roots()
12
20
  bus = bus or Bus(roots, inject=ctx.inject_message)
13
21
  tools = Tools(bus)
22
+ mine = proof_servers if proof_servers is not None else _servers()
23
+ put_on_wire = install or _proof.install
24
+ installed = []
14
25
 
15
26
  for tool in TOOLS:
16
27
  ctx.register_tool(
@@ -23,6 +34,14 @@ def register(ctx, roots=None, bus=None):
23
34
 
24
35
  # Hooks get keyword arguments only, and may gain more: always take **kwargs.
25
36
  def pre_llm_call(session_id=None, platform=None, user_message=None, conversation_history=None, **_kw):
37
+ # #1822: the proof argument, once Hermes has loaded: never at registration. Any failure
38
+ # leaves roots unlinked and the turn as it was.
39
+ if not installed:
40
+ installed.append(True)
41
+ try:
42
+ put_on_wire(bus, mine)
43
+ except Exception:
44
+ pass
26
45
  return bus.turn_start(session_id, platform, user_message, conversation_history)
27
46
 
28
47
  def on_session_end(session_id=None, **_kw):
@@ -39,4 +58,9 @@ def register(ctx, roots=None, bus=None):
39
58
  ctx.register_hook("on_session_finalize", on_session_finalize)
40
59
  ctx.register_hook("subagent_start", subagent_start)
41
60
  atexit.register(bus.close_all)
61
+ # A reload unloads the plugin without exiting: shut this Bus then, so the next one can take over
62
+ # the proof wiring. An older Hermes has no on_unload.
63
+ on_unload = getattr(ctx, "on_unload", None)
64
+ if callable(on_unload):
65
+ on_unload(bus.close_all)
42
66
  return bus
@@ -0,0 +1,177 @@
1
+ """The per-session proof argument (#1822, #1856).
2
+
3
+ The instance's /mcp reads a reserved argument on a `tools/call` to tell which
4
+ bus agent is calling. It must reach the wire and nothing else: Hermes shows a
5
+ call's arguments to hooks, callbacks, approval prompts, its tool guardrails (a
6
+ repeated call's stub result prints them to the model) and the CLI progress line.
7
+ So it is added at the last layer, in Hermes's one function that hands arguments
8
+ to the MCP SDK (tools/mcp_tool_handlers.py `_call_tool_racing_stdio_death`,
9
+ Hermes v0.23.0), and not by middleware, whose output every layer above sees.
10
+
11
+ How the proof gets from the agent thread to that function, which runs on the MCP
12
+ loop thread and has no session: `registry.dispatch` (tools/registry.py, the
13
+ last call before the handler, which receives the same `args` object) hands the
14
+ handler a copy of the arguments and notes the session's proof under that copy's
15
+ identity; the wire function looks the identity up. Its `server_name` is the raw
16
+ server name Hermes was configured with, so the match is exact: `open-artifacts`
17
+ and `open_artifacts` make the same registry prefix but are different names here.
18
+
19
+ One process, several profiles: the first Bus to install is wired in (see `install`); a second
20
+ profile stays unlinked, with no second link and no overwritten hash, unless the first is shut
21
+ down (a plugin reload), when the new Bus takes over. The dispatch path is a
22
+ read: it never opens a link.
23
+
24
+ Every piece fails to unlinked: a missing function leaves both untouched, an error
25
+ finding the proof sends the call as it was, a call that did not come through
26
+ `dispatch` finds no note.
27
+ """
28
+
29
+ import functools
30
+ import inspect
31
+
32
+ # The reserved argument the instance's /mcp reads and removes.
33
+ ARG = "_oa_agent_proof"
34
+
35
+ # The raw MCP server key of an instance's entry: exactly this, nothing else is trusted.
36
+ DEFAULT_SERVERS = ("open-artifacts",)
37
+
38
+ # id(args copy handed to the handler) -> the proof for that call, only while it is in flight.
39
+ _CALLS = {}
40
+ _MARK = "_oa_proof_wrapper"
41
+ _CFG = "_oa_proof_cfg"
42
+
43
+
44
+ def proof_servers():
45
+ """The raw server names that are this instance's."""
46
+ return DEFAULT_SERVERS
47
+
48
+
49
+ def _wire_wrapper(original, cfg):
50
+ async def wrapped(*a, **kw):
51
+ a2, kw2 = a, kw
52
+ try:
53
+ # (server, server_name, tool_name, args, progress_callback=None)
54
+ if "args" in kw:
55
+ args, server_name = kw["args"], kw.get("server_name", a[1] if len(a) > 1 else None)
56
+ else:
57
+ args, server_name = (a[3], a[1]) if len(a) > 3 else (None, None)
58
+ proof = _CALLS.get(id(args)) if isinstance(args, dict) else None
59
+ if proof and isinstance(server_name, str) and server_name in cfg["names"]:
60
+ send = {**args, ARG: proof}
61
+ if "args" in kw:
62
+ kw2 = {**kw, "args": send}
63
+ else:
64
+ a2 = a[:3] + (send,) + a[4:]
65
+ except Exception:
66
+ a2, kw2 = a, kw
67
+ return await original(*a2, **kw2)
68
+
69
+ functools.update_wrapper(wrapped, original, assigned=("__name__", "__qualname__", "__doc__"), updated=())
70
+ setattr(wrapped, _MARK, original)
71
+ setattr(wrapped, _CFG, cfg)
72
+ return wrapped
73
+
74
+
75
+ def _dispatch_wrapper(original, cfg):
76
+ def wrapped(name, args, **kwargs):
77
+ sent = args
78
+ key = None
79
+ try:
80
+ bus = cfg["bus"]
81
+ if bus is not None and isinstance(name, str) and name.startswith("mcp__") and isinstance(args, dict):
82
+ proof = bus.proof_for(kwargs.get("session_id"))
83
+ if proof:
84
+ sent = dict(args) # a copy with a identity of its own, and the same content
85
+ key = id(sent)
86
+ _CALLS[key] = proof
87
+ except Exception:
88
+ sent, key = args, None
89
+ try:
90
+ return original(name, sent, **kwargs)
91
+ finally:
92
+ if key is not None:
93
+ _CALLS.pop(key, None)
94
+
95
+ setattr(wrapped, _MARK, original)
96
+ setattr(wrapped, _CFG, cfg)
97
+ return wrapped
98
+
99
+
100
+ def _positional(fn):
101
+ """The names of fn's parameters that can be passed by position, in order; None when unreadable."""
102
+ try:
103
+ params = inspect.signature(fn).parameters.values()
104
+ except (TypeError, ValueError):
105
+ return None
106
+ return [p for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
107
+
108
+
109
+ def _dispatch_fits(fn):
110
+ """dispatch(name, args, ..., **kwargs): the wrapper reads `name` and `args` by position and
111
+ `session_id` from the keywords, so it must be able to take them."""
112
+ try:
113
+ pos = _positional(fn)
114
+ if pos is None or [p.name for p in pos[:2]] != ["name", "args"]:
115
+ return False
116
+ params = inspect.signature(fn).parameters
117
+ return "session_id" in params and params["session_id"].kind != inspect.Parameter.POSITIONAL_ONLY or any(
118
+ p.kind is p.VAR_KEYWORD for p in params.values()
119
+ )
120
+ except Exception:
121
+ return False
122
+
123
+
124
+ def _wire_fits(fn):
125
+ """(server, server_name, tool_name, args, ...): the wrapper reads server_name and args by
126
+ position 1 and 3, or by keyword."""
127
+ try:
128
+ pos = _positional(fn)
129
+ return pos is not None and len(pos) >= 4 and pos[1].name == "server_name" and pos[3].name == "args"
130
+ except Exception:
131
+ return False
132
+
133
+
134
+ def _holder_is_free(cfg):
135
+ """True when the Bus holding the wiring is shut down. Anything it cannot
136
+ say counts as in use."""
137
+ try:
138
+ return cfg["bus"].wiring_free() is True
139
+ except Exception:
140
+ return False
141
+
142
+
143
+ def install(bus, names, registry=None, handlers=None):
144
+ """Wraps the two Hermes functions, once per process. True when `bus` is the one in charge of them.
145
+
146
+ Several Hermes profiles can load this plugin into one process, each with its own Bus. The first
147
+ install wins; a later one for another Bus changes nothing and returns False: that profile stays
148
+ unlinked (its sessions find no open link in the first Bus, so they get no proof), and it opens no
149
+ second link and overwrites no hash. False too, with nothing touched, when Hermes lacks either
150
+ function."""
151
+ try:
152
+ if registry is None:
153
+ from tools.registry import registry # only importable inside Hermes
154
+ if handlers is None:
155
+ import tools.mcp_tool_handlers as handlers
156
+ dispatch = getattr(registry, "dispatch", None)
157
+ wire = getattr(handlers, "_call_tool_racing_stdio_death", None)
158
+ if not callable(dispatch) or not callable(wire):
159
+ return False
160
+ cfg = getattr(dispatch, _CFG, None) or getattr(wire, _CFG, None)
161
+ if cfg is not None:
162
+ if cfg["bus"] is bus:
163
+ return True
164
+ # A plugin reload makes a new Bus: it takes the wiring over once the holder is shut down.
165
+ # Never while it runs, even with no link open: that is another profile, which stays unlinked.
166
+ if not _holder_is_free(cfg):
167
+ return False
168
+ cfg["bus"], cfg["names"] = bus, tuple(names)
169
+ return True
170
+ if not (_dispatch_fits(dispatch) and _wire_fits(wire)):
171
+ return False
172
+ cfg = {"bus": bus, "names": tuple(names)}
173
+ registry.dispatch = _dispatch_wrapper(dispatch, cfg)
174
+ handlers._call_tool_racing_stdio_death = _wire_wrapper(wire, cfg)
175
+ return True
176
+ except Exception:
177
+ return False