Skip to content

The agent that grows with you

feat(gateway): session.export returns the /save transcript for the client to write

Teknium8930c3c6323b
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 8ddd7b8745c..6bc8dc943c6 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4672,6 +4672,19 @@ export interface RollbackSessionDiffResult {
empty?: boolean
error?: string | null
}
+/** ``format``: json (default) / md / markdown / html / snapshot (``normalize_save_format``). */
+export interface SessionExportParams {
+ session_id: string
+ profile?: string | null
+ format?: string
+ redact?: boolean
+}
+/** ``gateway/session_tui_ops.py::export_session``: the rendered ``/save`` body and its default file name. The client writes it (the gateway may be remote); nothing is written on the host. */
+export interface SessionExportResult {
+ format: string
+ filename: string
+ content: string
+}
export interface SessionAutomationParams {
session_id: string
kind: 'goal' | 'loop' | 'heartbeat'
@@ -6762,6 +6775,8 @@ export interface CanonicalRpcMethods {
/** Drop this connection's subscription; a stale subscription id answers detached=false. end_reason (snake_case): the viewer is closing the conversation; the last viewer leaving an idle local session ends its row with that reason. */
'session.detach': { params: SessionDetachParams; result: SessionDetachResult }
'session.events.since': { params: CanonicalEventsParams; result: CanonicalEventsResult }
+ /** The /save transcript rendered for the client to write (the gateway writes nothing). */
+ 'session.export': { params: SessionExportParams; result: SessionExportResult }
/** Frozen launch policy projection of one local session. */
'session.info': { params: CanonicalSessionInfoParams; result: CanonicalSessionInfo }
'session.interrupt': { params: CanonicalControlParams; result: CanonicalSessionHandle }
@@ -6820,6 +6835,7 @@ export const CANONICAL_RPC_METHODS = [
'session.create',
'session.detach',
'session.events.since',
+ 'session.export',
'session.info',
'session.interrupt',
'session.list',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 63a15992b38..c486207d621 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -36600,6 +36600,68 @@
"title": "SessionEventsStatsResult",
"type": "object"
},
+ "SessionExportParams": {
+ "additionalProperties": false,
+ "description": "``format``: json (default) / md / markdown / html / snapshot (``normalize_save_format``).",
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "format": {
+ "default": "json",
+ "title": "Format",
+ "type": "string"
+ },
+ "redact": {
+ "default": false,
+ "title": "Redact",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "session_id"
+ ],
+ "title": "SessionExportParams",
+ "type": "object"
+ },
+ "SessionExportResult": {
+ "additionalProperties": false,
+ "description": "``gateway/session_tui_ops.py::export_session``: the rendered ``/save`` body and its default\nfile name. The client writes it (the gateway may be remote); nothing is written on the host.",
+ "properties": {
+ "format": {
+ "title": "Format",
+ "type": "string"
+ },
+ "filename": {
+ "title": "Filename",
+ "type": "string"
+ },
+ "content": {
+ "title": "Content",
+ "type": "string"
+ }
+ },
+ "required": [
+ "format",
+ "filename",
+ "content"
+ ],
+ "title": "SessionExportResult",
+ "type": "object"
+ },
"SessionForeignIdParams": {
"additionalProperties": false,
"properties": {
@@ -47482,6 +47544,24 @@
}
}
},
+ {
+ "name": "session.export",
+ "summary": "The /save transcript rendered for the client to write (the gateway writes nothing).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionExportParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionExportResult"
+ }
+ }
+ },
{
"name": "session.info",
"summary": "Frozen launch policy projection of one local session.",
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.py
index ede599354ed..415c39f4472 100644
--- a/gateway/session_tui_ops.py
+++ b/gateway/session_tui_ops.py
@@ -22,6 +22,7 @@ from hermes_state_runtime import RuntimeStoreError
def handlers(connection):
return {'session.save': partial(save_session, connection),
+ 'session.export': partial(export_session, connection),
'reload.env': partial(reload_env, connection),
'delegation.pause': partial(pause_delegation, connection),
'rollback.list': partial(rollback, connection, kind='list'),
@@ -81,6 +82,40 @@ async def save_session(connection, ref, params):
return await asyncio.to_thread(write)
+async def export_session(connection, ref, params):
+ """``session.export``: the ``/save`` transcript rendered for the CLIENT to write (json/md/html,
+ optional force-redaction). Nothing is written on the gateway host, so a remote Desktop and a
+ local Ink both save to the user's own disk (T10/T11)."""
+ _live_ref(connection, ref, params, {'session_id', 'profile', 'format', 'redact'}, 'session:read')
+ fmt, redact = params.get('format', 'json'), params.get('redact', False)
+ if not isinstance(fmt, str) or not isinstance(redact, bool):
+ raise RuntimeStoreError('invalid_params')
+ from hermes_cli.session_export import default_save_filename, normalize_save_format
+ try:
+ fmt = normalize_save_format(fmt)
+ except ValueError:
+ raise RuntimeStoreError('invalid_params') from None
+ authority = connection.authority
+ from gateway.session_ancillary import physical_target
+ target = physical_target(authority, ref)
+
+ def render():
+ from hermes_cli.session_export import load_save_snapshot, render_session_for_save
+ from hermes_state import SessionExportTooLargeError
+ try:
+ data = load_save_snapshot(authority.db, target, fmt)
+ except SessionExportTooLargeError as exc:
+ raise RuntimeStoreError('export_too_large') from exc
+ if not data:
+ raise RuntimeStoreError('not_found')
+ if redact:
+ from hermes_cli.session_export_md import redact_session_data
+ data = redact_session_data(data)
+ return render_session_for_save(data, fmt)
+ content = await asyncio.to_thread(render)
+ return {'format': fmt, 'filename': default_save_filename(target, fmt), 'content': content}
+
+
async def reload_env(connection, ref, params):
"""``/reload``: re-read the profile's ``.env`` (main's ``reload.env`` / CLI ``/reload``).
diff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.py
index 66fa0832876..f42d3ec15a1 100644
--- a/tests/gateway/test_session_tui_ops.py
+++ b/tests/gateway/test_session_tui_ops.py
@@ -32,6 +32,37 @@ def test_session_save_exports_the_stored_transcript_under_the_profile_home(tmp_p
asyncio.run(probe())
+def test_session_export_returns_the_rendered_transcript_for_the_client_to_write(tmp_path):
+ """T10/T11: ``session.export`` hands the client the rendered ``/save`` transcript; the gateway
+ writes nothing, so a remote Desktop and a local Ink save to the user's own disk."""
+ with owner(tmp_path) as (home, _peer, desc):
+ async def probe():
+ async with websocket(home, desc) as ws:
+ sid = (await rpc(ws, 'session.create', request_id='exp', source='tui', toolsets=[]))['result']['session_id']
+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='first',
+ text='EXPORT_ME sk-ant-api03-' + 'a' * 40)
+ await settled(home)
+ saved = home / 'sessions' / 'saved'
+ before = sorted(saved.iterdir()) if saved.exists() else []
+ as_json = (await rpc(ws, 'session.export', session_id=sid))['result']
+ assert as_json['format'] == 'json' and as_json['filename'].endswith('.json'), as_json
+ contents = [m.get('content') for m in json.loads(as_json['content'])['messages']]
+ assert any('EXPORT_ME' in (c or '') for c in contents), contents
+ md = (await rpc(ws, 'session.export', session_id=sid, format='markdown', redact=True))['result']
+ assert md['format'] == 'md' and md['filename'].endswith('.md')
+ assert 'EXPORT_ME' in md['content'] and 'a' * 40 not in md['content']
+ html = (await rpc(ws, 'session.export', session_id=sid, format='html'))['result']
+ assert html['content'].lstrip().lower().startswith('<!doctype html')
+ assert (sorted(saved.iterdir()) if saved.exists() else []) == before # nothing written
+ for params, reason in [({'session_id': sid, 'format': 'pdf'}, 'invalid_params'),
+ ({'session_id': sid, 'redact': 'yes'}, 'invalid_params'),
+ ({'session_id': sid, 'profile': 'foreign'}, 'profile_mismatch'),
+ ({}, 'invalid_params')]:
+ assert (await rpc(ws, 'session.export', **params))['error']['message'] == reason, params
+ asyncio.run(probe())
+
+
@pytest.mark.platforms("linux")
def test_reload_env_rereads_the_profile_dotenv_for_a_controlled_session(tmp_path):
with owner(tmp_path) as (home, _peer, desc):
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index e4dfe831ded..7e575fd4a57 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -264,6 +264,28 @@ canonical_method("rollback.session_diff", params=RollbackSessionDiffParams, resu
"retained checkpoint, as data for its terminal renderer.")
+class SessionExportParams(Params):
+ """``format``: json (default) / md / markdown / html / snapshot (``normalize_save_format``)."""
+
+ session_id: str
+ profile: str | None = None
+ format: str = "json"
+ redact: bool = False
+
+
+class SessionExportResult(Result):
+ """``gateway/session_tui_ops.py::export_session``: the rendered ``/save`` body and its default
+ file name. The client writes it (the gateway may be remote); nothing is written on the host."""
+
+ format: str
+ filename: str
+ content: str
+
+
+canonical_method("session.export", params=SessionExportParams, result=SessionExportResult,
+ doc="The /save transcript rendered for the client to write (the gateway writes nothing).")
+
+
class SessionAutomationParams(Params):
session_id: str
kind: Literal["goal", "loop", "heartbeat"]