Skip to content

The agent that grows with you

fix(worker): managed workers send the configured instruction and prefill examples

Teknium1ae678efdbe4
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index c27ae238ac5..a7aa4a9906d 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -303,7 +303,7 @@ def execute(frame, channel):
set_current_session_key(frame['route'])
os.environ['HERMES_GATEWAY_SESSION'] = '1'
from gateway.session_worker_construct import construct_kwargs
- construct = construct_kwargs(frame)
+ construct = {'ephemeral_system_prompt': policy.skills_prompt, **construct_kwargs(frame)}
controls = WorkerControls(channel, frame['route'])
register_gateway_notify(frame['route'], controls.approval)
agent = None
@@ -318,7 +318,7 @@ def execute(frame, channel):
gateway_session_key=frame['route'], user_id=frame['user_id'], chat_id=frame['chat_id'],
skip_context_files=policy.ignore_rules, load_soul_identity=not policy.ignore_rules,
skip_memory=policy.ignore_rules, skip_background_review=True, quiet_mode=True,
- ephemeral_system_prompt=policy.skills_prompt, pass_session_id=policy.pass_session_id,
+ pass_session_id=policy.pass_session_id,
checkpoints_enabled=policy.checkpoints_enabled, **construct,
stream_delta_callback=lambda text: channel.send('delta', text=text) if text else None,
clarify_callback=controls.clarify,
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 9ad2353cb69..79ae75853a2 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -65,7 +65,7 @@ def _bootstrap(authority, ref, row, policy, scope):
'finite': row['payload'].get('finite', False), 'unattended': row['payload'].get('unattended') is True,
'yolo': _session_yolo(authority, live.route, policy)})
from gateway.session_worker_construct import construct_inputs
- request['construct_v1'] = construct_inputs(authority, policy)
+ request['construct_v1'] = construct_inputs(authority, policy, live.source.chat_id)
hydrated = replace(policy, config_json=json.dumps(_worker_config(authority, policy)), request_json=json.dumps(request),
terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)
return {'version': 1, 'home': authority.profile_id, 'scope': scope,
diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.py
index 4107fced06c..399665b58e8 100644
--- a/gateway/session_worker_construct.py
+++ b/gateway/session_worker_construct.py
@@ -7,12 +7,16 @@ and they ride the hydrated request beside ``turn_v1``. The child validates the c
"""
import json
-KEYS = frozenset({'fallback_model'})
+KEYS = frozenset({'fallback_model', 'ephemeral_system_prompt', 'prefill_messages'})
-def construct_inputs(authority, policy):
+def construct_inputs(authority, policy, chat_id):
"""Owner side, per turn (off the owner loop: config reads)."""
- return {'fallback_model': _fallback_chain(authority, policy)}
+ from gateway.session_authorities import owner_scope
+ with owner_scope(authority):
+ return {'fallback_model': _fallback_chain(authority, policy),
+ 'ephemeral_system_prompt': _ephemeral_prompt(authority, policy, chat_id),
+ 'prefill_messages': _prefill(authority, policy)}
def _fallback_chain(authority, policy):
@@ -25,11 +29,28 @@ def _fallback_chain(authority, policy):
from hermes_cli.fallback_config import get_fallback_chain
return get_fallback_chain(policy.config(authority)) or None
refresh = getattr(authority.runner, '_refresh_fallback_model', None)
- if refresh is None:
+ return refresh() if refresh is not None else None
+
+
+def _ephemeral_prompt(authority, policy, chat_id):
+ """``TurnRunner``'s combined ephemeral prompt for a LOCAL turn (no platform context block):
+ the gateway prompt (``agent.system_prompt`` / ``display.personality`` / channel override) plus
+ the frozen ``-s`` skills blocks. API-time only, never part of the persisted system prefix.
+ A bypass session never reads the profile: only its frozen launch additions apply."""
+ configured = None
+ resolve = getattr(authority.runner, '_get_system_prompt_for_channel', None)
+ if not policy.ignore_user_config and resolve is not None:
+ from gateway.config import Platform
+ configured = resolve(Platform.LOCAL, chat_id or '')
+ return '\n\n'.join(p for p in (configured, policy.skills_prompt) if p) or None
+
+
+def _prefill(authority, policy):
+ """The runner's prefill examples, exactly as the in-process constructor passes them. A bypass
+ session never loads the profile's prefill file (and the safe policy drops prefill anyway)."""
+ if policy.ignore_user_config:
return None
- from gateway.session_authorities import owner_scope
- with owner_scope(authority):
- return refresh()
+ return getattr(authority.runner, '_prefill_messages', None) or None
def construct_kwargs(frame):
@@ -38,8 +59,12 @@ def construct_kwargs(frame):
inputs = json.loads(frame['policy'].get('request_json') or '{}').get('construct_v1')
if inputs is None:
return {}
- chain = inputs.get('fallback_model') if isinstance(inputs, dict) else None
if (not isinstance(inputs, dict) or set(inputs) != KEYS
- or not (chain is None or (isinstance(chain, list) and all(isinstance(e, dict) for e in chain)))):
+ or not _dict_list(inputs['fallback_model']) or not _dict_list(inputs['prefill_messages'])
+ or not isinstance(inputs['ephemeral_system_prompt'], (str, type(None)))):
raise ValueError('invalid_managed_worker_bootstrap')
- return {'fallback_model': chain}
+ return dict(inputs)
+
+
+def _dict_list(value):
+ return value is None or (isinstance(value, list) and all(isinstance(e, dict) for e in value))
diff --git a/tests/gateway/test_managed_worker_construct.py b/tests/gateway/test_managed_worker_construct.py
index 0b600e9b587..0a05208b5aa 100644
--- a/tests/gateway/test_managed_worker_construct.py
+++ b/tests/gateway/test_managed_worker_construct.py
@@ -1,5 +1,6 @@
"""Managed execution gets the same owner-resolved agent-construction inputs as the in-process
-turn (``construct_v1``): the configured fallback chain (andrexibiza N3).
+turn (``construct_v1``): the configured fallback chain (andrexibiza N3) and the configured
+instruction + prefill examples (andrexibiza N4).
One ordinary daemon, two sessions: in-process and ``gateway.managed_workers``. The loopback
primary refuses with 429 ``insufficient_quota``; a healthy loopback backup is configured in
@@ -119,7 +120,7 @@ def run_pair(tmp_path, extra_config, turn):
api_key='loopback-only', toolsets=[])
assert 'result' in created, created
sid = created['result']['session_id']
- results[name] = await turn(ws, sid, name, settle, SimpleNamespace(primary=primary, backup=backup))
+ results[name] = await turn(ws, sid, name, settle, SimpleNamespace(primary=primary, backup=backup, query=query))
results[name]['workers'] = query('SELECT COUNT(*) FROM worker_executions WHERE session_id=?', (sid,))[0][0]
try:
with daemon(root, home, env, barrier=False) as (_owner, desc):
@@ -147,27 +148,58 @@ def test_managed_turn_falls_back_like_the_in_process_turn(tmp_path):
assert (results['inproc']['workers'], results['managed']['workers']) == (0, 1), results
+def test_managed_turn_sends_configured_instruction_and_prefill(tmp_path):
+ """``agent.system_prompt`` and ``prefill_messages_file`` reach the managed model request in
+ the same places as in process, and stay out of the persisted system prompt."""
+ def extra(home):
+ (home / 'prefill.json').write_text(json.dumps([{'role': 'user', 'content': 'PREFILL_Q_MARK'},
+ {'role': 'assistant', 'content': 'PREFILL_A_MARK'}]))
+ return {'agent': {'system_prompt': 'SYS_PROMPT_MARK'}, 'prefill_messages_file': str(home / 'prefill.json')}
+
+ async def turn(ws, sid, name, settle, servers):
+ start = len(servers.primary.requests)
+ assert (await settle(ws, sid, name + '-plain', 'PLAIN_TURN'))['final_response'] == 'PRIMARY_OK'
+ [request] = servers.primary.requests[start:]
+ system = [m['content'] for m in request['messages'] if m['role'] == 'system']
+ prefill = [m['content'] for m in request['messages'] if 'PREFILL_' in str(m.get('content'))]
+ [(stored,)] = servers.query('SELECT p.prompt FROM sessions s JOIN system_prompts p '
+ 'ON p.hash = s.system_prompt_hash WHERE s.id=?', (sid,))
+ return {'system_mark': [('SYS_PROMPT_MARK' in s) for s in system], 'prefill': prefill,
+ 'stored': 'SYS_PROMPT_MARK' in stored}
+ results = run_pair(tmp_path, extra, turn)
+ for name in ('inproc', 'managed'):
+ found = {k: results[name][k] for k in ('system_mark', 'prefill', 'stored')}
+ assert found == {'system_mark': [True], 'prefill': ['PREFILL_Q_MARK', 'PREFILL_A_MARK'], 'stored': False}, (name, results)
+
+
def test_construct_inputs_follow_the_session_mode(tmp_path, monkeypatch):
- """Ordinary: the owner's per-turn profile refresh; config-only: the frozen snapshot, never the
- profile; safe mode: no chain. The child accepts only the closed shape."""
+ """Ordinary: the owner's per-turn profile refresh, configured prompt and prefill; config-only:
+ the frozen snapshot's chain and launch skills only, never the profile; safe mode: nothing.
+ The child accepts only the closed shape."""
from gateway.session_local import _bypass_policy
from gateway.session_policy import build_policy
from gateway.session_worker_construct import construct_inputs, construct_kwargs
chain = [{'provider': 'custom', 'model': 'b', 'base_url': 'http://127.0.0.1:9/v1'}]
- refreshed = []
- runner = SimpleNamespace(_refresh_fallback_model=lambda: refreshed.append(1) or chain, config=None)
+ profile_reads = []
+ runner = SimpleNamespace(config=None, _prefill_messages=[{'role': 'user', 'content': 'P'}],
+ _refresh_fallback_model=lambda: profile_reads.append('fallback') or chain,
+ _get_system_prompt_for_channel=lambda *a: profile_reads.append('prompt') or 'SYS')
authority = SimpleNamespace(runner=runner, profile_id=str(tmp_path))
launch = {'cwd': str(tmp_path), 'model': 'm', 'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1'}
- ordinary = build_policy(launch, {'fallback_providers': [{'provider': 'custom', 'model': 'frozen'}]})
+ ordinary = build_policy(launch, {})
config_only = _bypass_policy({**launch, 'ignore_user_config': True}, private_secrets={})
safe = _bypass_policy({**launch, 'safe_mode': True}, private_secrets={})
- assert construct_inputs(authority, ordinary)['fallback_model'] == chain and refreshed == [1]
- assert construct_inputs(authority, config_only)['fallback_model'] is None
- assert construct_inputs(authority, safe)['fallback_model'] is None and refreshed == [1]
- request = {'construct_v1': construct_inputs(authority, ordinary)}
- frame = {'policy': {'request_json': json.dumps(request)}}
+ assert construct_inputs(authority, ordinary, 'c') == {
+ 'fallback_model': chain, 'ephemeral_system_prompt': 'SYS', 'prefill_messages': runner._prefill_messages}
+ assert profile_reads == ['fallback', 'prompt']
+ empty = {'fallback_model': None, 'ephemeral_system_prompt': None, 'prefill_messages': None}
+ assert construct_inputs(authority, config_only, 'c') == empty
+ assert construct_inputs(authority, safe, 'c') == empty and profile_reads == ['fallback', 'prompt']
+ frame = {'policy': {'request_json': json.dumps({'construct_v1': construct_inputs(authority, ordinary, 'c')})}}
assert construct_kwargs(frame)['fallback_model'] == chain
assert construct_kwargs({'policy': {'request_json': '{}'}}) == {}
- for bad in ({'fallback_model': 'x'}, {'fallback_model': None, 'extra': 1}, []):
+ for bad in ({**empty, 'fallback_model': 'x'}, {**empty, 'extra': 1}, {**empty, 'ephemeral_system_prompt': 1},
+ {**empty, 'prefill_messages': ['x']}, []):
with pytest.raises(ValueError):
construct_kwargs({'policy': {'request_json': json.dumps({'construct_v1': bad})}})