Skip to content

The agent that grows with you

fix: join finite gateway chat delegations in the admitted turn

Teknium5977ef75fdd7
diff --git a/gateway/session_finite.py b/gateway/session_finite.py
new file mode 100644
index 00000000000..44c8a7af2d7
--- /dev/null
+++ b/gateway/session_finite.py
@@ -0,0 +1,36 @@
+"""Admission-scoped finite consumers, independent of viewer or daemon lifetime."""
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+from hermes_state_runtime import RuntimeStoreError
+
+_finite_turn = ContextVar('finite_turn', default=None)
+
+
+def finite_turn_required():
+ # None preserves legacy standalone CLI's marker. A bound owner turn must
+ # never inherit process launch flags from another viewer.
+ return _finite_turn.get()
+
+
+@contextmanager
+def finite_turn_scope(finite):
+ token = _finite_turn.set(finite)
+ try:
+ yield
+ finally:
+ _finite_turn.reset(token)
+
+
+def admit_finite(params):
+ if 'finite' not in params:
+ return {}
+ if type(params['finite']) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ return {'finite': params['finite']}
+
+
+async def execute_finite_admission(authority, ref, row):
+ from gateway.session_ingress import execute_admission
+ with finite_turn_scope(row['payload'].get('finite', False)):
+ return await execute_admission(authority, ref, row)
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 41d64909761..a97750653ee 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -14,6 +14,7 @@ class GatewayChatView:
self.generation = snapshot.get("execution_generation", 0)
self.prompts = {p["prompt_id"]: p for p in snapshot.get("prompts", [])}
self.quiet = quiet
+ self.finite = False
self.streams = {}
self.completions = {}
self.changed = asyncio.Event()
@@ -77,7 +78,8 @@ class GatewayChatView:
async def submit(self, text):
return await self.client.rpc("prompt.submit", session_id=self.session_id,
- input_id=uuid.uuid4().hex, text=text)
+ input_id=uuid.uuid4().hex, text=text,
+ **({"finite": True} if self.finite else {}))
async def command(self, text):
command, _, rest = text.partition(" ")
@@ -128,6 +130,7 @@ class GatewayChatView:
async def run(self, query=None, *, oneshot=False):
self.quiet = self.quiet or oneshot
+ self.finite = oneshot
for prompt in self.prompts.values():
self.show_prompt(prompt)
renderer = asyncio.create_task(self.render())
diff --git a/tests/cli/test_finite_chat_delegation.py b/tests/cli/test_finite_chat_delegation.py
index b8be3a76c87..abc0498b91e 100644
--- a/tests/cli/test_finite_chat_delegation.py
+++ b/tests/cli/test_finite_chat_delegation.py
@@ -1,8 +1,11 @@
"""Finite chat must consume parallel delegated results before the CLI exits."""
+import asyncio
import http.server
import json
import os
+import sqlite3
+from contextlib import closing
from pathlib import Path
import subprocess
import sys
@@ -16,7 +19,7 @@ import pytest
REPO_ROOT = Path(__file__).resolve().parents[2]
[email protected]("mode", ["quiet", "oneshot", "redirected"])
[email protected]("mode", ["quiet", "oneshot", "redirected", "resumed"])
def test_finite_chat_joins_parallel_children_before_final_response(tmp_path, mode):
"""Real parser, CLI, agent loops and delegate_task. Only inference is synthetic.
@@ -104,6 +107,8 @@ def test_finite_chat_joins_parallel_children_before_final_response(tmp_path, mod
url = f"http://127.0.0.1:{server.server_port}/v1"
(home / "config.yaml").write_text(
f"model:\n provider: custom\n base_url: {url}\n api_mode: chat_completions\n"
+ "gateway:\n multiplex_profiles: false\n"
+ "auxiliary:\n title_generation:\n enabled: false\n"
"memory:\n memory_enabled: false\n user_profile_enabled: false\n"
"terminal:\n env: local\n oneshot_completion_wait_seconds: 1\n"
f"delegation:\n max_concurrent_children: 2\n base_url: {url}\n"
@@ -121,16 +126,51 @@ def test_finite_chat_joins_parallel_children_before_final_response(tmp_path, mod
HERMES_MANAGED_DIR=str(tmp_path / "managed"), TERMINAL_CWD=str(tmp_path),
OPENAI_BASE_URL=url, OPENAI_API_KEY="local-test-only", PYTHONPATH=str(REPO_ROOT),
PYTHONDONTWRITEBYTECODE="1", LANG="C.UTF-8")
- mode_flags = {"quiet": ["-Q"], "oneshot": ["--oneshot"], "redirected": []}
+ mode_flags = {"quiet": ["-Q"], "oneshot": ["--oneshot"], "redirected": [],
+ "resumed": ["-Q"]}
command = [
sys.executable, "-c", "from hermes_cli.main import main; main()", "chat",
- *mode_flags[mode], "--provider", "custom", "--model", "test-model",
+ *mode_flags[mode], "--provider", "custom", "--model", "test-model", "--base-url", url,
"--toolsets", "delegation", "--ignore-rules", "--query-file", str(query),
- "--reasoning", "high", "--max-turns", "10", "--run-budget", "60",
+ "--reasoning", "high", "--max-turns", "10",
]
+ from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+
+ async def create_resume_target(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, "session.create", request_id="interactive-origin", source="cli",
+ model="test-model", provider="custom", base_url=url,
+ toolsets=["delegation"], cwd=str(tmp_path), ignore_rules=True)
+ return created["result"]["stored_session_id"]
+
+ async def check_receipt(desc, row):
+ sid, request_id, payload = row
+ payload = json.loads(payload)
+ assert payload["finite"] is True
+ async with websocket(home, desc) as ws:
+ assert "result" in await rpc(ws, "session.resume", session_id=sid)
+ retry = dict(session_id=sid, input_id=request_id, **payload)
+ assert (await rpc(ws, "prompt.submit", **retry))["result"]["status"] == "terminal"
+ conflict = await rpc(ws, "prompt.submit", **{**retry, "finite": False})
+ assert conflict["error"]["message"] == "admission_conflict"
+ invalid = await rpc(ws, "prompt.submit", **{**retry, "finite": "true"})
+ assert invalid["error"]["message"] == "invalid_params"
try:
- result = subprocess.run(command, cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,
- capture_output=True, text=True, encoding="utf-8", timeout=75)
+ # Own the ordinary authority explicitly: a finite viewer must not own its lifetime.
+ with daemon(REPO_ROOT, home, env, barrier=False) as (owner, desc):
+ if mode == "resumed":
+ sid = asyncio.run(create_resume_target(desc))
+ command = command[:5] + ["-Q", "--resume", sid, "--query-file", str(query)]
+ result = subprocess.run(command, cwd=tmp_path, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, encoding="utf-8", timeout=75)
+ assert owner.poll() is None
+ with closing(sqlite3.connect(f"file:{home / 'state.db'}?mode=ro", uri=True)) as db:
+ admissions = db.execute("SELECT status FROM session_admissions").fetchall()
+ saved = db.execute("SELECT target_session_id,request_id,payload_json FROM session_admissions").fetchone()
+ # Inline children never leave a detached-result receipt for a later viewer.
+ assert db.execute("SELECT count(*) FROM async_delegations").fetchone() == (0,)
+ assert admissions == [("terminal",)], admissions
+ asyncio.run(check_receipt(desc, saved))
finally:
server.shutdown()
server.server_close()
diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.py
index c1f2835684c..42190ca2329 100644
--- a/tests/hermes_cli/test_gateway_chat.py
+++ b/tests/hermes_cli/test_gateway_chat.py
@@ -8,7 +8,7 @@ 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", "usage_file"):
+ for option in ("yolo", "worktree", "usage_file", "run_budget"):
args = argparse.Namespace(**{option: True})
assert gateway_chat.launch_from_args(args) == 2
assert option.replace("_", "-") in capsys.readouterr().err
diff --git a/tests/tools/test_finite_delegation_outcomes.py b/tests/tools/test_finite_delegation_outcomes.py
index dbb2a8d823b..a106736a443 100644
--- a/tests/tools/test_finite_delegation_outcomes.py
+++ b/tests/tools/test_finite_delegation_outcomes.py
@@ -6,6 +6,7 @@ child timeout/status conversion, interrupt propagation and cleanup are real.
from __future__ import annotations
import json
+import os
import threading
from types import SimpleNamespace
@@ -226,3 +227,26 @@ def test_nonfinite_marker_preserves_background_dispatch(harness, monkeypatch, ma
if api_history:
assert event["origin_session_id"] == "history-session"
assert all(child.closed.wait(2) for child in children)
+
+
+def test_owner_finite_scope_overrides_history_without_leaking(harness, monkeypatch):
+ from concurrent.futures import ThreadPoolExecutor
+ from gateway.session_finite import finite_turn_scope, finite_turn_required
+ from tools.delegate_tool_dispatch import _resolve_async_wake_sid
+
+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")
+ gate = threading.Barrier(2)
+ before = dict(os.environ)
+
+ def resolve(finite):
+ with finite_turn_scope(finite):
+ sc.set_session_vars(async_delivery=True, session_history_delivery="1")
+ gate.wait(5)
+ return _resolve_async_wake_sid("history", True)
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ results = list(pool.map(resolve, [True, False]))
+ assert results == [None, ""]
+ assert dict(os.environ) == before
+ assert finite_turn_required() is None
+ assert _resolve_async_wake_sid("history", True) is None
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index da75fd9d8a5..bbca2cc6ccd 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -217,10 +217,11 @@ def _resolve_async_wake_sid(origin_wake_sid: str, origin_session_history_deliver
continuation must read that row, not an authoritative caller-owned snapshot."""
from gateway.session_context import get_session_env
- # Finite chat owns no later turn to consume a detached result. Reuse its
- # approval/lifecycle marker without disabling terminal notify completions:
- # those have their own bounded exit linger and durable result receipts.
- if get_session_env("HERMES_SINGLE_QUERY_SESSION") == "1":
+ # Finite consumers need the result in this tool round. Owner admission scope
+ # wins over legacy standalone launch markers, without changing terminal delivery.
+ from gateway.session_finite import finite_turn_required
+ finite = finite_turn_required()
+ if finite is True or (finite is None and get_session_env("HERMES_SINGLE_QUERY_SESSION") == "1"):
return None
try:
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index df80a97eaa5..1dff974aba1 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -158,16 +158,20 @@ final response before the CLI exits.
- **Automatic joining:** no opt-in or background-mode override is needed.
Interactive TTY chat and messaging sessions keep background delegation.
-- **Existing safeguards:** delegation limits, timeouts, cancellation, and
- `approvals.single_query_mode` still apply. Joining does not auto-approve commands
- or guarantee successful child outcomes. Inspect results and verify artifacts.
-- **Terminal completions:** this does not change background terminal notification
- behavior or the bounded `terminal.oneshot_completion_wait_seconds` exit wait.
- That setting is not a delegation timeout.
-
-Delegation remains process-local. Interrupting or terminating the parent can
-cancel unfinished children. Use a durable scheduler for work that must survive
-the initiating process.
+- **Per-input policy:** the CLI records finite consumption with the admitted prompt,
+ including when resuming an interactive session. It does not change that session's
+ creation policy, sibling viewers, or the daemon environment.
+- **Existing safeguards:** delegation limits, timeouts, and cancellation still apply.
+ Joining does not auto-approve commands or guarantee successful child outcomes.
+ Inspect results and verify artifacts. Managed/safe workers still reject child
+ delegation until their child-registration contract is available.
+- **Separate limits:** `--run-budget` remains unsupported by gateway chat; it is not
+ required for joining. `terminal.oneshot_completion_wait_seconds` is not a
+ delegation timeout. Canonical terminal notifications remain gateway-owned.
+
+Closing the CLI detaches rather than terminating its gateway-owned turn. Child
+execution is still process-local to that owner: use a durable scheduler for work
+that must survive an owner restart.
### `hermes -z <prompt>` — scripted one-shot