Skip to content

The agent that grows with you

fix(gateway): canonical /compress honours --preview, here [N] and refuses --aggressive

teknium180052ce8acc8
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index 9e3fc82ffdc..b5aaeb1b3bb 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -30,7 +30,9 @@ function mutationSummary(operation: string, value: Record<string, unknown>): str
if (operation === 'branch') { return `branch: ${value.branched_session_id}` }
- if (operation === 'compress') { return `compress: ${value.target_session_id ?? value.session_id}` }
+ if (operation === 'compress') {
+ return value.status === 'preview' ? (value.lines as string[]).join('\n') : `compress: ${value.target_session_id ?? value.session_id}`
+ }
return `${operation}: ok`
}
@@ -262,6 +264,9 @@ export class CanonicalDesktopProtocol {
// through the normal request path (which also re-primes revision/generation).
async settle(method: string, params: Record<string, unknown>, value: any, request: (method: string, params: Record<string, unknown>) => Promise<any>): Promise<any> {
if (method !== 'session.compress') { return value }
+
+ // `--preview` in the focus argument is a read-only report: no transcript changed.
+ if (value?.status === 'preview') { return { ...value, host_ack: { output: (value.lines as string[]).join('\n') } } }
const resumed = await request('session.resume', { session_id: params.session_id })
return { ...value, messages: resumed.messages, info: resumed.info, host_ack: { output: `compressed context: ${value.message_count} messages retained` } }
diff --git a/gateway/session_mutation_compress.py b/gateway/session_mutation_compress.py
index 0806b2268d1..14da4831b7e 100644
--- a/gateway/session_mutation_compress.py
+++ b/gateway/session_mutation_compress.py
@@ -5,11 +5,34 @@ import json
from hermes_state_runtime import RuntimeStoreError
+def compress_request(payload):
+ """``session.mutate(compress)`` payload → the shared ``CompressRequest``.
+
+ A ``focus``-only payload is the raw ``/compress`` argument string (Ink/Desktop send it that
+ way, like ``session.compress`` always has), so it goes through the parser every native surface
+ uses: ``--preview`` stays read-only and ``here [N]`` stays a boundary instead of becoming a
+ focus topic. ``--aggressive`` has no canonical implementation and is refused before any write.
+ """
+ from agent.conversation_compression_manual import CompressRequest, parse_compress_args
+ if set(payload) <= {'focus'}:
+ request = parse_compress_args(payload.get('focus', ''))
+ else:
+ request = CompressRequest(preview=payload.get('preview', False), partial=payload.get('partial', False),
+ keep_last=payload.get('keep_last', 2), focus_topic=payload.get('focus'))
+ if request.aggressive:
+ raise RuntimeStoreError('unsupported_compress_options')
+ return request
+
+
async def prepare_compress(authority, live, payload, prepared):
from gateway.session_policy import restore_policy, policy_scope
from agent.context_compressor import ContextCompressor
from agent.agent_init import _parse_config_int
+ from agent.model_metadata import estimate_request_tokens_rough
+ from hermes_cli.partial_compress import (
+ rejoin_compressed_head_and_tail, split_history_for_partial_compress, summarize_compress_preview)
from utils import is_truthy_value
+ request = compress_request(payload)
snapshot = prepared['snapshot']
policy = restore_policy(snapshot['receipt']['policy'])
config = policy.config(authority)
@@ -21,6 +44,17 @@ async def prepare_compress(authority, live, payload, prepared):
raise RuntimeStoreError('runtime_coordination_required')
history = authority.db.get_messages_as_conversation(snapshot['target'])
messages = [m for m in history if m.get('role') in {'user', 'assistant', 'tool'}]
+ head, tail = messages, []
+ if request.partial:
+ head, tail = split_history_for_partial_compress(messages, request.keep_last)
+ if not tail: # degenerate split: nothing to keep verbatim → full compression
+ head = messages
+ if request.preview:
+ # Read-only: the report is the whole result; the caller commits nothing.
+ report = summarize_compress_preview(messages, request.partial, request.keep_last, request.focus_topic,
+ estimate_request_tokens_rough(messages))
+ return {'status': 'preview', 'lines': report['lines'], 'head_count': report['head_count'],
+ 'tail_count': report['tail_count'], 'message_count': report['total']}
def summarize():
with policy_scope(policy, authority=authority):
compressor = ContextCompressor(model, base_url=runtime.get('base_url') or '',
@@ -29,10 +63,10 @@ async def prepare_compress(authority, live, payload, prepared):
protect_first_n=options.get('protect_first_n', 3), protect_last_n=options.get('protect_last_n', 20),
min_tail_user_messages=max(1, _parse_config_int(options.get('min_tail_user_messages', 1), 1)),
custom_providers=config.get('custom_providers'))
- compressed = compressor.compress(json.loads(json.dumps(messages)), force=True,
- focus_topic=payload.get('focus'))
+ compressed = compressor.compress(json.loads(json.dumps(head)), force=True,
+ focus_topic=request.focus_topic)
if not any(m.get('_compressed_summary') for m in compressed):
raise RuntimeStoreError('nothing_to_compress')
- return compressed
+ return rejoin_compressed_head_and_tail(compressed, tail)
compressed = await asyncio.to_thread(summarize)
return dict(prepared, messages=compressed, in_place=is_truthy_value(options.get('in_place'), default=True))
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index fac275a84a1..f6246434080 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -89,6 +89,9 @@ async def mutate_session(authority, actor, ref, params):
prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
prepared = await prepare(authority, live, params['payload'], prepared)
applied = False
+ if prepared.get('status') == 'preview':
+ # ``--preview`` is a read-only report: no receipt, no publication, no eviction.
+ return {'session_id': ref.session_id, 'operation': operation, **prepared}
if prepared is not None and 'snapshot' not in prepared:
# Exact retry: the durable receipt is the result. Never re-prepare (compress
# would summarize again); the runtime repairs below still run, because the
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 8bb97bd81c6..f71fe651471 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -129,6 +129,10 @@ class GatewayChatView:
operation, payload = slash_mutation(command, rest.strip())
original = self.session_id
result = await self.mutations.apply(self.client, original, operation, payload)
+ if result.get('status') == 'preview':
+ self.mutations.acknowledge(original, operation, payload)
+ print('\n'.join(result['lines']))
+ return True
target = result.get('branched_session_id', original)
snapshot = await self.client.rpc('session.resume', session_id=target)
self.session_id = target
@@ -138,7 +142,7 @@ class GatewayChatView:
print(f"{operation}: {target}")
return True
if command == "/help":
- print("/stop, /approve <id> <choice>, /answer <id> <text>, /discard <admission_id> (turn lost during restart), /quit (detach). /branch [title], /model <model> [--provider name], /compress [focus].")
+ print("/stop, /approve <id> <choice>, /answer <id> <text>, /discard <admission_id> (turn lost during restart), /quit (detach). /branch [title], /model <model> [--provider name], /compress [here [N] | <focus>] [--preview].")
return True
raise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")
diff --git a/hermes_cli/gateway_mutations.py b/hermes_cli/gateway_mutations.py
index c3cdcb5813f..7c472e2e5a6 100644
--- a/hermes_cli/gateway_mutations.py
+++ b/hermes_cli/gateway_mutations.py
@@ -25,7 +25,8 @@ class PreparedMutations:
# the tuple; never refresh its preconditions behind the user.
if str(exc) in {'invalid_params', 'revision_conflict', 'stale_generation',
'session_busy', 'unknown_execution', 'permission_denied',
- 'model_resolution_failed', 'nothing_to_compress'}:
+ 'model_resolution_failed', 'nothing_to_compress',
+ 'unsupported_compress_options'}:
self.pending.pop(key)
raise
return entry['result']
@@ -34,6 +35,27 @@ class PreparedMutations:
self.pending.pop((session_id, operation, json.dumps(payload, sort_keys=True)), None)
+def compress_payload(arg):
+ """Structured ``session.mutate(compress)`` payload from the raw ``/compress`` arguments.
+
+ The shared parser is the one every native surface uses, so ``--preview`` stays a read-only
+ flag and ``here [N]`` a boundary instead of becoming a focus topic; ``--aggressive`` has no
+ canonical implementation and is refused before anything reaches the authority.
+ """
+ from agent.conversation_compression_manual import AGGRESSIVE_UNSUPPORTED, parse_compress_args
+ request = parse_compress_args(arg)
+ if request.aggressive:
+ raise GatewayClientError(AGGRESSIVE_UNSUPPORTED)
+ payload = {}
+ if request.focus_topic:
+ payload['focus'] = request.focus_topic
+ if request.preview:
+ payload['preview'] = True
+ if request.partial:
+ payload.update(partial=True, keep_last=request.keep_last)
+ return payload
+
+
def slash_mutation(command, arg):
name = command.lstrip('/')
if name == 'model':
@@ -43,7 +65,8 @@ def slash_mutation(command, arg):
raise GatewayClientError('unsupported_model_options')
return name, {'model': parsed.model_input, **(
{'provider': parsed.explicit_provider} if parsed.explicit_provider else {})}
- fields = {'branch': 'title', 'compress': 'focus'}
- if name not in fields:
+ if name == 'compress':
+ return name, compress_payload(arg)
+ if name != 'branch':
raise GatewayClientError('unsupported_command')
- return name, {fields[name]: arg} if arg else {}
+ return name, {'title': arg} if arg else {}
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index dba87f1538f..22559d438d8 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -13,7 +13,7 @@ def validate_action(operation, payload):
return
if operation == 'branch' and (not payload or (set(payload) == {'title'} and isinstance(payload['title'], str))):
return
- if operation == 'compress' and (not payload or (set(payload) == {'focus'} and isinstance(payload['focus'], str))):
+ if operation == 'compress' and _valid_compress_payload(payload):
return
if operation in {'delete', 'reset'} and not payload:
return
@@ -33,6 +33,19 @@ def validate_action(operation, payload):
raise RuntimeStoreError('invalid_params')
+_COMPRESS_FIELDS = {'focus': str, 'preview': bool, 'partial': bool, 'keep_last': int}
+
+
+def _valid_compress_payload(payload):
+ # ``focus`` alone may still be the raw ``/compress`` argument string (Ink/Desktop
+ # clients); the structured flags come from the shared parser on the native CLI/ACP path.
+ if set(payload) - _COMPRESS_FIELDS.keys():
+ return False
+ if any(type(value) is not _COMPRESS_FIELDS[key] for key, value in payload.items()):
+ return False
+ return 'keep_last' not in payload or (payload.get('partial') is True and payload['keep_last'] >= 1)
+
+
def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
if operation == 'compress':
from hermes_state_mutation_compress import compress_in_transaction
diff --git a/tests/gateway/test_session_mutation_compress_preview.py b/tests/gateway/test_session_mutation_compress_preview.py
new file mode 100644
index 00000000000..602c82c7f0b
--- /dev/null
+++ b/tests/gateway/test_session_mutation_compress_preview.py
@@ -0,0 +1,75 @@
+"""``/compress --preview`` is read-only on the canonical mutation path, every surface.
+
+Review of #106742 (F10): the ACP/CLI canonical path forwarded ``--preview`` as ``{'focus': '--preview'}``
+and the authority summarized and prepared replacement history. The shared parser every native
+surface uses must govern the payload, and a preview must not write a receipt, a summary or a revision.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_authority import SessionAuthority
+from gateway.session_controls import AuthorityConnection
+from gateway.session_local import create_local_session
+from hermes_cli.gateway_client import GatewayClientError
+from hermes_cli.gateway_mutations import slash_mutation
+import hermes_state_runtime as rt
+
+
+def test_slash_mutation_parses_compress_through_the_shared_parser():
+ assert slash_mutation('/compress', '--preview') == ('compress', {'preview': True})
+ assert slash_mutation('/compress', 'billing --dry-run') == ('compress', {'focus': 'billing', 'preview': True})
+ assert slash_mutation('/compress', 'here 3') == ('compress', {'partial': True, 'keep_last': 3})
+ assert slash_mutation('/compress', 'keep context') == ('compress', {'focus': 'keep context'})
+ with pytest.raises(GatewayClientError, match='aggressive'):
+ slash_mutation('/compress', '--aggressive')
+
+
+async def test_preview_mutation_reports_without_summarizing_or_writing(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from agent.context_compressor import ContextCompressor
+
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ summaries = []
+ monkeypatch.setattr(ContextCompressor, '__init__', lambda self, *a, **k: None)
+ monkeypatch.setattr(ContextCompressor, 'compress', lambda self, messages, **kw: summaries.append(kw) or messages)
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None,
+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)
+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ ref = create_local_session(authority, owner.actor, dict(request_id='preview', source='cli', cwd=str(tmp_path),
+ model='frozen', toolsets=[]))
+ for i in range(4):
+ db.append_message(ref.session_id, 'user', f'question {i}')
+ db.append_message(ref.session_id, 'assistant', f'answer {i}')
+ before = db.get_session(ref.session_id)
+ watermark = authority.sessions[ref.session_id].event_stream.watermark()
+ try:
+ for raw in ('--preview', 'here 2 --preview'):
+ operation, payload = slash_mutation('/compress', raw)
+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'preview-' + raw, 'expected_revision': before['runtime_revision'],
+ 'expected_generation': before['runtime_generation'], 'operation': operation, 'payload': payload}})
+ assert reply.get('result', {}).get('status') == 'preview', reply
+ assert reply['result']['lines'][0].startswith('Preview'), reply
+ assert summaries == [], 'a preview reached the summarizer'
+ after = db.get_session(ref.session_id)
+ assert (after['runtime_revision'], after['runtime_generation']) == (before['runtime_revision'], before['runtime_generation'])
+ assert len(db.get_messages(ref.session_id)) == 8
+ assert not db.list_meta_prefix('gateway.mutation.v1.'), 'a preview left a mutation receipt'
+ assert authority.sessions[ref.session_id].event_stream.since(*watermark)['events'] == []
+ refused = await owner.dispatch({'id': 2, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'aggressive', 'expected_revision': before['runtime_revision'],
+ 'expected_generation': before['runtime_generation'], 'operation': operation,
+ 'payload': {'focus': '--aggressive'}}})
+ assert refused['error']['message'] == 'unsupported_compress_options', refused
+ assert summaries == []
+ finally:
+ await owner.close()
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index 5479e966bff..ad3a986d28e 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -164,6 +164,9 @@ export async function runCanonicalSessionControl(
}
}))
ctx.transcript.sys(`model → ${result.model}`)
+ } else if (result.status === 'preview') {
+ // `--preview` is a read-only report; nothing to re-hydrate.
+ ctx.transcript.sys((result.lines as string[]).join('\n'))
} else {
const before = getUiState()
const snapshot = asRpcResult(await gw.request('session.resume', { session_id: ctx.sid }))
diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.md
index 79e5cdfa512..b69c614229c 100644
--- a/website/docs/user-guide/cli.md
+++ b/website/docs/user-guide/cli.md
@@ -129,7 +129,7 @@ for the exact supported subset and trust boundary.
## Interface Layout
:::info The classic CLI is a gateway client
-`hermes chat` (and the bare `hermes` prompt when `display.interface` is `cli`) no longer runs the agent inside your terminal process. It discovers or starts the profile's gateway (`hermes gateway ensure`), creates or resumes the session there, and attaches over the gateway's local WebSocket — the same session a Desktop window, the TUI, or a Telegram topic can open at the same time. Closing the terminal detaches (`Detached; accepted work continues at the gateway.`); it does not cancel the turn. Your working directory, `--model`, `--provider`, `--reasoning`, `--toolsets`, `--max-turns`, `--ignore-rules`, `--base-url`/`--api-key`, and `--safe-mode`/`--ignore-user-config` are frozen into the session at creation and cannot be changed by `--resume`. `--resume <id-or-title>` and `-c <title>` name the session; the gateway resolves the title (exact id first, then the latest `"<title> #N"` continuation, followed to its live tip) among the sessions you may read, and reports `No session found matching '…'` (exit 1) otherwise. `-c <title> --create-if-missing` creates a session with that title when none exists and resumes it when one does, so programmatic callers (Bot Mode's `Bot Chat` turns) get a deterministic thread. Options that only make sense for an in-process agent — `--image`, `--skills`, `--worktree`, `--checkpoints`, `--yolo`, `--pass-session-id`, bare `--continue` (no name), `--create-if-missing` without `-c <name>`, `--run-budget`, `--verbose`, `--compact`, `--list-tools`, `--list-toolsets`, and `--resume latest` — are refused up front (`Unsupported gateway CLI options: …`, exit 2); the refusal lists, per flag, where that capability lives now (the TUI flag, the `config.yaml` key, or the `hermes` subcommand), and nothing falls back to a local agent. A `--safe-mode` / `--ignore-user-config` launch reads no profile default model, so it must name one; the refusal prints a complete example such as `hermes chat --safe-mode --provider openrouter --model anthropic/claude-sonnet-4 -q "hello"`. In this mode the slash surface is `/stop`, `/approve <id> <choice>`, `/answer <id> <text>`, `/discard <admission_id>`, `/branch [title]`, `/model <model> [--provider name]`, `/compress [focus]`, `/help` and `/quit`; other slash commands print `Unsupported gateway CLI command; use /help.` Use the TUI (`hermes --tui`) for the full slash registry.
+`hermes chat` (and the bare `hermes` prompt when `display.interface` is `cli`) no longer runs the agent inside your terminal process. It discovers or starts the profile's gateway (`hermes gateway ensure`), creates or resumes the session there, and attaches over the gateway's local WebSocket — the same session a Desktop window, the TUI, or a Telegram topic can open at the same time. Closing the terminal detaches (`Detached; accepted work continues at the gateway.`); it does not cancel the turn. Your working directory, `--model`, `--provider`, `--reasoning`, `--toolsets`, `--max-turns`, `--ignore-rules`, `--base-url`/`--api-key`, and `--safe-mode`/`--ignore-user-config` are frozen into the session at creation and cannot be changed by `--resume`. `--resume <id-or-title>` and `-c <title>` name the session; the gateway resolves the title (exact id first, then the latest `"<title> #N"` continuation, followed to its live tip) among the sessions you may read, and reports `No session found matching '…'` (exit 1) otherwise. `-c <title> --create-if-missing` creates a session with that title when none exists and resumes it when one does, so programmatic callers (Bot Mode's `Bot Chat` turns) get a deterministic thread. Options that only make sense for an in-process agent — `--image`, `--skills`, `--worktree`, `--checkpoints`, `--yolo`, `--pass-session-id`, bare `--continue` (no name), `--create-if-missing` without `-c <name>`, `--run-budget`, `--verbose`, `--compact`, `--list-tools`, `--list-toolsets`, and `--resume latest` — are refused up front (`Unsupported gateway CLI options: …`, exit 2); the refusal lists, per flag, where that capability lives now (the TUI flag, the `config.yaml` key, or the `hermes` subcommand), and nothing falls back to a local agent. A `--safe-mode` / `--ignore-user-config` launch reads no profile default model, so it must name one; the refusal prints a complete example such as `hermes chat --safe-mode --provider openrouter --model anthropic/claude-sonnet-4 -q "hello"`. In this mode the slash surface is `/stop`, `/approve <id> <choice>`, `/answer <id> <text>`, `/discard <admission_id>`, `/branch [title]`, `/model <model> [--provider name]`, `/compress [here [N] | <focus>] [--preview]`, `/help` and `/quit`; other slash commands print `Unsupported gateway CLI command; use /help.` Use the TUI (`hermes --tui`) for the full slash registry.
:::
<img className="docs-terminal-figure" src="/docs/img/docs/cli-layout.svg" alt="Stylized preview of the Hermes CLI layout showing the banner, conversation area, and fixed input prompt." />