The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: compose worker compression lifecycle and delegation persistence
Teknium6c57ad37c31e
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex 71cfb739d53..428124f0e56 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -82,7 +82,13 @@ class WorkerRPC:return response['result']-class RuntimeSessionStore:+from agent.runtime_session_compression import RuntimeSessionCompressionMixin+++from agent.runtime_session_lifecycle import RuntimeSessionLifecycleMixin+++class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecycleMixin):"""Synchronous durable results with a private byte-bounded retry journal.A failed write remains pending, and failure is sticky until explicit retry or@@ -176,7 +182,9 @@ class RuntimeSessionStore:entry = self.journal['pending'][0]result = self.rpc('worker.persist', **self.scope, **entry)candidate = dict(self.journal, pending=self.journal['pending'][1:])+ candidate = self._compression_receipt_journal(candidate, result)self._save(candidate)+ self.scope = candidate['scope']self.journal = candidateresults.append(result)except Exception as exc:@@ -197,8 +205,11 @@ class RuntimeSessionStore:def append_messages_batch(self, session_id, messages, compression_lock_holder=None,turn_lease_holder=None, chunk_rows=None, turn_lease_ttl_seconds=300.0):self._session(session_id)- if compression_lock_holder is not None or chunk_rows is not None or turn_lease_ttl_seconds != 300.0:+ if chunk_rows is not None:raise WorkerPersistenceError('unsupported_operation')+ if compression_lock_holder is not None or turn_lease_ttl_seconds != 300.0:+ return self._append_compression_messages(session_id, messages, compression_lock_holder,+ turn_lease_holder, turn_lease_ttl_seconds)result = self._apply('transcript.append', {'messages': messages, 'turn_lease_holder': turn_lease_holder})for message, annotation in zip(messages, result['annotations'], strict=True):message.update(annotation)@@ -243,10 +254,6 @@ class RuntimeSessionStore:raise WorkerPersistenceError('pending_receipt')return True- def get_session(self, session_id):- self._session(session_id)- return self._apply('session.context', {})['session']-def get_session_title(self, session_id):return self.get_session(session_id).get('title')diff --git a/gateway/session_worker.py b/gateway/session_worker.pyindex 2a2e4c5c974..f3d5ebf7a96 100644--- a/gateway/session_worker.py+++ b/gateway/session_worker.py@@ -38,18 +38,22 @@ def _claim(connection, ref, params):raise RuntimeStoreError('worker_not_live') from exc# Reuse the durable adoption digest as the producer claim. Changing any# assignment, principal, profile, PID birth or secret cannot adopt it.- return admission_fingerprint(canonical_target=ref.session_id, payload={- key: params[key] for key in _SCOPE} | {'principal': connection.actor.subject})+ from hermes_state_worker_compression import worker_claim_origin+ origin = worker_claim_origin(authority.db, params)+ return admission_fingerprint(canonical_target=origin, payload={+ key: params[key] for key in _SCOPE} | {'session_id': origin, 'principal': connection.actor.subject})def _verify(connection, ref, params, claim):+ from hermes_state_worker_compression import worker_retry_targetauthority = connection.authority+ target = worker_retry_target(authority.db, params)with authority.db._read_ctx() as conn:row = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?',(params['execution_id'],)).fetchone()if row is None:raise RuntimeStoreError('not_found')- if row['session_id'] != ref.session_id:+ if row['session_id'] != target:raise RuntimeStoreError('permission_denied')if type(params['generation']) is not int or row['generation'] != params['generation']:raise RuntimeStoreError('stale_generation')@@ -58,6 +62,9 @@ def _verify(connection, ref, params, claim):async def worker_request(connection, ref, params, *, operation):+ if operation == "persist" and isinstance(params.get("operation"), str) and params["operation"].startswith("delegation."):+ from gateway.session_worker_delegation import worker_delegation_request+ return await worker_delegation_request(connection, ref, params)extra = {'register': {'kind'}, 'adopt': set(), 'persist': {'epoch', 'sequence', 'operation', 'payload'}}[operation]if set(params) != _SCOPE | extra:raise RuntimeStoreError('invalid_params')diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex e8818dc274b..7a7493ee56a 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -543,7 +543,11 @@ def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,sequence, operation, payload):"""One closed durable mutation and receipt; never call a self-committing API here."""from hermes_state_worker_context import worker_context, worker_prompt, worker_sidecars+ from hermes_state_worker_compression import WORKER_COMPRESSION_HANDLERS, worker_receipt_assignment+ from hermes_state_worker_lifecycle import WORKER_LIFECYCLE_HANDLERShandlers = {+ **WORKER_LIFECYCLE_HANDLERS,+ **WORKER_COMPRESSION_HANDLERS,'session.context': worker_context,'session.prompt': worker_prompt,'session.sidecars': worker_sidecars,@@ -563,7 +567,7 @@ def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,payload={'operation': operation, 'payload': json.loads(encoded)})def write(conn):_epoch(conn, epoch)- row = _worker_assignment(conn, execution_id, session_id, generation)+ row = worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest)if row['owner_epoch'] != epoch:raise RuntimeStoreError('stale_epoch')old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?',diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex cb49f39098c..ebf4ab2ab8f 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -301,63 +301,14 @@ class SessionSessionsMixin:sidebar even though its transcript is intact (#99222). Stores outside the profile tree (explicit``db_path`` in tests, ad-hoc copies) derive nothing and keep NULL — never guess."""- if not (profile_name or "").strip():- profile_name = self._own_profile_name()- def _do(conn):- system_prompt_hash = self._store_system_prompt(conn, system_prompt)- conn.execute(- """INSERT INTO sessions (- id, source, user_id, session_key, chat_id, chat_type, thread_id,- model, model_config, system_prompt, system_prompt_hash,- parent_session_id, cwd, profile_name, git_repo_root,- origin_json, display_name, started_at- )- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id) DO UPDATE SET- model = COALESCE(sessions.model, excluded.model),- model_config = CASE- WHEN excluded.model_config IS NOT NULL- AND json_type(- sessions.model_config, '$._reset_from'- ) IS NOT NULL- AND json_remove(- sessions.model_config, '$._reset_from'- ) = '{}'- THEN json_set(- excluded.model_config,- '$._reset_from',- json_extract(- sessions.model_config, '$._reset_from'- )- )- ELSE COALESCE(- sessions.model_config, excluded.model_config- )- END,- system_prompt_hash = COALESCE(- sessions.system_prompt_hash,- excluded.system_prompt_hash- ),- system_prompt = CASE- WHEN sessions.system_prompt_hash IS NULL- AND excluded.system_prompt_hash IS NOT NULL- THEN NULL- ELSE sessions.system_prompt- END,-""" + _UPSERT_KEEP_EXISTING_SQL,- (- session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model,- json.dumps(model_config) if model_config else None, system_prompt_hash,- parent_session_id, cwd, profile_name, git_repo_root, origin_json, display_name,- time.time(),- ),- )- if system_prompt_hash is not None:- self._delete_unreferenced_system_prompts(conn)- if parent_session_id:- self._inherit_parent_session_metadata(conn, session_id)- # Transcript-critical: a failed row creation aborts the turn.- self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)+ from hermes_state_worker_lifecycle import insert_session_row_in_transaction+ params = dict(session_id=session_id, source=source, model=model, model_config=model_config,+ system_prompt=system_prompt, user_id=user_id, session_key=session_key,+ chat_id=chat_id, chat_type=chat_type, thread_id=thread_id,+ parent_session_id=parent_session_id, cwd=cwd, profile_name=profile_name,+ git_repo_root=git_repo_root, origin_json=origin_json, display_name=display_name)+ self._execute_write(lambda conn: insert_session_row_in_transaction(self, conn, **params),+ patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)def create_session(self, session_id: str, source: str, **kwargs) -> str:"""Create (upsert) a session record. Returns the session_id."""