The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Desktop create speed tier and cwd_explicit reach the owner
Teknium1fdd18466d50
diff --git a/apps/desktop/src/api/canonical-create-options.test.ts b/apps/desktop/src/api/canonical-create-options.test.tsindex 2bb0d073cb9..f9bd00ecc66 100644--- a/apps/desktop/src/api/canonical-create-options.test.ts+++ b/apps/desktop/src/api/canonical-create-options.test.ts@@ -17,13 +17,13 @@ const BASE = { cols: 96, source: 'desktop', profile: 'default' }// [label, desktopSessionCreateParams output, expected owner frame subset | named refusal]const CASES: Array<[string, Record<string, unknown>, Record<string, unknown> | RegExp]> = [- ['inherited workspace', { ...BASE, cwd: '/w', cwd_explicit: false, fast: false }, { cwd: '/w' }],- ['picked workspace', { ...BASE, cwd: '/w', cwd_explicit: true, fast: false }, { cwd: '/w' }],- ['composer effort', { ...BASE, cwd: '/w', cwd_explicit: false, reasoning_effort: 'high', fast: false }, { cwd: '/w', reasoning: 'high' }],- ['onboarding minimal effort', { ...BASE, reasoning_effort: 'minimal', fast: false, title: 'Welcome' }, { reasoning: 'minimal', title: 'Welcome' }],+ ['inherited workspace', { ...BASE, cwd: '/w', cwd_explicit: false, fast: false }, { cwd: '/w', cwd_explicit: false, service_tier: 'normal' }],+ ['picked workspace', { ...BASE, cwd: '/w', cwd_explicit: true, fast: false }, { cwd: '/w', cwd_explicit: true, service_tier: 'normal' }],+ ['composer effort', { ...BASE, cwd: '/w', cwd_explicit: false, reasoning_effort: 'high', fast: false }, { cwd: '/w', reasoning: 'high', service_tier: 'normal' }],+ ['onboarding minimal effort', { ...BASE, reasoning_effort: 'minimal', fast: false, title: 'Welcome' }, { reasoning: 'minimal', title: 'Welcome', service_tier: 'normal' }],['Bot Chat', { ...BASE, title: 'Bot Chat', hidden: true, follow_profile_config: true }, { follow_profile_config: true, hidden: true }],- ['Fast speed', { ...BASE, cwd: '/w', cwd_explicit: false, fast: true }, /fast speed is not available on the shared gateway yet/],- ['Ultrafast speed', { ...BASE, fast: true, service_tier: 'ultrafast' }, /ultrafast speed is not available on the shared gateway yet/]+ ['Fast speed', { ...BASE, cwd: '/w', cwd_explicit: false, fast: true }, { cwd: '/w', service_tier: 'priority' }],+ ['Ultrafast speed', { ...BASE, fast: true, service_tier: 'ultrafast' }, { service_tier: 'ultrafast' }]]test.each(CASES)('%s: the Desktop create frame is admitted by the owner contract or refused by name', async (_label, params, expected) => {diff --git a/apps/desktop/src/api/canonical-protocol.test.ts b/apps/desktop/src/api/canonical-protocol.test.tsindex 1e3bda29d84..69ae00b742b 100644--- a/apps/desktop/src/api/canonical-protocol.test.ts+++ b/apps/desktop/src/api/canonical-protocol.test.ts@@ -92,7 +92,7 @@ test('canonical create retries retain identity and reject unsupported explicit iexpect(first).toMatchObject({ source: 'gui', cwd: '/tmp', request_id: expect.any(String) })expect(protocol.prepare('session.create', { ...params })).toEqual(first)expect(first).not.toHaveProperty('profile')- expect(() => protocol.prepare('session.create', { ...params, fast: true })).toThrow('fast')+ expect(protocol.prepare('session.create', { ...params, fast: true })).toMatchObject({ service_tier: 'priority' })expect(() => protocol.prepare('session.create', { ...params, provider: 'custom' })).toThrow('provider')protocol.result('session.create', first, { session_id: 'canonical', stored_session_id: 'canonical' })expect(protocol.prepare('session.create', params).request_id).not.toBe(first.request_id)diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex 32a3db7adc6..4c8ab3a54b2 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -384,24 +384,26 @@ export class CanonicalDesktopProtocol {}// The composer's per-session create options in the owner's create contract: the effort is the- // frozen launch `reasoning`; `cwd_explicit` is provenance the owner has no field for (it freezes- // `cwd` as given). No owner field carries a speed tier, so a non-normal pick is refused by name- // rather than silently running the chat at the profile's tier.+ // frozen launch `reasoning`; the speed pick is `service_tier` (main: an explicit tier wins, Fast+ // pins priority, Normal pins normal over a profile tier, omitted inherits); `cwd_explicit` is the+ // provenance that lets a named profile's own workspace beat an inherited cwd.private prepareCreate(input: Record<string, unknown>): Record<string, unknown> {- const { reasoning_effort: effort, cwd_explicit: _provenance, fast, service_tier: tier, ...params } = input-- if (fast === true || (typeof tier === 'string' && tier && tier !== 'normal')) {- throw new Error(`Starting a chat at ${tier === 'ultrafast' ? 'ultrafast' : 'fast'} speed is not available on the shared gateway yet; switch speed to Normal`)- }+ const { reasoning_effort: effort, fast, service_tier: picked, ...params } = input+ const tier = typeof picked === 'string' && picked ? picked : fast === true ? 'priority' : fast === false ? 'normal' : undefinedif (typeof effort === 'string' && effort) { params.reasoning = effort }- const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'reasoning', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config'])++ if (tier) { params.service_tier = tier }++ if (typeof params.cwd_explicit !== 'boolean') { delete params.cwd_explicit }++ const allowed = new Set(['request_id', 'source', 'cwd', 'model', 'toolsets', 'reasoning', 'profile', 'cols', 'title', 'hidden', 'follow_profile_config', 'service_tier', 'cwd_explicit'])const unsupported = Object.keys(params).filter(key => !allowed.has(key))if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>- ['request_id', 'cwd', 'model', 'toolsets', 'reasoning', 'title', 'hidden', 'follow_profile_config'].includes(key) || (key === 'profile' && siblingRoute(value))))+ ['request_id', 'cwd', 'model', 'toolsets', 'reasoning', 'title', 'hidden', 'follow_profile_config', 'service_tier', 'cwd_explicit'].includes(key) || (key === 'profile' && siblingRoute(value))))const key = JSON.stringify(result)const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex cea07c83a2b..ddf57798dc6 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4734,6 +4734,8 @@ export interface CanonicalCreateParams {title?: string | nullhidden?: booleanfollow_profile_config?: boolean | null+ service_tier?: string | null+ cwd_explicit?: boolean | null}export interface CanonicalSnapshot {session_id: stringdiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 7b513aa8845..6b4c191c301 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -8751,6 +8751,30 @@],"default": null,"title": "Follow Profile Config"+ },+ "service_tier": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Service Tier"+ },+ "cwd_explicit": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Cwd Explicit"}},"title": "CanonicalCreateParams",diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex d84b4744ca2..339431512f1 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1172,7 +1172,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):pr = runner._provider_routingreasoning_config = (policy.current_reasoning_config(runner) if policy elserunner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))- runner._service_tier = runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key)+ runner._service_tier = (policy.current_service_tier(runner, ctx.session_key) if policy else+ runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key))from gateway.session_api_turn import api_executionapi = api_execution.get()if api is not None:diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex b1b012fd67a..c1854d8e251 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -10,7 +10,8 @@ from hermes_state_runtime import RuntimeStoreErrorCREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets','provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor','yolo', 'safe_mode', 'ignore_user_config',- 'skills', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config'})+ 'skills', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config',+ 'service_tier', 'cwd_explicit'})# Sections a ``follow_profile_config`` session re-reads from the owning profile's CURRENT config each# turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases')@@ -103,6 +104,16 @@ class LocalSessionPolicy:authority = active_authority(runner)return resolve_reasoning_config(self.config(authority), self.current_model(authority) or '')+ def current_service_tier(self, runner, session_key):+ """The next turn's tier: a typed session /fast, else the policy's (frozen, or the profile's when following)."""+ from agent.fast_mode import parse_service_tier+ from gateway.session_authorities import active_authority+ from gateway.session_state import SERVICE_TIER_UNSET+ state = runner._peek_session_state(session_key) if session_key else None+ if state is not None and state.conversation.service_tier_override is not SERVICE_TIER_UNSET:+ return state.conversation.service_tier_override+ return parse_service_tier((self.config(active_authority(runner)).get('agent') or {}).get('service_tier'))+def current_model(self, authority):"""The model this session's next turn runs: the profile's current default when following."""live = self._live_profile(authority, present_sections(json.loads(self.config_json)))@@ -194,6 +205,8 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True)cwd = params.get('cwd', str(resolve_agent_cwd()))if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():raise RuntimeStoreError('invalid_params')+ if params.get('cwd_explicit') is False and 'cwd' in params:+ cwd = _profile_workspace_cwd(get_hermes_home()) or cwdfrom gateway.session_local_editor import validate_editorvalidate_editor(source, params.get('editor'))launch_skills(params)@@ -217,6 +230,20 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True)safe_mode=safe_mode, ignore_user_config=ignore_user_config)+def _profile_workspace_cwd(home):+ """A NAMED profile's configured ``terminal.cwd``, which beats a client cwd the Desktop only inherited+ (``cwd_explicit: false``; main's ``_completion_cwd``). Placeholders and missing dirs are unset."""+ import os+ from hermes_constants import profile_name_for_home+ if profile_name_for_home(home) in {None, 'default'}:+ return None+ from hermes_cli.config import read_user_config_raw+ terminal = read_user_config_raw(Path(home) / 'config.yaml').get('terminal')+ raw = str((terminal if isinstance(terminal, dict) else {}).get('cwd') or '').strip()+ configured = os.path.abspath(os.path.expanduser(raw)) if raw not in {'', '.', 'auto', 'cwd'} else None+ return configured if configured and os.path.isdir(configured) else None++def _apply_launch_overrides(params, config):"""Validate the explicit model/agent launch overrides and fold them into *config*."""from urllib.parse import urlsplit@@ -233,9 +260,21 @@ def _apply_launch_overrides(params, config):or url.username or url.password or url.query or url.fragment):raise RuntimeStoreError('invalid_params')config.setdefault('model', {})[key] = value- for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config'):+ for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config',+ 'cwd_explicit'):if flag in params and type(params[flag]) is not bool:raise RuntimeStoreError('invalid_params')+ if 'service_tier' in params:+ # An explicit speed pick (Desktop Fast / Ultrafast / Normal): normal pins normal over a+ # profile tier; an unknown word is refused, never read as normal.+ from agent.fast_mode import parse_exact_service_tier+ try:+ tier = parse_exact_service_tier(params['service_tier']) if isinstance(params['service_tier'], str) else None+ except ValueError:+ tier = None+ if tier is None:+ raise RuntimeStoreError('invalid_params')+ config.setdefault('agent', {})['service_tier'] = tier or 'normal'if params.get('checkpoints'):section = config.get('checkpoints')section = dict(section) if isinstance(section, dict) else {'enabled': bool(section)} if section else {}diff --git a/tests/gateway/test_session_create_tier_cwd.py b/tests/gateway/test_session_create_tier_cwd.pynew file mode 100644index 00000000000..94cedeef6df--- /dev/null+++ b/tests/gateway/test_session_create_tier_cwd.py@@ -0,0 +1,84 @@+"""Desktop create parity on the shared owner: speed tier and cwd provenance (B09 / C-hx-1).++Main's session.create honoured an explicit ``service_tier`` (Fast pins priority, Normal pins normal over+a profile tier, an unknown word is refused) and ``cwd_explicit`` (an inherited client cwd yields to a+NAMED profile's own ``terminal.cwd``). The owner freezes both into the LocalSessionPolicy the turn runs.+"""+import json+from types import SimpleNamespace++import pytest+++def _owner(home, monkeypatch, config):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ import hermes_state_runtime as rt+ home.mkdir(parents=True, exist_ok=True)+ (home / 'config.yaml').write_text(json.dumps(config))+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(run, '_hermes_home', home)+ store = SessionStore(home / 'sessions', GatewayConfig())+ db = store._db+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _handle_message=None, _peek_session_state=lambda key: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))+ runner.session_authority = authority+ return store, runner, authority, AuthorityConnection(authority, object(), {'user_id': 'human'})+++async def _create(owner, authority, request_id, cwd, **extra):+ from gateway.session_policy import policy_for_source+ response = await owner.dispatch({'id': request_id, 'method': 'session.create', 'params': dict(+ request_id=request_id, source='gui', cwd=str(cwd), toolsets=[], model='m', **extra)})+ if 'error' in response:+ return response['error']['data']['reason']+ live = authority.sessions[response['result']['session_id']]+ return live, policy_for_source(authority.runner, live.source)+++async def test_create_speed_tier_is_the_turns_tier_and_normal_pins_over_the_profile(tmp_path, monkeypatch):+ store, runner, authority, owner = _owner(tmp_path / 'home', monkeypatch, {+ 'model': {'default': 'm'}, 'agent': {'service_tier': 'fast'}})+ try:+ _, fast = await _create(owner, authority, 'fast', tmp_path, service_tier='fast')+ _, ultra = await _create(owner, authority, 'ultra', tmp_path, service_tier='ultrafast')+ live, normal = await _create(owner, authority, 'normal', tmp_path, service_tier='normal')+ _, inherited = await _create(owner, authority, 'inherit', tmp_path)+ assert fast.current_service_tier(runner, None) == 'priority'+ assert ultra.current_service_tier(runner, None) == 'ultrafast'+ assert normal.current_service_tier(runner, None) is None+ assert inherited.current_service_tier(runner, None) == 'priority'+ # A typed session /fast on this chat still beats the frozen pick.+ runner._peek_session_state = lambda key: SimpleNamespace(conversation=SimpleNamespace(+ service_tier_override='priority')) if key == live.route else None+ assert normal.current_service_tier(runner, live.route) == 'priority'+ assert await _create(owner, authority, 'bad', tmp_path, service_tier='warp') == 'invalid_params'+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_inherited_cwd_yields_to_a_named_profiles_workspace_and_a_pick_does_not(tmp_path, monkeypatch):+ workspace, client = tmp_path / 'profile-workspace', tmp_path / 'client'+ workspace.mkdir()+ client.mkdir()+ store, _runner, authority, owner = _owner(tmp_path / 'root' / 'profiles' / 'work', monkeypatch, {+ 'model': {'default': 'm'}, 'terminal': {'cwd': str(workspace)}})+ try:+ _, inherited = await _create(owner, authority, 'inherited', client, cwd_explicit=False)+ _, picked = await _create(owner, authority, 'picked', client, cwd_explicit=True)+ assert inherited.cwd == str(workspace)+ assert json.loads(inherited.terminal_json)['TERMINAL_CWD'] == str(workspace)+ assert picked.cwd == str(client)+ finally:+ await owner.close()+ store.close_all_db_handles()diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex fd417f610a1..e3967ef2b67 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -37,6 +37,8 @@ class CanonicalCreateParams(ProfileParams):title: str | None = Nonehidden: bool = Falsefollow_profile_config: bool | None = None+ service_tier: str | None = None+ cwd_explicit: bool | None = Noneclass CanonicalResumeParams(ProfileParams):