Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 46 additions & 2 deletions gateway/platforms/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,7 @@ async def _handle_capabilities(self, request: "web.Request") -> "web.Response":
"sessions": {"method": "GET", "path": "/api/sessions"},
"session_create": {"method": "POST", "path": "/api/sessions"},
"session": {"method": "GET", "path": "/api/sessions/{session_id}"},
"session_prompt": {"method": "POST", "path": "/api/sessions/{session_id}/prompt"},
"session_update": {"method": "PATCH", "path": "/api/sessions/{session_id}"},
"session_delete": {"method": "DELETE", "path": "/api/sessions/{session_id}"},
"session_messages": {"method": "GET", "path": "/api/sessions/{session_id}/messages"},
Expand Down Expand Up @@ -1250,15 +1251,17 @@ def _parse_nonnegative_int(value: Any, default: int, maximum: int) -> int:
@staticmethod
def _session_response(session: Dict[str, Any]) -> Dict[str, Any]:
"""Return a stable, client-safe session representation."""
from hermes_state import apply_session_live_work
viewed = apply_session_live_work(dict(session))
safe_keys = (
"id", "source", "user_id", "model", "title", "started_at", "ended_at",
"end_reason", "message_count", "tool_call_count", "input_tokens",
"output_tokens", "cache_read_tokens", "cache_write_tokens",
"reasoning_tokens", "estimated_cost_usd", "actual_cost_usd",
"api_call_count", "parent_session_id", "last_active", "preview",
"_lineage_root_id",
"_lineage_root_id", "live", "metadata", "owner", "profile",
)
payload = {key: session.get(key) for key in safe_keys if key in session}
payload = {key: viewed.get(key) for key in safe_keys if key in viewed}
# Avoid exposing full system prompts/model_config through the client API;
# callers only need to know whether those snapshots exist.
payload["has_system_prompt"] = bool(session.get("system_prompt"))
Expand Down Expand Up @@ -1406,6 +1409,40 @@ async def _handle_patch_session(self, request: "web.Request") -> "web.Response":
session = db.get_session(session_id) or session
return web.json_response({"object": "hermes.session", "session": self._session_response(session)})

async def _handle_session_prompt(self, request: "web.Request") -> "web.Response":
"""POST /api/sessions/{session_id}/prompt — persist Work Start work_ref."""
auth_err = self._check_auth(request)
if auth_err:
return auth_err
session_id = request.match_info["session_id"]
session, err = self._get_existing_session_or_404(session_id)
if err:
return err
body, err = await self._read_json_body(request)
if err:
return err
work_ref = str(body.get("work_ref") or body.get("work_id") or "").strip()
if work_ref:
db = self._ensure_session_db()
owner = str(body.get("owner") or "").strip() or None
profile = str(body.get("profile") or "").strip() or None
db.attach_session_work(session_id, work_ref, owner=owner, profile=profile)
refreshed = db.get_session(session_id)
if refreshed:
session = refreshed
if not session:
return web.json_response(
_openai_error(f"Session not found: {session_id}", code="session_not_found"),
status=404,
)
return web.json_response({
"object": "hermes.session",
"accepted": True,
"ok": True,
"session_id": session_id,
"session": self._session_response(session),
})

async def _handle_delete_session(self, request: "web.Request") -> "web.Response":
"""DELETE /api/sessions/{session_id}."""
auth_err = self._check_auth(request)
Expand Down Expand Up @@ -4102,6 +4139,13 @@ async def connect(self) -> bool:
self._app.router.add_get("/api/sessions/{session_id}", self._handle_get_session)
self._app.router.add_patch("/api/sessions/{session_id}", self._handle_patch_session)
self._app.router.add_delete("/api/sessions/{session_id}", self._handle_delete_session)
self._app.router.add_post("/api/sessions/{session_id}/prompt", self._handle_session_prompt)
self._app.router.add_get("/api/profiles/sessions", self._handle_list_sessions)
self._app.router.add_get("/api/profiles/sessions/{session_id}", self._handle_get_session)
self._app.router.add_post("/api/profiles/sessions/{session_id}/prompt", self._handle_session_prompt)
self._app.router.add_get("/sessions", self._handle_list_sessions)
self._app.router.add_get("/sessions/{session_id}", self._handle_get_session)
self._app.router.add_post("/sessions/{session_id}/prompt", self._handle_session_prompt)
self._app.router.add_get("/api/sessions/{session_id}/messages", self._handle_session_messages)
self._app.router.add_post("/api/sessions/{session_id}/fork", self._handle_fork_session)
self._app.router.add_post("/api/sessions/{session_id}/chat", self._handle_session_chat)
Expand Down
84 changes: 82 additions & 2 deletions hermes_cli/web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1512,13 +1512,15 @@ async def get_sessions(
archived_only=archived_only,
)
now = time.time()
from hermes_state import apply_session_live_work
for s in sessions:
s["is_active"] = (
s.get("ended_at") is None
and (now - s.get("last_active", s.get("started_at", 0))) < 300
)
# SQLite stores the flag as 0/1; expose a real JSON boolean.
s["archived"] = bool(s.get("archived"))
apply_session_live_work(s)
return {"sessions": sessions, "total": total, "limit": limit, "offset": offset}
finally:
db.close()
Expand Down Expand Up @@ -4471,18 +4473,66 @@ async def get_session_stats():

@app.get("/api/sessions/{session_id}")
async def get_session_detail(session_id: str):
from hermes_state import SessionDB
from hermes_state import SessionDB, apply_session_live_work
db = SessionDB()
try:
sid = db.resolve_session_id(session_id)
session = db.get_session(sid) if sid else None
if not session:
raise HTTPException(status_code=404, detail="Session not found")
return session
session["archived"] = bool(session.get("archived"))
return apply_session_live_work(session)
finally:
db.close()


def _session_prompt_work_ref(body: Dict[str, Any]) -> str:
raw = body.get("work_ref")
if raw is None:
raw = body.get("work_id")
return str(raw or "").strip()


async def _prompt_session_work(session_id: str, body: Dict[str, Any]) -> Dict[str, Any]:
"""Persist Work Start ``work_ref`` onto the Hermes session store."""
from hermes_state import SessionDB, apply_session_live_work
db = SessionDB()
try:
sid = db.resolve_session_id(session_id)
if not sid:
raise HTTPException(status_code=404, detail="Session not found")
work_ref = _session_prompt_work_ref(body)
if work_ref:
owner = str(body.get("owner") or "").strip() or None
profile = str(body.get("profile") or "").strip() or None
db.attach_session_work(sid, work_ref, owner=owner, profile=profile)
session = db.get_session(sid)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
session["archived"] = bool(session.get("archived"))
apply_session_live_work(session)
return {
"accepted": True,
"ok": True,
"session_id": sid,
"session": session,
}
finally:
db.close()


@app.post("/api/sessions/{session_id}/prompt")
async def prompt_session_endpoint(session_id: str, request: Request):
"""Work Start wake: attach ``work_ref`` Hermes owns, then list/get can observe it."""
try:
body = await request.json()
except Exception:
body = {}
if not isinstance(body, dict):
body = {}
return await _prompt_session_work(session_id, body)



@app.get("/api/sessions/{session_id}/latest-descendant")
async def get_session_latest_descendant(session_id: str):
Expand Down Expand Up @@ -6127,6 +6177,36 @@ async def list_profiles_endpoint():
return {"profiles": _fallback_profile_dicts(profiles_mod)}


# Literal ``/api/profiles/sessions`` family — profile-scoped alias of
# dashboard ``/api/sessions``. Register before ``/api/profiles/{name}``
# so ``sessions`` is not captured as a profile name.
@app.get("/api/profiles/sessions")
async def get_profile_sessions(
limit: int = 20,
offset: int = 0,
min_messages: int = 0,
archived: str = "exclude",
order: str = "created",
):
return await get_sessions(
limit=limit,
offset=offset,
min_messages=min_messages,
archived=archived,
order=order,
)


@app.get("/api/profiles/sessions/{session_id}")
async def get_profile_session_detail(session_id: str):
return await get_session_detail(session_id)


@app.post("/api/profiles/sessions/{session_id}/prompt")
async def prompt_profile_session_endpoint(session_id: str, request: Request):
return await prompt_session_endpoint(session_id, request)


@app.post("/api/profiles")
async def create_profile_endpoint(body: ProfileCreate):
from hermes_cli import profiles as profiles_mod
Expand Down
111 changes: 110 additions & 1 deletion hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,63 @@ def get_last_init_error() -> Optional[str]:
return _last_init_error


def parse_session_metadata(raw: Any) -> Dict[str, Any]:
"""Parse the Hermes-owned session metadata JSON blob."""
if isinstance(raw, dict):
return dict(raw)
if not raw:
return {}
if isinstance(raw, str):
try:
parsed = json.loads(raw)
except (TypeError, ValueError):
return {}
return parsed if isinstance(parsed, dict) else {}
return {}


def session_owned_work_ids(metadata: Dict[str, Any]) -> List[str]:
"""Return work ids Hermes stored. Empty means none — never invent."""
raw = metadata.get("work_ids")
if raw is None:
raw = metadata.get("work_refs")
if isinstance(raw, str):
raw = [raw]
if not isinstance(raw, (list, tuple)):
return []
seen = set()
owned: List[str] = []
for item in raw:
work_id = str(item or "").strip()
if not work_id or work_id in seen:
continue
seen.add(work_id)
owned.append(work_id)
return owned


def apply_session_live_work(session: Dict[str, Any]) -> Dict[str, Any]:
"""Project Hermes-owned ``live`` and ``metadata.work_ids`` onto a session row.

``is_active`` is a dashboard activity heuristic and is not live. A
session is live only when Hermes stored that fact (Work Start wake).
Work ids are only those Hermes persisted — omit/empty stays honest.
"""
meta = parse_session_metadata(session.get("metadata"))
work_ids = session_owned_work_ids(meta)
archived = bool(session.get("archived"))
live = bool(meta.get("live")) and not archived
session["live"] = live
session["metadata"] = {"work_ids": work_ids}
owner = str(meta.get("owner") or session.get("owner") or "").strip()
profile = str(meta.get("profile") or session.get("profile") or "").strip()
if owner:
session["owner"] = owner
if profile:
session["profile"] = profile
return session


def format_session_db_unavailable(prefix: str = "Session database not available") -> str:
"""Format a user-facing 'session DB unavailable' message with cause.

Expand Down Expand Up @@ -265,6 +322,7 @@ def _log_wal_fallback_once(db_label: str, exc: Exception) -> None:
handoff_error TEXT,
rewind_count INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
metadata TEXT,
FOREIGN KEY (parent_session_id) REFERENCES sessions(id)
);

Expand Down Expand Up @@ -1444,6 +1502,57 @@ def _do(conn):
rowcount = self._execute_write(_do)
return rowcount > 0

def get_session_metadata(self, session_id: str) -> Dict[str, Any]:
"""Return Hermes-owned session metadata, or ``{}`` if unset."""
session = self.get_session(session_id)
if not session:
return {}
return parse_session_metadata(session.get("metadata"))

def set_session_metadata(self, session_id: str, metadata: Dict[str, Any]) -> bool:
"""Replace Hermes-owned session metadata. Returns True if a row updated."""
payload = json.dumps(metadata if isinstance(metadata, dict) else {})

def _do(conn):
cursor = conn.execute(
"UPDATE sessions SET metadata = ? WHERE id = ?",
(payload, session_id),
)
return cursor.rowcount

return self._execute_write(_do) > 0

def attach_session_work(
self,
session_id: str,
work_ref: str,
*,
owner: Optional[str] = None,
profile: Optional[str] = None,
) -> bool:
"""Persist a work id this session owns and mark the session live.

``work_ref`` is required. Empty/missing refs are refused so list/get
never invent work. Owner/profile are stored only when the wake
supplies them — this path does not mint a default identity.
"""
work_id = str(work_ref or "").strip()
if not work_id or not self.get_session(session_id):
return False
meta = self.get_session_metadata(session_id)
work_ids = session_owned_work_ids(meta)
if work_id not in work_ids:
work_ids.append(work_id)
meta["work_ids"] = work_ids
meta["live"] = True
owner_id = str(owner or "").strip()
profile_id = str(profile or "").strip()
if owner_id:
meta["owner"] = owner_id
if profile_id:
meta["profile"] = profile_id
return self.set_session_metadata(session_id, meta)

def get_session_by_title(self, title: str) -> Optional[Dict[str, Any]]:
"""Look up a session by exact title. Returns session dict or None."""
with self._lock:
Expand Down Expand Up @@ -1743,7 +1852,7 @@ def list_sessions_rich(
for key in (
"id", "ended_at", "end_reason", "message_count",
"tool_call_count", "title", "last_active", "preview",
"model", "system_prompt", "cwd",
"model", "system_prompt", "cwd", "metadata",
):
if key in tip_row:
merged[key] = tip_row[key]
Expand Down
Loading
Loading