Skip to content

The agent that grows with you

refactor(gateway): one coding-posture flag, opted into by session.create only

kshitijk4poor3479bb19cf1b
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.py
index a8b251be579..826883f9a89 100644
--- a/gateway/session_kanban.py
+++ b/gateway/session_kanban.py
@@ -53,8 +53,7 @@ def build_kanban_policy(connection, params, config):
if value:
params_policy[name] = value
private = {}
- # A worker's task worktree is no client pick of the coding posture: it keeps the profile's toolsets.
- policy = build_policy(params_policy, config, private_secrets=private, workspace_posture=False)
+ policy = build_policy(params_policy, config, private_secrets=private)
if policy.model is None:
from gateway.run import _resolve_gateway_model
policy = replace(policy, model=_resolve_gateway_model(policy.config()))
diff --git a/gateway/session_local.py b/gateway/session_local.py
index a56d2ddc4f7..f4aa27d68d5 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -176,7 +176,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
config = _load_gateway_config()
raw_model = params.get('model')
params = resolve_launch_route(params, config)
- policy = build_policy(params, config, private_secrets=private_secrets)
+ # A client's session.create is the one caller whose named folder may select the coding posture.
+ policy = build_policy(params, config, private_secrets=private_secrets, workspace_posture=True)
if isinstance(raw_model, str) and params.get('model') != raw_model:
# Owner-stamped provenance (not a create field): a remote client cannot re-resolve the
# typed `-m` alias against its own home, so resume compares a repeat against this.
diff --git a/gateway/session_local_migration.py b/gateway/session_local_migration.py
index 1a60b41080b..0f8ab11b025 100644
--- a/gateway/session_local_migration.py
+++ b/gateway/session_local_migration.py
@@ -101,8 +101,7 @@ def adopt_legacy_session(authority, actor, row):
params, api_mode = legacy_launch_params(row)
params['source'] = LEGACY_CREATION_SOURCES.get(row['source'], row['source'])
private = {}
- # The row's saved folder is no fresh client pick: an adopted session keeps the profile's toolsets.
- policy = build_policy(params, _load_gateway_config(), private_secrets=private, workspace_posture=False)
+ policy = build_policy(params, _load_gateway_config(), private_secrets=private)
if api_mode:
config = json.loads(policy.config_json)
config.setdefault('model', {})['api_mode'] = api_mode
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 8bfa6ddf6b8..2645980bf16 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -137,9 +137,7 @@ class LocalSessionPolicy:
return self.toolsets
# The workspace decision is the creation-time one: a project file the agent writes mid-session must
# not switch this conversation's toolsets (prompt cache). Only a profile change (``focus`` off) does.
- from agent.coding_context import focus_toolsets
- posture = focus_toolsets(config) if self.coding_posture else None
- return tuple(sorted(_resolve_toolsets({}, config, self.source, self.safe_mode, posture)))
+ return tuple(sorted(_resolve_toolsets({}, config, self.source, self.safe_mode, self.coding_posture)))
def current_reasoning_config(self, runner, session_key=None):
"""The next turn's reasoning: a typed session /reasoning (the messaging handler's override), else
@@ -255,7 +253,7 @@ def present_sections(config):
return config
-def build_policy(params, config, *, private_secrets=None, profile_terminal=True, workspace_posture=True):
+def build_policy(params, config, *, private_secrets=None, profile_terminal=True, workspace_posture=False):
from agent.runtime_cwd import resolve_agent_cwd
from tools.terminal_scope import build_profile_terminal_scope, default_terminal_scope
from hermes_constants import get_hermes_home
@@ -292,13 +290,12 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,
# still targets this, and a later profile edit supersedes it.
config.setdefault('model', {})['selection_profile'] = list(profile_target(config))
_apply_launch_overrides(params, config)
- # Only a folder the client named is a workspace: the daemon's own directory (the fallback above, used by
- # hosted rooms) must not switch a session into the coding posture, nor may a caller that opts out
- # (Kanban workers, legacy-row adoption).
- # ``tool`` is a third-party integration, not a person's workspace.
+ # The posture is opt-in (``session.create`` only) and needs a folder the client named: the daemon's own
+ # directory (the fallback above) is no workspace, and ``tool`` is a third-party integration. An explicit
+ # pick wins anyway; skipping it here also spares the probe.
named = workspace_posture and source != 'tool' and 'cwd' in params and 'toolsets' not in params
- posture = _coding_posture(config, source, cwd) if named else None
- enabled = _resolve_toolsets(params, config, source, safe_mode, posture)
+ coding_posture = named and _in_coding_workspace(config, source, cwd)
+ enabled = _resolve_toolsets(params, config, source, safe_mode, coding_posture)
terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()
# The client's launch folder is a path on THIS host: a remote or container backend keeps its own
# configured cwd unless the user picked this folder for the session.
@@ -313,7 +310,7 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,
return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),
json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),
safe_mode=safe_mode, ignore_user_config=ignore_user_config,
- coding_posture=posture is not None)
+ coding_posture=coding_posture)
def terminal_uses_host_cwd(terminal):
@@ -396,10 +393,11 @@ def _apply_launch_overrides(params, config):
config['agent'].pop('reasoning_overrides', None)
-def _resolve_toolsets(params, config, source, safe_mode, posture=None):
- """Validate explicit toolsets and return the session's enabled toolset set. Without a pick, the
- coding *posture* (``_coding_posture``) replaces the profile default; the gateway decides it, never
- the client."""
+def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False):
+ """Validate explicit toolsets and return the session's enabled toolset set. Without a pick, a
+ *coding_posture* session runs ``focus_toolsets`` instead of the profile default while the profile
+ stays on ``focus``; the gateway decides it, never the client."""
+ from agent.coding_context import focus_toolsets
from hermes_cli.tools_config import _get_platform_tools
from toolsets import validate_toolset
explicit = params.get('toolsets')
@@ -408,15 +406,14 @@ def _resolve_toolsets(params, config, source, safe_mode, posture=None):
or ('desktop_ui' in explicit and source != 'gui')):
raise RuntimeStoreError('invalid_params')
config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicit
- enabled = _get_platform_tools(config, 'acp' if source == 'acp' else 'cli')
+ posture = focus_toolsets(config) if explicit is None and coding_posture else None
+ enabled = set(posture) if posture is not None else _get_platform_tools(config, 'acp' if source == 'acp' else 'cli')
if explicit is not None:
from toolsets import resolve_toolset
requested = {t for name in explicit for t in resolve_toolset(name)}
effective = {t for name in enabled for t in resolve_toolset(name)}
if not requested <= effective:
raise RuntimeStoreError('invalid_params')
- elif posture is not None:
- enabled = set(posture)
if explicit is None and source in {'tui', 'gui'}:
# Same surface toolsets as the native TUI factory, without its env inference.
# The fold-in lands after _get_platform_tools subtracted agent.disabled_toolsets, so
@@ -434,16 +431,15 @@ def _resolve_toolsets(params, config, source, safe_mode, posture=None):
return enabled
-def _coding_posture(config, source, cwd):
- """The coding posture's toolsets for *cwd* (``agent.coding_context: focus`` in a code workspace),
- else None. A detection failure keeps the profile default rather than refusing the session."""
+def _in_coding_workspace(config, source, cwd):
+ """Whether *cwd* selects the coding posture (``agent.coding_context: focus`` in a code workspace).
+ A detection failure keeps the profile default rather than refusing the session."""
from agent.coding_context import coding_selection
try:
- selection = coding_selection(platform=SURFACES[source], cwd=cwd, config=config)
+ return coding_selection(platform=SURFACES[source], cwd=cwd, config=config) is not None
except Exception:
logger.debug('coding posture detection failed for %s; keeping the profile default', cwd, exc_info=True)
- return None
- return selection
+ return False
def _extract_config_secrets(value, private, path=()):
diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.py
index e4bb3f607dd..30f8d4cee1f 100644
--- a/hermes_cli/cli_init_mixin.py
+++ b/hermes_cli/cli_init_mixin.py
@@ -32,7 +32,7 @@ def _gateway_launch(cli):
"provider": provider if explicit_model and provider not in {None, "", "auto"} else None,
"api_key": getattr(cli, "_explicit_api_key", None),
"base_url": getattr(cli, "_explicit_base_url", None),
- # Only a picked list (-t or the coding posture); the gateway resolves the profile default (#138670).
+ # Only a typed -t; the gateway resolves the profile default and the coding posture (#138670).
"toolsets": getattr(cli, "enabled_toolsets", None) if getattr(cli, "_explicit_toolsets", False) else None,
"reasoning": getattr(cli, "_explicit_reasoning", None),
"max_turns": getattr(cli, "_explicit_max_turns", None),
@@ -253,8 +253,8 @@ class CLIInitMixin:
def _init_toolsets(self, toolsets):
from cli import CLI_CONFIG, validate_toolset
self.enabled_toolsets = toolsets
- # Only a picked list rides session.create; _build_cli_from_args clears this for the profile default,
- # which the gateway resolves itself (an explicit list with a stale name is refused, #138670).
+ # Only a picked list rides session.create; _build_cli_from_args clears this unless -t was typed (the
+ # gateway resolves the profile default and coding posture itself; a stale explicit name is refused, #138670).
self._explicit_toolsets = toolsets is not None
from agent.skill_utils import parse_config_string_list
diff --git a/tests/gateway/test_session_policy_coding_posture.py b/tests/gateway/test_session_policy_coding_posture.py
index b1cc5eb9572..c780cb11e5f 100644
--- a/tests/gateway/test_session_policy_coding_posture.py
+++ b/tests/gateway/test_session_policy_coding_posture.py
@@ -4,6 +4,12 @@ import pytest
FOCUS = {'agent': {'coding_context': 'focus'}, 'platform_toolsets': {'cli': ['terminal'], 'acp': ['terminal']}}
+def create(params, config, **kwargs):
+ """The ``session.create`` build (``stage_local_session``), the one caller that opts in."""
+ from gateway.session_policy import build_policy
+ return build_policy(params, config, workspace_posture=True, **kwargs)
+
+
@pytest.fixture
def project(tmp_path):
root = tmp_path / 'project'
@@ -14,87 +20,99 @@ def project(tmp_path):
@pytest.mark.parametrize('source', ['cli', 'tui', 'gui', 'acp', 'oneshot'])
def test_focus_in_a_code_workspace_selects_the_coding_posture(project, source):
- from gateway.session_policy import build_policy
- policy = build_policy({'source': source, 'cwd': str(project)}, FOCUS)
+ policy = create({'source': source, 'cwd': str(project)}, FOCUS)
assert 'coding' in policy.toolsets and 'terminal' not in policy.toolsets
def test_surface_toolsets_still_fold_in_over_the_posture(project):
- from gateway.session_policy import build_policy
- assert 'project' in build_policy({'source': 'tui', 'cwd': str(project)}, FOCUS).toolsets
- gui = build_policy({'source': 'gui', 'cwd': str(project)}, FOCUS).toolsets
+ assert 'project' in create({'source': 'tui', 'cwd': str(project)}, FOCUS).toolsets
+ gui = create({'source': 'gui', 'cwd': str(project)}, FOCUS).toolsets
assert {'coding', 'desktop_ui', 'catalog'} <= set(gui)
def test_profile_default_outside_a_workspace_or_without_focus(project, tmp_path):
- from gateway.session_policy import build_policy
plain = tmp_path / 'notes'
plain.mkdir()
- assert build_policy({'source': 'cli', 'cwd': str(plain)}, FOCUS).toolsets == ('terminal',)
+ assert create({'source': 'cli', 'cwd': str(plain)}, FOCUS).toolsets == ('terminal',)
auto = {**FOCUS, 'agent': {'coding_context': 'auto'}}
- assert build_policy({'source': 'cli', 'cwd': str(project)}, auto).toolsets == ('terminal',)
+ assert create({'source': 'cli', 'cwd': str(project)}, auto).toolsets == ('terminal',)
def test_an_explicit_pick_wins_over_the_posture(project):
- from gateway.session_policy import build_policy
- policy = build_policy({'source': 'cli', 'cwd': str(project), 'toolsets': ['terminal']}, FOCUS)
+ policy = create({'source': 'cli', 'cwd': str(project), 'toolsets': ['terminal']}, FOCUS)
assert policy.toolsets == ('terminal',)
def test_a_following_session_keeps_the_posture_for_its_own_cwd(project):
- from gateway.session_policy import build_policy
- policy = build_policy({'source': 'cli', 'cwd': str(project), 'follow_profile_config': True}, FOCUS)
+ policy = create({'source': 'cli', 'cwd': str(project), 'follow_profile_config': True}, FOCUS)
assert 'coding' in policy.current_toolsets(FOCUS)
def test_a_project_file_written_mid_session_does_not_switch_toolsets(tmp_path):
- from gateway.session_policy import build_policy
plain = tmp_path / 'notes'
plain.mkdir()
- policy = build_policy({'source': 'cli', 'cwd': str(plain), 'follow_profile_config': True}, FOCUS)
+ policy = create({'source': 'cli', 'cwd': str(plain), 'follow_profile_config': True}, FOCUS)
(plain / 'pyproject.toml').write_text('[project]\nname = "late"\n')
assert policy.current_toolsets(FOCUS) == ('terminal',)
def test_a_following_session_still_takes_a_profile_change(project):
- from gateway.session_policy import build_policy
- policy = build_policy({'source': 'cli', 'cwd': str(project), 'follow_profile_config': True}, FOCUS)
+ policy = create({'source': 'cli', 'cwd': str(project), 'follow_profile_config': True}, FOCUS)
off = {**FOCUS, 'agent': {'coding_context': 'off'}}
assert policy.current_toolsets(off) == ('terminal',)
def test_plugin_mcp_servers_stay_in_the_posture(project, monkeypatch):
- from gateway.session_policy import build_policy
monkeypatch.setattr('hermes_cli.plugins.get_portable_mcp_server_names_nowait', lambda: {'plug'})
- assert {'coding', 'plug'} <= set(build_policy({'source': 'gui', 'cwd': str(project)}, FOCUS).toolsets)
+ assert {'coding', 'plug'} <= set(create({'source': 'gui', 'cwd': str(project)}, FOCUS).toolsets)
@pytest.mark.parametrize('source', ['tool', 'gui'])
def test_the_daemons_own_directory_is_not_a_workspace(project, monkeypatch, source):
- from gateway.session_policy import build_policy
monkeypatch.chdir(project)
monkeypatch.setattr('agent.runtime_cwd.resolve_agent_cwd', lambda: project)
- assert 'coding' not in build_policy({'source': source}, FOCUS, profile_terminal=False).toolsets
+ assert 'coding' not in create({'source': source}, FOCUS, profile_terminal=False).toolsets
def test_a_profile_default_listing_coding_is_not_replayed_as_a_workspace(tmp_path):
- from gateway.session_policy import build_policy
plain = tmp_path / 'notes'
plain.mkdir()
config = {**FOCUS, 'platform_toolsets': {'cli': ['coding', 'web']}}
- policy = build_policy({'source': 'cli', 'cwd': str(plain), 'follow_profile_config': True}, config)
+ policy = create({'source': 'cli', 'cwd': str(plain), 'follow_profile_config': True}, config)
assert not policy.coding_posture and 'web' in policy.toolsets
assert policy.current_toolsets(config) == policy.toolsets
@pytest.mark.parametrize('params', [{'source': 'tool'}, {'source': 'cli', 'toolsets': ['terminal']}])
def test_tool_sources_and_picks_keep_their_toolsets_in_a_workspace(project, params):
- from gateway.session_policy import build_policy
- policy = build_policy({**params, 'cwd': str(project)}, FOCUS)
+ policy = create({**params, 'cwd': str(project)}, FOCUS)
assert not policy.coding_posture and policy.toolsets == ('terminal',)
-def test_a_caller_can_opt_out_of_the_workspace_posture(project):
+def test_only_session_create_opts_into_the_workspace_posture(project):
+ # Kanban workers, legacy-row adoption, cron and hosted rooms build without opting in.
from gateway.session_policy import build_policy
- policy = build_policy({'source': 'cli', 'cwd': str(project)}, FOCUS, workspace_posture=False)
- assert policy.toolsets == ('terminal',)
+ assert build_policy({'source': 'cli', 'cwd': str(project)}, FOCUS).toolsets == ('terminal',)
+
+
+
+async def test_session_create_selects_the_posture_for_its_named_folder(project, tmp_path, monkeypatch):
+ """The real ``session.create`` path (``create_local_session``), not a direct ``build_policy`` call."""
+ from types import SimpleNamespace
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+ from hermes_state_local import local_receipt
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {**FOCUS, 'model': {'default': 'm'}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='posture')
+ actor = Principal('owner', str(tmp_path), frozenset({'session:create', 'session:read'}), 'socket')
+ ref = create_local_session(authority, actor, {'request_id': 'r', 'source': 'cli', 'cwd': str(project)})
+ policy = local_receipt(store._db, ref.session_id)['policy']
+ assert policy['coding_posture'] is True and policy['toolsets'] == ['coding']