Skip to content

The agent that grows with you

feat(gateway): resolve --resume <title> and -c <title> [--create-if-missing] in the authority

Teknium11a83ad4d19f
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index c1df446b230..d4422f8c2d9 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -112,7 +112,15 @@ class AuthorityConnection:
async def create(self, ref, params):
from gateway.session_local import create_local_session, local_session_info
- ref = create_local_session(self.authority, self.actor, params)
+ from gateway.session_local_title import resolve_titled_session, title_new_session, validate_title
+ # ``-c <title> --create-if-missing``: resolve-or-create is one owner step (no await
+ # between lookup and creation), so concurrent programmatic callers converge.
+ title = validate_title(params.pop('title')) if 'title' in params else None
+ ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
+ if not ref:
+ ref = create_local_session(self.authority, self.actor, params)
+ if title:
+ title_new_session(self.authority, ref, title)
result = await self.resume(ref, {})
result['info'] = local_session_info(self.authority, ref)
return result
@@ -131,7 +139,7 @@ class AuthorityConnection:
'authority_epoch': self.authority.epoch,
'capabilities': ['durable-admission-v1', 'event-replay-v1', 'local-cli-create-v1', 'acp-editor-policy-v1', 'acp-session-mcp-v1'],
'session_create': {'sources': ['cli', 'tui', 'gui', 'acp'],
- 'parameters': sorted(CREATE_FIELDS)}}
+ 'parameters': sorted(CREATE_FIELDS | {'title'})}}
async def info(self, ref, params):
from gateway.session_local import local_session_info
@@ -164,6 +172,9 @@ class AuthorityConnection:
return {'sessions': sessions[:limit], 'scope': 'live'}
async def resume(self, ref, params):
+ if 'title' in params:
+ from gateway.session_local_title import resolve_titled_session
+ ref = resolve_titled_session(self.authority, self.actor, params['title'])
if params.get('editor') is not None:
self.authority.authorize(self.actor, ref, 'session:control')
from gateway.session_local_mcp import resume_editor_mcp
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.py
new file mode 100644
index 00000000000..8fbf07cde23
--- /dev/null
+++ b/gateway/session_local_title.py
@@ -0,0 +1,55 @@
+"""Title-keyed local session selection, resolved read-only by the authority.
+
+``hermes chat --resume <title>`` / ``-c <title> [--create-if-missing]`` used to open
+SessionDB in the client; the zero-writer client now sends the name and the owner
+applies the classic CLI rule (``hermes_cli.main._resolve_session_by_name_or_id``).
+"""
+from __future__ import annotations
+
+from gateway.session_contract import SessionRef
+from hermes_state_runtime import RuntimeStoreError
+
+
+def resolve_titled_session(authority, actor, name, *, missing_ok=False):
+ """Exact session id first, then title (latest ``"<title> #N"`` continuation wins over
+ the bare title), projected forward to the compression tip. Only a local session the
+ actor may read is returned; a foreign or non-local match is ``not_found`` so another
+ principal's titles are never confirmed."""
+ if not isinstance(name, str) or not name.strip():
+ raise RuntimeStoreError('invalid_params')
+ db = authority.db
+ row = db.get_session(name)
+ sid = row['id'] if row else db.resolve_session_by_title(name)
+ tip = db.get_session(db.get_compression_tip(sid) or sid) if sid else None
+ if tip is None or not str(tip.get('chat_id') or '').startswith('local-'):
+ if missing_ok:
+ return None
+ raise RuntimeStoreError('not_found')
+ ref = SessionRef(authority.profile_id, tip['chat_id'])
+ try:
+ authority.authorize(actor, ref, 'session:read')
+ except RuntimeStoreError as exc:
+ if exc.reason == 'permission_denied':
+ raise RuntimeStoreError('not_found') from None
+ raise
+ return ref
+
+
+def validate_title(title):
+ from hermes_state import SessionDB
+ try:
+ cleaned = SessionDB.sanitize_title(title) if isinstance(title, str) else None
+ except ValueError:
+ cleaned = None
+ if cleaned is None:
+ raise RuntimeStoreError('invalid_params')
+ return cleaned
+
+
+def title_new_session(authority, ref, title):
+ """User-provenance title on a just-created local session (auto-titling never overwrites it).
+ A concurrent creator that won the unique title is a conflict, not a silent orphan."""
+ try:
+ authority.db.set_session_title(ref.session_id, title)
+ except ValueError:
+ raise RuntimeStoreError('admission_conflict') from None
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index 0a9d746f143..67bea7e48d6 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -15,7 +15,7 @@ from hermes_cli.gateway_client import GatewayClientError, connect_gateway
_UNSUPPORTED = (
"image", "skills", "worktree", "w", "checkpoints", "pass_session_id",
"yolo", "accept_hooks",
- "continue_last", "create_if_missing", "no_restore_cwd", "usage_file",
+ "no_restore_cwd", "usage_file",
"run_budget", "verbose", "compact",
"list_tools", "list_toolsets",
)
@@ -28,14 +28,26 @@ def bypass_launch(args) -> bool:
return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False))
+def continue_title(args):
+ """``-c <name>`` (classic precedence: ignored when ``--resume`` is given). Bare ``-c`` needs the
+ breadcrumb/MRU lookup the authority does not expose, so it stays refused like ``--resume latest``."""
+ name = getattr(args, "continue_last", None)
+ return name if isinstance(name, str) and not getattr(args, "resume", None) else None
+
+
def validate_options(args):
unsupported = [name for name in _UNSUPPORTED if getattr(args, name, None)]
if getattr(args, "resume", None) == "latest":
unsupported.append("resume latest")
+ if getattr(args, "continue_last", None) is True:
+ unsupported.append("continue")
+ if getattr(args, "create_if_missing", False) and not continue_title(args):
+ unsupported.append("create-if-missing without -c <name>")
if unsupported:
flags = ", ".join("--" + name.replace("_", "-") for name in unsupported)
raise GatewayClientError(f"Unsupported gateway CLI options: {flags}. No local fallback or policy changes were made.")
- if getattr(args, "resume", None) and (getattr(args, "in_dir", None) or getattr(args, "source", None) or
+ resuming = getattr(args, "resume", None) or (continue_title(args) and not getattr(args, "create_if_missing", False))
+ if resuming and (getattr(args, "in_dir", None) or getattr(args, "source", None) or
any(getattr(args, name, None) not in (None, False) for name in _POLICY)):
raise GatewayClientError("Resume retains gateway session policy; creation overrides are unsupported on resume.")
if bypass_launch(args) and not getattr(args, "model", None):
@@ -46,8 +58,24 @@ async def run_gateway_chat(args):
from hermes_cli.gateway_chat_view import GatewayChatView
async with connect_gateway() as client:
description = await client.rpc("runtime.describe")
- if getattr(args, "resume", None):
- snapshot = await client.rpc("session.resume", session_id=args.resume)
+ title = continue_title(args)
+ create_if_missing = bool(title and getattr(args, "create_if_missing", False))
+ if getattr(args, "resume", None) or (title and not create_if_missing):
+ name = getattr(args, "resume", None) or title
+ try:
+ # Exact id first, then title (latest lineage continuation), as the classic CLI did.
+ snapshot = await client.rpc("session.resume", session_id=name)
+ except GatewayClientError as exc:
+ if str(exc) != "not_found":
+ raise
+ try:
+ snapshot = await client.rpc("session.resume", title=name)
+ except GatewayClientError as exc:
+ if str(exc) != "not_found":
+ raise
+ raise GatewayClientError(
+ f"No session found matching '{name}'. Use 'hermes sessions list' to see available "
+ "sessions, or pass -c <name> --create-if-missing to start a new session with that title.")
else:
contract = description.get("session_create", {})
source = getattr(args, "source", None) or "cli"
@@ -55,6 +83,8 @@ async def run_gateway_chat(args):
raise GatewayClientError(f"Gateway does not support source {source!r}")
parameters = contract.get("parameters", [])
policy = {key: getattr(args, key) for key in _POLICY if getattr(args, key, None) not in (None, False)}
+ if create_if_missing:
+ policy["title"] = title
if isinstance(policy.get("toolsets"), str):
policy["toolsets"] = [name.strip() for name in policy["toolsets"].split(",") if name.strip()]
cwd = str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())
@@ -77,7 +107,7 @@ async def run_gateway_chat(args):
oneshot = bool(oneshot_prompt or getattr(args, "oneshot_exit", False) or quiet or
(query and not (sys.stdin.isatty() and sys.stdout.isatty())))
view = GatewayChatView(client, snapshot, quiet=quiet)
- if getattr(args, "resume", None) and not quiet:
+ if (getattr(args, "resume", None) or title) and not quiet:
for row in snapshot.get("messages", []):
if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):
print(f"{row['role']}: {row['content']}")
diff --git a/tests/gateway/test_session_local_title.py b/tests/gateway/test_session_local_title.py
new file mode 100644
index 00000000000..55d67fe8771
--- /dev/null
+++ b/tests/gateway/test_session_local_title.py
@@ -0,0 +1,51 @@
+"""Authority-side title selection: main's classic rule, without leaking foreign titles."""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+from gateway.session import SessionSource
+from gateway.session_authority import LiveSession, SessionAuthority
+from gateway.session_contract import Principal
+from gateway.session_local_title import resolve_titled_session
+from hermes_state import SessionDB
+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch
+
+
+def _authority(db):
+ epoch = begin_runtime_epoch(db, instance_id='current')
+ return SessionAuthority(SimpleNamespace(_draining=False), profile_id='owned',
+ instance_id='current', db=db, epoch=epoch)
+
+
+def _local(db, authority, sid, *, user, title):
+ db.create_session(sid, source='cli', chat_id=sid, user_id=user)
+ db.set_session_title(sid, title)
+ source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id=user, chat_type='dm')
+ authority.sessions[sid] = LiveSession(source, 'route-' + sid)
+
+
+def test_title_resolves_like_classic_cli_and_never_confirms_foreign_titles(tmp_path):
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ authority = _authority(db)
+ _local(db, authority, 'local-a', user='human', title='thread')
+ _local(db, authority, 'local-a2', user='human', title='thread #2')
+ _local(db, authority, 'local-b', user='stranger', title='private')
+ # A non-local (messaging) session carrying a title is not resumable through the local client.
+ db.create_session('tg-1', source='telegram', chat_id='chat', user_id='human')
+ db.set_session_title('tg-1', 'telegram thread')
+ human = Principal('human', 'owned', frozenset({'session:read'}), 'viewer')
+
+ def resolve(title):
+ return resolve_titled_session(authority, human, title).session_id
+ # Latest "<title> #N" continuation wins over the bare title (classic lineage rule).
+ assert resolve('thread') == 'local-a2'
+ assert resolve('thread #2') == 'local-a2'
+ # A literal id passed as title still resolves (main tries id before title).
+ assert resolve('local-a') == 'local-a'
+ for foreign in ('private', 'telegram thread', 'nope'):
+ with pytest.raises(RuntimeStoreError, match='not_found'):
+ resolve(foreign)
+ assert resolve_titled_session(authority, human, 'nope', missing_ok=True) is None
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ resolve('')
diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.py
index 7d55a8bdbde..c1f2835684c 100644
--- a/tests/hermes_cli/test_gateway_chat.py
+++ b/tests/hermes_cli/test_gateway_chat.py
@@ -8,10 +8,17 @@ def test_unsupported_launch_options_fail_before_connection(monkeypatch, capsys):
from hermes_cli import gateway_chat
calls = []
monkeypatch.setattr(gateway_chat, "connect_gateway", lambda: calls.append(True))
- for option in ("yolo", "worktree", "continue_last", "usage_file"):
+ for option in ("yolo", "worktree", "usage_file"):
args = argparse.Namespace(**{option: True})
assert gateway_chat.launch_from_args(args) == 2
assert option.replace("_", "-") in capsys.readouterr().err
+ # Bare -c (breadcrumb/MRU) and a nameless --create-if-missing stay refused; only a
+ # titled -c is a gateway-resolvable selector.
+ assert gateway_chat.launch_from_args(argparse.Namespace(continue_last=True)) == 2
+ assert "--continue" in capsys.readouterr().err
+ assert gateway_chat.launch_from_args(argparse.Namespace(create_if_missing=True)) == 2
+ assert "create-if-missing" in capsys.readouterr().err
+ assert gateway_chat.launch_from_args(argparse.Namespace(continue_last="named", model="m", query="x")) == 2
assert calls == []
assert gateway_chat.launch_from_args(argparse.Namespace(resume="stored", source="tui", query="x")) == 2
# Bypass launches read no profile default model, so one must be explicit.
diff --git a/tests/hermes_cli/test_gateway_chat_title_live.py b/tests/hermes_cli/test_gateway_chat_title_live.py
index d8a7db657fc..68316b5e9e7 100644
--- a/tests/hermes_cli/test_gateway_chat_title_live.py
+++ b/tests/hermes_cli/test_gateway_chat_title_live.py
@@ -24,13 +24,13 @@ def test_title_create_if_missing_then_resume_by_title_is_deterministic(tmp_path,
"gateway": {"multiplex_profiles": False},
"model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_url},
"auxiliary": {"title_generation": {"enabled": False}},
- }))
+ }), encoding="utf-8")
env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}
env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
PYTHONUNBUFFERED="1", OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=model_url)
witness = tmp_path / "client-owner.json"
wrapper = tmp_path / "client.py"
- wrapper.write_text(f'''import json, runpy, sys
+ wrapper.write_text(encoding='utf-8', data=f'''import json, runpy, sys
owners = []
def trace(frame, event, arg):
if event == 'call' and frame.f_code.co_name == '__init__':
@@ -41,13 +41,13 @@ try:
runpy.run_module('hermes_cli.main', run_name='__main__')
finally:
sys.setprofile(None)
- open({str(witness)!r}, 'w').write(json.dumps(owners))
+ open({str(witness)!r}, 'w', encoding='utf-8').write(json.dumps(owners))
''')
def chat(*args):
result = subprocess.run([sys.executable, str(wrapper), "--cli", "chat", *args, "-Q"], env=env,
cwd=tmp_path, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90)
- assert json.loads(witness.read_text()) == [], witness.read_text()
+ assert json.loads(witness.read_text(encoding="utf-8")) == [], witness.read_text(encoding="utf-8")
sid = next((line.split("Session: ", 1)[1].strip() for line in result.stderr.splitlines()
if "Session: " in line), None)
return result, sid
@@ -68,7 +68,7 @@ finally:
except (OSError, ValueError):
pass
time.sleep(.1)
- assert descriptor.get("state") == "ready", log_path.read_text()
+ assert descriptor.get("state") == "ready", log_path.read_text(encoding="utf-8")
missing, _ = chat("-c", title, "-q", "WS_SHARED absent")
assert missing.returncode == 1 and f"No session found matching '{title}'" in missing.stderr, missing
@@ -76,7 +76,12 @@ finally:
created, sid = chat("-c", title, "--create-if-missing", "-q", "WS_SHARED create")
assert created.returncode == 0 and sid and "LOCAL_ACK_WS_SHARED" in created.stdout, created
- again, again_sid = chat("-c", title, "--create-if-missing", "-q", "WS_SHARED again")
+ # Bot Mode's exact turn shape (tools.bot_relay.BOT_CHAT_TURN_ARGS): --in + --query-file
+ # + --create-if-missing must resume the existing titled thread, never fork a second one.
+ query_file = tmp_path / "dm.txt"
+ query_file.write_text("WS_SHARED again", encoding="utf-8")
+ again, again_sid = chat("--in", str(tmp_path), "-c", title, "--create-if-missing",
+ "--query-file", str(query_file))
assert again.returncode == 0 and again_sid == sid, again
resumed, resumed_sid = chat("--resume", title, "-q", "WS_SHARED resumed")