Skip to content

The agent that grows with you

fix(gateway): resolve local paths against the session's folder, not the daemon's

unsupportedpastelsdddbc6dc383f
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index a6f26d98c91..3864add1249 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -1596,12 +1596,17 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
"""Expand ``@`` context references; returns None when the injection was refused (user notified)."""
try:
from agent.context_references import preprocess_context_references_async
+ from gateway.session_policy import policy_for_source
try:
from tools.terminal_scope import terminal_env as _ts_env
except ImportError:
_ts_env = os.environ.get
_msg_cwd = _ts_env("TERMINAL_CWD", os.path.expanduser("~"))
+ # A local session's references resolve in ITS workspace: this runs before the turn binds
+ # the policy scope, so TERMINAL_CWD is still the daemon's own.
+ if (_policy := policy_for_source(self, source)) is not None:
+ _msg_cwd = _policy.cwd
_msg_ctx_len = await self._inbound_model_context_length(source, session_key)
_ctx_result = await preprocess_context_references_async(
message_text, cwd=_msg_cwd, context_length=_msg_ctx_len, allowed_root=_msg_cwd
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 032f8619af7..e2433c40b92 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -284,7 +284,10 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True)
_apply_launch_overrides(params, config)
enabled = _resolve_toolsets(params, config, source, safe_mode)
terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()
- terminal['TERMINAL_CWD'] = cwd
+ # 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.
+ if params.get('cwd_explicit') is True or terminal_uses_host_cwd(terminal):
+ terminal['TERMINAL_CWD'] = cwd
request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}
request.setdefault('source', 'cli')
from gateway.session_local_mcp import private_editor_request
@@ -296,6 +299,14 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True)
safe_mode=safe_mode, ignore_user_config=ignore_user_config)
+def terminal_uses_host_cwd(terminal):
+ """Whether the terminal works in the session's host cwd: the local backend, or docker mounting it at
+ ``/workspace``. ssh, modal and the other sandboxes resolve their own cwd."""
+ backend = str(terminal.get('TERMINAL_ENV') or 'local').strip().lower()
+ mounts = str(terminal.get('TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE') or '').strip().lower() in {'1', 'true', 'yes', 'on'}
+ return backend == 'local' or (backend == 'docker' and mounts)
+
+
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."""
@@ -620,7 +631,8 @@ def restore_policy(data):
for value in (policy.config_json, policy.request_json, policy.terminal_json):
if not isinstance(json.loads(value), dict):
raise ValueError('invalid policy object')
- if json.loads(policy.terminal_json).get('TERMINAL_CWD') != policy.cwd:
+ terminal = json.loads(policy.terminal_json)
+ if terminal_uses_host_cwd(terminal) and terminal.get('TERMINAL_CWD') != policy.cwd:
raise ValueError('terminal policy mismatch')
return replace(policy, toolsets=tuple(policy.toolsets))
except (KeyError, TypeError, ValueError) as exc:
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.py
index 1db362718ff..7894acdf1dd 100644
--- a/hermes_cli/cli_chat_turn_mixin.py
+++ b/hermes_cli/cli_chat_turn_mixin.py
@@ -83,9 +83,7 @@ class CLIChatTurnMixin:
message = self._chat_route_images(message, images)
if isinstance(message, str) and not isinstance(message, TimelineNotification):
- message, blocked = self._chat_expand_context_references(message)
- if blocked is not None:
- return blocked
+ # ``@`` references are expanded once, by the gateway, against this session's cwd.
# Lone surrogates (rich-text clipboard paste) crash the OpenAI SDK's JSON serialization.
from agent.message_sanitization import _sanitize_surrogates
message = _sanitize_surrogates(message)
@@ -149,35 +147,6 @@ class CLIChatTurnMixin:
if turn.tts_thread is not None and turn.tts_thread.is_alive():
turn.tts_thread.join(timeout=5)
- def _chat_expand_context_references(self, message: str):
- """Expand ``@file:``/``@diff``/``@folder:`` references.
-
- Returns ``(message, blocked)``; ``blocked`` is the refusal text to return instead
- of running the turn when injection was refused, else None.
- """
- from cli import _DIM, _RST, _cprint
- if "@" not in message:
- return message, None
- try:
- from agent.context_references import preprocess_context_references
- from agent.model_metadata import get_model_context_length
- _ctx_len = get_model_context_length(
- self.model, base_url=self.base_url or "", api_key=self.api_key or "",
- provider=self.provider or "",
- config_context_length=getattr(self.agent, "_config_context_length", None) if self.agent else None)
- _ctx_result = preprocess_context_references(message, cwd=os.getcwd(), context_length=_ctx_len)
- if _ctx_result.expanded or _ctx_result.blocked:
- if _ctx_result.references:
- _cprint(f" {_DIM}{t('cli.chat.context_refs', count=len(_ctx_result.references), tokens=_ctx_result.injected_tokens)}{_RST}")
- for w in _ctx_result.warnings:
- _cprint(f" {_DIM}⚠ {w}{_RST}")
- if _ctx_result.blocked:
- return message, ("\n".join(_ctx_result.warnings) or t("cli.chat.context_injection_refused"))
- message = _ctx_result.message
- except Exception as e:
- logging.debug("@ context reference expansion failed: %s", e)
- return message, None
-
def _chat_route_images(self, message, images):
"""Attach images natively (vision model) or pre-describe them as text; returns the message to send.
diff --git a/tests/gateway/test_local_context_ref_session_cwd.py b/tests/gateway/test_local_context_ref_session_cwd.py
new file mode 100644
index 00000000000..106aa81824e
--- /dev/null
+++ b/tests/gateway/test_local_context_ref_session_cwd.py
@@ -0,0 +1,49 @@
+"""``@`` references on a local (CLI/TUI/Desktop) session resolve in that session's cwd.
+
+The inbound prepare step runs before the turn binds the session policy, so the process
+``TERMINAL_CWD`` there is the gateway daemon's own folder (``~`` or ``MESSAGING_CWD``), never the
+folder the client was launched from.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import session_policy
+from gateway.config import Platform
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+
+
+async def _context_length(_source, _session_key):
+ return 128000
+
+
+async def _expand(source, text):
+ runner = object.__new__(GatewayRunner)
+ runner._inbound_model_context_length = _context_length
+ return await runner._expand_inbound_context_references(source, "key", text)
+
+
[email protected](autouse=True)
+def workspaces(tmp_path, monkeypatch):
+ project, daemon = tmp_path / "project", tmp_path / "daemon-home"
+ for folder, body in ((project, "PROJECT-NOTES"), (daemon, "DECOY-NOTES")):
+ folder.mkdir()
+ (folder / "notes.txt").write_text(body, encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_CWD", str(daemon))
+ policies = {"local-chat": SimpleNamespace(cwd=str(project))}
+ monkeypatch.setattr(session_policy, "policy_for_source",
+ lambda runner, source: policies.get(source.chat_id) if source.platform == Platform.LOCAL else None)
+
+
+async def test_local_session_reference_reads_the_session_workspace():
+ expanded = await _expand(SessionSource(platform=Platform.LOCAL, chat_id="local-chat"), "read @file:notes.txt")
+ assert expanded is not None and "PROJECT-NOTES" in expanded
+ assert "DECOY-NOTES" not in expanded
+
+
+async def test_messaging_reference_keeps_the_terminal_cwd():
+ expanded = await _expand(SessionSource(platform=Platform.TELEGRAM, chat_id="123"), "read @file:notes.txt")
+ assert expanded is not None and "DECOY-NOTES" in expanded
diff --git a/tests/gateway/test_session_policy_remote_cwd.py b/tests/gateway/test_session_policy_remote_cwd.py
new file mode 100644
index 00000000000..3e6fe9edc2a
--- /dev/null
+++ b/tests/gateway/test_session_policy_remote_cwd.py
@@ -0,0 +1,37 @@
+"""A remote or container terminal backend never runs in the client's host launch folder.
+
+Ink sends its launch folder as every session's ``cwd``; that path exists on this host only. ssh and
+the sandboxes keep their own configured cwd (or their default) unless the user picked the folder, and
+docker with ``docker_mount_cwd_to_workspace`` still mounts it at ``/workspace``.
+"""
+import json
+from dataclasses import asdict
+
+import pytest
+
+LAUNCH = object() # the client's host launch folder
+
+
[email protected]("terminal,params,expected", [
+ ({"backend": "ssh", "cwd": "/srv/app"}, {}, ("/srv/app", None)),
+ ({"backend": "ssh"}, {}, ("~", None)),
+ ({"backend": "docker", "cwd": "/workspace/app"}, {}, ("/workspace/app", None)),
+ ({"backend": "docker", "docker_mount_cwd_to_workspace": True}, {}, ("/workspace", LAUNCH)),
+ ({"backend": "local"}, {}, (LAUNCH, None)),
+ ({"backend": "ssh", "cwd": "/srv/app"}, {"cwd_explicit": True}, (LAUNCH, None)),
+])
+def test_terminal_cwd_follows_the_backend(tmp_path, monkeypatch, terminal, params, expected):
+ from gateway.session_policy import build_policy, policy_scope, restore_policy
+ from tools.terminal_tool import _get_env_config
+
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text(json.dumps({"terminal": terminal}), encoding="utf-8") # JSON is YAML
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ launch = tmp_path / "project"
+ launch.mkdir()
+
+ policy = build_policy({"source": "tui", "cwd": str(launch), "model": "m", **params}, {})
+ with policy_scope(restore_policy(asdict(policy))):
+ config = _get_env_config()
+ assert (config["cwd"], config.get("host_cwd")) == tuple(str(launch) if v is LAUNCH else v for v in expected)
diff --git a/tests/hermes_cli/test_cli_codex_context_reference.py b/tests/hermes_cli/test_cli_codex_context_reference.py
deleted file mode 100644
index ffe4d47f91d..00000000000
--- a/tests/hermes_cli/test_cli_codex_context_reference.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Regression coverage for provider-aware @-context sizing in the CLI."""
-
-from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
-
-
-def test_at_context_resolution_passes_active_provider():
- """The CLI @-reference path must preserve the active Codex provider."""
- from cli import HermesCLI
-
- cli = HermesCLI.__new__(HermesCLI)
- cli.model = "gpt-5.6-terra"
- cli.base_url = "https://chatgpt.com/backend-api/codex"
- cli.api_key = "token"
- cli.provider = "openai-codex"
- cli.agent = SimpleNamespace(_config_context_length=None)
- cli._active_agent_route_signature = "route"
- cli._secret_capture_callback = lambda *_args, **_kwargs: None
- cli._last_turn_interrupted = False
- cli._ensure_runtime_credentials = lambda: True
- cli._resolve_turn_agent_config = lambda _message: {
- "signature": "route",
- "model": cli.model,
- "runtime": None,
- "request_overrides": None,
- }
- cli._init_agent = lambda **_kwargs: True
-
- blocked_result = SimpleNamespace(
- expanded=False,
- blocked=True,
- references=[],
- injected_tokens=0,
- warnings=["blocked for test"],
- )
- with patch("agent.context_references.preprocess_context_references", return_value=blocked_result), \
- patch("agent.model_metadata.get_model_context_length", return_value=372_000) as mock_context, \
- patch("cli._cprint"):
- result = cli.chat("inspect @file:example.py")
-
- assert result == "blocked for test"
- mock_context.assert_called_once_with(
- "gpt-5.6-terra",
- base_url="https://chatgpt.com/backend-api/codex",
- api_key="token",
- provider="openai-codex",
- config_context_length=None,
- )
diff --git a/tests/hermes_cli/test_cli_context_reference_passthrough.py b/tests/hermes_cli/test_cli_context_reference_passthrough.py
new file mode 100644
index 00000000000..7af6862d36d
--- /dev/null
+++ b/tests/hermes_cli/test_cli_context_reference_passthrough.py
@@ -0,0 +1,41 @@
+"""The classic CLI leaves ``@`` references to the gateway, which expands them once against the
+session's cwd; a client-side pass first expanded them twice (PLG-4)."""
+
+from types import SimpleNamespace
+
+import pytest
+
+
+class _Staged(Exception):
+ pass
+
+
+def test_chat_submits_at_references_unexpanded(tmp_path, monkeypatch):
+ from cli import HermesCLI
+
+ (tmp_path / "example.py").write_text("CLIENT-SIDE-CONTENT", encoding="utf-8")
+ monkeypatch.chdir(tmp_path)
+ cli = HermesCLI.__new__(HermesCLI)
+ cli.model = "gpt-5.6-terra"
+ cli.base_url = "https://chatgpt.com/backend-api/codex"
+ cli.api_key = "token"
+ cli.provider = "openai-codex"
+ cli.agent = SimpleNamespace(_config_context_length=None)
+ cli._active_agent_route_signature = "route"
+ cli._secret_capture_callback = lambda *_args, **_kwargs: None
+ cli._last_turn_interrupted = False
+ cli._ensure_runtime_credentials = lambda: True
+ cli._resolve_turn_agent_config = lambda _message: {
+ "signature": "route", "model": cli.model, "runtime": None, "request_overrides": None}
+ cli._init_agent = lambda **_kwargs: True
+ staged = []
+
+ def _stage(_agent, message):
+ staged.append(message)
+ raise _Staged
+
+ cli._chat_stage_user_message = _stage
+ with pytest.raises(_Staged):
+ cli.chat("inspect @file:example.py")
+
+ assert staged == ["inspect @file:example.py"]
diff --git a/ui-tui/src/__tests__/canonicalImages.test.ts b/ui-tui/src/__tests__/canonicalImages.test.ts
index cea63b16eb0..05969a9e1ae 100644
--- a/ui-tui/src/__tests__/canonicalImages.test.ts
+++ b/ui-tui/src/__tests__/canonicalImages.test.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto'
-import { mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -52,6 +52,25 @@ it('stages private immutable local bytes, uploads remote bytes, and never falls
} finally { resetUiState(); vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) }
})
+it('resolves a relative image path in the session folder, never the ui-tui install', async () => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'ink-relative-')))
+ const project = join(home, 'project')
+ mkdirSync(project)
+ writeFileSync(join(project, 'shot.png'), png)
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ vi.stubEnv('HERMES_CWD', '')
+ const gw = { request: vi.fn() } as any
+
+ try {
+ resetUiState(); patchUiState({ sid: 'owner', info: { cwd: project } as never })
+ expect(readFileSync((await stageImagePath('shot.png caption', gw, captureDestination())).path)).toEqual(png)
+ // No session folder yet: the folder `hermes --tui` was launched from.
+ resetUiState(); patchUiState({ sid: 'owner' }); vi.stubEnv('HERMES_CWD', project)
+ expect(await stageImagePath('./shot.png', gw, captureDestination())).toMatchObject({ mime: 'image/png', name: 'shot.png' })
+ } finally { resetUiState(); vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) }
+})
+
it('extracts clipboard on the client and uploads only captured bytes to a remote owner', async () => {
const home = mkdtempSync(join(tmpdir(), 'ink-clipboard-'))
vi.stubEnv('HERMES_HOME', home)
diff --git a/ui-tui/src/__tests__/useCompletion.test.ts b/ui-tui/src/__tests__/useCompletion.test.ts
index 67a9fcfea8c..6f27aa9a135 100644
--- a/ui-tui/src/__tests__/useCompletion.test.ts
+++ b/ui-tui/src/__tests__/useCompletion.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
+import { patchUiState, resetUiState } from '../app/uiStore.js'
import { completionRequestForInput } from '../hooks/useCompletion.js'
describe('completionRequestForInput', () => {
@@ -32,4 +33,21 @@ describe('completionRequestForInput', () => {
it('leaves plain text alone', () => {
expect(completionRequestForInput('hello there')).toBeNull()
})
+
+ // The shared gateway's own cwd is its daemon folder: the listing must name the session's.
+ it('lists paths in the session folder, else the launch folder', () => {
+ try {
+ vi.stubEnv('HERMES_CWD', '/launch/dir')
+ patchUiState({ info: { cwd: '/work/repo' } as never })
+ expect(completionRequestForInput('read @file:sr')).toMatchObject({
+ method: 'complete.path',
+ params: { word: '@file:sr', cwd: '/work/repo' }
+ })
+ resetUiState()
+ expect(completionRequestForInput('./sr')).toMatchObject({ params: { word: './sr', cwd: '/launch/dir' } })
+ } finally {
+ resetUiState()
+ vi.unstubAllEnvs()
+ }
+ })
})
diff --git a/ui-tui/src/app/uiStore.ts b/ui-tui/src/app/uiStore.ts
index b29c0ecea1c..5bd1d07af65 100644
--- a/ui-tui/src/app/uiStore.ts
+++ b/ui-tui/src/app/uiStore.ts
@@ -51,6 +51,10 @@ export const $uiSessionId = computed($uiState, state => state.sid)
export const getUiState = () => $uiState.get()
+// The folder a user-typed path is relative to: the session's, else the one `hermes --tui` was
+// launched from. Never this process's cwd (the ui-tui install) or the shared gateway's.
+export const sessionCwd = (): string | undefined => $uiState.get().info?.cwd || process.env.HERMES_CWD || undefined
+
export const patchUiState = (next: Partial<UiState> | ((state: UiState) => UiState)) =>
$uiState.set(typeof next === 'function' ? next($uiState.get()) : { ...$uiState.get(), ...next })
diff --git a/ui-tui/src/hooks/useCompletion.ts b/ui-tui/src/hooks/useCompletion.ts
index f32c2535aa5..5ff69fb0024 100644
--- a/ui-tui/src/hooks/useCompletion.ts
+++ b/ui-tui/src/hooks/useCompletion.ts
@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from 'react'
import type { CompletionItem } from '../app/interfaces.js'
import { rankSlashItems } from '../app/slash/fuzzyScore.js'
-import { getUiState } from '../app/uiStore.js'
+import { getUiState, sessionCwd } from '../app/uiStore.js'
import { inlineSlashTrigger } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type { CompletionResponse } from '../gatewayTypes.js'
@@ -34,7 +34,7 @@ const TAB_PATH_RE = /((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))
export function completionRequestForInput(
input: string
):
- | { method: 'complete.path'; params: { word: string }; replaceFrom: number }
+ | { method: 'complete.path'; params: { word: string; cwd?: string }; replaceFrom: number }
| { method: 'complete.slash'; params: { text: string }; replaceFrom: number; skillsOnly?: boolean }
| null {
const isSlashCommand = looksLikeSlashCommand(input)
@@ -72,9 +72,11 @@ export function completionRequestForInput(
return null
}
+ const cwd = sessionCwd()
+
return {
method: 'complete.path',
- params: { word: pathWord },
+ params: { word: pathWord, ...(cwd ? { cwd } : {}) },
replaceFrom: input.length - pathWord.length
}
}
diff --git a/ui-tui/src/lib/imageAttachments.ts b/ui-tui/src/lib/imageAttachments.ts
index baad940dd39..d2df66881c6 100644
--- a/ui-tui/src/lib/imageAttachments.ts
+++ b/ui-tui/src/lib/imageAttachments.ts
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import type { SubmissionDestination } from '../app/submissionDestination.js'
+import { sessionCwd } from '../app/uiStore.js'
import type { GatewayClient } from '../gatewayClient.js'
import { t } from '../i18n/runtime.js'
@@ -36,7 +37,7 @@ function imageFormat(bytes: Buffer): { mime: string; ext: string } {
}
// Match an existing whole path first, so unquoted filenames with spaces survive.
-async function resolveImagePath(raw: string): Promise<{ path: string; remainder: string }> {
+async function resolveImagePath(raw: string, base: string): Promise<{ path: string; remainder: string }> {
const value = raw.trim()
const quoted = /^(["'])(.*?)\1(?:\s+([\s\S]*))?$/.exec(value)
@@ -51,7 +52,7 @@ async function resolveImagePath(raw: string): Promise<{ path: string; remainder:
if (path.startsWith('file://')) { path = fileURLToPath(path) }
if (path.startsWith('~/')) { path = join(homedir(), path.slice(2)) }
- path = resolve(path)
+ path = resolve(base, path)
try {
const info = await stat(path)
@@ -96,16 +97,19 @@ export async function stageClipboardImage(
}
export async function stageImagePath(raw: string, gw: GatewayClient, destination: SubmissionDestination): Promise<StagedImage> {
- const source = await resolveImagePath(raw)
+ // Explicit URL attachments may target another machine, even a loopback SSH
+ // tunnel. Only discovery-owned local connections share our profile filesystem.
+ const remote = Boolean(process.env.HERMES_TUI_GATEWAY_URL?.trim())
+ // A remote session's folder names the owner's filesystem; the bytes are read here.
+ const base = (remote ? process.env.HERMES_CWD : sessionCwd()) || process.cwd()
+ const source = await resolveImagePath(raw, base)
const bytes = await readFile(source.path)
if (bytes.length > MAX_IMAGE_BYTES) { throw new Error(t('canonical.images.tooLarge')) }
const { mime, ext } = imageFormat(bytes)
const name = basename(source.path)
- // Explicit URL attachments may target another machine, even a loopback SSH
- // tunnel. Only discovery-owned local connections share our profile filesystem.
- if (process.env.HERMES_TUI_GATEWAY_URL?.trim()) {
+ if (remote) {
const result = await gw.request<{ path?: string }>('image.attach_bytes', {
session_id: destination.sid, filename: `${randomUUID()}${ext}`, content_base64: bytes.toString('base64')
})