fix(gateway): expand @ references on every local route, once, on the model's text

Removing the classic CLI's own expansion pass (PLG-4) left three local
routes where @ references or their refusal no longer reached anyone.
They now share one step, gateway/session_context_refs.py:

- CLI API-only text: a voice turn or a pending model-switch or
  skills-reload note sends cli_turn_v1.api_text, which
  _prepare_turn_message swaps in for the admitted text after the inbound
  step had expanded only that admitted text. The inbound step now expands
  the text the model reads: when api_text is committed, its references are
  expanded and rebound for this execution (rebind_api_text). The stored
  user row stays as typed, and the committed row is untouched, so a retry
  expands afresh rather than twice.
- Managed workers: --safe-mode / --ignore-user-config sessions (and the
  managed-workers opt-in) branch to execute_managed before the inbound
  step, so the worker ran the raw text. execute_managed now expands the
  admitted text against the session's policy cwd before it spawns,
  and hands it to the bootstrap frame. The context length comes from the
  frozen policy rather than the profile file a bypass session must not
  read. A bypass session loads no plugins, so its references are
  built-in kinds only (parse_context_references(plugins=False)).
- Refusals: over the 50% budget, the gateway sent the refusal through
  LocalSessionAdapter.send, which publishes nothing (local delivery is
  settlement), and dropped the turn. A refused local turn now answers
  with its refusal as the turn's reply, so message.complete and the
  CLI's receipt carry it; a finite prompt fails with it. A refused
  managed turn settles the same way without spawning a worker.
  Messaging platforms still get the adapter send.

The expansion body moves out of run_inbound.py into the new module;
_expand_inbound_context_references keeps its contract.

Refs NousResearch#134889
This commit is contained in:
unsupportedpastels
2026-10-14 23:56:24 +00:00
committed by Mark S.
parent 0ca88e6771
commit 895c9fc93a
7 changed files with 363 additions and 44 deletions

View File

@@ -149,7 +149,8 @@ def format_reference_value(value: str) -> str:
return value
def parse_context_references(message: str) -> list[ContextReference]:
def parse_context_references(message: str, *, plugins: bool = True) -> list[ContextReference]:
"""``plugins=False`` reads built-in kinds only (a safe-mode / config-bypass session loads no plugins)."""
refs: list[ContextReference] = []
if not message:
return refs
@@ -165,7 +166,7 @@ def parse_context_references(message: str) -> list[ContextReference]:
refs.append(ContextReference(match.group(0), kind, target, match.start(), match.end(), line_start, line_end))
# Second pass: plugin-registered prefixes the built-in pattern missed.
for match in _PLUGIN_REFERENCE_PATTERN.finditer(message) if _context_reference_providers else ():
for match in _PLUGIN_REFERENCE_PATTERN.finditer(message) if plugins and _context_reference_providers else ():
kind = match.group("kind")
if kind in BUILTIN_PREFIXES or kind not in _context_reference_providers:
continue
@@ -198,9 +199,9 @@ def preprocess_context_references(
async def preprocess_context_references_async(
message: str, *, cwd: str | Path, context_length: int, url_fetcher: UrlFetcher = None,
allowed_root: str | Path | None = None,
allowed_root: str | Path | None = None, plugins: bool = True,
) -> ContextReferenceResult:
refs = parse_context_references(message)
refs = parse_context_references(message, plugins=plugins)
if not refs:
return ContextReferenceResult(message=message, original_message=message)
cwd_path = Path(cwd).expanduser().resolve()

View File

@@ -1594,37 +1594,14 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
self, source: SessionSource, session_key: str, message_text: str
) -> Optional[str]:
"""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
)
if _ctx_result.blocked:
_adapter = self._delivery_adapter_for(source)
if _adapter:
await _adapter.send(
source.chat_id,
"\n".join(_ctx_result.warnings) or t("gateway.notify.context_injection_refused"),
)
return None
if _ctx_result.expanded:
message_text = _ctx_result.message
except Exception as exc:
logger.warning("@ context reference expansion failed: %s", exc)
logger.debug("@ context reference expansion failure detail", exc_info=True)
return message_text
from gateway.session_context_refs import inbound_references
expanded, refusal = await inbound_references(self, source, session_key, message_text)
if refusal is None:
return expanded
_adapter = self._delivery_adapter_for(source)
if _adapter:
await _adapter.send(source.chat_id, refusal)
return None
async def _prepare_inbound_message_text(
self, *, event: MessageEvent, source: SessionSource, history: list[dict[str, Any]],
@@ -1651,10 +1628,10 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
message_text = await self._enrich_inbound_voice(event, source, message_text, audio_paths)
message_text = self._prepend_inbound_media_file_notes(message_text, audio_file_paths, video_paths)
message_text = self._prepend_inbound_document_notes(event, message_text)
if "@" in message_text:
message_text = await self._expand_inbound_context_references(source, session_key, message_text)
if message_text is None:
return None
from gateway.session_context_refs import turn_references
message_text = await turn_references(self, event, source, session_key, message_text)
if message_text is None:
return None
# After expansion: the quoted reply is someone else's text and stays literal — an
# ``@file:`` inside it must never read a local file on the replier's behalf.
return self._prepend_inbound_reply_context(event, source, message_text)

View File

@@ -638,7 +638,8 @@ class GatewayTurnPrepareMixin:
"""Everything between session resolution and the agent run: session open, task-local env,
context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns
``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of
running (history unreadable); ``None`` drops the turn (inbound text rejected)."""
running (history unreadable, a local turn's refused ``@`` references); ``None`` drops the turn
(inbound text rejected)."""
from gateway.run import _load_gateway_config
from tools.approval_yolo import restore_gateway_yolo
_was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
@@ -711,7 +712,8 @@ class GatewayTurnPrepareMixin:
event=event, source=source, history=history, session_key=session_key,
)
if message_text is None:
return None, _session_env_tokens
# A refused local turn answers with its refusal (session_context_refs.turn_references).
return getattr(event, "_gateway_turn_refusal", None), _session_env_tokens
message_text, persist_user_message, persist_user_timestamp = (
self._hmwa_apply_message_timestamp(event, message_text)

View File

@@ -74,6 +74,15 @@ def cli_turn(message_id):
return bound[1]
def rebind_api_text(message_id, text):
"""This admission's ``api_text`` with its ``@`` references expanded, for the rest of this execution
(``session_context_refs.turn_references``). The committed row keeps what the CLI sent, so a retry
expands it afresh rather than twice."""
bound = _cli_turn.get()
if bound is not None and message_id is not None and str(message_id) == bound[0]:
_cli_turn.set((bound[0], {**bound[1], 'api_text': text}))
def one_turn_runtime(override, model, runtime_kwargs, config):
"""``(model, runtime_kwargs)`` of a committed ``model_override`` for this one turn, resolved by the
same ``switch_model`` pipeline ``/model`` uses against the session's current route. Nothing is

View File

@@ -0,0 +1,111 @@
"""``@`` references of one turn: expanded once, in the session's workspace, on the text the model reads.
The inbound prepare step, the classic CLI's API-only text (``cli_turn_v1.api_text``: voice prefix,
model-switch and skills notes) and managed workers (``--safe-mode`` / ``--ignore-user-config``,
which never pass the inbound step) all expand here. A local session's refusal is the turn's reply:
its adapter delivers through settlement, so a side ``send`` would never reach the viewer.
"""
import logging
import os
from contextlib import suppress
from functools import partial
from gateway.config import Platform
logger = logging.getLogger(__name__)
async def expand_references(text, *, cwd, context_length, plugins=True):
"""``(text, refusal)``: the expanded text, or the refusal when the injection was refused. A failed
expansion leaves the text as typed."""
from agent.i18n import t
try:
from agent.context_references import preprocess_context_references_async
expand = partial(preprocess_context_references_async, cwd=cwd, context_length=context_length, allowed_root=cwd)
result = await (expand(text) if plugins else expand(text, plugins=False))
except Exception as exc:
logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
return text, None
if result.blocked:
return text, "\n".join(result.warnings) or t("gateway.notify.context_injection_refused")
return (result.message if result.expanded else text), None
def _inbound_cwd(runner, source):
from gateway.session_policy import policy_for_source
try:
from tools.terminal_scope import terminal_env
except ImportError:
terminal_env = os.environ.get
# 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(runner, source)) is not None:
return policy.cwd
return terminal_env("TERMINAL_CWD", os.path.expanduser("~"))
async def inbound_references(runner, source, session_key, text):
"""``expand_references`` for an inbound turn: a local session's policy cwd, else the terminal cwd."""
try:
cwd = _inbound_cwd(runner, source)
context_length = await runner._inbound_model_context_length(source, session_key)
except Exception as exc:
logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
return text, None
return await expand_references(text, cwd=cwd, context_length=context_length)
async def turn_references(runner, event, source, session_key, text):
"""An inbound turn's text with the references of the text the model reads expanded; None when
refused. The classic CLI's committed ``api_text`` replaces ``text`` at the turn
(``TurnRunner._prepare_turn_message``), so ITS references are expanded and rebound for this
execution, and ``text`` stays the stored user row as typed. A refused local turn leaves its
refusal on ``event`` for the prepare step to answer with."""
from gateway.session_cli_turn import cli_turn, rebind_api_text
api_text = cli_turn(event.message_id).get('api_text')
target = text if api_text is None else api_text
if "@" not in target:
return text
if source.platform == Platform.LOCAL:
expanded, refusal = await inbound_references(runner, source, session_key, target)
if refusal is not None:
event._gateway_turn_refusal = refusal
return None
elif (expanded := await runner._expand_inbound_context_references(source, session_key, target)) is None:
return None
if api_text is None:
return expanded
rebind_api_text(event.message_id, expanded)
return text
async def managed_turn_text(authority, row, policy):
"""``(text, refusal)`` for a managed worker's admitted text, expanded against the session's
workspace. Built-in kinds only for a bypass session, which loads no plugins; the context length
is the frozen policy's, never the profile file a bypass session must not read. ``None`` text means
the admitted text as committed."""
text = (row.get('payload') or {}).get('text')
if not isinstance(text, str) or "@" not in text:
return None, None
try:
from agent.model_metadata import get_model_context_length_async
model_config = policy.config(authority).get('model') or {}
pinned = model_config.get('context_length') if isinstance(model_config, dict) else None
with suppress(TypeError, ValueError):
pinned = int(pinned) if pinned is not None else None
context_length = await get_model_context_length_async(
policy.current_model(authority) or '', base_url=policy.base_url or '', api_key='',
provider=policy.provider or '', config_context_length=pinned if isinstance(pinned, int) else None)
except Exception as exc:
logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
return text, None
return await expand_references(text, cwd=policy.cwd, context_length=context_length,
plugins=not policy.ignore_user_config)
def refused_turn_result(row, refusal):
"""A turn that never ran because its references were refused: the refusal is its answer, and a
finite (``chat -q`` / ``-z``) prompt fails with it, as ``execute_admission`` settles a notice."""
if row['payload'].get('finite') is True:
return {'final_response': '', 'messages': [], 'failed': True, 'completed': False, 'error': refusal}
return {'final_response': refusal, 'messages': []}

View File

@@ -53,7 +53,7 @@ def managed_policy(authority, ref):
return policy
def _bootstrap(authority, ref, row, policy, scope):
def _bootstrap(authority, ref, row, policy, scope, text=None):
from gateway.session_ingress import row_turn_author
from gateway.session_policy import launch_key
from gateway.session_policy_credentials import recover_config_secrets
@@ -77,7 +77,7 @@ def _bootstrap(authority, ref, row, policy, scope):
terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)
return {'version': 1, 'home': authority.profile_id, 'scope': scope,
'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),
'text': row['payload']['text'], 'route': live.route,
'text': row['payload']['text'] if text is None else text, 'route': live.route,
**({'attachments_v1': row['payload']['attachments_v1']} if 'attachments_v1' in row['payload'] else {}),
'user_id': live.source.user_id, 'chat_id': live.source.chat_id,
'turn_author': row_turn_author(policy, row),
@@ -451,6 +451,12 @@ def _interrupted_before_bootstrap(authority, row):
async def execute_managed(authority, ref, row, policy):
from gateway.run_turn_progress import publish_worker_tool_event
# This route never passes the inbound prepare step, so the worker would read ``@`` tokens as typed.
from gateway.session_context_refs import managed_turn_text, refused_turn_result
text, refusal = await managed_turn_text(authority, row, policy)
if refusal is not None:
authority.pending_results[row['admission_id']] = {'result': refused_turn_result(row, refusal), 'usage': {}}
return refusal
try:
env = await asyncio.to_thread(_worker_env, authority)
cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]
@@ -488,7 +494,7 @@ async def execute_managed(authority, ref, row, policy):
admission_id=row['admission_id'], process=process, principal_id=row['principal_id'], hello=hello))
worker.worker = (scope['pid'], scope['birth'])
# The child reads nothing else until the exact reservation has committed.
frame = await asyncio.to_thread(_bootstrap, authority, ref, row, policy, scope)
frame = await asyncio.to_thread(_bootstrap, authority, ref, row, policy, scope, text)
worker.secrets.extend(v for v in (frame['api_key'], scope['secret']) if isinstance(v, str) and v)
await asyncio.to_thread(worker.send, frame)
worker.writer.start()

View File

@@ -0,0 +1,213 @@
"""``@`` references reach the model on every local route now that the classic CLI leaves them to the
gateway: its API-only text (voice prefix, model-switch notes), managed workers (``--safe-mode`` /
``--ignore-user-config``), and a refused injection's explanation.
"""
import asyncio
import threading
from types import SimpleNamespace
import pytest
from gateway import session_policy
from gateway.config import GatewayConfig, Platform
from gateway.platforms.event import MessageEvent
from gateway.run import GatewayRunner
from gateway.session import SessionSource
@pytest.fixture
def project(tmp_path, monkeypatch):
project, daemon = tmp_path / 'project', tmp_path / 'daemon'
for folder, body in ((project, 'PROJECT-NOTES'), (daemon, 'DECOY-NOTES')):
folder.mkdir()
(folder / 'notes.txt').write_text(body, encoding='utf-8')
for name in ('a', 'b', 'c'): # each under the 50% budget of 1000 tokens, together over it
(project / f'{name}.txt').write_text(name * 1800, encoding='utf-8')
monkeypatch.setenv('TERMINAL_CWD', str(daemon))
monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: SimpleNamespace(
cwd=str(project)) if source.platform == Platform.LOCAL else None)
return project
def _runner(monkeypatch, context_length):
runner = object.__new__(GatewayRunner)
runner.config = GatewayConfig(platforms={})
runner.adapters = {}
async def _context_length(_source, _session_key):
return context_length
monkeypatch.setattr(runner, '_inbound_model_context_length', _context_length, raising=False)
return runner
def _event(text):
return MessageEvent(text=text, source=SessionSource(platform=Platform.LOCAL, chat_id='local-chat'),
message_id='adm-1')
async def _prepare(runner, event):
return await runner._prepare_inbound_message_text(
event=event, source=event.source, history=[], session_key='key')
@pytest.mark.asyncio
async def test_cli_api_text_reaches_the_model_expanded_and_the_stored_row_stays_as_typed(project, monkeypatch):
from gateway.session_cli_turn import cli_turn_scope
from gateway.run_turn_runner import TurnRunner
from gateway.turn_context import TurnContext
from tests.gateway.test_local_viewer_events_submit import _RecordingAgent, _gateway_runner
event = _event('read @file:notes.txt')
with cli_turn_scope('adm-1', {'api_text': '[voice] read @file:notes.txt'}):
prepared = await _prepare(_runner(monkeypatch, 128_000), event)
assert prepared == 'read @file:notes.txt'
monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: None) # the turn's own read
ctx = TurnContext(
source=event.source, message=prepared, history=[], session_id='sid', session_key='key',
user_config={}, inbound_message_id='adm-1', AIAgent=_RecordingAgent,
resolve_display_setting=lambda *_a: False, _run_still_current=lambda: True,
_hooks_ref=SimpleNamespace(loaded_hooks=False))
# The turn runs on an executor thread with a copy of this context, as run_sync does.
await asyncio.to_thread(TurnRunner(_gateway_runner(), ctx).run_sync)
[(message, kwargs)] = ctx.agent_holder[0].calls
assert message.startswith('[voice] read @file:notes.txt') and 'PROJECT-NOTES' in message
assert 'DECOY-NOTES' not in message
assert kwargs['persist_user_message'] == 'read @file:notes.txt'
@pytest.mark.asyncio
async def test_a_refused_local_turn_answers_with_its_refusal(project, monkeypatch):
event = _event('compare @file:a.txt @file:b.txt @file:c.txt')
assert await _prepare(_runner(monkeypatch, 1000), event) is None
assert 'refused' in event._gateway_turn_refusal
# The prepare step hands that refusal back as the turn's reply instead of dropping the turn.
runner = _runner(monkeypatch, 1000)
async def _none(*_args, **_kwargs):
return None
async def _open(*_args):
return False, False
runner._hmwa_open_session = _open
runner._set_session_env = lambda context: []
runner._hmwa_acquire_turn_lease = runner._mark_durable_active_turn = _none
runner._hmwa_first_contact_notes = _none
runner._voice_channel_sidecar_note = lambda *_args: None
runner.session_store = object()
runner._async_session_store = SimpleNamespace(_store=runner.session_store, load_transcript=lambda _sid: _history())
runner._hmwa_run_session_hygiene = lambda *args: _history()
monkeypatch.setattr('gateway.run_turn_prepare.build_session_context', lambda *_args: None)
entry = SimpleNamespace(yolo=None, session_id='sid', session_key='key')
reply, _tokens = await runner._hmwa_prepare_turn(_event(event.text), event.source, entry, 'key', 'key', 1)
assert isinstance(reply, str) and 'refused' in reply
async def _history():
return []
def _managed(tmp_path, monkeypatch, text):
from gateway import session_managed_worker as managed
from gateway.session_local import _bypass_policy
policy = _bypass_policy({'cwd': str(tmp_path), 'model': 'fixture', 'provider': 'custom',
'base_url': 'http://127.0.0.1:9/v1', 'safe_mode': True}, private_secrets={})
monkeypatch.setattr('gateway.session_policy.launch_key', lambda *args: None)
async def _context_length(model, **kwargs):
assert kwargs['api_key'] == '' # never a launch secret for a metadata probe
return 1000
monkeypatch.setattr('agent.model_metadata.get_model_context_length_async', _context_length)
sent, spawned = [], []
class Worker:
def __init__(self, process):
self.stop, self.secrets, self.worker = asyncio.Event(), [], None
self.writer = SimpleNamespace(start=lambda: None)
async def next_frame(self, *_args, **_kwargs):
if not sent:
return {'pid': 1}
from hermes_state_runtime import RuntimeStoreError
raise RuntimeStoreError('managed_worker_failed') # end the turn once the bootstrap went out
def send(self, frame):
sent.append(frame)
def close(self):
pass
async def _acquire(*_args, **_kwargs):
spawned.append(True)
return object()
scope = {'profile_id': str(tmp_path), 'session_id': 'sid', 'execution_id': 'x', 'generation': 1,
'pid': 1, 'birth': 0, 'secret': 's', 'epoch': 1}
async def _tracked(_authority, write):
return scope if not sent else None
monkeypatch.setattr(managed, '_worker_env', lambda authority: None)
monkeypatch.setattr(managed, 'ManagedWorker', Worker)
monkeypatch.setattr('gateway.session_worker_spawn.acquire_process', _acquire)
monkeypatch.setattr('gateway.session_managed_worker_log.worker_log_path', lambda profile: None)
monkeypatch.setattr('gateway.session_runtime_workers.tracked_write', _tracked)
live = SimpleNamespace(source=SimpleNamespace(user_id='u', chat_id='c', platform=None), route='managed-refs',
event_stream=SimpleNamespace(lock=threading.Lock(), publish=lambda *a, **k: None),
controls=SimpleNamespace(snapshot=lambda *a: None))
authority = SimpleNamespace(profile_id=str(tmp_path), sessions={'sid': live}, runner=None, pending_results={},
waiters={}, adopt_agent=lambda *a: None, _publish_pending=lambda ref: None)
row = {'admission_id': 'adm', 'generation': 1, 'principal_id': 'u', 'payload': {'text': text}}
authority.executing = {'sid': 1}
run = managed.execute_managed(authority, SimpleNamespace(session_id='sid'), row, policy)
return run, authority, sent, spawned
@pytest.mark.asyncio
async def test_a_managed_worker_runs_the_expanded_text(tmp_path, monkeypatch):
from gateway.session_managed_worker import ManagedExecutionUnknown
(tmp_path / 'notes.txt').write_text('PROJECT-NOTES', encoding='utf-8')
run, _authority, sent, _spawned = _managed(tmp_path, monkeypatch, 'read @file:notes.txt')
with pytest.raises(ManagedExecutionUnknown):
await run
[frame] = sent
assert frame['text'].startswith('read @file:notes.txt') and 'PROJECT-NOTES' in frame['text']
@pytest.mark.asyncio
async def test_a_managed_turn_with_refused_references_answers_without_spawning(tmp_path, monkeypatch):
for name in ('a', 'b', 'c'):
(tmp_path / f'{name}.txt').write_text(name * 1800, encoding='utf-8')
run, authority, sent, spawned = _managed(tmp_path, monkeypatch, '@file:a.txt @file:b.txt @file:c.txt')
reply = await run
assert 'refused' in reply and not spawned and not sent
assert authority.pending_results['adm']['result']['final_response'] == reply
@pytest.mark.asyncio
async def test_a_bypass_session_expands_built_in_references_only(tmp_path, monkeypatch):
from agent.context_references import (ContextCompletionItem, ContextReferenceProvider,
_context_reference_providers, register_context_reference_provider)
class Probe(ContextReferenceProvider):
prefix, description = 'probe', 'probe provider'
async def autocomplete(self, query, *, limit=10):
return [ContextCompletionItem(text=query)]
async def expand(self, target):
return 'PLUGIN-RAN'
from gateway.session_managed_worker import ManagedExecutionUnknown
(tmp_path / 'notes.txt').write_text('PROJECT-NOTES', encoding='utf-8')
register_context_reference_provider(Probe())
try:
run, _authority, sent, _spawned = _managed(tmp_path, monkeypatch, '@probe:x @file:notes.txt')
with pytest.raises(ManagedExecutionUnknown):
await run
finally:
_context_reference_providers.pop('probe', None)
assert 'PROJECT-NOTES' in sent[0]['text'] and 'PLUGIN-RAN' not in sent[0]['text']