@cello-protocol/cli 0.0.309 → 0.0.311

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 CHANGED
@@ -40,7 +40,7 @@ function usageLine(op) {
40
40
  return p.required ? text : `[${text}]`;
41
41
  });
42
42
  const signal = op.command === "send" ? [SIGNAL_FLAGS] : [];
43
- const scoped = [...(op.scoped ? ["[--agent <name-or-id>]"] : []), ...(op.acts ? ["[--force]"] : []), ...(op.plain ? ["[--json]"] : [])];
43
+ const scoped = [...(op.scoped ? ["[--agent <name-or-id>]"] : []), ...(op.acts ? ["[--force]"] : []), ...(op.plain ? ["[--json]"] : []), ...(op.command === "agents" ? ["[--labels]"] : [])];
44
44
  return `cello ${[op.command, ...positional, ...signal, ...flags, ...scoped].join(" ")}`;
45
45
  }
46
46
  function commandHelp(op) {
@@ -79,7 +79,7 @@ Usage: cello <command> [args]
79
79
  ${sections.join("\n\n")}
80
80
 
81
81
  Run 'cello <command> --help' for details on any command.
82
- Commands print JSON on one line, and --pretty indents it.
82
+ Commands print indented JSON.
83
83
  A failure prints {"error","message"} on standard error and exits ${EXIT_REFUSED}.
84
84
  A usage mistake exits ${EXIT_USAGE}, and wait exits ${EXIT_TIMEOUT} when its time runs out.
85
85
  Any agent that can run a shell command can use all of this with no MCP.
@@ -123,10 +123,13 @@ function readValue(param, raw) {
123
123
  usageError(`${flag(param.name)} must be one of ${param.allowed.join(", ")}, got ${raw}`);
124
124
  return raw;
125
125
  }
126
- // One line by default, because the usual reader is a program or an agent paying for every character.
127
- let pretty = false;
126
+ // Indented always: the few extra characters cost an agent next to nothing, and a person can read it.
128
127
  let asJson = false;
129
- const render = (value) => `${pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)}\n`;
128
+ // cello agents --labels: one line per agent, name then agent_id, for pasting into the account site.
129
+ // The person carries it there; the daemon never sends names anywhere.
130
+ let labels = false;
131
+ const render = (value) => `${JSON.stringify(value, null, 2)}\n`;
132
+ const labelLines = (value) => (value.agents ?? []).map((a) => `${a.name} ${a.agent_id}\n`).join("");
130
133
  // Fails on anything it doesn't recognise, so a mistyped flag can't quietly change what a command does.
131
134
  function parse(op, args) {
132
135
  const params = {};
@@ -143,8 +146,8 @@ function parse(op, args) {
143
146
  flagsEnded = true;
144
147
  continue;
145
148
  }
146
- if (arg === "--pretty") {
147
- pretty = true;
149
+ if (op.command === "agents" && arg === "--labels") {
150
+ labels = true;
148
151
  continue;
149
152
  }
150
153
  if (op.plain && arg === "--json") {
@@ -583,7 +586,7 @@ async function main() {
583
586
  }
584
587
  const result = answer;
585
588
  client.close();
586
- process.stdout.write(op.plain && !asJson ? op.plain(result) : render(result));
589
+ process.stdout.write(labels ? labelLines(result) : op.plain && !asJson ? op.plain(result) : render(result));
587
590
  // The id, never the name: a name is a label, and it could later mean a different agent.
588
591
  if (op.method === "use_agent")
589
592
  writeFileSync(currentAgentFile(), `${result.agent_id}\n`, { mode: 0o600 });
@@ -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
- const steps = [mcpAdd, ["plugins", "enable", "cello"]];
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) {
@@ -240,7 +240,7 @@ The code stops agents that are simply trying commands, and pipes and scripts wit
240
240
  summary: "List your agents, and whether each one is online.",
241
241
  scoped: false,
242
242
  acts: false,
243
- description: "List the agents on this machine, whether each one is online, and how much is unread for each.",
243
+ description: "List the agents on this machine, whether each one is online, and how much is unread for each. With --labels, print one line per agent, its name then its agent_id, to paste into the account site so it can show your agents' names. Nothing is sent: you carry it there.",
244
244
  params: [],
245
245
  },
246
246
  {
@@ -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() / "cello" / "session-bindings.json"
203
- self._bindings: Dict[str, str] = self._load_bindings()
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 _load_bindings(self) -> Dict[str, str]:
220
- try:
221
- data = json.loads(Path(self._bindings_path).read_text(encoding="utf-8"))
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 _persist_bindings(self) -> None:
231
- path = Path(self._bindings_path)
285
+ def _change_bindings(self, change: Callable[[Dict[str, str]], None]) -> bool:
232
286
  try:
233
- path.parent.mkdir(parents=True, exist_ok=True)
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", path, exc)
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._bindings[session_id] = chat_id
249
- self._persist_bindings()
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
- if self._bindings.pop(session_id, None) is not None:
254
- self._persist_bindings()
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
- for sid in stale:
269
- del self._bindings[sid]
270
- if stale:
271
- self._persist_bindings()
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
- logger.warning("[cello] Landing session %s isn't open in any chat, so this goes to %s's own CELLO chat", landing_sid, self._agent_name)
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._unbind_session(session_id)
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 adapter is None:
982
- logger.error("[cello] %s named agent %r, which no adapter here holds, so it wasn't tracked", tool_name, args.get("agent") if isinstance(args, dict) else None)
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)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cello-protocol/cli",
3
- "version": "0.0.309",
3
+ "version": "0.0.311",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.7"