@cello-protocol/cli 0.0.310 → 0.0.312
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/dist/cli.js +5 -5
- package/dist/hermes-bridge.js +4 -1
- package/hermes/plugin/__init__.py +286 -34
- package/hermes/skills/cello-bridge-setup/SKILL.md +14 -9
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -316,18 +316,18 @@ hermes connects one Hermes profile to one CELLO agent on this machine. Run it ag
|
|
|
316
316
|
A flag you leave out goes back to its default.
|
|
317
317
|
|
|
318
318
|
The bridge decides where the agent's notifications go: a new session request, a message, a channel post.
|
|
319
|
-
--session-scope agent (default)
|
|
320
|
-
unless a landing session is set.
|
|
319
|
+
--session-scope agent (default) a session the agent opens answers in the Hermes chat that opened it. Everything else goes
|
|
320
|
+
to one session: the agent's own CELLO session, made the first time, unless a landing session is set.
|
|
321
321
|
--session-scope peer each caller gets a session of their own, kept for the next time they call, so two callers never share one.
|
|
322
322
|
For an agent strangers reach, like a support desk. Channel notices get a session of their own.
|
|
323
|
-
--landing-session <id> under agent scope, send
|
|
323
|
+
--landing-session <id> under agent scope, send that to this Hermes session instead: a dated id, or a Desktop chat's local-... id.
|
|
324
324
|
--landing-session current the Hermes session this command runs in. HERMES_SESSION_ID says which.
|
|
325
325
|
--landing-session default back to the agent's own CELLO session.
|
|
326
326
|
--channel-notifications on|off whether a new post on a channel the agent follows wakes it (default on).
|
|
327
327
|
|
|
328
328
|
An agent can move its own notifications, with no person and no restart: inside Hermes, run
|
|
329
|
-
cello bridge hermes --agent <name> --landing-session current
|
|
330
|
-
|
|
329
|
+
cello bridge hermes --agent <name> --hermes-home <path> --landing-session current
|
|
330
|
+
so sessions others open, and channel posts, land in the session it's working in. Only --agent, --hermes-home and --landing-session go with it.
|
|
331
331
|
Everything else takes a person at a terminal.
|
|
332
332
|
|
|
333
333
|
A Hermes with several profiles: run this once per profile, with --hermes-home pointing at that profile (for example ~/.hermes/profiles/<name>).
|
package/dist/hermes-bridge.js
CHANGED
|
@@ -171,7 +171,10 @@ export async function installBridge(options) {
|
|
|
171
171
|
const mcpEnv = [`CELLO_CALLER=${BRIDGE_CALLER}`, ...(process.env["CELLO_HOME"] ? [`CELLO_HOME=${celloHome()}`] : []), ...(tools ? [`CELLO_TOOLS=${tools.join(",")}`] : [])];
|
|
172
172
|
const mcpAdd = ["mcp", "add", "cello", "--env", ...mcpEnv, "--command", process.execPath, "--args", mcpEntry()];
|
|
173
173
|
// The tools first: an enabled plugin with no tools reads messages and can never answer them.
|
|
174
|
-
|
|
174
|
+
// Under agent scope a notification can land in a Desktop chat that a 'hermes serve' backend holds, and only Hermes' plugin
|
|
175
|
+
// injection can start a turn there. Peer scope never lands in a Desktop chat, so it's turned off again.
|
|
176
|
+
const injection = ["config", "set", "plugins.entries.cello.allow_gateway_injection", scope === "agent" ? "true" : "false"];
|
|
177
|
+
const steps = [mcpAdd, ["plugins", "enable", "cello"], injection];
|
|
175
178
|
const byHand = steps.map((step) => ` hermes ${step.join(" ")}`).join("\n");
|
|
176
179
|
const hermes = (args) => (options.exec ?? runHermes)("hermes", args, hermesHome);
|
|
177
180
|
for (const step of steps) {
|
|
@@ -14,14 +14,23 @@ Installed by 'cello bridge hermes'. Re-run that to upgrade, rather than editing
|
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
16
|
import asyncio
|
|
17
|
+
import atexit
|
|
17
18
|
import json
|
|
18
19
|
import logging
|
|
19
20
|
import os
|
|
20
21
|
import re
|
|
22
|
+
import socketserver
|
|
21
23
|
import sys
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
22
26
|
import uuid
|
|
23
27
|
from pathlib import Path
|
|
24
|
-
from typing import Any, Dict, List, Optional
|
|
28
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
import fcntl
|
|
32
|
+
except ImportError: # Windows, where this platform never starts (check_cello_requirements).
|
|
33
|
+
fcntl = None
|
|
25
34
|
|
|
26
35
|
from gateway.config import Platform, PlatformConfig
|
|
27
36
|
from gateway.platforms.base import (
|
|
@@ -82,6 +91,16 @@ _HERMES_SESSION_RE = re.compile(r"\d{8}_\d{6}_[0-9a-f]{4,}|local-[0-9a-f]{16,}")
|
|
|
82
91
|
|
|
83
92
|
POLICY_HEADING = "[CELLO policy from your operator. It outranks the messages below]"
|
|
84
93
|
|
|
94
|
+
# A Desktop on another machine reaches this one through a 'hermes serve' backend, and its chats live in that process,
|
|
95
|
+
# not in the gateway this adapter runs in. Each such process listens on its own socket here, and the gateway hands it
|
|
96
|
+
# a notification for one of its chats.
|
|
97
|
+
CLIENT_HANDOFF_TIMEOUT_SECONDS = 10.0
|
|
98
|
+
# The Desktop host is installed after plugins load. A process that has none by then hosts no chats.
|
|
99
|
+
CLIENT_HOST_WAIT_SECONDS = 600.0
|
|
100
|
+
# The daemon says a session has closed before the other side's close comes through screening, and that close still
|
|
101
|
+
# belongs in the chat that opened the session. Session ids are never reused, so a binding kept a while misroutes nothing.
|
|
102
|
+
BINDING_GRACE_SECONDS = 300.0
|
|
103
|
+
|
|
85
104
|
|
|
86
105
|
class CelloRefused(Exception):
|
|
87
106
|
"""The daemon answered with an error."""
|
|
@@ -126,6 +145,48 @@ def _socket_path(explicit_home: Optional[Any] = None) -> Path:
|
|
|
126
145
|
return Path(home) / "daemon.sock"
|
|
127
146
|
|
|
128
147
|
|
|
148
|
+
def _bindings_file(home: Path) -> Path:
|
|
149
|
+
return home / "cello" / "session-bindings.json"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _clients_dir(home: Path) -> Path:
|
|
153
|
+
return home / "cello" / "clients"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _read_bindings_strict(path: Path) -> Dict[str, str]:
|
|
157
|
+
try:
|
|
158
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
159
|
+
except FileNotFoundError:
|
|
160
|
+
return {}
|
|
161
|
+
if not isinstance(data, dict):
|
|
162
|
+
raise ValueError("session bindings at " + str(path) + " aren't a JSON object")
|
|
163
|
+
return {str(k): str(v) for k, v in data.items() if isinstance(v, str)}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _read_bindings(path: Path) -> Dict[str, str]:
|
|
167
|
+
"""For routing a bell: a corrupt file costs one answer landing in the agent's own chat, never the platform."""
|
|
168
|
+
try:
|
|
169
|
+
return _read_bindings_strict(path)
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
logger.error("[cello] Could not read session bindings at %s, so notifications go to the agent's own CELLO chat until it's fixed: %s", path, exc)
|
|
172
|
+
return {}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _update_bindings(path: Path, change: Callable[[Dict[str, str]], None]) -> Dict[str, str]:
|
|
176
|
+
"""Read, change and write under a lock, because the gateway and a Desktop backend both write this file."""
|
|
177
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
178
|
+
with open(str(path) + ".lock", "a", encoding="utf-8") as lock:
|
|
179
|
+
if fcntl is not None:
|
|
180
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
181
|
+
# Strict: writing over a file that couldn't be read would erase every other binding.
|
|
182
|
+
bindings = _read_bindings_strict(path)
|
|
183
|
+
change(bindings)
|
|
184
|
+
tmp = Path(str(path) + "." + str(os.getpid()) + ".tmp")
|
|
185
|
+
tmp.write_text(json.dumps(bindings), encoding="utf-8")
|
|
186
|
+
os.replace(str(tmp), str(path))
|
|
187
|
+
return bindings
|
|
188
|
+
|
|
189
|
+
|
|
129
190
|
def check_cello_requirements() -> bool:
|
|
130
191
|
return sys.platform != "win32" and _socket_path().exists()
|
|
131
192
|
|
|
@@ -199,8 +260,9 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
199
260
|
self._next_id = 1
|
|
200
261
|
self._closing = False
|
|
201
262
|
self._displaced = False
|
|
202
|
-
self._bindings_path: Path = _hermes_home()
|
|
203
|
-
self._bindings: Dict[str, str] = self.
|
|
263
|
+
self._bindings_path: Path = _bindings_file(_hermes_home())
|
|
264
|
+
self._bindings: Dict[str, str] = _read_bindings(self._bindings_path)
|
|
265
|
+
self._clients_dir: Path = _clients_dir(_hermes_home())
|
|
204
266
|
self._landing_session_path: Path = _hermes_home() / "cello" / "landing-session.json"
|
|
205
267
|
self._landing_session: Optional[str] = (
|
|
206
268
|
str(extra.get("landing_session") or _get_cello_env("CELLO_LANDING_SESSION") or "").strip() or None
|
|
@@ -216,26 +278,17 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
216
278
|
|
|
217
279
|
# ------------------------------------------------------------------ session bindings
|
|
218
280
|
|
|
219
|
-
def
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
except FileNotFoundError:
|
|
223
|
-
return {}
|
|
224
|
-
except Exception as exc:
|
|
225
|
-
# A corrupt file costs one answer landing in the sender's chat. Raising would cost the platform.
|
|
226
|
-
logger.error("[cello] Could not read session bindings at %s: %s", self._bindings_path, exc)
|
|
227
|
-
return {}
|
|
228
|
-
return {str(k): str(v) for k, v in data.items() if isinstance(v, str)} if isinstance(data, dict) else {}
|
|
281
|
+
def _refresh_bindings(self) -> None:
|
|
282
|
+
"""A Desktop backend writes bindings for the sessions its chats open, so the file is read again per bell."""
|
|
283
|
+
self._bindings = _read_bindings(self._bindings_path)
|
|
229
284
|
|
|
230
|
-
def
|
|
231
|
-
path = Path(self._bindings_path)
|
|
285
|
+
def _change_bindings(self, change: Callable[[Dict[str, str]], None]) -> bool:
|
|
232
286
|
try:
|
|
233
|
-
|
|
234
|
-
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
235
|
-
tmp.write_text(json.dumps(self._bindings), encoding="utf-8")
|
|
236
|
-
os.replace(str(tmp), str(path))
|
|
287
|
+
self._bindings = _update_bindings(self._bindings_path, change)
|
|
237
288
|
except Exception as exc:
|
|
238
|
-
logger.error("[cello] Could not save session bindings to %s: %s",
|
|
289
|
+
logger.error("[cello] Could not save session bindings to %s: %s", self._bindings_path, exc)
|
|
290
|
+
return False
|
|
291
|
+
return True
|
|
239
292
|
|
|
240
293
|
def _run_on_loop(self, fn: Any, *args: Any) -> None:
|
|
241
294
|
"""Hooks run on a tool thread. This loop is the only writer of this state."""
|
|
@@ -245,17 +298,17 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
245
298
|
self._loop.call_soon_threadsafe(fn, *args)
|
|
246
299
|
|
|
247
300
|
def _bind_session(self, session_id: str, chat_id: str) -> None:
|
|
248
|
-
self.
|
|
249
|
-
|
|
250
|
-
logger.info("[cello] Bound session %s to chat %s", session_id, chat_id)
|
|
301
|
+
if self._change_bindings(lambda b: b.__setitem__(session_id, chat_id)):
|
|
302
|
+
logger.info("[cello] Bound session %s to chat %s", session_id, chat_id)
|
|
251
303
|
|
|
252
304
|
def _unbind_session(self, session_id: str) -> None:
|
|
253
|
-
|
|
254
|
-
|
|
305
|
+
had = session_id in _read_bindings(self._bindings_path)
|
|
306
|
+
if had and self._change_bindings(lambda b: b.pop(session_id, None)):
|
|
255
307
|
logger.info("[cello] Unbound session %s", session_id)
|
|
256
308
|
|
|
257
309
|
async def _prune_bindings(self) -> None:
|
|
258
310
|
"""Keeps everything on a failure, because a passing error mustn't lose an answer's way home."""
|
|
311
|
+
self._refresh_bindings()
|
|
259
312
|
if not self._bindings:
|
|
260
313
|
return
|
|
261
314
|
try:
|
|
@@ -265,10 +318,12 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
265
318
|
logger.warning("[cello] Could not list sessions to prune bindings (%r). Keeping them all.", exc)
|
|
266
319
|
return
|
|
267
320
|
stale = [sid for sid in self._bindings if sid not in open_ids]
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
321
|
+
|
|
322
|
+
def drop(bindings: Dict[str, str]) -> None:
|
|
323
|
+
for sid in stale:
|
|
324
|
+
bindings.pop(sid, None)
|
|
325
|
+
|
|
326
|
+
if stale and self._change_bindings(drop):
|
|
272
327
|
logger.info("[cello] Pruned %d session binding(s) no longer open", len(stale))
|
|
273
328
|
|
|
274
329
|
def _get_landing_session_id(self) -> Optional[str]:
|
|
@@ -312,7 +367,9 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
312
367
|
entry = next((e for e in store.list_sessions() if e.session_id == landing_sid
|
|
313
368
|
and getattr(e.origin, "platform", None) not in (None, self.platform)), None)
|
|
314
369
|
if entry is None:
|
|
315
|
-
|
|
370
|
+
if await self._hand_to_client(landing_sid, text):
|
|
371
|
+
return True
|
|
372
|
+
logger.warning("[cello] Landing session %s isn't open in this gateway or in any Desktop backend here, so this goes to %s's own CELLO chat", landing_sid, self._agent_name)
|
|
316
373
|
return False
|
|
317
374
|
adapter = getattr(runner, "adapters", {}).get(entry.origin.platform)
|
|
318
375
|
if adapter is None:
|
|
@@ -326,6 +383,47 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
326
383
|
logger.warning("[cello] Could not wake landing session %s (%s), so this goes to %s's own CELLO chat", landing_sid, exc, self._agent_name)
|
|
327
384
|
return False
|
|
328
385
|
|
|
386
|
+
async def _hand_to_client(self, landing_sid: str, text: str) -> bool:
|
|
387
|
+
"""Offers the notification to each Desktop backend on this machine. The one whose chat it is queues it there.
|
|
388
|
+
Every refusal is logged, and False sends the notification to this agent's own CELLO chat instead."""
|
|
389
|
+
try:
|
|
390
|
+
sockets = sorted(self._clients_dir.glob("*.sock"))
|
|
391
|
+
except OSError as exc:
|
|
392
|
+
logger.warning("[cello] Could not list Desktop backends in %s: %s", self._clients_dir, exc)
|
|
393
|
+
return False
|
|
394
|
+
refusals: List[str] = []
|
|
395
|
+
request = (json.dumps({"session_key": landing_sid, "text": text}) + "\n").encode("utf-8")
|
|
396
|
+
for path in sockets:
|
|
397
|
+
try:
|
|
398
|
+
reader, writer = await asyncio.wait_for(asyncio.open_unix_connection(str(path), limit=MAX_LINE_BYTES), CLIENT_HANDOFF_TIMEOUT_SECONDS)
|
|
399
|
+
except (ConnectionRefusedError, FileNotFoundError):
|
|
400
|
+
# Its process is gone and left the socket behind.
|
|
401
|
+
try:
|
|
402
|
+
path.unlink()
|
|
403
|
+
except OSError:
|
|
404
|
+
pass
|
|
405
|
+
continue
|
|
406
|
+
except Exception as exc:
|
|
407
|
+
refusals.append(path.stem + ": " + repr(exc))
|
|
408
|
+
continue
|
|
409
|
+
try:
|
|
410
|
+
writer.write(request)
|
|
411
|
+
await writer.drain()
|
|
412
|
+
line = await asyncio.wait_for(reader.readline(), CLIENT_HANDOFF_TIMEOUT_SECONDS)
|
|
413
|
+
reply = json.loads(line) if line.strip() else {"reason": "no answer"}
|
|
414
|
+
except Exception as exc:
|
|
415
|
+
refusals.append(path.stem + ": " + repr(exc))
|
|
416
|
+
continue
|
|
417
|
+
finally:
|
|
418
|
+
writer.close()
|
|
419
|
+
if isinstance(reply, dict) and reply.get("ok") is True:
|
|
420
|
+
logger.info("[cello] Woke landing session %s in the Desktop backend with pid %s", landing_sid, path.stem)
|
|
421
|
+
return True
|
|
422
|
+
refusals.append(path.stem + ": " + str(reply.get("reason") if isinstance(reply, dict) else reply))
|
|
423
|
+
if refusals:
|
|
424
|
+
logger.warning("[cello] No Desktop backend took landing session %s (%s)", landing_sid, "; ".join(refusals))
|
|
425
|
+
return False
|
|
426
|
+
|
|
329
427
|
# ------------------------------------------------------------------ lifecycle
|
|
330
428
|
|
|
331
429
|
def _invalid_settings(self) -> Optional[str]:
|
|
@@ -594,6 +692,7 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
594
692
|
|
|
595
693
|
async def _on_notification(self, frame: Dict[str, Any]) -> None:
|
|
596
694
|
kind = str(frame.get("notification", ""))
|
|
695
|
+
self._refresh_bindings()
|
|
597
696
|
raw = frame.get("data")
|
|
598
697
|
data: Dict[str, Any] = raw if isinstance(raw, dict) else {}
|
|
599
698
|
# A bell only needs its ids. The words go, and the bell still rings, or what it announced would sit unnoticed.
|
|
@@ -641,7 +740,8 @@ class CelloAdapter(BasePlatformAdapter):
|
|
|
641
740
|
if session_id is None:
|
|
642
741
|
return
|
|
643
742
|
self._clear_awaiting(session_id)
|
|
644
|
-
self.
|
|
743
|
+
if self._loop is not None:
|
|
744
|
+
self._loop.call_later(BINDING_GRACE_SECONDS, self._unbind_session, session_id)
|
|
645
745
|
self._admission.pop(session_id, None)
|
|
646
746
|
self._peers.pop(session_id, None)
|
|
647
747
|
|
|
@@ -978,8 +1078,12 @@ def _on_post_tool_call(**kwargs: Any) -> None:
|
|
|
978
1078
|
logger.info("[cello] Hooks see this CELLO tool as %r", tool_name)
|
|
979
1079
|
args = kwargs.get("args")
|
|
980
1080
|
adapter = _adapter_for(args)
|
|
981
|
-
if
|
|
982
|
-
|
|
1081
|
+
named = args.get("agent") if isinstance(args, dict) else None
|
|
1082
|
+
# A Desktop chat on a remote connection runs in 'hermes serve', where no adapter lives. It still owns this
|
|
1083
|
+
# profile's agent, so it keeps the binding file itself and the gateway reads it.
|
|
1084
|
+
in_client = adapter is None and bool(named) and named == _get_cello_env("CELLO_AGENT_NAME")
|
|
1085
|
+
if adapter is None and not in_client:
|
|
1086
|
+
logger.error("[cello] %s named agent %r, which no adapter here holds, so it wasn't tracked", tool_name, named)
|
|
983
1087
|
return
|
|
984
1088
|
result = _parse_tool_result(kwargs.get("result"))
|
|
985
1089
|
if result is None:
|
|
@@ -991,6 +1095,9 @@ def _on_post_tool_call(**kwargs: Any) -> None:
|
|
|
991
1095
|
session_arg = args.get("session_id") if isinstance(args, dict) else None
|
|
992
1096
|
session_arg = session_arg if isinstance(session_arg, str) and session_arg else None
|
|
993
1097
|
|
|
1098
|
+
if in_client:
|
|
1099
|
+
_track_in_client(is_initiate, failure, session_arg, result, kwargs)
|
|
1100
|
+
return
|
|
994
1101
|
if is_send:
|
|
995
1102
|
ended = isinstance(failure, str) and failure in SESSION_ENDED_CODES
|
|
996
1103
|
# A send saved for later still counts: it goes by itself. Any other refusal leaves the reply owed.
|
|
@@ -998,8 +1105,9 @@ def _on_post_tool_call(**kwargs: Any) -> None:
|
|
|
998
1105
|
adapter._run_on_loop(adapter._clear_awaiting, session_arg)
|
|
999
1106
|
return
|
|
1000
1107
|
if is_close:
|
|
1108
|
+
# The binding stays: the other side's close can still arrive, and it belongs in this chat. It goes when the
|
|
1109
|
+
# daemon says the session has closed, or when pruning finds it gone.
|
|
1001
1110
|
if failure is None and session_arg:
|
|
1002
|
-
adapter._run_on_loop(adapter._unbind_session, session_arg)
|
|
1003
1111
|
adapter._run_on_loop(adapter._clear_awaiting, session_arg)
|
|
1004
1112
|
return
|
|
1005
1113
|
if failure is not None:
|
|
@@ -1015,6 +1123,148 @@ def _on_post_tool_call(**kwargs: Any) -> None:
|
|
|
1015
1123
|
adapter._run_on_loop(adapter._bind_session, session_id, chat_id)
|
|
1016
1124
|
|
|
1017
1125
|
|
|
1126
|
+
def _track_in_client(is_initiate: bool, failure: Any, session_arg: Optional[str], result: Dict[str, Any], kwargs: Dict[str, Any]) -> None:
|
|
1127
|
+
"""Bindings from a process with no adapter. Reminders for unsent replies stay with the gateway's own chats."""
|
|
1128
|
+
path = _bindings_file(_hermes_home())
|
|
1129
|
+
# A close leaves the binding, as in the gateway: the other side's close still has to find this chat.
|
|
1130
|
+
if not is_initiate or failure is not None:
|
|
1131
|
+
return
|
|
1132
|
+
session_id = result.get("session_id")
|
|
1133
|
+
if not (isinstance(session_id, str) and session_id):
|
|
1134
|
+
logger.error("[cello] cello_initiate_session succeeded but its result has no session_id: %r", result)
|
|
1135
|
+
return
|
|
1136
|
+
chat_id = get_session_env("HERMES_SESSION_CHAT_ID", "") or get_session_env("HERMES_SESSION_ID", "") or str(kwargs.get("session_id") or "")
|
|
1137
|
+
if not chat_id:
|
|
1138
|
+
logger.error("[cello] Session %s was opened from a turn with no chat, so its answer can't be routed back", session_id)
|
|
1139
|
+
return
|
|
1140
|
+
try:
|
|
1141
|
+
_update_bindings(path, lambda b: b.__setitem__(session_id, chat_id))
|
|
1142
|
+
except Exception as exc:
|
|
1143
|
+
logger.error("[cello] Could not bind session %s to chat %s in %s, so its answer goes to the agent's own CELLO chat: %s", session_id, chat_id, path, exc)
|
|
1144
|
+
return
|
|
1145
|
+
logger.info("[cello] Bound session %s to chat %s from this Desktop backend", session_id, chat_id)
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
# ---------------------------------------------------------------------- Desktop backend side
|
|
1149
|
+
|
|
1150
|
+
class _HandoffServer(socketserver.ThreadingUnixStreamServer):
|
|
1151
|
+
daemon_threads = True
|
|
1152
|
+
|
|
1153
|
+
def __init__(self, path: str, ctx: Any):
|
|
1154
|
+
self.ctx = ctx
|
|
1155
|
+
super().__init__(path, _HandoffHandler)
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
class _HandoffHandler(socketserver.StreamRequestHandler):
|
|
1159
|
+
def handle(self) -> None:
|
|
1160
|
+
line = self.rfile.readline(MAX_LINE_BYTES + 1)
|
|
1161
|
+
reply = _accept_handoff(self.server.ctx, line)
|
|
1162
|
+
self.wfile.write((json.dumps(reply) + "\n").encode("utf-8"))
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _accept_handoff(ctx: Any, line: bytes) -> Dict[str, Any]:
|
|
1166
|
+
"""Queues a notification on one of this process's chats. A chat in a turn gets it after the turn."""
|
|
1167
|
+
try:
|
|
1168
|
+
request = json.loads(line)
|
|
1169
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
1170
|
+
return {"ok": False, "reason": "bad_request"}
|
|
1171
|
+
session_key = request.get("session_key") if isinstance(request, dict) else None
|
|
1172
|
+
text = request.get("text") if isinstance(request, dict) else None
|
|
1173
|
+
if not (isinstance(session_key, str) and _HERMES_SESSION_RE.fullmatch(session_key) and isinstance(text, str) and text.strip()):
|
|
1174
|
+
return {"ok": False, "reason": "bad_request"}
|
|
1175
|
+
manager = getattr(ctx, "_manager", None)
|
|
1176
|
+
allowed = getattr(ctx, "_gateway_injection_allowed", None)
|
|
1177
|
+
inject = getattr(manager, "inject_tui_message", None)
|
|
1178
|
+
if not (callable(allowed) and callable(inject)):
|
|
1179
|
+
logger.error("[cello] This Hermes has no Desktop injection this plugin knows, so the gateway can't hand chat %s a notification", session_key)
|
|
1180
|
+
return {"ok": False, "reason": "hermes_has_no_desktop_injection"}
|
|
1181
|
+
if not getattr(manager, "has_tui_message_injector", False):
|
|
1182
|
+
return {"ok": False, "reason": "no_desktop_host"}
|
|
1183
|
+
if not allowed():
|
|
1184
|
+
logger.error("[cello] The gateway has a notification for chat %s, and Hermes won't let this plugin start a turn there. Re-run 'cello bridge hermes', which sets plugins.entries.cello.allow_gateway_injection: true.", session_key)
|
|
1185
|
+
return {"ok": False, "reason": "injection_not_allowed"}
|
|
1186
|
+
# A chat that compressed carries on under a new id, and the binding still names the old one.
|
|
1187
|
+
for target in dict.fromkeys([session_key, _compression_tip(ctx, session_key)]):
|
|
1188
|
+
if target is None:
|
|
1189
|
+
continue
|
|
1190
|
+
try:
|
|
1191
|
+
took = inject(session_key=target, content=text, plugin_id=ctx.plugin_id)
|
|
1192
|
+
except Exception as exc:
|
|
1193
|
+
logger.error("[cello] Hermes failed to queue a notification on chat %s: %r", target, exc)
|
|
1194
|
+
return {"ok": False, "reason": "inject_failed: " + type(exc).__name__}
|
|
1195
|
+
if took:
|
|
1196
|
+
if target != session_key:
|
|
1197
|
+
_rekey_bindings(ctx, session_key, target)
|
|
1198
|
+
logger.info("[cello] Queued a notification from the gateway on chat %s", target)
|
|
1199
|
+
return {"ok": True}
|
|
1200
|
+
return {"ok": False, "reason": "chat_not_live_here"}
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
def _compression_tip(ctx: Any, session_key: str) -> Optional[str]:
|
|
1204
|
+
home = getattr(getattr(ctx, "_manager", None), "home_path", None) or _hermes_home()
|
|
1205
|
+
try:
|
|
1206
|
+
from hermes_state import SessionDB
|
|
1207
|
+
db = SessionDB(Path(home) / "state.db", read_only=True)
|
|
1208
|
+
except Exception as exc:
|
|
1209
|
+
logger.warning("[cello] Could not open %s to follow chat %s past a compression: %r", Path(home) / "state.db", session_key, exc)
|
|
1210
|
+
return None
|
|
1211
|
+
try:
|
|
1212
|
+
return db.get_compression_tip(session_key)
|
|
1213
|
+
except Exception as exc:
|
|
1214
|
+
logger.warning("[cello] Could not follow chat %s past a compression: %r", session_key, exc)
|
|
1215
|
+
return None
|
|
1216
|
+
finally:
|
|
1217
|
+
try:
|
|
1218
|
+
db.close()
|
|
1219
|
+
except Exception:
|
|
1220
|
+
pass
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def _rekey_bindings(ctx: Any, old: str, new: str) -> None:
|
|
1224
|
+
home = getattr(getattr(ctx, "_manager", None), "home_path", None) or _hermes_home()
|
|
1225
|
+
path = _bindings_file(Path(home))
|
|
1226
|
+
|
|
1227
|
+
def move(bindings: Dict[str, str]) -> None:
|
|
1228
|
+
for sid, chat in list(bindings.items()):
|
|
1229
|
+
if chat == old:
|
|
1230
|
+
bindings[sid] = new
|
|
1231
|
+
|
|
1232
|
+
try:
|
|
1233
|
+
_update_bindings(path, move)
|
|
1234
|
+
except Exception as exc:
|
|
1235
|
+
logger.error("[cello] Chat %s became %s after a compression, and its bindings couldn't be moved: %s", old, new, exc)
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def _host_handoffs(ctx: Any, home: Path) -> None:
|
|
1239
|
+
manager = getattr(ctx, "_manager", None)
|
|
1240
|
+
deadline = time.monotonic() + CLIENT_HOST_WAIT_SECONDS
|
|
1241
|
+
while not getattr(manager, "has_tui_message_injector", False):
|
|
1242
|
+
if time.monotonic() > deadline:
|
|
1243
|
+
logger.debug("[cello] No Desktop host appeared in this process after %.0fs, so it takes no notifications from the gateway", CLIENT_HOST_WAIT_SECONDS)
|
|
1244
|
+
return
|
|
1245
|
+
time.sleep(1.0)
|
|
1246
|
+
directory = _clients_dir(home)
|
|
1247
|
+
path = directory / (str(os.getpid()) + ".sock")
|
|
1248
|
+
try:
|
|
1249
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
1250
|
+
os.chmod(str(directory), 0o700)
|
|
1251
|
+
if path.exists():
|
|
1252
|
+
path.unlink()
|
|
1253
|
+
server = _HandoffServer(str(path), ctx)
|
|
1254
|
+
os.chmod(str(path), 0o600)
|
|
1255
|
+
except Exception as exc:
|
|
1256
|
+
logger.error("[cello] Could not listen at %s, so CELLO notifications can't reach this process's Desktop chats: %s", path, exc)
|
|
1257
|
+
return
|
|
1258
|
+
atexit.register(lambda: path.unlink() if path.exists() else None)
|
|
1259
|
+
logger.info("[cello] This process hosts Desktop chats. The gateway can hand them notifications at %s", path)
|
|
1260
|
+
server.serve_forever()
|
|
1261
|
+
|
|
1262
|
+
|
|
1263
|
+
def _start_handoff_host(ctx: Any) -> None:
|
|
1264
|
+
home = getattr(getattr(ctx, "_manager", None), "home_path", None)
|
|
1265
|
+
threading.Thread(target=_host_handoffs, args=(ctx, Path(home) if home else _hermes_home()), name="cello-handoff", daemon=True).start()
|
|
1266
|
+
|
|
1267
|
+
|
|
1018
1268
|
def _on_post_llm_call(**kwargs: Any) -> None:
|
|
1019
1269
|
if kwargs.get("platform") != "cello":
|
|
1020
1270
|
return
|
|
@@ -1064,3 +1314,5 @@ def register(ctx) -> None:
|
|
|
1064
1314
|
)
|
|
1065
1315
|
ctx.register_hook("post_tool_call", _on_post_tool_call)
|
|
1066
1316
|
ctx.register_hook("post_llm_call", _on_post_llm_call)
|
|
1317
|
+
if sys.platform != "win32":
|
|
1318
|
+
_start_handoff_host(ctx)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: cello-bridge-setup
|
|
3
3
|
description: "Connect this Hermes to a CELLO agent, or explain how the connection behaves."
|
|
4
|
-
version: 2.
|
|
4
|
+
version: 2.1.0
|
|
5
5
|
platforms: [linux, macos]
|
|
6
6
|
metadata:
|
|
7
7
|
hermes:
|
|
@@ -16,26 +16,31 @@ CELLO lets this agent talk to agents owned by other people, with signed and encr
|
|
|
16
16
|
A person sets it up at their own terminal. You can't do it from a turn, so tell your operator these steps:
|
|
17
17
|
|
|
18
18
|
1. `cello login --server <url>`, then `cello create-agent <name>`.
|
|
19
|
-
2. `cello bridge hermes --agent <name>`. It installs the plugin and
|
|
19
|
+
2. `cello bridge hermes --agent <name> --hermes-home <path>`. It installs the plugin, the tools and this skill. `<path>` is `~/.hermes` for the default profile and `~/.hermes/profiles/<profile>` for any other. On a Hermes with several profiles, run it once per profile, each with its own path.
|
|
20
20
|
3. For anything customers can reach, add `--public`. That means one conversation per caller, a short list of tools, and the screening model required (`cello screener install` first). Add `--allow-initiate` if this agent also has to open sessions.
|
|
21
|
-
4. Restart the gateway
|
|
21
|
+
4. Restart the process that runs the gateway, so it loads the plugin. On a server that's `systemctl --user restart hermes-gateway.service`. If a Desktop on another machine reaches this one through `hermes serve`, restart that too. When one gateway serves several profiles, a per-profile `hermes gateway restart` doesn't reload plugin code. Do this by hand, not from a script.
|
|
22
22
|
5. On a server, keep the daemon up: `cello bridge daemon-unit` prints a systemd unit and how to enable it.
|
|
23
23
|
|
|
24
|
-
Run step 2 again after every upgrade, because Hermes keeps a copy of the plugin. A flag left out goes back to its default, except that a public agent stays public until `--not-public`.
|
|
24
|
+
Run step 2 again after every upgrade, because Hermes keeps a copy of the plugin, then step 4. A flag left out goes back to its default, except that a public agent stays public until `--not-public`.
|
|
25
25
|
|
|
26
26
|
## Where notifications land
|
|
27
27
|
|
|
28
|
-
Under
|
|
28
|
+
Under `--public` or `--session-scope peer`, each caller gets a session of their own and none of this applies. Under the default scope:
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
- **A session you open answers in the chat that opened it.** The peer's replies, and its close, come back to the Hermes session you called `cello_initiate_session` from. That holds for a Desktop chat too, local or remote. You don't need to move anything first.
|
|
31
|
+
- **Everything else goes to the landing session:** a session someone else opens, a channel post, anything not tied to a chat of yours. That's this agent's own CELLO session, unless a landing session is set.
|
|
31
32
|
|
|
32
|
-
|
|
33
|
+
To have those come to the session you're working in, run this in the terminal from that session:
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
cello bridge hermes --agent <name> --hermes-home <path> --landing-session current
|
|
36
|
+
|
|
37
|
+
`current` is the session you run it in (`HERMES_SESSION_ID` says which). `--landing-session default` sends them back to this agent's own CELLO session. It applies from the next notification, with no restart. Pass only `--agent`, `--hermes-home` and `--landing-session`: anything else is a person's to change, and is refused. Never unset `CELLO_CALLER` to get around a refusal.
|
|
38
|
+
|
|
39
|
+
If a notification lands somewhere else, the gateway log says why. `Landing session ... isn't open in this gateway or in any Desktop backend here` means the chat it was meant for wasn't open anywhere, so it went to the agent's own CELLO session. A Desktop chat on another machine also needs `plugins.entries.cello.allow_gateway_injection: true` in the profile's config, which step 2 sets.
|
|
35
40
|
|
|
36
41
|
## How it behaves
|
|
37
42
|
|
|
38
|
-
A peer's message arrives as an ordinary message in the conversation, already read. Nothing you write in the chat reaches the peer. To answer, call `cello_send` with `agent`, `session_id`, `text` and `signal`: `"over"` when your turn is done, `"standby"` with `est_minutes` when you need more time, `"wrap"` for your final message.
|
|
43
|
+
A peer's message arrives as an ordinary message in the conversation, already read. Nothing you write in the chat reaches the peer. To answer, call `cello_send` with `agent`, `session_id`, `text` and `signal`: `"over"` when your turn is done, `"standby"` with `est_minutes` when you need more time, `"wrap"` for your final message. Then end your turn. The answer arrives as a new message, so don't wait or poll for it.
|
|
39
44
|
|
|
40
45
|
- Pass `agent` on every `cello_*` call.
|
|
41
46
|
- Never pass `force`. It takes the agent from the bridge, and this conversation stops hearing anything.
|