#!/usr/bin/env python3 """HedgeDoc 1.x <-> patched JOE 4.8 agent 0.7.17. The agent owns the Socket.IO/OT connection. Patched JOE owns the real editor buffer. They communicate over a private Unix stream socket. Usage: hd-joe [--cookie ...] ... explicit, works anywhere hd-joe ... inside an hd-managed folder: opens NAME if a symlink for it already exists in the current tag directory, otherwise creates a new note tagged with that directory's name (see hd_core.py's find_hd_root/tag_from_cwd/ resolve_or_create_note) JOE -> agent: I D agent -> JOE: I D R replace the entire JOE buffer atomically C move the cursor (used after an AI/agent block rewrite, to land back at the next input prompt) """ from __future__ import annotations import argparse, json, logging, os, socket, subprocess, sys, tempfile, threading, time from pathlib import Path from typing import Optional # hd_core.py/hd_client.py live in ../hd_common, shared verbatim with hd-cli # (see hd_common/README.md) -- add it to sys.path before importing either, # regardless of where this script is actually invoked from. sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hd_common")) import hd_core import joe_wrapper from hd_client import HedgeDocClient, HedgeDocDocument, Operation logger = logging.getLogger("picocalc.hd") def byte_to_char(s: str, byte_pos: int) -> int: if byte_pos < 0: raise ValueError("negative byte position") raw = s.encode("utf-8") if byte_pos > len(raw): raise ValueError("byte position outside document") try: return len(raw[:byte_pos].decode("utf-8")) except UnicodeDecodeError as e: raise ValueError("JOE position is not on a UTF-8 character boundary") from e def byte_range_to_text(s: str, pos: int, length: int) -> tuple[int, int]: raw = s.encode("utf-8") if pos < 0 or length < 0 or pos + length > len(raw): raise ValueError("byte range outside document") try: a = len(raw[:pos].decode("utf-8")) b = len(raw[:pos+length].decode("utf-8")) except UnicodeDecodeError as e: raise ValueError("JOE range is not UTF-8 aligned") from e return a, b def op_to_joe_commands(old_text: str, op: Operation): """Convert a HedgeDoc UTF-16 OT operation into JOE byte edits.""" source_u = 0 byte_pos = 0 doc_u = len(old_text.encode("utf-16-le")) // 2 out = [] for c in op: if isinstance(c, bool): raise ValueError("invalid OT bool") if isinstance(c, int): if c >= 0: end_u = source_u + c if end_u > doc_u: raise ValueError("retain exceeds document") from hd_client import utf16_to_char_index a = utf16_to_char_index(old_text, source_u) b = utf16_to_char_index(old_text, end_u) segment = old_text[a:b] byte_pos += len(segment.encode("utf-8")) source_u = end_u else: n = -c end_u = source_u + n if end_u > doc_u: raise ValueError("delete exceeds document") from hd_client import utf16_to_char_index a = utf16_to_char_index(old_text, source_u) b = utf16_to_char_index(old_text, end_u) deleted = old_text[a:b] out.append(("D", byte_pos, len(deleted.encode("utf-8")))) source_u = end_u continue if isinstance(c, str): raw = c.encode("utf-8") if raw: out.append(("I", byte_pos, raw)) byte_pos += len(raw) continue raise ValueError(f"invalid OT component {c!r}") if source_u != doc_u: raise ValueError("OT did not consume document") return out class Agent: def __init__(self, client: HedgeDocClient, sock_path: Path, buffer_path: Path, hd_root: Optional[Path] = None, note_id: Optional[str] = None): self.client = client self.sock_path = sock_path self.buffer_path = buffer_path self.server: Optional[socket.socket] = None self.conn: Optional[socket.socket] = None self.stop = threading.Event() self.lock = threading.RLock() self.rx = b"" self.hd_root = hd_root self.note_id = note_id self._last_cache_write = 0.0 client.on_remote_operation_detail = self.remote_operation client.on_connection_state_changed = self.on_connection_state_changed def send_cmd(self, kind, pos, payload): c = self.conn if not c: return if kind == "I": line = f"I {pos} {payload.hex()}\n".encode() else: line = f"D {pos} {payload}\n".encode() try: with self.lock: c.sendall(line) except OSError: self.stop.set() def replace_buffer(self, text: str): """Ask JOE to replace its entire buffer in one atomic editor-side operation. No longer called from remote_operation() (see below -- it was the cause of the cursor-jumps-to-BOF bug), kept as a primitive for a future hard-resync path.""" c = self.conn if not c: return raw = text.encode("utf-8") line = b"R " + raw.hex().encode("ascii") + b"\n" try: with self.lock: c.sendall(line) except OSError: self.stop.set() def send_cursor(self, byte_pos: int): c = self.conn if not c: return line = f"C {byte_pos}\n".encode() try: with self.lock: c.sendall(line) except OSError: self.stop.set() def send_message(self, text: str): c = self.conn if not c: return line = b"M " + text.encode("utf-8").hex().encode("ascii") + b"\n" try: with self.lock: c.sendall(line) except OSError: self.stop.set() def on_connection_state_changed(self, connected: bool): # Called from hd_client's Socket.IO thread, not JOE's socket thread # -- send_message() takes self.lock itself, same as every other # command sent to JOE, so this is safe to call from either. if connected: self.send_message("Back online -- syncing resumed.") else: self.send_message("OFFLINE -- edits are NOT being saved to the server.") # Marker the HedgeDoc AI mod uses for its input prompt (see hd-joe README / # the user's own description: "man skriver vid -> och tva enter skickar"). AGENT_PROMPT_MARKER = "\n->" def _agent_prompt_byte_pos(self, text: str): """Byte offset right after the next-message prompt marker, if present.""" idx = text.rfind(self.AGENT_PROMPT_MARKER) if idx == -1: return None char_pos = idx + len(self.AGENT_PROMPT_MARKER) if text[char_pos:char_pos + 1] == " ": char_pos += 1 return len(text[:char_pos].encode("utf-8")) def remote_operation(self, doc: HedgeDocDocument, op: Operation): # The client has already transformed/applied op to produce doc.text. with self.lock: old = getattr(self, "_shadow_text", None) if old is None: self._shadow_text = doc.text if self.conn is None: self.buffer_path.write_text(doc.text, encoding="utf-8") return # A delete this large is very likely a HedgeDoc AI/agent # integration rewriting its whole block (placeholder -> answer). # This only decides where we put the cursor afterward -- the # buffer update itself always goes through the incremental path # below, never a whole-buffer replace, which is what used to # send the cursor to BOF: bdel() on the entire buffer collapses # every pointer in it -- including the cursor -- to byte 0, with # no way back. Incremental D+I commands only touch the pointers # inside the actually-changed range. large_delete = any(isinstance(c, int) and c < -100 for c in op) try: cmds = op_to_joe_commands(old, op) for kind, pos, data in cmds: self.send_cmd(kind, pos, data) self._shadow_text = doc.text except Exception: logger.exception("Cannot translate remote OT for JOE") return if large_delete: cursor_pos = self._agent_prompt_byte_pos(doc.text) if cursor_pos is not None: self.send_cursor(cursor_pos) # Keep the local mirror reasonably fresh while a session is open, # not just at quit -- so someone else's edits (via webUI, say) # show up if you `cat` the symlink mid-session, not only after # you close JOE. Throttled to at most once/second: each write # takes the same interprocess lock `hdc sync` uses and rewrites # state.json, which isn't free, and a fast remote typist would # otherwise trigger it on every keystroke. The quit-time # update_note_cache() call already guarantees a final, fully # up-to-date write regardless of this throttle. if self.hd_root and self.note_id: now = time.monotonic() if now - self._last_cache_write >= 1.0: self._last_cache_write = now try: hd_core.update_note_cache(self.hd_root, self.note_id, doc.text) except Exception: logger.exception("Could not refresh local cache for %s", self.note_id) def handle_local(self, line: str): parts = line.split(" ", 2) if not parts or parts[0] not in ("I", "D"): return try: kind = parts[0] pos = int(parts[1]) with self.lock: text = self.client.document.text if kind == "I": raw = bytes.fromhex(parts[2].strip()) ins = raw.decode("utf-8") cp = byte_to_char(text, pos) self.client.insert(cp, ins) else: n = int(parts[2]) a, b = byte_range_to_text(text, pos, n) self.client.send_operation(self._delete_op(text, a, b)) except Exception: # Covers the offline case among others: send_operation() already # updated self.client.document.text optimistically (that's why # local editing keeps working while disconnected) *before* # _emit_pending()'s socket.emit() raises BadNamespaceError -- so # this can fire with the local edit already applied in memory. logger.exception("Local JOE edit rejected") finally: # Must run whether or not the block above raised: document.text # may already have moved (see above), and if _shadow_text isn't # kept in sync with it, the NEXT remote operation gets translated # into JOE IPC commands against a stale baseline -- a corruption # risk, not just a lost-edit one. self._shadow_text = self.client.document.text @staticmethod def _delete_op(text: str, a: int, b: int): # a, b are Python character indices (from byte_range_to_text); every # other op in this file is built in UTF-16 code units via utf16_len. # Real HedgeDoc (ot.js) rejects a literal 0 anywhere in the op array # ("unknown operation: 0") -- zero-length retains must be omitted, # not sent as 0, exactly like insert_operation/replace_operation. from hd_client import utf16_len a_u = utf16_len(text[:a]) b_u = utf16_len(text[:b]) tail_u = utf16_len(text) - b_u op = [] if a_u: op.append(a_u) op.append(-(b_u - a_u)) if tail_u: op.append(tail_u) return op def serve(self): self.sock_path.unlink(missing_ok=True) self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.server.bind(str(self.sock_path)) self.server.listen(1) self.server.settimeout(0.5) try: while not self.stop.is_set(): try: c,_ = self.server.accept() except socket.timeout: continue self.conn = c self._shadow_text = self.client.document.text c.settimeout(0.5) buf = b"" while not self.stop.is_set(): try: data = c.recv(65536) except socket.timeout: continue if not data: break buf += data while b"\n" in buf: raw, buf = buf.split(b"\n",1) if raw: self.handle_local(raw.decode("ascii")) try: c.close() except OSError: pass self.conn = None break finally: self.stop.set() if self.server: self.server.close() self.sock_path.unlink(missing_ok=True) def drain_pending(client: HedgeDocClient, timeout: float = 15.0, poll: float = 0.05) -> bool: """Block until every locally queued operation has been ACKed, or timeout. JOE exiting only ends the editor process; the agent's Socket.IO connection to HedgeDoc keeps running in its own thread and will still receive ACKs for anything still in the local pending queue. The only thing that was silently discarding typed-but-unacked text was closing that connection immediately after JOE exited, instead of waiting for the queue to actually drain first. """ import time deadline = time.monotonic() + timeout last_count = client.pending_count if last_count: logger.info("Draining %d unsent local operation(s) before exit...", last_count) while client.pending_count > 0: if time.monotonic() >= deadline: logger.error( "Exiting with %d local operation(s) still unacknowledged after " "%.1fs drain timeout -- these were NOT saved to the server.", client.pending_count, timeout, ) return False time.sleep(poll) if last_count: logger.info("Drain complete: all local operations acknowledged.") return True def main(): ap=argparse.ArgumentParser( description="Run patched JOE as a HedgeDoc editor", epilog="Either give an explicit ' ', or a single NAME to " "open-or-create inside an hd-managed folder (see hd_core.find_hd_root) " "-- run from inside ~/notes// for that second form.", ) ap.add_argument("target", nargs="+", metavar="URL NOTE_ID | NAME") ap.add_argument("--cookie") # Default points at the real compiled binary directly, not bare "joe" # resolved via PATH: once joe_wrapper.py is installed AT the "joe" name # (see install.sh), a bare "joe" would loop back into that wrapper. # This subprocess call is always meant to reach the real editor, so it # names it explicitly rather than relying on the wrapper's own (correct # but incidental) handling of "an existing plain file, not an hd note" # to avoid recursing. _default_joe = joe_wrapper.DEFAULT_REAL_JOE if Path(joe_wrapper.DEFAULT_REAL_JOE).exists() else "joe" ap.add_argument("--joe", default=_default_joe) ap.add_argument("--socket") ap.add_argument("--buffer", help="persistent working file") ap.add_argument("--quiet", action="store_true", help="disable normal log messages") ap.add_argument("--log", help="log file (default: ~/.local/state/picocalc/hd-joe.log)") ap.add_argument("--debug", action="store_true", help="verbose debug logging") args=ap.parse_args() if len(args.target) not in (1, 2): ap.error("expected either 'URL NOTE_ID' or a single NAME") log_path = Path(args.log).expanduser() if args.log else Path("~/.local/state/picocalc/hd-joe.log").expanduser() if not args.quiet: log_path.parent.mkdir(parents=True, exist_ok=True) handler = logging.FileHandler(log_path, encoding="utf-8") handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger.setLevel(logging.DEBUG if args.debug else logging.INFO) logger.handlers.clear() logger.addHandler(handler) logger.propagate = False else: logger.handlers.clear() logger.addHandler(logging.NullHandler()) logger.setLevel(logging.CRITICAL) # Resolve what to actually connect to. Two explicit args always win and # never need .hd/ at all (a server with no local login, or hd-joe used # standalone outside any hd-managed folder). A single NAME requires an # .hd/ directory somewhere above the current directory, git-style. cwd = Path.cwd() hd_root = hd_core.find_hd_root(cwd) hd_dir = hd_root / ".hd" if hd_root else None discovered_cookie = None if hd_dir: try: discovered_cookie = hd_core.Cookies.load(hd_dir).header except (FileNotFoundError, json.JSONDecodeError, KeyError): discovered_cookie = None if len(args.target) == 2: url, note_id = args.target cookie = args.cookie or discovered_cookie # may legitimately be None -- unauthenticated notes exist else: name = args.target[0] if hd_root is None: print(f"'{name}' isn't 'URL NOTE_ID', and no .hd/ directory was found " f"above {cwd} -- run 'hdc init' first, or pass both explicitly.", file=sys.stderr) return 1 config = hd_core.Config.load(hd_dir) cookie = args.cookie or discovered_cookie if not cookie: print(f"{hd_dir / 'cookies.json'} has no usable cookie -- re-run 'hdc init'.", file=sys.stderr) return 1 problems = hd_core.load_problems(hd_dir) if problems: print(f"{len(problems)} problem(s) from the last 'hdc sync':", file=sys.stderr) for p in problems: print(f" - {p}", file=sys.stderr) print(file=sys.stderr) try: note_id, created = hd_core.resolve_or_create_note(hd_root, cwd, name, config.url, cookie) except ValueError as exc: print(f"Refusing: {exc}", file=sys.stderr) return 1 url = config.url if created: print(f"Created new note '{name}' -- id {note_id}") client=HedgeDocClient(url,note_id,cookie=cookie,verbose=not args.quiet) sock=Path(args.socket or f"/tmp/joe-hedgedoc-{os.getpid()}.sock") persistent=Path(args.buffer).expanduser() if args.buffer else None tmp=None proc=None agent=None try: client.connect() doc=client.wait_ready() if persistent: persistent.parent.mkdir(parents=True,exist_ok=True) persistent.write_text(doc.text,encoding="utf-8") path=persistent else: fd,name_=tempfile.mkstemp(prefix=f"hedgedoc-{note_id}-",suffix=".md") os.close(fd); tmp=Path(name_) tmp.write_text(doc.text,encoding="utf-8"); path=tmp agent=Agent(client,sock,path,hd_root=hd_root,note_id=note_id) th=threading.Thread(target=agent.serve,daemon=True) th.start() env=os.environ.copy() env["JOE_HEDGE_SOCKET"]=str(sock) env["JOE_HEDGE_BUFFER"]=str(path) proc=subprocess.Popen([args.joe,str(path)],env=env) rc=proc.wait() agent.stop.set() fully_synced = drain_pending(client, timeout=float(os.environ.get("HD_DRAIN_TIMEOUT", "15.0"))) if hd_root: if fully_synced: try: hd_core.update_note_cache(hd_root, note_id, client.document.text) except Exception: logger.exception("Could not refresh local cache for %s", note_id) else: # Do NOT write client.document.text here: it's the locally # optimistic buffer, but the server never acknowledged it # (still offline, most likely). Writing it into the cache # anyway, with a matching content_hash, would tell every # future 'hdc sync' this note is already up to date -- the # skip-fetch check (state.json's last_seen_time == /history's # time) would then never re-fetch it, permanently hiding a # real divergence from the server behind a false "in sync". # Leaving the tracked cache untouched means the next # successful sync still sees the truth -- but the user's # actual keystrokes still shouldn't just vanish because of # that, so they're saved to a separate, untracked recovery # file instead. JOE's process has already exited by this # point, so this is a plain terminal print, not something # the user could miss inside JOE's own UI. try: recovery_path = hd_core.save_offline_recovery(hd_root, note_id, client.document.text) recovery_msg = f"Your edits were saved to {recovery_path} instead." except Exception: logger.exception("Could not write offline recovery file for %s", note_id) recovery_msg = "Additionally, saving an offline recovery copy also failed -- see the log." print( f"\nhd-joe: {client.pending_count} edit(s) to '{note_id}' were " f"NOT saved to the server (connection issue?). {recovery_msg}", file=sys.stderr, ) return rc finally: if proc and proc.poll() is None: proc.terminate() if agent: agent.stop.set() client.close() try: sock.unlink(missing_ok=True) except OSError: pass if tmp: try: tmp.unlink() except FileNotFoundError: pass if __name__=="__main__": raise SystemExit(main())