Skip to content

The agent that grows with you

Merge origin/main into feat/unified-gateway-runtime (Sep 11 evening)

Teknium8e72cc70ca23
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index b7267d7a183,2d04ce8720b..bc3985a0937
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@@ -241,8 -222,8 +241,9 @@@ export function useComposerQueue(
onSubmit(entry.text, {
attachments: entry.attachments,
...(entry.displayText ? { displayText: entry.displayText } : {}),
+ ...(entry.displayKind ? { displayKind: entry.displayKind } : {}),
fromQueue: true,
+ submission_id: entry.id,
sessionId: drainRuntimeSessionId,
storedSessionId: drainQueueSessionKey
})
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index 9153d3008eb,d17c486257c..d6e9ab9a1c2
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@@ -5,7 -5,7 +5,7 @@@ import { afterEach, describe, expect, i
import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'
import { $clarifyRequests } from '@/store/clarify'
import type { ComposerAttachment } from '@/store/composer'
- import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'
-import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
++import { $queuedPromptsBySession, clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
import { $gateway } from '@/store/gateway'
import {
clearAllPrompts,
@@@ -56,11 -53,12 +56,14 @@@ function renderSubmitHook(
editor.dataset.slot = 'composer-rich-input'
editor.textContent = text
const editorRef = { current: editor }
+ const loadIntoComposer = vi.fn()
+ const stashAt = vi.fn()
const onCancel = vi.fn()
const onSteer = vi.fn(async () => true)
+ const onSteerHidden = vi.fn(async () => true)
const onSubmit = vi.fn(async () => true)
+ const loadIntoComposer = vi.fn()
+ const stashAt = vi.fn()
const queueCurrentDraft = vi.fn(() => true)
let updatePaneVisible: Dispatch<SetStateAction<boolean>> | undefined
@@@ -153,29 -153,66 +161,89 @@@ describe('useComposerSubmit external re
vi.restoreAllMocks()
})
+ it.each(['interrupt', 'steer'] as const)('restores a rejected %s draft without queue admission', async mode => {
+ const h = renderSubmitHook({ busy: true, busyInputMode: mode, text: 'keep guidance' })
+ h.onSteer.mockRejectedValue(new Error('correction unsupported'))
+ act(() => h.hook.result.current.submitDraft())
+ await waitFor(() => expect(h.loadIntoComposer).toHaveBeenCalledWith('keep guidance', []))
+ expect(h.stashAt).toHaveBeenCalledWith('stored-session', 'keep guidance', [])
+ expect(h.onSteer).toHaveBeenCalledWith('keep guidance', mode)
+ expect(h.onSubmit).not.toHaveBeenCalled()
+ expect(h.queueCurrentDraft).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session')).toEqual([])
+ })
+
+ it('routes a refused native steer through canonical queue admission', async () => {
+ $connection.set({ mode: 'local', wsUrl: 'ws://localhost/api/ws?native_dial=unminted' } as never)
+ $queuedPromptsBySession.set({})
+ const h = renderSubmitHook({ busy: true, text: 'keep guidance' })
+ h.onSteer.mockResolvedValue(false)
+
+ try {
+ act(() => h.hook.result.current.steerDraft())
+ await waitFor(() => expect(h.onSubmit).toHaveBeenCalledWith('keep guidance', expect.objectContaining({ fromQueue: true, sessionId: 'runtime-session', storedSessionId: 'stored-session' })))
+ expect(getQueuedPrompts('stored-session')).toEqual([])
+ } finally { $connection.set(null); $queuedPromptsBySession.set({}) }
+ it.each([true, false])('steers a busy external visible submit and queues only on rejection (%s)', async accepted => {
+ const { onSteer, onSubmit, clearDraft } = renderSubmitHook({ busy: true, text: 'unsent draft' })
+ onSteer.mockResolvedValue(accepted)
+
+ await act(async () => {
+ expect(requestComposerSubmit('Start without connections.', { target: 'main' })).toBe(true)
+ })
+
+ expect(onSteer).toHaveBeenCalledExactlyOnceWith('Start without connections.')
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(clearDraft).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session').map(({ text, attachments }) => ({ text, attachments }))).toEqual(
+ accepted ? [] : [{ text: 'Start without connections.', attachments: [] }]
+ )
+
+ await act(async () => {
+ requestComposerSubmit('/status', { target: 'main' })
+ })
+ expect(getQueuedPrompts('stored-session').at(-1)?.text).toBe('/status')
+ expect(onSteer).toHaveBeenCalledTimes(1)
+ expect(onSubmit).not.toHaveBeenCalled()
+ })
+
+ it.each([true, false])(
+ 'delivers a busy hidden request as a steer with no user turn and queues it hidden on refusal (%s)',
+ async accepted => {
+ const { onSteer, onSteerHidden, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: true })
+ onSteerHidden.mockResolvedValue(accepted)
+
+ await act(async () => {
+ requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
+ })
+
+ expect(onSteerHidden).toHaveBeenCalledExactlyOnceWith('[setup] links opened')
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session').map(({ text, displayKind }) => ({ text, displayKind }))).toEqual(
+ accepted ? [] : [{ text: '[setup] links opened', displayKind: 'hidden' }]
+ )
+ expect(loadIntoComposer).not.toHaveBeenCalled()
+ expect(stashAt).not.toHaveBeenCalled()
+ }
+ )
+
+ it('drops an idle hidden request the gateway rejects instead of restoring it into the draft', async () => {
+ const { onSteer, onSubmit, loadIntoComposer, stashAt } = renderSubmitHook({ busy: false })
+ onSubmit.mockResolvedValue(false)
+
+ await act(async () => {
+ requestComposerSubmit('[setup] links opened', { target: 'main', displayKind: 'hidden' })
+ })
+
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith('[setup] links opened', {
+ composerScope: 'stored-session',
+ displayKind: 'hidden'
+ })
+ expect(onSteer).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('stored-session')).toEqual([])
+ expect(loadIntoComposer).not.toHaveBeenCalled()
+ expect(stashAt).not.toHaveBeenCalled()
})
it('does not fan out a main ship across keep-alives or other projects', async () => {
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index 0fc592b883a,30d016bdb91..8bc60e6f692
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -36,8 -34,9 +36,9 @@@ interface UseComposerSubmitArgs
loadIntoComposer: (text: string, attachments: ComposerAttachment[]) => void
onCancel: ChatBarProps['onCancel']
onSteer: ChatBarProps['onSteer']
+ onSteerHidden: ChatBarProps['onSteerHidden']
onSubmit: ChatBarProps['onSubmit']
- queueCurrentDraft: () => boolean
+ queueCurrentDraft: () => boolean | Promise<boolean>
queueEdit: QueueEditState | null
queuedPrompts: QueuedPromptEntry[]
sessionId: string | null | undefined
@@@ -99,11 -98,17 +101,15 @@@ export function useComposerSubmit(
stashAt(submittedScope, text, submittedAttachments)
}
+ // A hidden submit is machine text (a setup note, never something the user
+ // typed), so a rejection drops it instead of loading it into the draft.
+ const rejected = displayKind ? () => {} : restore
+
void Promise.resolve(
- attachments
- ? onSubmit(text, { attachments, composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
- : onSubmit(text, { composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
+ onSubmit(text, { ...target, ...(attachments ? { attachments } : {}), composerScope: submittedScope, ...(displayKind ? { displayKind } : {}) })
)
- .then(accepted => void (accepted === false ? restore() : clearSessionDraft(submittedScope)))
- .catch(restore)
+ .then(accepted => void (accepted === false ? rejected() : clearSessionDraft(submittedScope)))
+ .catch(rejected)
}
// External "submit this prompt" requests (e.g. the review pane's agent-ship
diff --cc apps/desktop/src/app/chat/composer/index.tsx
index 05f7ca46e48,ac0097a7352..e54ab8915b5
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@@ -1219,13 -1202,8 +1222,14 @@@ export function ChatBar(
<div className={cn(composerFloatingStrip, 'px-[5px] pb-1.5 empty:hidden')}>
<ActionBadges sessionId={statusSessionId} />
<SuggestionPills sessionId={statusSessionId} />
+ <PreparedImageRecovery
+ occupied={hasText || attachments.length > 0 || busy || disabled}
+ onRestore={loadIntoComposer}
+ request={requestBusyConfig}
+ sessionKey={activeQueueSessionKey}
+ />
<OnboardingSkip />
+ <OnboardingStart />
</div>
{/* Session-scoped status stack (todos, subagents, background tasks,
queue). An in-flow dock child: the dock is bottom-anchored, so it
diff --cc apps/desktop/src/app/chat/composer/types.ts
index 49ead6ef2e2,56516b558b6..146f85b7cc4
--- a/apps/desktop/src/app/chat/composer/types.ts
+++ b/apps/desktop/src/app/chat/composer/types.ts
@@@ -54,7 -54,9 +54,9 @@@ export interface ChatBarProps
onPickFolders?: () => void
onPickImages?: () => void
onRemoveAttachment?: (id: string) => void
- onSteer?: (text: string) => Promise<boolean> | boolean
+ onSteer?: (text: string, mode?: 'interrupt' | 'steer') => Promise<boolean> | boolean
+ /** Delivers a hidden note to the model mid-turn with no user turn (gateway session.steer). */
+ onSteerHidden?: (text: string) => Promise<boolean> | boolean
onSubmit: (value: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onTranscribeAudio?: (audio: Blob) => Promise<string>
}
diff --cc apps/desktop/src/app/chat/index.tsx
index f9f3be192c2,49dd37ac0b9..5f596de07d3
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@@ -101,7 -101,8 +101,8 @@@ interface ChatViewProps extends Omit<Re
onPickFolders: () => void
onPickImages: () => void
onRemoveAttachment: (id: string) => void
- onSteer: (text: string) => Promise<boolean> | boolean
+ onSteer: (text: string, mode?: 'interrupt' | 'steer') => Promise<boolean> | boolean
+ onSteerHidden?: (text: string) => Promise<boolean> | boolean
onSubmit: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
onEdit: (message: AppendMessage) => Promise<void>
diff --cc apps/desktop/src/app/chat/session-tile-actions.ts
index b9edd04bd0b,5759cf484e5..801c6b20e05
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@@ -364,8 -363,39 +364,39 @@@ export function useSessionTileActions(
}
}, [bindRecoveredRuntime, copy.stopFailed, requestSessionGateway, update])
+ // A hidden note mid-turn rides session.steer into the model's next tool
+ // result: no optimistic bubble, no user turn. The main composer has the same
+ // primitive in use-prompt-actions.
+ const injectHiddenPrompt = useCallback(
+ async (rawText: string): Promise<boolean> => {
+ const text = rawText.trim()
+ const sessionId = runtimeIdRef.current
+
+ if (!text || !sessionId) {
+ return false
+ }
+
+ try {
+ const { result } = await withSessionNotFoundResume(
+ sessionId,
+ storedIdRef.current,
+ liveId => requestSessionGateway<{ status?: string }>('session.steer', { session_id: liveId, text }),
+ {
+ requestGateway: requestSessionGateway,
+ onRecovered: bindRecoveredRuntime
+ }
+ )
+
+ return result?.status === 'queued'
+ } catch {
+ return false
+ }
+ },
+ [bindRecoveredRuntime, requestSessionGateway]
+ )
+
const steerPrompt = useCallback(
- async (rawText: string): Promise<boolean> => {
+ async (rawText: string, mode: 'interrupt' | 'steer' = 'interrupt'): Promise<boolean> => {
const text = rawText.trim()
const sessionId = runtimeIdRef.current
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 97330ef224b,88283501fe8..5d8bd74ada1
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@@ -879,14 -813,51 +879,50 @@@ export function usePromptActions(
})
return result
- } catch {
- // Swallow — caller queues the text so nothing is lost.
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+ throw err
}
-
- return false
},
- [activeSessionIdRef, appendSessionTextMessage, requestGateway, selectedStoredSessionIdRef, updateSessionState]
+ [activeSessionIdRef, appendSessionTextMessage, copy.promptFailed, requestGateway, selectedStoredSessionIdRef, updateSessionState]
)
+ // A hidden note that lands mid-turn must reach the model without becoming a
+ // user turn. session.steer injects it into the model's next tool result and
+ // records nothing in the transcript; a redirect would paint it as the user's
+ // own bubble and store it as one.
+ const injectHiddenPrompt = useCallback(
+ async (rawText: string): Promise<boolean> => {
+ const text = sanitizeComposerInput(rawText).trim()
+ const sessionId = activeSessionIdRef.current
+
+ if (!text || !sessionId) {
+ return false
+ }
+
+ const send = async (id: string): Promise<boolean> => {
+ const response = await requestGateway<SessionRedirectResponse>('session.steer', { session_id: id, text })
+
+ return response?.status === 'queued'
+ }
+
+ try {
+ const { result } = await withSessionNotFoundResume(sessionId, selectedStoredSessionIdRef.current, send, {
+ requestGateway,
+ onRecovered: recoveredId => {
+ activeSessionIdRef.current = recoveredId
+ setActiveSessionId(recoveredId)
+ }
+ })
+
+ return result
+ } catch {
+ return false
+ }
+ },
+ [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]
+ )
+
// After a durable rewind the surviving bubbles' cached rowIds are stale (the
// gateway re-inserted the kept prefix as new SQLite rows). Rebind them to the
// authoritative post-rewrite ids so the NEXT rewind/edit/regenerate doesn't
diff --cc apps/desktop/src/store/composer-queue.ts
index 6f300e1d9dd,f51828f87d0..09fe55cf7f8
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@@ -141,7 -128,7 +144,7 @@@ export const getQueuedPrompts = (key: s
export const enqueueQueuedPrompt = (
key: string | null | undefined,
- payload: { id?: string; text: string; attachments: ComposerAttachment[]; displayText?: string }
- payload: { text: string; attachments: ComposerAttachment[]; displayText?: string; displayKind?: 'hidden' }
++ payload: { id?: string; text: string; attachments: ComposerAttachment[]; displayText?: string; displayKind?: 'hidden' }
): null | QueuedPromptEntry => {
const sid = sidOf(key)
@@@ -150,9 -137,10 +153,10 @@@
}
const entry: QueuedPromptEntry = {
- id: nextId(),
+ id: payload.id ?? nextId(),
text: payload.text,
...(payload.displayText ? { displayText: payload.displayText } : {}),
+ ...(payload.displayKind ? { displayKind: payload.displayKind } : {}),
attachments: cloneAttachments(payload.attachments),
queuedAt: Date.now()
}
diff --cc cron/jobs.py
index d97ccc0add2,d24acc0b19b..a0195218d3d
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@@ -27,7 -27,8 +27,8 @@@ except ImportError: # pragma: no cove
msvcrt = None
from datetime import datetime, timedelta
from pathlib import Path
-from hermes_constants import get_hermes_home
+from hermes_constants import display_hermes_home, get_hermes_home
+ from cron.env_settings import cron_env_setting
from typing import Optional, Dict, List, Any, Callable, Set, Tuple, Union, Collection
logger = logging.getLogger(__name__)
diff --cc cron/scheduler_delivery.py
index f9816fb2719,90c02b331c0..472bce257a9
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@@ -679,25 -694,90 +679,88 @@@ def _deliver_to_bot_chat(job: dict, con
receipt = read_delivery_result(home, key)
if receipt is None:
owner = find_canonical_live_owner(home)
- if owner is not None:
- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)
- if receipt is not None:
- if receipt["message"] != message:
- raise ValueError("delivery id already belongs to a different payload")
- status = receipt["status"]
- target = f"bot-chat:{profile_label}"
- receipts = job.setdefault("_bot_chat_delivery_receipts", {})
- receipts[target] = {"status": status, "delivery_id": key}
- logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
- job_id, profile_label, key, status)
- if status == "settled":
- return None
- detail = ("completion unverified; do not resend" if status in ("queued", "claimed")
- else receipt.get("error") or receipt.get("reason") or "not completed")
- return f"{target} {status} (receipt {key}): {detail}"
+ if owner is None:
+ return f"bot-chat delivery to profile '{profile_label}' unverified: no canonical Bot Chat"
+ receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)
+ if receipt["message"] != message:
+ raise ValueError("delivery id already belongs to a different payload")
+ status = receipt["status"]
+ target = f"bot-chat:{profile_label}"
+ receipts = job.setdefault("_bot_chat_delivery_receipts", {})
+ receipts[target] = {"status": status, "delivery_id": key}
+ logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
+ job_id, profile_label, key, status)
+ if status == "settled":
+ return None
+ detail = ("completion unverified; do not resend" if status in ("queued", "claimed")
+ else receipt.get("error") or receipt.get("reason") or "not completed")
+ return f"{target} {status} (receipt {key}): {detail}"
except Exception as exc:
- # Discovery/admission uncertainty must never open a second-writer fallback.
return f"bot-chat delivery to profile '{profile_label}' unverified: {exc}"
+ hermes_bin = shutil.which("hermes")
+ if hermes_bin:
+ argv = [hermes_bin]
+ else:
+ try:
+ import importlib.util as _ilu
+ found = _ilu.find_spec("hermes_cli") is not None
+ except Exception:
+ found = False
+ if not found:
+ return "bot-chat delivery failed: hermes CLI not resolvable"
+ argv = [sys.executable, "-m", "hermes_cli.main"]
+
+ def _fail(msg: str, **log_kwargs) -> str:
+ logger.warning("Job '%s': %s", job_id, msg, **log_kwargs)
+ return msg
+
+ from agent.delegation_context import delegated_child_subprocess_env
+ from tools.environments.local import strip_launch_profile_env
+ env = strip_launch_profile_env(delegated_child_subprocess_env(os.environ))
+ if profile:
+ argv += ["-p", profile]
+ # -p owns profile resolution; this scheduler's HERMES_HOME must not shadow it.
+ env.pop("HERMES_HOME", None)
+ else:
+ # Multiplex workers carry the profile in a ContextVar, not os.environ.
+ env["HERMES_HOME"] = str(source_home)
+
+ query_file = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", delete=False,
+ ) as fh:
+ fh.write(message)
+ query_file = fh.name
+
+ argv += [
+ "chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing",
+ "-Q", "--query-file", query_file,
+ ]
+ result = subprocess.run(
+ argv, capture_output=True, text=True, timeout=_get_bot_chat_delivery_timeout(), env=env,
+ creationflags=windows_hide_flags())
+ if result.returncode != 0:
+ tail = (result.stderr or result.stdout or "").strip()[-500:]
+ return _fail(
+ f"bot-chat delivery to profile '{profile_label}' failed (exit {result.returncode})"
+ + (f": {tail}" if tail else ""))
+ logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)
+ return None
+ except subprocess.TimeoutExpired:
+ return _fail(
+ f"bot-chat delivery to profile '{profile_label}' timed out "
+ f"after {_get_bot_chat_delivery_timeout()}s (the bot's turn may "
+ "still complete; raise cron.bot_chat_delivery_timeout_seconds if "
+ "this recurs)")
+ except Exception as e:
+ return _fail(f"bot-chat delivery failed: {str(e) or type(e).__name__}", exc_info=True)
+ finally:
+ if query_file:
+ with contextlib.suppress(OSError):
+ os.unlink(query_file)
+
def _normalize_deliver_value(deliver) -> str:
"""Normalize ``deliver`` to its canonical comma-separated string; ``"local"`` when falsy.
diff --cc gateway/platforms/api_server_openai_routes.py
index b2f50c7f4d1,6da8690fa55..f640b1c7067
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@@ -616,17 -600,25 +617,28 @@@ class OpenAICompatRoutesMixin
async def _run_idempotent(
self, request: "web.Request", body: Dict[str, Any], compute, *,
- log_label: str, fingerprint_keys: List[str]) -> tuple:
- """Run ``compute()`` once per Idempotency-Key + body fingerprint ->
- ``((result, usage), None)`` or ``(None, 500 response)``."""
- from gateway.platforms.api_server import (
- _error_response, _idem_cache, _make_request_fingerprint)
+ log_label: str, fingerprint_keys: List[str], route: str) -> tuple:
+ """Run ``compute()`` once per (principal scope, logical route, Idempotency-Key) + body fingerprint
+ -> ``((result, usage), None)`` or ``(None, 500 response)``.
+
+ ``_idem_cache`` is process-global: under ``gateway.multiplex_profiles`` every profile's
+ ``/p/<profile>/v1/...`` mirror shares it, so the key carries ``_run_idempotency_scope`` (the same
+ ``sha256(profile, expected API key)`` namespace the durable ``/v1/runs`` API uses) — a client key
+ colliding across profiles, or a rotated API_SERVER_KEY, never replays another principal's response.
+ ``route`` is the logical endpoint (``/v1/...`` and its ``/p/<profile>/v1/...`` alias are the same
+ route), folded into the key because the store keeps the fingerprint only as the slot's value.
+ """
+ from gateway.platforms.api_server import _error_response, _idem_cache, _make_request_fingerprint
+ from hermes_state_runtime import RuntimeStoreError
idempotency_key = request.headers.get("Idempotency-Key")
try:
- if idempotency_key:
++ # Durable /v1/runs admissions own idempotency under session authority; the in-memory
++ # cache only serves the pre-authority path.
+ if idempotency_key and getattr(self.gateway_runner, 'session_authority', None) is None:
+ principal_scope = self._run_idempotency_scope(request)
+ scoped_key = f"{principal_scope}\0{route}\0{idempotency_key}"
fp = _make_request_fingerprint(body, keys=fingerprint_keys)
- result, usage = await _idem_cache.get_or_set(idempotency_key, fp, compute)
+ result, usage = await _idem_cache.get_or_set(scoped_key, fp, compute)
else:
result, usage = await compute()
return (result, usage), None
diff --cc gateway/run.py
index ba0470abe45,4fe3668fc88..e7e96b0985e
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -1657,12 -1662,8 +1662,11 @@@ class HygieneTurnHoldExceeded(Exception
def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:
"""Return the authoritative profile set for one multiplex gateway config."""
+ reserved = getattr(config, "_runtime_profile_homes", None)
+ if reserved is not None:
+ return list(reserved)
from hermes_cli.profiles import profiles_to_serve
- return list(profiles_to_serve(
- multiplex=True, profile_allowlist=getattr(config, "multiplex_profile_allowlist", None)))
+ return list(profiles_to_serve(multiplex=True))
def _cron_tick_profile_homes(config: object) -> list[tuple[str, "Path"]]:
diff --cc gateway/run_startup.py
index 684f4c64012,48fe8259630..61e03e94527
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@@ -932,13 -941,9 +954,14 @@@ class GatewayStartupMixin
with _log_suppressed(logging.WARNING, "Process checkpoint recovery: %s"):
from tools.process_registry import process_registry
recovered = process_registry.recover_from_checkpoint()
+ recovered += self._recover_secondary_process_checkpoints(process_registry)
if recovered:
logger.info("Recovered %s background process(es) from previous run", recovered)
+ # The gateway owns delegation state: replay durable completions the previous
+ # process never delivered. Explicit here, never at tools import (clients).
+ with _log_suppressed(logging.WARNING, "Could not restore async delegation completions: %s"):
+ from tools.async_delegation import restore_undelivered_completions
+ restore_undelivered_completions(process_registry.completion_queue)
# Recover sessions active at last exit (exact turn markers + 120s recency fallback for
# marker-less older turns). SKIP after a clean exit — the previous process already drained.
_clean_marker = _hermes_home / ".clean_shutdown"