The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): stamp created_source when a gateway session is inserted
David Dudok de Wit2f45f17f1db1
diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex d55e0d71860..2d5b413b23f 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -76,6 +76,38 @@ _TURN_PROFILE: ContextVar = ContextVar('follow_profile_read', default=None) # (# ``oneshot`` (finite ``chat -q`` / ``-z`` runs) run as the CLI but keep their own stored label, so human# pickers hide them (INTERNAL_LISTING_SOURCES).SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp', 'tool': 'cli', 'oneshot': 'cli'}+# ``tool`` and ``oneshot`` stay stored under their own labels so pickers can hide them.+# Every other creation label is rewritten to ``source='local'`` on peer refresh.+_KEEP_STORED_LABEL = frozenset({'tool', 'oneshot'})+STORED_AS_LOCAL = frozenset(SURFACES) - _KEEP_STORED_LABEL+++def created_surface(label):+ """``created_source`` for a policy or live label.++ ``local`` and ``unknown`` are not surfaces. A policy label maps through+ ``SURFACES`` (``gui`` is ``desktop``). Any other label is kept as itself.+ """+ if label in (None, '', 'local', 'unknown'):+ return None+ mapped = SURFACES.get(label, label)+ if mapped in ('', 'local', 'unknown'):+ return None+ return mapped+++def surface_groups():+ """Policy label and agent surface for one conversation, keyed by either name.++ ``--source gui`` and ``--source desktop`` are the same rows. ``tool`` and+ ``oneshot`` are not aliases of ``cli`` here: they keep their own stored label.+ """+ groups = {}+ for label in STORED_AS_LOCAL:+ group = frozenset({label, SURFACES[label]})+ for name in group:+ groups[name] = group+ return groupsdef _refuse(field, detail=None):diff --git a/hermes_state_local.py b/hermes_state_local.pyindex c239a8643cb..20037d13a04 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -56,11 +56,20 @@ def commit_local_session(db, *, epoch, receipt):policy, entry = receipt['policy'], receipt['entry']from datetime import datetimestarted = datetime.fromisoformat(entry['created_at']).timestamp()- conn.execute('''INSERT INTO sessions(id,source,user_id,session_key,chat_id,chat_type,- model,cwd,profile_name,origin_json,started_at) VALUES(?,?,?,?,?,'dm',?,?,?,?,?)+ # Auxiliary usage inserts created_source='unknown' when it creates the row, and+ # that value never moves (record_auxiliary_usage carries no surface). The agent's+ # own accounting passes its surface (turn_usage._agent_session_source) and is not+ # that writer. Stamp the agent surface in this insert so a later usage write+ # cannot fill the column. gui's in-process agent is desktop; a managed worker+ # creates with the policy label gui.+ from gateway.session_policy import created_surface+ created = created_surface(policy['source'])+ conn.execute('''INSERT INTO sessions(id,source,created_source,user_id,session_key,chat_id,chat_type,+ model,cwd,profile_name,origin_json,started_at) VALUES(?,?,?,?,?,?,'dm',?,?,?,?,?)ON CONFLICT(id) DO NOTHING''',- (sid, policy['source'], receipt['principal_id'], route, entry['origin']['chat_id'],- policy['model'], _row_cwd(policy), db._own_profile_name(), _json(entry['origin']), started))+ (sid, policy['source'], created, receipt['principal_id'], route,+ entry['origin']['chat_id'], policy['model'], _row_cwd(policy), db._own_profile_name(),+ _json(entry['origin']), started))conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?)",(route, _json(entry), started))conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, encoded))diff --git a/tests/gateway/test_resume_latest_local_cli.py b/tests/gateway/test_resume_latest_local_cli.pyindex 16128ff743c..4b5c8156cb8 100644--- a/tests/gateway/test_resume_latest_local_cli.py+++ b/tests/gateway/test_resume_latest_local_cli.py@@ -71,3 +71,53 @@ async def test_resume_latest_matches_the_owners_local_rows_by_creating_surface(tfinally:await owner.close()store.close_all_db_handles()+++async def test_auxiliary_usage_cannot_replace_the_insert_stamp(tmp_path, monkeypatch):+ """Auxiliary usage creates a missing row as created_source='unknown'.++ The agent's own token accounting passes its surface, so it is not that writer.+ session.create stamps the surface in the insert; a later record_auxiliary_usage+ must leave it, and session.resume latest='cli' still finds the row.+ """+ store, authority, owner = _owner(tmp_path / 'home', monkeypatch)+ try:+ created = await _call(owner, 'session.create', request_id='chat', source='cli',+ cwd=str(tmp_path), toolsets=[], model='m')+ sid = created['session_id']+ authority.db.record_auxiliary_usage(sid, 'compression', model='m', input_tokens=4, output_tokens=1)+ live = authority.sessions[sid]+ store._record_gateway_session_peer(sid, live.route, live.source)+ authority.sessions.clear()+ resumed = await _call(owner, 'session.resume', latest='cli')+ assert isinstance(resumed, dict) and resumed['session_id'] == sid, resumed+ row = authority.db.get_session(sid)+ assert (row['source'], row['created_source']) == ('local', 'cli')+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_worker_create_after_peer_refresh_still_resumes(tmp_path, monkeypatch):+ """The peer refresh rewrites source to local and worker_create is refused.+ The insert stamp must already hold cli, or latest cannot see the row."""+ from hermes_state_runtime import RuntimeStoreError+ from hermes_state_worker_lifecycle import worker_create++ store, authority, owner = _owner(tmp_path / 'home', monkeypatch)+ try:+ created = await _call(owner, 'session.create', request_id='chat', source='cli',+ cwd=str(tmp_path), toolsets=[], model='m')+ sid = created['session_id']+ live = authority.sessions[sid]+ store._record_gateway_session_peer(sid, live.route, live.source)+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ authority.db._execute_write(lambda conn: worker_create(authority.db, conn, sid, {'source': 'cli'}))+ authority.sessions.clear()+ resumed = await _call(owner, 'session.resume', latest='cli')+ assert isinstance(resumed, dict) and resumed['session_id'] == sid, resumed+ finally:+ await owner.close()+ store.close_all_db_handles()