Skip to content

The agent that grows with you

fix: freeze local CLI reasoning and execution launch options

Tekniumd0954a9ede1d
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index 85d29c259b2..cdeca8758ca 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -52,6 +52,14 @@ class GatewayTurnPrepareMixin:
_credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,
_resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,
)
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ from gateway.run import _runtime_agent_kwargs
+ runtime = resolve_runtime_provider(requested=policy.provider,
+ explicit_base_url=policy.base_url, target_model=policy.model)
+ return policy.model, _runtime_agent_kwargs(runtime)
skey = self._resolve_session_key_or_none(source, session_key)
model = _resolve_gateway_model(user_config)
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index a0f9cd9f2b7..6ec32f7dcf3 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -797,7 +797,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
policy = policy_for_source(runner, ctx.source)
platform_key = policy.platform if policy else ("cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value)
combined_ephemeral = self._combined_ephemeral_prompt()
- max_iterations = _current_max_iterations()
+ max_iterations = policy.max_turns if policy else _current_max_iterations()
try:
model, runtime_kwargs = runner._resolve_session_agent_runtime(
source=ctx.source, session_key=ctx.session_key, user_config=ctx.user_config,
@@ -811,7 +811,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
except Exception as exc:
return {"final_response": f"⚠️ Provider authentication failed: {exc}", "messages": [], "api_calls": 0, "tools": []}
pr = runner._provider_routing
- reasoning_config = runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model)
+ reasoning_config = (policy.reasoning_config if policy else
+ runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))
runner._reasoning_config = reasoning_config
runner._service_tier = runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key)
stream_consumer, stream_delta_cb, interim_cb, want_interim = self._setup_stream_consumer(platform_key)
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index f11f958bdd4..b620ed87ce9 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -107,11 +107,12 @@ class AuthorityConnection:
async def describe(self, ref, params):
await self.ping(ref, params)
+ from gateway.session_policy import CREATE_FIELDS
return {'instance_id': self.authority.instance_id, 'profile_id': self.authority.profile_id,
'authority_epoch': self.authority.epoch,
'capabilities': ['durable-admission-v1', 'event-replay-v1', 'local-cli-create-v1'],
'session_create': {'sources': ['cli', 'tui', 'gui'],
- 'parameters': ['request_id', 'source', 'cwd', 'model', 'toolsets']}}
+ 'parameters': sorted(CREATE_FIELDS)}}
async def info(self, ref, params):
from gateway.session_local import local_session_info
diff --git a/gateway/session_execution.py b/gateway/session_execution.py
index b39610fdaad..3167452b80f 100644
--- a/gateway/session_execution.py
+++ b/gateway/session_execution.py
@@ -41,6 +41,10 @@ class GatewaySessionAgentMixin:
def _skip_context_files(self, platform_key) -> bool:
"""gateway.platforms.<plat>.skip_context_files: messaging platforms may opt out of
filesystem-heavy context-file discovery (SOUL.md, AGENTS.md, .cursorrules)."""
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self._runner, self._ctx.source)
+ if policy:
+ return policy.ignore_rules
platforms_cfg = (self._ctx.user_config.get("gateway") or {}).get("platforms") or {}
# ``hermes gateway setup`` writes ``gateway.platforms`` as a LIST of enabled platform names,
# not a dict; treat any non-dict shape as "no per-platform overrides" rather than crashing.
@@ -147,6 +151,8 @@ class GatewaySessionAgentMixin:
ctx = self._ctx
runner = self._runner
src = ctx.source
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(runner, src)
return ctx.AIAgent(
model=turn_route["model"], **turn_route["runtime"], **_checkpoint_agent_kwargs(ctx.user_config),
max_iterations=max_iterations, quiet_mode=True, verbose_logging=False,
@@ -168,7 +174,8 @@ class GatewaySessionAgentMixin:
fallback_model=self._runner._refresh_fallback_model(),
skip_context_files=skip_context_files,
# Keep the persona even with minimal context: soul identity is one small file.
- load_soul_identity=True,
+ load_soul_identity=not bool(policy and policy.ignore_rules),
+ skip_memory=bool(policy and policy.ignore_rules),
)
def _resolve_turn_agent(self, turn_route, platform_key, combined_ephemeral, max_iterations, reasoning_config, pr):
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 4c81a5c7902..7a214e09d30 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -6,7 +6,8 @@ from pathlib import Path
from hermes_state_runtime import RuntimeStoreError
-CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets'})
+CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',
+ 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules'})
SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop'}
@@ -24,6 +25,29 @@ class LocalSessionPolicy:
def config(self):
return json.loads(self.config_json)
+ @property
+ def provider(self):
+ return self.config().get('model', {}).get('provider')
+
+ @property
+ def base_url(self):
+ return self.config().get('model', {}).get('base_url')
+
+ @property
+ def ignore_rules(self):
+ return json.loads(self.request_json).get('ignore_rules', False)
+
+ @property
+ def max_turns(self):
+ from hermes_cli.config import resolve_turn_limit
+ cfg = self.config()
+ return resolve_turn_limit(cfg.get('agent', {}).get('max_turns', cfg.get('max_turns')))
+
+ @property
+ def reasoning_config(self):
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(self.config(), self.model or '')
+
def build_policy(params, config):
from hermes_cli.tools_config import _get_platform_tools
@@ -42,6 +66,32 @@ def build_policy(params, config):
if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():
raise RuntimeStoreError('invalid_params')
config = json.loads(json.dumps(config))
+ from urllib.parse import urlsplit
+ from hermes_constants import parse_reasoning_effort
+ for key in ('provider', 'base_url'):
+ if key in params:
+ value = params[key]
+ if not isinstance(value, str) or not value.strip():
+ raise RuntimeStoreError('invalid_params')
+ if key == 'base_url':
+ url = urlsplit(value)
+ if (url.scheme not in {'http', 'https'} or not url.hostname
+ or url.username or url.password or url.query or url.fragment):
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('model', {})[key] = value
+ if 'ignore_rules' in params and type(params['ignore_rules']) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ if 'max_turns' in params:
+ value = params['max_turns']
+ if type(value) is not int or value <= 0:
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('agent', {})['max_turns'] = value
+ if 'reasoning' in params:
+ if not isinstance(params['reasoning'], str) or parse_reasoning_effort(params['reasoning']) is None:
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('agent', {})['reasoning_effort'] = params['reasoning']
+ # An explicit launch level wins over a per-model default, just like CLI.
+ config['agent'].pop('reasoning_overrides', None)
explicit = params.get('toolsets')
if 'toolsets' in params:
if (not isinstance(explicit, list) or any(not isinstance(x, str) or not validate_toolset(x) for x in explicit)
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index 767578ad990..ff03be2a08e 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -14,12 +14,12 @@ from hermes_cli.gateway_client import GatewayClientError, connect_gateway
# the authority. Reject them, rather than mutate process-wide gateway settings.
_UNSUPPORTED = (
"image", "skills", "worktree", "w", "checkpoints", "pass_session_id",
- "ignore_user_config", "ignore_rules", "safe_mode", "yolo", "accept_hooks",
+ "ignore_user_config", "safe_mode", "yolo", "accept_hooks",
"continue_last", "create_if_missing", "no_restore_cwd", "usage_file",
- "run_budget", "api_key", "base_url", "verbose", "compact",
+ "run_budget", "api_key", "verbose", "compact",
"list_tools", "list_toolsets",
)
-_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns")
+_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns", "base_url", "ignore_rules")
def validate_options(args):
@@ -30,7 +30,7 @@ def validate_options(args):
flags = ", ".join("--" + name.replace("_", "-") for name in unsupported)
raise GatewayClientError(f"Unsupported gateway CLI options: {flags}. No local fallback or policy changes were made.")
if getattr(args, "resume", None) and (getattr(args, "in_dir", None) or getattr(args, "source", None) or
- any(getattr(args, name, None) is not None for name in _POLICY)):
+ any(getattr(args, name, None) not in (None, False) for name in _POLICY)):
raise GatewayClientError("Resume retains gateway session policy; creation overrides are unsupported on resume.")
diff --git a/tests/gateway/test_session_policy.py b/tests/gateway/test_session_policy.py
index 2344dee7321..16eab24cc19 100644
--- a/tests/gateway/test_session_policy.py
+++ b/tests/gateway/test_session_policy.py
@@ -32,7 +32,7 @@ def test_policy_selects_surface_and_isolates_cwd(tmp_path):
list(pool.map(run, policies))
assert dict(os.environ) == before
for params in ({'source': 'cron'}, {'toolsets': ['not-a-toolset']}, {'cwd': '.'},
- {'provider': 'custom'}, {'skills': ['x']}, {'toolsets': ['desktop_ui'], 'source': 'cli'}):
+ {'provider': 12}, {'skills': ['x']}, {'toolsets': ['desktop_ui'], 'source': 'cli'}):
with pytest.raises(RuntimeStoreError, match='invalid_params'):
build_policy(params, {})
@@ -54,3 +54,24 @@ def test_launch_policy_reaches_real_turn_runner(tmp_path):
receipt = json.loads((state / 'policy-receipt.json').read_text())
assert receipt['cwd_effects'] and receipt['same_agents'] and receipt['no_spill']
print(json.dumps(receipt))
+
+
+def test_launch_options_are_frozen_and_validated(tmp_path):
+ from gateway.session_policy import build_policy
+ from hermes_constants import parse_reasoning_effort
+ from hermes_state_runtime import RuntimeStoreError
+ cfg = {'agent': {'max_turns': 8, 'reasoning_effort': 'low'}}
+ params = dict(cwd=str(tmp_path), provider='custom', base_url='http://127.0.0.1:1234/v1',
+ model='fixture', reasoning='high', max_turns=3, ignore_rules=True)
+ policy = build_policy(params, cfg)
+ assert policy.provider == 'custom' and policy.base_url == params['base_url']
+ assert policy.ignore_rules and policy.max_turns == 3
+ assert policy.reasoning_config == parse_reasoning_effort('high')
+ cfg['agent']['reasoning_effort'] = 'none'
+ assert policy.reasoning_config == parse_reasoning_effort('high')
+ assert build_policy(dict(cwd=str(tmp_path), ignore_rules=False), cfg).ignore_rules is False
+ for bad in ({'max_turns': True}, {'max_turns': 0}, {'reasoning': 'garbage'},
+ {'ignore_rules': 'false'}, {'base_url': 'http://user:secret@localhost/v1'}):
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ build_policy(dict(cwd=str(tmp_path), **bad), cfg)
+
diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.py
index a2518898e31..8fb8258b61e 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", "ignore_rules", "safe_mode", "worktree", "continue_last", "usage_file"):
+ for option in ("yolo", "safe_mode", "worktree", "continue_last", "usage_file"):
args = argparse.Namespace(**{option: True})
assert gateway_chat.launch_from_args(args) == 2
assert option.replace("_", "-") in capsys.readouterr().err