Skip to content

The agent that grows with you

Merge origin/main (#45: 255 commits to 3b63f7b0a4c) into feat/unified-gateway-runtime

Tekniuma89f374d7cde
diff --cc apps/desktop/src/app/session/hooks/use-cwd-actions.ts
index 1dc3c353466,e70497f3b6c..758844dc632
--- a/apps/desktop/src/app/session/hooks/use-cwd-actions.ts
+++ b/apps/desktop/src/app/session/hooks/use-cwd-actions.ts
@@@ -18,6 -18,6 +18,13 @@@ interface CwdActionsOptions
requestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>
}
++// The shared owner refuses a re-home while a turn runs (its frozen policy would change under it).
++function cwdChangeError(err: unknown): unknown {
++ const busy = (err as { data?: { reason?: string } } | null)?.data?.reason === 'session_busy'
++
++ return busy ? new Error(translateNow('sidebar.projects.moveBusy')) : err
++}
++
export function useCwdActions({ activeSessionIdRef, onSessionRuntimeInfo, requestGateway }: CwdActionsOptions) {
const { t } = useI18n()
const copy = t.desktop
@@@ -107,9 -114,7 +121,7 @@@
const message = err instanceof Error ? err.message : String(err)
if (!message.includes('unknown method')) {
- // The shared owner refuses a re-home while a turn runs (its frozen policy would change under it).
- const busy = (err as { data?: { reason?: string } })?.data?.reason === 'session_busy'
- notifyError(busy ? new Error(translateNow('sidebar.projects.moveBusy')) : err, copy.cwdChangeFailed)
- notifyError(err, copy.cwdChangeFailed)
++ notifyError(cwdChangeError(err), copy.cwdChangeFailed)
return
}
diff --cc hermes_cli/kanban_db.py
index b468102d13d,36d5736f73e..0e2b4e51d1b
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@@ -2370,15 -2380,12 +2372,15 @@@ def release_stale_claims
"WHERE status = 'running' AND claim_expires IS NOT NULL "
" AND claim_expires < ?", (now,),
).fetchall()
+ from hermes_cli.kanban_owner_recovery import owner_reclaim_paused
for row in stale:
+ if owner_reclaim_paused(conn, row["id"]):
+ continue
host_local = (row["claim_lock"] or "").startswith(host_prefix)
- hb = row["last_heartbeat_at"]
+ hb = _to_epoch(row["last_heartbeat_at"])
# Backstop: a heartbeat older than the max-stale threshold means no
# observable progress — reclaim even if the PID is alive (logic loop).
- heartbeat_stale = hb is not None and (now - int(hb)) > DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS
+ heartbeat_stale = hb is not None and (now - hb) > DEFAULT_CLAIM_HEARTBEAT_MAX_STALE_SECONDS
started_at = _row_get(row, "worker_started_at")
if (host_local and row["worker_pid"] and _worker_alive(row["worker_pid"], started_at)
and not heartbeat_stale):
diff --cc hermes_cli/kanban_db_context.py
index 0c5fc99df7d,00000000000..bdef72e14e2
mode 100644,000000..100644
--- a/hermes_cli/kanban_db_context.py
+++ b/hermes_cli/kanban_db_context.py
@@@ -1,219 -1,0 +1,219 @@@
+"""Worker-context rendering for ``build_worker_context``: the capped markdown sections a spawned
+worker reads about its task (header, attachments, prior attempts, parent handoffs, role
+history, comments).
+
+Split out of ``hermes_cli.kanban_db``; origin-resident helpers are reached late-bound via
+``_kb`` so monkeypatching ``kanban_db.<name>`` keeps working.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import time
+from typing import TYPE_CHECKING, Any, Optional
+
+import hermes_cli.kanban_db as _kb
+
+if TYPE_CHECKING:
+ from hermes_cli.kanban_db import Attachment, Comment, Task
+
+# build_worker_context() caps, sized for a ~100k-char prompt with headroom.
+_CTX_MAX_PRIOR_ATTEMPTS = 10 # most recent N prior runs shown in full
+_CTX_MAX_COMMENTS = 30 # most recent N comments shown in full
+_CTX_MAX_FIELD_BYTES = 4 * 1024 # per summary/error/metadata/result
+_CTX_MAX_BODY_BYTES = 8 * 1024 # per task.body (opening post)
+_CTX_MAX_COMMENT_BYTES = 2 * 1024 # per comment
+
+
+def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:
+ """Truncate to ``limit`` chars with a visible ellipsis."""
+ if not s:
+ return ""
+ s = s.strip()
+ if len(s) <= limit:
+ return s
+ return s[:limit] + f"… [truncated, {len(s) - limit} chars omitted]"
+
+
+def _ctx_stamp(ts: int, now: int) -> str:
+ """``YYYY-MM-DD HH:MM`` plus a relative age when one is available."""
+ disp = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts))
+ age = _kb._relative_age(ts, now)
+ return f"{disp}, {age}" if age else disp
+
+
+def _ctx_metadata_line(metadata: Any) -> Optional[str]:
+ if not metadata:
+ return None
+ try:
+ return f"_metadata_: `{_ctx_cap(json.dumps(metadata, ensure_ascii=False, sort_keys=True))}`"
+ except Exception:
+ return None
+
+
+def _ctx_tail(items: list, cap: int, noun: str) -> tuple[list, Optional[str]]:
+ """Keep the newest ``cap`` items; describe the omitted head, if any."""
+ omitted = max(0, len(items) - cap)
+ if not omitted:
+ return items, None
+ return items[-cap:], (
+ f"_({omitted} earlier {noun}{'s' if omitted != 1 else ''} "
+ f"omitted; showing most recent {cap})_"
+ )
+
+
+def _ctx_header(lines: list[str], task: Task) -> None:
+ lines.append(f"# Kanban task {task.id}: {task.title}")
+ lines.append("")
+ lines.append(f"Assignee: {task.assignee or '(unassigned)'}")
+ lines.append(f"Status: {task.status}")
+ if task.tenant:
+ lines.append(f"Tenant: {task.tenant}")
+ lines.append(f"Workspace: {task.workspace_kind} @ {task.workspace_path or '(unresolved)'}")
+ if task.max_runtime_seconds is not None:
+ terminal_timeout = _kb._worker_terminal_timeout_env(
+ task.max_runtime_seconds, os.environ.get("TERMINAL_TIMEOUT"),
+ )
+ effective_terminal_timeout = terminal_timeout or os.environ.get("TERMINAL_TIMEOUT")
+ lines.append(f"Max runtime: {task.max_runtime_seconds}s")
+ if effective_terminal_timeout:
+ lines.append(f"Terminal timeout: {effective_terminal_timeout}s")
+ if task.branch_name:
+ lines.append(f"Branch: {task.branch_name}")
+ lines.append("")
+ if task.body and task.body.strip():
+ lines.append("## Body")
+ lines.append(_ctx_cap(task.body, _CTX_MAX_BODY_BYTES))
+ lines.append("")
+
+
+def _ctx_attachments(lines: list[str], attachments: list[Attachment]) -> None:
+ """Absolute on-disk paths so the worker's file tools read them directly
+ (remote terminal backends need the attachments dir mounted)."""
+ if not attachments:
+ return
+ lines.append("## Attachments")
+ lines.append(
+ "Files attached to this task. Read them with the file/terminal "
+ "tools at the absolute paths below:"
+ )
+ for att in attachments:
+ size_kb = max(1, (att.size + 1023) // 1024) if att.size else 0
+ size_str = f", {size_kb} KB" if size_kb else ""
+ ctype = f", {att.content_type}" if att.content_type else ""
+ lines.append(f"- `{att.filename}`{ctype}{size_str} → `{att.stored_path}`")
+ lines.append("")
+
+
+def _ctx_prior_attempts(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:
+ """Closed runs on this task (the active run is this worker), newest
+ ``_CTX_MAX_PRIOR_ATTEMPTS`` in full, older ones as a one-line marker."""
+ all_prior = [r for r in _kb.list_runs(conn, task_id) if r.ended_at is not None]
+ shown, omitted_note = _ctx_tail(all_prior, _CTX_MAX_PRIOR_ATTEMPTS, "attempt")
+ if not shown:
+ return
+ first_shown_idx = len(all_prior) - len(shown) + 1
+ lines.append("## Prior attempts on this task")
+ if omitted_note:
+ lines.append(omitted_note)
+ for offset, run in enumerate(shown):
+ profile = run.profile or "(unknown)"
+ outcome = run.outcome or run.status
+ lines.append(
+ f"### Attempt {first_shown_idx + offset} — {outcome} ({profile}, {_ctx_stamp(run.started_at, now)})"
+ )
+ if run.summary and run.summary.strip():
+ lines.append(_ctx_cap(run.summary))
+ if run.error and run.error.strip():
+ lines.append(f"_error_: {_ctx_cap(run.error)}")
+ meta_line = _ctx_metadata_line(run.metadata)
+ if meta_line:
+ lines.append(meta_line)
+ lines.append("")
+
+
+def _ctx_parent_results(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:
+ """Done-parent handoffs: newest ``completed`` run's summary+metadata,
+ falling back to ``task.result`` for pre-runs-table data. Stamped with a
+ relative age so the worker re-verifies stale upstream results."""
+ parent_rows = conn.execute(
+ "SELECT parent_id FROM task_links WHERE child_id = ? ORDER BY parent_id", (task_id,),
+ ).fetchall()
+ wrote_header = False
+ for pid in (r["parent_id"] for r in parent_rows):
+ pt = _kb.get_task(conn, pid)
+ if not pt or pt.status != "done":
+ continue
+ runs = [r for r in _kb.list_runs(conn, pid) if r.outcome == "completed"]
+ runs.sort(key=lambda r: r.started_at, reverse=True)
+ run = runs[0] if runs else None
+ if not wrote_header:
+ lines.append("## Parent task results")
+ lines.append(
+ "_Handoffs from upstream tasks, captured when each parent "
+ "completed (see age below). These are point-in-time "
+ "snapshots, not live state — if a result drives your "
+ "current work and it's not recent, re-verify against the "
+ "source before acting on it as current._"
+ )
+ wrote_header = True
+ done_ts = run.ended_at if run is not None and run.ended_at else (pt.completed_at or None)
+ age = _kb._relative_age(done_ts, now)
+ lines.append(f"### {pid}" + (f" (completed {age})" if age else ""))
+ if run is not None and run.summary and run.summary.strip():
+ lines.append(_ctx_cap(run.summary))
+ elif pt.result:
+ lines.append(_ctx_cap(pt.result))
+ else:
+ lines.append("(no result recorded)")
+ meta_line = _ctx_metadata_line(run.metadata) if run is not None else None
+ if meta_line:
+ lines.append(meta_line)
+ lines.append("")
+
+
+def _ctx_role_history(lines: list[str], conn: sqlite3.Connection, task: Task, now: int) -> None:
+ """The assignee's 5 most recent completed runs on OTHER tasks — implicit
+ role continuity without wiring anything into SOUL.md / MEMORY.md."""
+ if not task.assignee:
+ return
+ role_rows = conn.execute(
+ "SELECT t.id, t.title, r.summary, r.ended_at "
+ "FROM task_runs r JOIN tasks t ON r.task_id = t.id "
+ "WHERE r.profile = ? AND r.task_id != ? "
+ " AND r.outcome = 'completed' "
+ "ORDER BY r.ended_at DESC LIMIT 5", (task.assignee, task.id),
+ ).fetchall()
+ if not role_rows:
+ return
+ lines.append(f"## Recent work by @{task.assignee}")
+ for row in role_rows:
+ first = _kb._first_line(row["summary"], 200) or "(no summary)"
+ lines.append(
- f"- {row['id']} — {row['title']} ({_ctx_stamp(int(row['ended_at']), now)}): {first}"
++ f"- {row['id']} — {row['title']} ({_ctx_stamp(_kb._to_epoch(row['ended_at']) or 0, now)}): {first}"
+ )
+ lines.append("")
+
+
+def _ctx_comments(lines: list[str], comments: list[Comment], now: int) -> None:
+ """Newest ``_CTX_MAX_COMMENTS`` comments. The explicit "comment from
+ worker" framing stops an operator-controlled HERMES_PROFILE like
+ "hermes-system" being read as a system directive above an
+ attacker-influenceable body (defense-in-depth)."""
+ shown, omitted_note = _ctx_tail(comments, _CTX_MAX_COMMENTS, "comment")
+ if not shown:
+ return
+ lines.append("## Comment thread")
+ if omitted_note:
+ lines.append(omitted_note)
+ for c in shown:
+ # Render author with explicit "comment from worker" framing so operator-controlled HERMES_PROFILE
+ # values like "hermes-system" or "operator" can't be misread by the next worker as a system
+ # directive above the (attacker-influenceable) comment body. Defense-in-depth — the LLM-controlled
+ # author-forgery surface was already closed in #22435. See #22452.
+ safe_author = (c.author or "").replace("`", "")
+ lines.append(f"comment from worker `{safe_author}` at {_ctx_stamp(c.created_at, now)}:")
+ lines.append(_ctx_cap(c.body, _CTX_MAX_COMMENT_BYTES))
+ lines.append("")
diff --cc hermes_cli/kanban_db_dispatch.py
index 0338cc90a7c,7ae9f4dcfcf..1e01999a2f1
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@@ -778,13 -776,10 +779,13 @@@ def detect_stale_running
"WHERE t.status = 'running'"
).fetchall()
+ from hermes_cli.kanban_owner_recovery import owner_reclaim_paused
for row in rows:
+ if owner_reclaim_paused(conn, row["id"]):
+ continue
if row["active_started_at"] is None:
continue
- elapsed = now - int(row["active_started_at"])
+ elapsed = now - (_kb._to_epoch(row["active_started_at"]) or now) # unreadable clock: never reclaim
if elapsed < stale_timeout_seconds:
continue
diff --cc hermes_cli/web_server_app.py
index 2121894427e,00000000000..abd93f67def
mode 100644,000000..100644
--- a/hermes_cli/web_server_app.py
+++ b/hermes_cli/web_server_app.py
@@@ -1,227 -1,0 +1,227 @@@
+"""HTTP lifespan composition; standalone backend services remain opt-in owners."""
+
+from contextlib import asynccontextmanager
+import asyncio
+import logging
+import os
+import threading
+
+from fastapi import FastAPI
+from hermes_cli.pty_session import run_reaper
+
+logger = logging.getLogger("hermes_cli.web_server")
+
+
+def _unlink_pty_markers(app: FastAPI) -> None:
+ """Second pass after ``PTY_REGISTRY.close_all()``: drop channel markers left in app state,
+ including stale paths from sessions reaped earlier (``PtySession.close()`` only removes
+ markers owned by live registry sessions)."""
+ from hermes_cli.web_server import _get_pty_active_session_files
+
+ for marker in set(_get_pty_active_session_files(app).values()):
+ try:
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+@asynccontextmanager
+async def standalone_lifespan(app: "FastAPI"):
+ from hermes_cli.web_server import (
+ _eager_reconcile_own_session_db, _warm_gateway_module,
+ _start_desktop_cron_ticker, _dashboard_selftest_loop,
+ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,
+ )
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {} # dict[str, set]
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {} # dict[str, Path]
+ # Serializes chat-argv resolution so concurrent /api/pty connections don't
+ # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not
+ # module globals) so they bind to the running loop, not the import-time one.
+ app.state.chat_argv_lock = asyncio.Lock()
+
+ # Bring state.db schema current BEFORE the first session-list poll
+ # (#79531/#80037): a store left behind by `hermes update` otherwise 500s
+ # every poll until its owner completes schema reconciliation.
+ # Off-thread so a locked store never delays the socket (Desktop
+ # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at
+ # shutdown: its sqlite connection must be closed by the thread that is
+ # stepping it. A daemon copy that outlived the lifespan had its
+ # connection closed from the main thread mid-probe (pytest's leaked-DB
+ # sweep) and segfaulted the interpreter. The worker is time-bounded by
+ # SessionDB's lock patience, so the join cannot hang shutdown.
+ eager_reconcile_thread = threading.Thread(
+ target=_eager_reconcile_own_session_db,
+ name="statedb-eager-reconcile",
+ )
+ eager_reconcile_thread.start()
+
+ # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the
+ # import holds the GIL, so run_in_executor still froze the loop 15-22s and
+ # the Desktop's 10s ready-probe timed out (GH-73083).
+ _warm_gateway_module()
+
+ # Snapshot the checkout revision so lazy-import paths (model picker) can
+ # refuse with "restart required" after `hermes update` replaced the code
+ # (#86207); the update flow does not reliably restart the dashboard.
+ from gateway.code_skew import record_boot_fingerprint
+
+ record_boot_fingerprint()
+
+ # Hosted Bot rooms belong to the backend process. Recovery may need a
+ # contended state.db migration, so keep it off the pre-yield path: Group
+ # Chat must degrade on its own rather than block every Desktop feature.
+ from tui_gateway import methods_groups as _hosted_groups
+ import tui_gateway.server
+
+ try:
+ tui_gateway.server.install_tui_message_injector()
+ except Exception:
+ logger.warning("TUI message injector did not install", exc_info=True)
+
+ hosted_room_start_cancel = threading.Event()
+
+ def _start_hosted_rooms() -> None:
+ try:
+ _hosted_groups.start_hosted_room_service()
+ except Exception:
+ logger.exception("Hosted Group Chat recovery failed during backend startup")
+ finally:
+ if hosted_room_start_cancel.is_set():
+ _hosted_groups.stop_hosted_room_service(timeout=1.0)
+
+ hosted_room_start_thread = threading.Thread(
+ target=_start_hosted_rooms,
+ daemon=True,
+ name="hosted-room-startup",
+ )
+ hosted_room_start_thread.start()
+
+ # Desktop-spawned backends fire cron jobs themselves, since the app has no
+ # gateway running the scheduler. Server `hermes dashboard` is unaffected —
+ # it relies on its own gateway.
+ from hermes_cli.process_identity import is_desktop_owned_backend
+ cron_stop: threading.Event | None = None
+ cron_thread: threading.Thread | None = None
+ desktop_owned = is_desktop_owned_backend()
+ if desktop_owned:
+ # Reap an orphaned gateway from an abnormal previous exit (reparented to
+ # launchd, still holding the platform WebSocket) before forking a fresh
+ # one that would race the same credential (#77276). Runs
+ # unconditionally; protection of a healthy standalone gateway lives
+ # INSIDE the reaper (registration probed with cleanup_stale=False).
+ # Startup grace: spare a gateway still claiming gateway.pid/lock (#122533).
+ try:
+ from hermes_cli.dashboard_procs import _REAP_MIN_AGE_SECONDS
+ from hermes_cli.gateway import _reap_unsupervised_gateway_orphans
+
+ _reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)
+ except Exception:
+ logger.exception("Desktop startup: orphan gateway reap failed")
+
+ cron_stop = threading.Event()
+ cron_thread = threading.Thread(
+ target=_start_desktop_cron_ticker,
+ args=(cron_stop,),
+ daemon=True,
+ name="desktop-cron-ticker",
+ )
+ cron_thread.start()
+
+ # Reap idle/dead keep-alive PTY sessions (30-min TTL).
+ pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
+ # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.
+ selftest_task = asyncio.create_task(_dashboard_selftest_loop())
+ # Live auto-archive timer, independent of list requests.
+ auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())
+
+ # Managed local runtime (local_runtime.enabled): bring llama-server back so a
+ # restart doesn't strand a llamacpp main model. Off-thread and best-effort;
+ # failure falls back to cloud providers like a cold start. Server only —
+ # models load on first inference (an empty router holds no VRAM).
+ def _boot_local_runtime():
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
+
+ ensure_local_runtime(load_config())
+ except Exception as exc:
+ logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)
+
+ threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
+
- # Nous free tier: the ONE place its identity is created. Inventories credentials, mints only
++ # Nous free tier: the one boot-time creator of its identity. Inventories credentials, mints only
+ # when HERMES_GUEST_ONBOARDING=1, records the answer for setup.status / free_tier.status and
+ # broadcasts `setup.ready`. Off-thread so a slow portal never delays the socket; the desktop's
+ # first setup.status waits on the record (bounded) instead.
+ from hermes_cli.free_tier_bootstrap import start_background_bootstrap
+
+ start_background_bootstrap()
+
+ try:
+ yield
+ finally:
+ try:
+ tui_gateway.server.clear_tui_message_injector()
+ except Exception:
+ logger.debug("TUI message injector clear skipped", exc_info=True)
+ hosted_room_start_cancel.set()
+ _hosted_groups.stop_hosted_room_service(timeout=5.0)
+ hosted_room_start_thread.join(timeout=1.0)
+ if cron_stop is not None:
+ cron_stop.set()
+ pty_reaper_task.cancel()
+ selftest_task.cancel()
+ auto_archive_task.cancel()
+ eager_reconcile_thread.join()
+ await PTY_REGISTRY.close_all()
+
+ # PtySession.close() removes markers owned by live registry sessions.
+ # This second pass cleans any channel markers left in app state,
+ # including stale paths from sessions reaped earlier.
+ _unlink_pty_markers(app)
+
+ # Stop the managed llama-server with its parent (an orphan pins VRAM).
+ try:
+ from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime
+
+ shutdown_local_runtime()
+ except Exception:
+ # Shutdown boundary: a supervisor that fails to stop must not skip the
+ # managed-gateway teardown below; log it so the orphan is diagnosable.
+ logger.warning("managed local runtime shutdown failed", exc_info=True)
+ if desktop_owned:
+ _terminate_desktop_managed_gateway()
+
+
+@asynccontextmanager
+async def http_lifespan(app: FastAPI):
+ """The gateway already owns schema, rooms, scheduler and model services."""
+ from hermes_cli.web_server import _dashboard_selftest_loop
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {}
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {}
+ app.state.chat_argv_lock = asyncio.Lock()
+ tasks = [
+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),
+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),
+ ]
+ try:
+ yield
+ finally:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ await PTY_REGISTRY.close_all()
+ _unlink_pty_markers(app)
+
+
+@asynccontextmanager
+async def app_lifespan(app: FastAPI):
+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan
+ async with lifespan(app):
+ yield