Skip to content

The agent that grows with you

Merge origin/main (#21: 191 commits to e675225af2b) into feat/unified-gateway-runtime

Tekniumb09c202d9e68
diff --cc apps/desktop/electron/main.ts
index 9a17d065e34,9f0d7303e75..057f2e5ae6f
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -665,12 -683,12 +665,12 @@@ import
bindGeometryPersistence,
computeWindowOptions,
debounce,
- firstLaunchSize,
sanitizeWindowState,
MIN_HEIGHT as WINDOW_MIN_HEIGHT,
- MIN_WIDTH as WINDOW_MIN_WIDTH
+ MIN_WIDTH as WINDOW_MIN_WIDTH,
+ windowSize
} from './window-state'
-import { hiddenWindowsChildOptions, windowsShellCommand } from './windows-child-options'
+import { hiddenWindowsChildOptions } from './windows-child-options'
import { buildPathExtCandidates, chooseUpdaterArgs, resolveVenvHermesCommand } from './windows-hermes-path'
import {
connectWindowsRemote,
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index d248594823a,ad1714f5853..9e6a174a6ef
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -6,8 -6,7 +6,8 @@@ import { translateNow, useI18n } from '
import { isSlashCommandText } from '@/lib/chat-runtime'
import { isSideTaskSlashCommand } from '@/lib/desktop-slash-commands'
import { triggerHaptic } from '@/lib/haptics'
+import type { BusyInputMode } from '@/store/busy-input-mode'
- import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
+ import { answerSetupCard, hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
import {
clearSessionDraft,
type ComposerAttachment,
@@@ -231,6 -221,104 +231,109 @@@ export function useComposerSubmit(
[activeQueueSessionKeyRef, inputDisabled, paneVisible, scope.target, sessionId, surfaceId]
)
+ // Returns false when the submit was refused and must not refocus the input.
+ const submitWhileBusy = (text: string, payloadPresent: boolean, blockingPrompt: boolean) => {
+ // Slash commands should execute immediately even while the agent is
+ // busy — they're client-side operations (/yolo, /skin, /new, /help,
+ // etc.) or self-contained gateway RPCs (/status, /compress). onSubmit
+ // routes them to executeSlashCommand, which has its own per-command
+ // busy guard for commands that genuinely need an idle session (skill
+ // /send directives). Queuing them would make every slash command wait
+ // for the current turn to finish, which is how the TUI never behaves.
+ if (isSlashCommandText(text)) {
+ if (attachments.length) {
+ // Slash commands cannot ride alongside attachments — warn the user
+ // instead of silently queuing the payload (which would then reach the
+ // idle path and be submitted as plain text with no command execution).
+ notify({
+ kind: 'warning',
+ title: copy.slashCommandIgnoredTitle,
+ message: copy.slashCommandIgnoredBody
+ })
+
+ return false
+ }
+
+ triggerHaptic('submit')
+ clearDraft()
+ dispatchSubmit(text)
+ } else if (!blockingPrompt && !attachments.length && text.trim()) {
- // Cursor-style stop-and-correct: interrupt the live turn and redirect
- // it with this text. redirect() preserves the shown reasoning/work; if
- // the turn already ended, steerDraft re-queues so nothing is lost.
- // Compaction is the gateway's call: it answers `queued` under the
- // compression lock. The client flag can outlive an aborted compaction.
- steerDraft()
++ // Busy Send follows the backend busy-input policy: interrupt redirects
++ // the live turn (Cursor-style stop-and-correct), steer injects at the
++ // next tool boundary, queue admits it as the next turn. If the turn
++ // already ended, steerDraft re-queues so nothing is lost. Compaction is
++ // the gateway's call: it answers `queued` under the compression lock.
++ // Unloaded policy (null) must not turn an intended queue into an interrupt.
++ if (busyInputMode === 'queue') {
++ queueCurrentDraft()
++ } else if (busyInputMode !== null) {
++ steerDraft(busyInputMode)
++ }
+ } else if (payloadPresent) {
+ // Attachments can't ride a redirect (no tool-result image carriage) —
+ // queue the whole payload for the next turn. Same for a turn parked on
+ // an approval/sudo/secret prompt: a steer can't reach the model while
+ // the tool batch is blocked, so the message runs as the next turn.
+ queueCurrentDraft()
+ } else {
+ // Stop button (the only way to reach here while busy with an empty
+ // composer — empty Enter is short-circuited in the keydown handler).
+ triggerHaptic('cancel')
+ void Promise.resolve(onCancel())
+ }
+
+ return true
+ }
+
+ // True when the draft was consumed as a parked setup card's answer.
+ const answerParkedCard = (text: string, payloadPresent: boolean) => {
+ // A clarify card parked on this session owns the turn: the agent is blocked
+ // inside its tool batch waiting on `clarify.respond`, so a follow-up routed
+ // through steer/queue sits undelivered until the clarify's own timeout
+ // (default 5 min) — the message looks sent and nothing happens. Typing a
+ // real message instead of picking an option IS the answer "none of these":
+ // skip the question so the tool returns, then route the words normally.
+ // A setup card is the exception: the setup turn reads typed words as its
+ // answer, so they go back as the card's answer and the turn carries on.
+ //
+ // A slash command or attachments cannot be a setup answer either. The skip
+ // is fire-and-forget, not awaited: it clears the card synchronously and
+ // both RPCs ride the same socket in call order, so the gateway resolves the
+ // clarify before it sees the follow-up. Awaiting first would leave the draft
+ // live for a tick — long enough for a second Enter to send it twice.
+ //
+ // /btw and /bg run beside the turn (snapshot / separate session) and answer
+ // neither parked card. With attachments the draft isn't routed as a slash
+ // command, so it falls back to the ordinary-message behavior.
+ const isSideQuestion = !attachments.length && isSideTaskSlashCommand(text)
+ const cardParked = payloadPresent && !queueEdit && !isSideQuestion && hasClarifyRequest(sessionId)
+
+ if (
+ cardParked &&
+ !attachments.length &&
+ !SLASH_COMMAND_RE.test(text.trim()) &&
+ answerSetupCard(sessionId, text.trim())
+ ) {
+ triggerHaptic('submit')
+ resetBrowseState(sessionId)
+ clearDraft()
+ focusInput()
+
+ return true
+ }
+
+ if (cardParked) {
+ void skipClarifyRequest(sessionId)
+ }
+
+ // Same for a pending connection card: ordinary typing continues the operation.
+ if (payloadPresent && !queueEdit && !isSideQuestion && hasConnectionRequest(sessionId)) {
+ void skipConnectionRequest(sessionId)
+ }
+
+ return false
+ }
+
const submitDraft = () => {
if (disabled) {
return
diff --cc apps/desktop/src/app/chat/composer/index.tsx
index 4a8771e8ad7,8d213fc9008..198806ead32
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@@ -12,12 -12,11 +12,12 @@@ import
} from 'react'
import { useTourMarker } from '@/app/chat/tour-marker'
+import type { GatewayRequester } from '@/app/contrib/types'
import { useHudComposerDrag } from '@/app/hud/composer-drag'
+import { useBusyInputMode } from '@/app/session/hooks/use-busy-input-mode'
import { composerFloatingStrip, composerInputBacking } from '@/components/chat/composer-dock'
- import { $chatOnboardingSolo, $chatOnboardingThreadIds } from '@/components/onboarding-chat/assembly'
+ import { useSetupChatView } from '@/components/onboarding-chat/assembly'
import { OnboardingSkip } from '@/components/onboarding-chat/skip'
-import { Button } from '@/components/ui/button'
import { Slot as ContribSlot } from '@/contrib/react/slot'
import { useI18n } from '@/i18n'
import { chatMessageText } from '@/lib/chat-messages'
@@@ -30,10 -29,10 +30,10 @@@ import { cn } from '@/lib/utils
import { sessionCompacting } from '@/store/compaction'
import { browseBackward, browseForward, deriveUserHistory, isBrowsingHistory } from '@/store/composer-input-history'
import { POPOUT_WIDTH_REM } from '@/store/composer-popout'
-import { parkQueuedPrompts, removeQueuedPrompt, unparkQueuedPrompts } from '@/store/composer-queue'
+import { parkQueuedPrompts } from '@/store/composer-queue'
import { $hudMode } from '@/store/hud'
import { $showsAdvancedChrome } from '@/store/interface-mode'
+ import { $chatOnboardingSolo } from '@/store/onboarding-intro'
import { sessionBlockingPrompt } from '@/store/prompts'
import { toggleReview } from '@/store/review'
import { $gatewayState } from '@/store/session'
@@@ -84,10 -82,10 +85,11 @@@ import { useSlashCompletions } from './
import { useStatusDrawer } from './hooks/use-status-drawer'
import { useSessionStatusPresence } from './hooks/use-status-presence'
import { shouldConvertPasteToAttachment } from './large-paste'
+ import { LocalSetupCard } from './local-setup-card'
import { ActionBadges } from './micro-actions'
import { chipTypedPathOnSpace, pathifyRefs } from './path-refs'
-import { QueuePanel } from './queue-panel'
+import { PreparedImageRecovery } from './prepared-image-recovery'
+import { renderComposerQueueSlot } from './queue-slot'
import { RestoredDraftNotice } from './restored-draft-notice'
import {
beginComposerComposition,
@@@ -1168,10 -1125,9 +1136,10 @@@ export function ChatBar(
foldVoice={foldVoice}
hasComposerPayload={hasComposerPayload}
hideModelPill={guidedChat}
- minimal={minimal}
+ minimal={minimal || chatOnboardingSolo}
onDictate={dictate}
onQueue={queueDraft}
+ onSteer={canSteer ? () => steerDraft('steer') : undefined}
onToggleAutoSpeak={handleToggleAutoSpeak}
state={state}
voiceStatus={voiceStatus}
@@@ -1515,9 -1496,33 +1483,10 @@@
onUndone={clearDraft}
readLiveText={syncDraftFromEditor}
/>
+ <LocalSetupCard busy={busy} guidedChat={guidedChat} />
<VoiceActivity state={voiceActivityState} />
<VoicePlaybackActivity />
- {queueEdit && editingQueuedPrompt && (
- <div className="flex items-center justify-between gap-2 rounded-lg border border-[color-mix(in_srgb,var(--dt-composer-ring)_32%,transparent)] bg-accent/18 px-2 py-1">
- <div className="min-w-0 text-[0.7rem] text-muted-foreground/88">
- {t.composer.editingQueuedInComposer}
- </div>
- <div className="flex shrink-0 items-center gap-1">
- <Button
- className="h-6 rounded-md px-2 text-[0.68rem]"
- onClick={() => exitQueuedEdit('cancel')}
- type="button"
- variant="ghost"
- >
- {t.common.cancel}
- </Button>
- <Button
- className="h-6 rounded-md px-2 text-[0.68rem]"
- onClick={() => exitQueuedEdit('save')}
- type="button"
- >
- {t.common.save}
- </Button>
- </div>
- </div>
- )}
+ {queueEdit && editingQueuedPrompt && <QueuedEditBanner onExit={exitQueuedEdit} />}
{attachments.length > 0 && <AttachmentList attachments={attachments} onRemove={onRemoveAttachment} />}
<div
className={cn(
diff --cc apps/desktop/src/app/contrib/wiring.tsx
index 205313fdb2e,35ba636524b..5eb3efae7cf
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@@ -174,6 -171,14 +170,13 @@@ import { useTitlebarToolContributions
import { type AmbientGatewayRequest, createSessionRpcDispatcher } from './session-rpc-dispatcher'
import { ChatRoutesSurface, SidebarSurface, StatusbarSurface, TerminalSurface } from './surfaces'
import type { WiringActions, WiringApi } from './types'
+ import {
+ useCreditsNoticeDemo,
+ useFreshSessionRequest,
+ useGatewayScopeRefresh,
+ useOpenKeybindsListener,
+ usePublishRestartPreviewServer
+ } from './wiring-effects'
-import { POOL_LIMITS_SETTINGS_ROUTE } from './wiring-routing'
// Overlay views the controller mounts over the shell — lazy, load on demand.
// The workspace-route full-page views (skills/messaging/artifacts) are the
@@@ -770,6 -705,17 +685,20 @@@ export function ContribWiring({ childre
updateSessionState
})
+ const runKickoffSlash = useCallback<KickoffSlashCommand>(
- (command, options) => executeSlashCommand(command, { ...options, typed: false }),
++ async (command, options) => {
++ // The branch's slash dispatcher reports admission (boolean); the kickoff only awaits completion.
++ await executeSlashCommand(command, { ...options, typed: false })
++ },
+ [executeSlashCommand]
+ )
+
+ const kickoffFirstChat = useOnboardingKickoff({
+ requestGateway: ambientRequestGateway,
+ resumeSession: adoptSessionRoute,
+ runSlashCommand: runKickoffSlash
+ })
+
// Runs outside the selected ChatBar so queues belonging to background
// sessions continue once those sessions are idle. The session dispatcher
// routes each send to its owner; a disconnected foreground is not a global gate.
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index 4b15f7a01cf,8a926751f36..a050687fe90
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@@ -196,54 -206,10 +209,63 @@@ export function useSlashCommand(deps: S
const compressInFlightRef = useRef(new Set<string>())
return useCallback(
- async (rawCommand: string, options?: SubmitTextOptions & { recordInput?: boolean; typed?: boolean }) => {
+ async (
+ rawCommand: string,
- options?: { hidden?: boolean; sessionId?: string; recordInput?: boolean; typed?: boolean }
++ options?: SubmitTextOptions & { hidden?: boolean; recordInput?: boolean; typed?: boolean }
+ ) => {
+ const initialRuntimeId = options?.sessionId ?? activeSessionIdRef.current
+ const initialSelectedId = selectedStoredSessionIdRef.current
+ const initialRoutedId = getRoutedStoredSessionId()
+
+ let submitted = true
+
+ const initialStoredId =
+ options?.storedSessionId ??
+ (options?.sessionId
+ ? ($sessionStates.get()[options.sessionId]?.storedSessionId ?? null)
+ : (initialRoutedId ?? initialSelectedId))
+
+ const destination =
+ options?.destination ?? captureSubmissionDestination(initialStoredId ?? initialRuntimeId, ambientRequestGateway)
+
+ const requestGateway = destination.requestGateway
- const retryOptions = { ...options, retryText: rawCommand }
++ // `hidden` (the first-run `/initiate-setup`) types the saved user row hidden: no bubble, live
++ // or after a reload. It rides retryOptions so a prepared-submission retry stays hidden too.
++ const retryOptions = {
++ ...options,
++ retryText: rawCommand,
++ ...(options?.hidden && { displayKind: 'hidden' as const })
++ }
+
+ try {
+ const prepared = await readPreparedSubmission(
+ preparedSubmissionKey(
+ resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),
+ destination,
+ rawCommand,
+ options?.attachments ?? $composerAttachments.get(),
+ retryOptions
+ )
+ )
+
+ if (prepared) {
+ return await submitPromptText(prepared.text, {
+ ...retryOptions,
+ sessionId: initialRuntimeId ?? undefined,
+ storedSessionId: initialStoredId,
+ displayText: prepared.displayText,
+ submission_id: prepared.id,
+ destination
+ })
+ }
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+
+ return false
+ }
+
+ const submissionId = options?.submission_id ?? crypto.randomUUID()
+
// Resolve the session this command targets through the SHARED ladder that
// submit.ts uses. A slash command runs backend commands against a runtime
// session, and per-session state (`/goal`, `/usage`, `/status`) is keyed by
@@@ -427,23 -385,16 +448,19 @@@
// rather than re-reading the globals — a session switch between
// dispatch and this branch would otherwise queue the kickoff on
// whichever chat is now in front (#63352).
- const queued = queueKickoffIfSessionBusy({
- displayText,
- foregroundBusy: busyRef.current,
- sessionId,
- storedSessionId,
- text: message
- })
+ const queued = options?.fromQueue
+ ? 'idle'
+ : queueKickoffIfSessionBusy({
+ displayText,
+ foregroundBusy: busyRef.current,
+ id: submissionId,
+ sessionId,
+ storedSessionId,
+ text: message
+ })
if (queued !== 'idle') {
- renderSlashOutput(
- queued === 'queued'
- ? 'session busy — message queued to send when the current turn finishes'
- : 'session busy — stop the current reply first (Stop button or Esc), then send this command'
- )
+ renderSlashOutput(BUSY_KICKOFF_TEXT[queued])
return
}
@@@ -456,8 -407,9 +473,9 @@@
// its kickoff as a user message into whatever conversation was on
// screen. Every other target the dispatcher serves (tile, background
// queue drain, a session created by this very call) had the same leak.
- // `hidden` (the first-run `/initiate-setup`) types the saved user row hidden: no bubble, live
- // or after a reload.
- await submitPromptText(message, {
++ // retryOptions carries main's `hidden` → displayKind 'hidden' for the first-run kickoff.
+ submitted = await submitPromptText(message, {
+ ...retryOptions,
sessionId,
storedSessionId,
displayText,
diff --cc apps/desktop/src/app/settings/config-settings.tsx
index 499a716e945,34e05aca3c4..658ceffba86
--- a/apps/desktop/src/app/settings/config-settings.tsx
+++ b/apps/desktop/src/app/settings/config-settings.tsx
@@@ -482,7 -484,9 +483,8 @@@ function ConfigSettingsInner(
label={c.alwaysExternalLinksTitle}
onChange={setAlwaysExternalLinks}
/>
- <PoolLimitsSetting />
<QuickEntrySettings />
+ <DeveloperSettings />
</>
)}
{/* Device-local attach/preview byte cap (main-process IPC guard). Chat is
diff --cc apps/desktop/src/i18n/ar.ts
index 64d8b3996a7,14022b536fa..cc424b3ae93
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -37,17 -37,9 +37,16 @@@ export const arOverrides =
artifactCard: arArtifacts.artifactCard,
artifactPreview: arArtifacts.artifactPreview,
sidebar: arChrome.sidebar,
- composer: arChat.composer,
+ composer: {
+ ...arChat.composer,
+ redirect: 'إعادة توجيه التشغيل الحالي',
+ queueLostNote: 'فُقد الدور أثناء إعادة التشغيل',
+ restoreImageDraft: 'استعادة مسودة الصورة',
+ queueLostDiscard: 'تجاهل',
+ queueLostDiscardTip: 'أعادت البوابة التشغيل أثناء هذا الدور ولا يمكن إكماله. تجاهله لتستمر الأدوار المنتظرة خلفه.'
+ },
statusStack: arChat.statusStack,
updates: arBoot.updates,
- guidedGreeting: arBoot.guidedGreeting,
install: arBoot.install,
onboarding: arBoot.onboarding,
modelPicker: arSettings.modelPicker,
diff --cc apps/desktop/src/i18n/de.ts
index fd4c5585643,4ecf64de3f7..f35afd607be
--- a/apps/desktop/src/i18n/de.ts
+++ b/apps/desktop/src/i18n/de.ts
@@@ -3846,6 -3860,6 +3854,7 @@@ export const deOverrides =
openDirective: 'Öffnen',
queueMessage: 'Nachricht einreihen',
steer: 'Laufenden Lauf steuern',
++ redirect: 'Laufenden Lauf umleiten',
stop: 'Stopp',
send: 'Senden',
speaking: 'Spricht',
@@@ -3994,6 -4013,6 +4008,11 @@@
queueDelete: 'Löschen',
queueResume: 'Fortsetzen',
queueResumeTip: 'Durch Stopp pausiert — fortsetzen, um die eingereihten Turns zu senden',
++ queueLostNote: 'Turn beim Neustart verloren',
++ restoreImageDraft: 'Bildentwurf wiederherstellen',
++ queueLostDiscard: 'Verwerfen',
++ queueLostDiscardTip:
++ 'Das Gateway wurde mitten im Turn neu gestartet und kann ihn nicht abschließen. Verwirf ihn, damit die eingereihten Turns dahinter laufen.',
queueStuckTitle: 'Eingereihte Nachricht nicht gesendet',
queueStuckBody:
'Ein eingereihter Turn konnte nicht gesendet werden. Er ist noch in der Warteschlange — versuchen Sie, ihn erneut zu senden.',
diff --cc apps/desktop/src/i18n/es.ts
index 4898ff2c50a,26a338ee134..34e2b80b407
--- a/apps/desktop/src/i18n/es.ts
+++ b/apps/desktop/src/i18n/es.ts
@@@ -3840,6 -3854,6 +3848,7 @@@ export const esOverrides =
openDirective: 'Abrir',
queueMessage: 'Poner mensaje en cola',
steer: 'Guiar la ejecución actual',
++ redirect: 'Redirigir la ejecución actual',
stop: 'Detener',
send: 'Enviar',
speaking: 'Hablando',
@@@ -3989,6 -4008,6 +4003,11 @@@
queueDelete: 'Borrar',
queueResume: 'Reanudar',
queueResumeTip: 'La cola se pausó al detener; reanuda el envío de los turnos en cola',
++ queueLostNote: 'Turno perdido durante el reinicio',
++ restoreImageDraft: 'Restaurar borrador con imagen',
++ queueLostDiscard: 'Descartar',
++ queueLostDiscardTip:
++ 'El gateway se reinició a mitad del turno y no puede terminarlo. Descártalo para que se ejecuten los turnos en cola que esperan detrás.',
queueStuckTitle: 'Mensaje en cola no enviado',
queueStuckBody: 'Un turno en cola no llegó a enviarse. Sigue en la cola; vuelve a intentarlo.',
queueDroppedTitle: 'Entrada en cola descartada',
diff --cc apps/desktop/src/i18n/fr.ts
index 6da5d7237b9,c3df6153dc8..31b3bf21e77
--- a/apps/desktop/src/i18n/fr.ts
+++ b/apps/desktop/src/i18n/fr.ts
@@@ -3854,6 -3868,6 +3862,7 @@@ export const frOverrides =
openDirective: 'Ouvrir',
queueMessage: "Mettre le message en file d'attente",
steer: "Diriger l'exécution en cours",
++ redirect: "Rediriger l'exécution en cours",
stop: 'Arrêter',
send: 'Envoyer',
speaking: 'Parle',
@@@ -4004,6 -4024,6 +4019,11 @@@
queueDelete: 'Supprimer',
queueResume: 'Reprendre',
queueResumeTip: "Mis en pause par Arrêter — reprendre l'envoi des tours en file d'attente",
++ queueLostNote: 'Tour perdu pendant le redémarrage',
++ restoreImageDraft: "Restaurer le brouillon d'image",
++ queueLostDiscard: 'Ignorer',
++ queueLostDiscardTip:
++ "La passerelle a redémarré en plein tour et ne peut pas le terminer. Ignorez-le pour que les tours en file d'attente derrière lui s'exécutent.",
queueStuckTitle: "Message en file d'attente non envoyé",
queueStuckBody:
"Un tour en file d'attente a continué à échouer lors de l'envoi. Il est toujours en file d'attente — essayez de l'envoyer à nouveau.",
diff --cc apps/desktop/src/i18n/ja.ts
index 849c1e04a59,13123c2f9de..f7bd4f0f5a1
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -1,9 -1,8 +1,9 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
- import { defineLocale } from './define-locale'
+ import { defineLocale, type TranslationOverrides } from './define-locale'
import { introJa } from './intro-ja'
import { jaAuxTasks } from './ja_aux_tasks'
+import { jaBoot } from './ja_boot'
import { jaLocalModels } from './ja_local_models'
import { jaModelMenu } from './ja_model_menu'
import { jaNotices } from './ja_notices'
@@@ -2378,6 -2464,6 +2406,7 @@@ export const jaOverrides =
startVoice: '音声会話を開始',
openDirective: '開く',
queueMessage: 'メッセージをキューに入れる',
++ redirect: '現在の実行をリダイレクト',
stop: '停止',
send: '送信',
speaking: '話しています',
diff --cc apps/desktop/src/i18n/ru.ts
index 6d156a2a424,2585081ecf6..6d070245867
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@@ -1,10 -1,10 +1,11 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
- import { defineLocale } from './define-locale'
+ import { defineLocale, type TranslationOverrides } from './define-locale'
import { ruAuxTasks } from './ru_aux_tasks'
+import { ruBoot } from './ru_boot'
import { ruModelMenu } from './ru_model_menu'
import { ruNotices } from './ru_notices'
+ import { ruOnboarding } from './ru_onboarding'
import { ruPluginSettings } from './ru_plugins'
import { ruProjects } from './ru_projects'
import { ruSharedMetrics } from './ru_shared_metrics'
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 6874354aa77,6f43aac1e94..a7cdf96460b
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -98,16 -92,9 +92,16 @@@ export const zhHantOverrides =
artifactCard: zhHantArtifacts.artifactCard,
artifactPreview: zhHantArtifacts.artifactPreview,
sidebar: zhHantChrome.sidebar,
- composer: zhHantChat.composer,
+ composer: {
+ ...zhHantChat.composer,
++ redirect: '重新導向目前的執行',
+ queueLostNote: '重新啟動期間該回合已遺失',
+ restoreImageDraft: '還原圖片草稿',
+ queueLostDiscard: '捨棄',
+ queueLostDiscardTip: '閘道在該回合進行中重新啟動,無法完成。捨棄後其後的排隊回合將繼續執行。'
+ },
statusStack: zhHantChat.statusStack,
updates: zhHantBoot.updates,
- guidedGreeting: zhHantBoot.guidedGreeting,
install: zhHantBoot.install,
onboarding: zhHantBoot.onboarding,
modelPicker: zhHantSettings.modelPicker,
diff --cc gateway/run_inbound.py
index 93c8876dd30,e56bec6b93f..ed66581e9e9
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@@ -958,9 -1021,89 +958,9 @@@ class GatewayInboundMixin(GatewayInboun
async with self._async_profile_scope_for_source(source):
return True, await plain_handler(event)
if canonical in self._HM_CANONICAL_COMMANDS:
- return await getattr(self, f"_hm_cmd_{canonical}")(event, source, _quick_key)
+ return await getattr(self, f"_hm_cmd_{canonical.replace('-', '_')}")(event, source, _quick_key)
return False, None
- async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
- """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env — the
- gateway process has every API key in os.environ; output is redacted too)."""
- try:
- from tools.environments.local import build_subprocess_env
- proc = await asyncio.create_subprocess_shell(
- exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- env=build_subprocess_env(),
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
- output = (stdout or stderr).decode().strip()
- if output:
- from agent.redact import redact_sensitive_text
- output = redact_sensitive_text(output)
- return output or t("gateway.quick_command.no_output")
- except asyncio.TimeoutError:
- return t("gateway.quick_command.timed_out")
- except Exception as e:
- return t("gateway.quick_command.error", error=e)
-
- async def _hm_dispatch_quick_and_plugin_commands(
- self, event: "MessageEvent", source: SessionSource, command: Optional[str]
- ) -> Tuple[bool, Optional[str], Optional[str]]:
- """Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →
- ``(handled, result, command)``; an alias quick command rewrites ``command``."""
- if self._draining:
- return True, t("gateway.busy.drain_rejected_new_work", action=self._status_action_gerund()), command
-
- # User-defined quick commands (bypass agent loop, no LLM call)
- qcmd = self._hm_quick_commands().get(command) if command else None
- if qcmd is not None:
- # Quick commands are slash capabilities too — and type:exec ones run a shell command in
- # the gateway process. They are never in the registry, so the early gate never fires for
- # them; apply the same admin/user policy to the raw typed name here.
- # The early gate above only fires for registry-known commands, so quick commands (never in the
- # registry) would otherwise reach this dispatch sink unchecked. (#44727)
- _denied = self._check_slash_access(source, command)
- if _denied is not None:
- return True, _denied, command
- qtype = qcmd.get("type")
- if qtype == "exec":
- exec_cmd = qcmd.get("command", "")
- if not exec_cmd:
- return True, t("gateway.quick_command.no_command", command=command), command
- return True, await self._hm_run_exec_quick_command(command, exec_cmd), command
- if qtype != "alias":
- return True, t("gateway.quick_command.unsupported_type", command=command), command
- new_command = self._hm_expand_alias_quick_command(event, qcmd)
- if new_command is None:
- return True, t("gateway.quick_command.no_target", command=command), command
- command = new_command # Fall through to normal command dispatch below
-
- # Plugin-registered slash commands. Underscores normalize to hyphens so Telegram's
- # underscored autocomplete form matches plugin commands registered with hyphens.
- if command:
- try:
- from hermes_cli.plugins import get_plugin_command_handler
- plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
- if plugin_handler:
- # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
- # sits before it, so a handler reading get_session_env() would see an empty or a
- # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
- # so session_key is derived from source. Sync handlers run on the gateway pool
- # (contextvars carried), never the loop thread: blocking I/O there starves the
- # liveness watchdog and the process exits 75 mid-handler (#105279).
- _plugin_context = build_session_context(source, self.config)
- _plugin_context.session_key = self._session_key_for_source(source)
- user_args = event.get_command_args().strip()
- with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
- else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return True, str(result) if result else None, command
- except Exception as e:
- logger.warning("Plugin command dispatch failed: %s", e)
- return False, None, command
-
def _hm_bundle_slash_rewrite(
self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str
) -> bool:
diff --cc gateway/run_turn_prepare.py
index 270e7f2e6bc,00000000000..822f9120092
mode 100644,000000..100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@@ -1,730 -1,0 +1,730 @@@
+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+import asyncio
+import dataclasses
+import inspect
+import json
+import os
+import queue
+import threading
+import time
+from agent.i18n import t
+from agent.session_activity import format_iteration_progress
+from contextlib import nullcontext, suppress
+from contextvars import copy_context
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.platforms.event import MessageEvent
+from gateway.session import (
+ SessionSource, _session_key_namespace, build_channel_continuity_note,
+ build_session_context,
+)
+from gateway.session_transcript import TranscriptReadError
+from gateway.turn_context import TurnContext
+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError
+from hermes_constants import get_hermes_home_override
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Tuple
+from utils import base_url_hostname
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner # noqa: F401
+ from gateway.run_turn_runner import TurnRunner # noqa: F401
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:
+ """``_resolve_session_agent_runtime`` for a session bound to a launch policy: the route's FROZEN
+ config and launch credential, walking its own fallback chain on an AuthError. Module-level so
+ tests that bind the method onto bare namespaces still reach it."""
+ from gateway.run import _runtime_agent_kwargs
+ from gateway.session_policy import launch_key
+ from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback
+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ frozen = policy.config(authority)
+ key = launch_key(authority, policy)
+ launch_url = json.loads(policy.request_json).get('base_url')
+ # Every rung reads the session's FROZEN config, never live config.yaml: a later
+ # ``model.base_url`` edit must not carry this route's frozen credential to the new host
+ # (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.
+ with frozen_runtime_config(frozen):
+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url,
+ target_model=policy.model, config=frozen)
+ if runtime is None:
+ # Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the
+ # resolver already reads from the frozen scope, so a URL-matched credential pool still
+ # serves (and rotates on) the frozen endpoint.
+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError
+ # from the frozen primary (expired token, Portal down, exhausted pool) tries the
+ # route's own ``fallback_providers`` before the turn is refused. Only a launch URL is
+ # explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by
+ # the provider chain, which keeps the credential pool an explicit URL would drop.
+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url, target_model=policy.model)
+ else:
+ fallback_entry = None
+ if fallback_entry is not None:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ runner._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ policy.provider or '', policy.model or '',
+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
+ fallback_entry.get('model') or 'default')
+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)
+ return policy.model, _runtime_agent_kwargs(runtime)
+
+
+def _recover_or_remember_model(runner, skey, model):
+ """Last step of ``_resolve_session_agent_runtime``: remember a good model, recover an empty one."""
+ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and
+ # the session goes silent — reuse the last model resolved for this session, else process-wide.
+ if not model:
+ _lr_state = runner._peek_session_state(skey) if skey else None
+ _lr_star = runner._peek_session_state("*")
+ _recovered = (
+ (_lr_state.conversation.last_resolved_model if _lr_state else "")
+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")
+ )
+ if _recovered:
+ logger.warning(
+ "Empty model resolved for session=%s — recovering "
+ "last-known-good model %s (config read likely returned "
+ "empty; see #35314)", skey or "", _recovered,
+ )
+ model = _recovered
+ else:
+ # Cache the good resolution for future recovery turns.
+ if skey:
+ runner._session_state(skey).conversation.last_resolved_model = model
+ runner._session_state("*").conversation.last_resolved_model = model
+ return model
+
+
+class GatewayTurnPrepareMixin:
+ def _resolve_session_agent_runtime(
+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ ) -> tuple[str, dict]:
+ """Resolve model/runtime for a session.
+
+ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env
+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""
+ from gateway.run import (
+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,
+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,
+ )
+ from gateway.session_policy import policy_for_source
+ # Every exit path starts clean: a stale notice must never attach to another session's next
+ # turn (#74349). Set again below only when THIS resolution fell back.
+ self._pre_agent_fallback_notice = None
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ return _resolve_policy_agent_runtime(self, policy)
+ skey = self._resolve_session_key_or_none(source, session_key)
+ model = _resolve_gateway_model(user_config)
+ if skey:
+ self._rehydrate_session_model_override(skey)
+ _override_state = self._peek_session_state(skey) if skey else None
+ override = _override_state.conversation.model_override if _override_state else None
+ if override:
+ override_model = override.get("model", model)
+ override_runtime = {
+ k: override.get(k) for k in (
+ "provider", "requested_provider", "api_key", "base_url", "api_mode",
+ "max_tokens", "credential_pool", "request_overrides", "capabilities",
+ )
+ }
+ override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})
+ if override_runtime.get("api_key"):
+ if override_runtime.get("credential_pool") is None:
+ override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))
+ logger.debug(
+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",
+ skey or "", model, override_model, override_runtime.get("provider"),
+ )
+ return override_model, override_runtime
+ # No api_key on the override (credentials failed to re-resolve at rehydrate): resolve them
+ # for the override's own provider below, never layer it over the default provider's runtime.
+ logger.debug(
+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
+ skey or "", model, override_model,
+ )
+ elif logger.isEnabledFor(logging.DEBUG):
+ # The override_keys scan walks every session; only pay for it when DEBUG is on.
+ logger.debug(
+ "No session model override: session=%s config_model=%s override_keys=%s",
+ skey or "", model,
+ [
+ _key for _key, _st in list(self._sessions_map().items())
+ if _st.conversation.model_override is not None
+ ][:5] or "[]",
+ )
+
+ runtime_kwargs, unavailable_override = None, None
+ if override and override.get("provider"):
+ try:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
+ override["provider"], target_model=override.get("model") or None)
+ except Exception as exc:
+ # Layering the override on the default runtime sent its model to the default provider's
+ # endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say
+ # so; the persisted override is kept, so the next turn retries it.
+ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc,
+ exc_info=True)
+ unavailable_override, override = override, None
+ if runtime_kwargs is None:
+ runtime_kwargs = _resolve_runtime_agent_kwargs()
+ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn
+ # runner surfaces it through the agent's one-shot fallback notice (#74349).
+ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)
+ runtime_model = runtime_kwargs.pop("model", None)
+ if runtime_model:
+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)
+ model = runtime_model
+ if unavailable_override and not self._pre_agent_fallback_notice:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ unavailable_override["provider"], unavailable_override.get("model"), runtime_kwargs.get("provider"), model)
+
+ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners
+ if cfg and source is not None:
+ ch = _get_channel_override(
+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",
+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
+ )
+ if ch:
+ if ch.model:
+ model = ch.model
+ if ch.provider:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)
+ ch_runtime_model = runtime_kwargs.pop("model", None)
+ # Adopt the provider's bundled model only when the override named none.
+ if ch_runtime_model and not ch.model:
+ model = ch_runtime_model
+
+ if override and skey:
+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)
+
+ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the
+ # provider's first catalog model.
+ if not model and runtime_kwargs.get("provider"):
+ with suppress(Exception):
+ from hermes_cli.models import get_default_model_for_provider
+ model = get_default_model_for_provider(runtime_kwargs["provider"])
+ if model:
+ logger.info(
+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],
+ )
+
+ return _recover_or_remember_model(self, skey, model), runtime_kwargs
+
+ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:
+ """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode
+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""
+ from gateway.run import _deep_merge_request_overrides
+ from agent.fast_mode import STATIC_TIERS
+ from hermes_cli.models import resolve_fast_mode_overrides
+ # Tests bind this method onto bare namespaces, so no class-level tables here.
+ runtime = {
+ k: runtime_kwargs.get(k) for k in (
+ "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",
+ "credential_pool", "max_tokens", "capabilities",
+ )
+ }
+ runtime["args"] = list(runtime["args"] or [])
+ runtime["capabilities"] = dict(runtime["capabilities"] or {})
+ base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})
+ route = {
+ "model": model,
+ "runtime": runtime,
+ "signature": (
+ model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],
+ runtime["api_mode"], runtime["command"], tuple(runtime["args"]),
+ ),
+ }
+ tier = getattr(self, "_service_tier", None)
+ if tier not in STATIC_TIERS:
+ # None / auto / cold: the bounded window is applied per request by agent.fast_mode.
+ route["request_overrides"] = base_request_overrides
+ return route
+ try:
+ overrides = resolve_fast_mode_overrides(
+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"], tier=tier,
+ )
+ except Exception:
+ overrides = None
+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.
+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})
+ return route
+
+ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can
+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it
+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""
+ if not session_id or agent is None or self._session_db is None:
+ return
+ model = getattr(agent, "model", None)
+ if not model:
+ return
+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}
+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))
+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+ try:
+ db = self._session_db._db
+ row = db.get_session(session_id)
+ if not row:
+ return
+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed
+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity
+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact
+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without
+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored
+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).
+ raw_config = row.get("model_config")
+ config = {}
+ with suppress(Exception):
+ config = json.loads(raw_config) if raw_config else {}
+ if not isinstance(config, dict):
+ config = {}
+ gateway_runtime = dict(config.get("gateway_runtime") or {})
+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):
+ return
+ config["gateway_runtime"] = runtime
+ db.update_session_meta(session_id, json.dumps(config), model=model)
+ except Exception:
+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)
+
+ async def _hmwa_resolve_session(self, event, source):
+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram
+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop
+ the event."""
+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a
+ # cross-topic Reply doesn't fragment the conversation.
+ event_metadata = getattr(event, "metadata", None) or {}
+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if not expected_session_key else None)
+ if recovered is not None:
+ logger.info(
+ "telegram topic recovery: chat=%s user=%s %r -> %s",
+ source.chat_id, source.user_id, source.thread_id, recovered,
+ )
+ source = dataclasses.replace(source, thread_id=recovered)
+ with suppress(Exception):
+ event.source = source
+
+ if expected_session_key:
+ derived_session_key = self._session_key_for_source(source)
+ if derived_session_key != expected_session_key:
+ logger.warning(
+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",
+ expected_session_key, derived_session_key,
+ )
+ return
+
+ strict_session = bool(event_metadata.get("gateway_session_strict"))
+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()
+ if strict_session:
+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)
+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:
+ logger.warning(
+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",
+ pinned_session_id or "missing", expected_session_key or "missing",
+ )
+ return
+ else:
+ # Internal wakes observe reset policy without counting as user activity, or periodic
+ # notifications keep the routing key alive across every daily/idle boundary.
+ session_entry = await self.async_session_store.get_or_create_session(
+ source, touch_activity=not bool(getattr(event, "internal", False)),
+ )
+ session_key = session_entry.session_key
+ if not strict_session and pinned_session_id:
+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)
+ if resolved_entry is None:
+ return
+ session_entry = resolved_entry
+ self._cache_session_source(session_key, source)
+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):
+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)
+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner
+ if not await resolve_heartbeat_owner(self, event, session_entry):
+ return
+ return source, session_entry, session_key
+
+ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):
+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record
+ a fresh one. Returns the (possibly switched) session entry."""
+ binding = None
+ try:
+ if self._session_db:
+ binding = await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),
+ profile_name=self._telegram_topic_profile_name(source),
+ )
+ except Exception:
+ logger.debug("Failed to read Telegram topic binding", exc_info=True)
+ if not binding:
+ try:
+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
+ except Exception:
+ logger.debug("Failed to record Telegram topic binding", exc_info=True)
+ return session_entry
+ stored_session_id = str(binding.get("session_id") or "")
+ bound_session_id = stored_session_id
+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next
+ # message resumes the compressed child instead of reloading the oversized parent.
+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and
+ # safe. See #20470, #29712, #33414.
+ if bound_session_id and self._session_db is not None:
+ try:
+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)
+ except Exception:
+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)
+ canonical_session_id = bound_session_id
+ if canonical_session_id and canonical_session_id != bound_session_id:
+ bound_session_id = canonical_session_id
+ if bound_session_id and bound_session_id != session_entry.session_id:
+ # Route through SessionStore so the key → id mapping persists and the previous lane
+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB
+ # awaits above are a window for /new or /resume to move the route; the CAS on the
+ # snapshot id lets that win instead of being clobbered by a stale binding.
+ switched = await self.async_session_store.switch_session(
+ session_key, bound_session_id, expected_session_id=session_entry.session_id,
+ )
+ if switched is not None:
+ session_entry = switched
+ if bound_session_id and bound_session_id != stored_session_id:
+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",
+ )
+ return session_entry
+
+ async def _hmwa_open_session(self, session_entry, session_key, source):
+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.
+ Returns ``(_was_auto_reset, _is_new_session)``."""
- # Consume was_auto_reset immediately so it cannot re-fire and wipe overrides set between turns.
+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —
+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).
+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
+ if _was_auto_reset:
+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached
+ # agent so context_compressor._previous_summary cannot leak into new summaries.
+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session
+ # dict in one funnel call so the fresh session does not inherit the previous conversation's
+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache
+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(session_key, reason="auto_reset")
+ self._evict_cached_agent(session_key)
+ session_entry.was_auto_reset = False
+
+ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)
+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset
+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.
+ if _is_fresh_reset:
+ # See #6508.
+ session_entry.is_fresh_reset = False
+ if _is_new_session:
+ await self.hooks.emit("session:start", {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "session_id": session_entry.session_id,
+ "session_key": session_key,
+ })
+ return _was_auto_reset, _is_new_session
+
+ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):
+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""
+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES
+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'
+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])
+ # Long-lived channels: point the agent at the prior same-channel session for session_search.
+ try:
+ # Returns None (appends nothing) for other platforms or when there's no prior activity to
+ # recall. Deterministic — no extra API/DB calls (#36220).
+ continuity_note = build_channel_continuity_note(session_entry, source)
+ except Exception:
+ continuity_note = None
+ if continuity_note:
+ context_note = context_note + "\n\n" + continuity_note
+ turn_sidecar_notes.append(context_note)
+
+ try:
+ should_notify = reset_reason == "suspended"
+ adapter = self._delivery_adapter_for(source) if should_notify else None
+ if adapter:
+ notice = t("gateway.session.auto_reset_notice")
+ with suppress(Exception):
+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)
+ if session_info:
+ notice = f"{notice}\n\n{session_info}"
+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))
+ except Exception as e:
+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)
+
+ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.
+ session_entry.auto_reset_reason = None
+
+ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):
+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""
+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
+ try:
+ from agent.skill_commands import _load_skill_payload, _build_skill_message
+ _combined_parts: list[str] = []
+ _loaded_names: list[str] = []
+ for _sname in _skill_names:
+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)
+ if not _loaded:
+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
+ continue
+ _loaded_skill, _skill_dir, _display_name = _loaded
+ _part = _build_skill_message(
+ _loaded_skill, _skill_dir,
+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
+ f"Follow its instructions for this session.]",
+ )
+ if _part:
+ _combined_parts.append(_part)
+ _loaded_names.append(_sname)
+ if _combined_parts:
+ _combined_parts.append(event.text) # user's original text after the payloads
+ event.text = "\n\n".join(_combined_parts)
+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)
+ except Exception as e:
+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
+
+ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):
+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on
+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns
+ a resend notice). Released in _handle_message's finally, granted per (routing key, run
+ generation) so a stale unwind can't release a newer turn's."""
+ from gateway.run import _float_env
+ _lease_registry = getattr(self, "_turn_leases", None)
+ if _lease_registry is None:
+ return
+ try:
+ _lease_token = await _lease_registry.acquire(
+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,
+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),
+ )
+ except TurnLeaseTimeoutError:
+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.
+ self._clear_session_env(_session_env_tokens)
+ raise
+ if _lease_token is not None:
+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token
+
- async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, internal=False):
++ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, message, internal=False):
+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when
+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral
+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""
+ from gateway.run import _gateway_config_home, _home_target_env_var, _load_gateway_config
+ if history or internal: # internal = plugin/system turn: no human made first contact
+ return
+ # LOCAL sessions (one-shot, chat -q, ACP, TUI attach) are the classic in-process CLI's
+ # surfaces: it never appended this note, and mark_seen would rewrite config.yaml under
+ # an ordinary launch that promises to leave the profile's files untouched.
+ human_platform = bool(source.platform) and source.platform not in (Platform.LOCAL, Platform.WEBHOOK)
+ if human_platform and source.chat_type == "dm" and not await self.async_session_store.has_any_sessions():
- # Same branch logic as the TUI (profile-build offer once when "ask", else plain intro);
++ # Same branch logic as the TUI (offer once when "ask", else plain intro);
+ # first_contact_turn_note already falls back to the plain intro on error.
- from agent.onboarding import first_contact_turn_note
++ from agent.onboarding import first_contact_turn_note, setup_command
+ note = first_contact_turn_note(
+ _load_gateway_config(), _gateway_config_home() / "config.yaml",
- session_history_empty=True, install_has_prior_sessions=False,
- )
++ session_history_empty=True, install_has_prior_sessions=False, message=message,
++ command=setup_command(source.platform.value))
+ if note:
+ turn_sidecar_notes.append(note)
+
+ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).
+ if not human_platform:
+ return
+ platform_name = source.platform.value
+ env_key = _home_target_env_var(platform_name)
+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.
+ home_env = ""
+ if env_key:
+ # A secondary with no home channel must not borrow the default profile's from
+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
+ home_env = (get_secret(env_key) or "").strip()
+ except UnscopedSecretError:
+ home_env = (os.getenv(env_key) or "").strip()
+ except Exception:
+ logger.debug("Home-channel secret %s unreadable; treating it as unset", env_key, exc_info=True)
+ home_env = ""
+ # Also honor in-memory / yaml home_channel on this platform.
+ with suppress(Exception):
+ if not home_env and self.config.get_home_channel(source.platform):
+ home_env = "set"
+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.
+ if not home_env:
+ with suppress(Exception):
+ from gateway.config import load_gateway_config as _lgc
+ prof = (getattr(source, "profile", None) or "").strip()
+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):
+ home_env = "set"
+ if not home_env:
+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.
+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"
+ await self._deliver_platform_notice(
+ source, t("gateway.notify.no_home_channel", platform=platform_name.title(), sethome_cmd=sethome_cmd),
+ )
+
+ def _hmwa_apply_message_timestamp(self, event, message_text):
+ """Capture the platform event time as message metadata and keep the persisted transcript
+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a
+ model instruction, not authored text) — regardless of the toggle; only the in-context
+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""
+ from gateway.run import _load_gateway_config, _message_timestamps_enabled
+ from gateway.run_inbound import strip_discord_triggering_note
+ persist_user_message = None
+ persist_user_timestamp = None
+ try:
+ from hermes_time import get_timezone as _get_evt_tz
+ from gateway.message_timestamps import (
+ coerce_message_timestamp as _coerce_msg_ts,
+ render_user_content_with_timestamp as _render_msg_ts,
+ strip_leading_message_timestamps as _strip_msg_ts,
+ )
+ _evt_tz = _get_evt_tz()
+ if message_text and isinstance(message_text, str):
+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)
+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)
+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)
+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts
+ if _message_timestamps_enabled(_load_gateway_config()):
+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)
+ else:
+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.
+ message_text = _clean_message_text
+ except Exception as _ts_err:
+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ return message_text, persist_user_message, persist_user_timestamp
+
+ @dataclasses.dataclass
+ class _PreparedTurn:
+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""
+
+ history: Any
+ context_prompt: str
+ message_text: Any
+ persist_user_message: Any
+ persist_user_timestamp: Any
+ persist_user_display_kind: Optional[str]
+ persistence_session_id: Optional[str] = None
+ persistence_owner: Optional[str] = None
+ title_user_message: Optional[str] = None
+
+ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):
+ """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)."""
+ from gateway.run import _load_gateway_config
+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
++ self._restore_session_yolo(session_key, session_entry)
+ context = build_session_context(source, self.config, session_entry)
+ # Session context variables for tools (task-local, concurrency-safe)
+ _session_env_tokens = self._set_session_env(context)
+ # Self-injected turns (MessageEvent(internal=True)) persist with a DB-only display_kind so
+ # UIs render timeline notices, not user bubbles; role/content untouched.
+ from gateway.response_filters import display_kind_for_event
+ persist_user_display_kind = display_kind_for_event(event)
+ _redact_pii = False # privacy.redact_pii, re-read per message
+ with suppress(Exception):
+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))
+
+ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so
+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
+ # A LOCAL session (CLI one-shot, ACP, cron run-now, TUI attach) is the operator's own machine:
+ # the messaging block ("Source: Local", connected platforms, cron delivery targets) was never
+ # part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.
+ # Rendering it here would make every surface hop of one durable session a system-prompt
+ # (and prompt-cache) break.
+ if source.platform != Platform.LOCAL and event.internal and session_key:
+ await self._rehydrate_prompt_pins(session_key, session_entry.session_id)
+ context_prompt = "" if source.platform == Platform.LOCAL else \
+ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=event.internal)
+
+ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
+ # (appending to the ephemeral system prompt forced a full agent rebuild).
+ turn_sidecar_notes: List[str] = []
+ if _was_auto_reset:
+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)
+
+ # Keep human text separate from skills, sender metadata, and other model context.
+ # With no text (e.g. voice-only), retain the existing enriched-message title fallback.
+ title_user_message = event.text or None
+
+ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.
+ _auto = getattr(event, "auto_skill", None)
+ if _is_new_session and _auto:
+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)
+
+ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)
+
+ # A turn becomes durable recovery work only after it owns the per-session lease; marking
+ # earlier would falsely recover a message that never began processing.
+ await self._mark_durable_active_turn(event, session_entry.session_key)
+
+ # An unreadable store is not an empty conversation: stop before the agent invents continuity
+ # from []. Restore task-local context here (before the broad cleanup finally).
+ try:
+ history = await self.async_session_store.load_transcript(session_entry.session_id)
+ history = await self._hmwa_run_session_hygiene(
+ event, source, session_entry, session_key, history, _quick_key, run_generation,
+ )
+ except TranscriptReadError:
+ self._clear_session_env(_session_env_tokens)
+ return t("gateway.errors.history_unavailable"), _session_env_tokens
+
- await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, internal=event.internal)
++ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, event.text, internal=event.internal)
+
+ # Voice channel state rides the user message ONLY when changed (in the system prompt it
+ # forced a rebuild + prompt-cache re-key per message).
+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
+ if _vc_note:
+ turn_sidecar_notes.append(_vc_note)
+
+ # Auto-analyze user images so the model gets a description plus the local path.
+ message_text = await self._prepare_profile_scoped_inbound_message_text(
+ event=event, source=source, history=history, session_key=session_key,
+ )
+ if message_text is None:
+ return None, _session_env_tokens
+
+ message_text, persist_user_message, persist_user_timestamp = (
+ self._hmwa_apply_message_timestamp(event, message_text)
+ )
+
+ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn
+ # cannot leak them into the next turn.
+ if turn_sidecar_notes and session_key:
+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
+
+ # Bind this run generation to the adapter so deferred post-delivery callbacks are released
+ # by the run that registered them.
+ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)
+ # Delivery IDs are only unique in their transport namespace. Keyless turns
+ # need their own identity, even when another process writes to this session.
+ import uuid
+ namespace = [source.platform.value, source.profile, source.scope_id,
+ source.chat_id, source.thread_id, str(event.message_id)]
+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))
+ if event.message_id else str(uuid.uuid4()))
+ return self._PreparedTurn(
+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,
+ persist_user_display_kind, session_entry.session_id, owner,
+ title_user_message=title_user_message,
+ ), _session_env_tokens
diff --cc gateway/session_busy_controls.py
index 69544f4e45f,00000000000..e39fc938216
mode 100644,000000..100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@@ -1,119 -1,0 +1,127 @@@
+"""Session-scoped busy preferences and controls of the existing execution only."""
+from functools import partial
+from pathlib import Path
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+def handlers(connection):
+ return {
+ 'config.get': partial(busy_config, connection),
+ 'config.set': partial(busy_config, connection, write=True),
+ 'session.steer': partial(correct, connection, verb='steer'),
+ 'session.redirect': partial(correct, connection, verb='redirect'),
+ }
+
+
+def authorize(connection, ref, params, capability):
+ connection.authority.authorize(connection.actor, ref, capability)
+ if 'profile' in params:
+ from hermes_cli.profiles import profile_matches_home
+ profile = params['profile']
+ if not isinstance(profile, str):
+ raise RuntimeStoreError('invalid_params')
+ if profile and not profile_matches_home(profile, Path(connection.authority.profile_id)):
+ raise RuntimeStoreError('profile_mismatch')
+
+
+async def busy_config(connection, ref, params, *, write=False):
+ allowed = {'session_id', 'profile', 'key'} | ({'value'} if write else set())
+ if params.get('key') == 'verbose' and not set(params) - allowed and ref.session_id:
+ return verbose_config(connection, ref, params, write)
+ if params.get('key') == 'yolo' and not set(params) - allowed and ref.session_id:
- return yolo_config(connection, ref, params, write)
++ return await yolo_config(connection, ref, params, write)
+ if (set(params) - allowed or not ref.session_id or params.get('key') != 'busy'
+ or (write and params.get('value') not in ('interrupt', 'steer', 'queue'))):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ authority = connection.authority
+ live = authority.sessions[ref.session_id]
+ if write:
+ # UI negotiation is not a settings write and must not rebuild frozen
+ # launch policy, toolsets, history, or the retained AIAgent.
+ live.busy_input_mode = params['value']
+ value = getattr(live, 'busy_input_mode', None)
+ if value is None:
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, live.source)
+ value = (policy.config().get('display', {}).get('busy_input_mode', 'interrupt') if policy else
+ authority.runner._effective_busy_input_mode(live.source))
+ if value not in ('interrupt', 'steer', 'queue'):
+ value = 'interrupt'
+ return {'key': 'busy', 'value': value, 'scope': 'session'}
+
+
+_VERBOSE_CYCLE = ('off', 'new', 'all', 'verbose')
+
+
+def verbose_config(connection, ref, params, write):
+ """Session-scoped /verbose: the tool-progress mode the next tool events of
+ this session render with (read by TurnRunner), like busy never a settings write."""
+ value = params.get('value')
+ if write and value not in (*_VERBOSE_CYCLE, 'cycle'):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ live = connection.authority.sessions[ref.session_id]
+ current = getattr(live, 'tool_progress_mode', None) or 'all'
+ if write:
+ live.tool_progress_mode = current = (
+ _VERBOSE_CYCLE[(_VERBOSE_CYCLE.index(current) + 1) % 4] if value == 'cycle' else value)
+ return {'key': 'verbose', 'value': current, 'scope': 'session'}
+
+
+_YOLO_WORDS = {'1': True, 'on': True, 'true': True, '0': False, 'off': False, 'false': False}
+
+
- def yolo_config(connection, ref, params, write):
++async def yolo_config(connection, ref, params, write):
+ """Session-scoped /yolo (TUI slash + Shift+Tab, Desktop toggle): this session's approval bypass,
+ never HERMES_YOLO_MODE or approvals.mode. A ``--yolo`` launch is seeded first, so revoking it
- here is not re-enabled by the next turn's launch seeding."""
++ here is not re-enabled by the next turn's launch seeding. The route's persisted copy
++ (``SessionEntry.yolo``, re-armed every turn by ``_restore_session_yolo``) is written before the
++ live flag, like the messaging ``/yolo``, so an OFF here is not revived by the next turn."""
+ value = params.get('value')
+ if write and value is not None and str(value).strip().lower() not in _YOLO_WORDS:
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ from gateway.session_policy import policy_for_source
+ from tools.approval import apply_launch_yolo, disable_session_yolo, enable_session_yolo, is_session_yolo_enabled
+ live = connection.authority.sessions[ref.session_id]
- policy = policy_for_source(connection.authority.runner, live.source)
++ runner = connection.authority.runner
++ policy = policy_for_source(runner, live.source)
+ if policy is not None and policy.yolo:
+ apply_launch_yolo(live.route)
- enabled = is_session_yolo_enabled(live.route)
++ store = runner.async_session_store if getattr(runner, 'session_store', None) is not None else None
++ entry = await store.lookup_by_session_key(live.route) if store is not None else None
++ # After a restart only the persisted copy is set until the next turn re-arms it: still ON.
++ enabled = is_session_yolo_enabled(live.route) or getattr(entry, 'yolo', False) is True
+ if write:
+ enabled = not enabled if value is None else _YOLO_WORDS[str(value).strip().lower()]
++ if store is not None:
++ await store.set_session_yolo(live.route, enabled)
+ (enable_session_yolo if enabled else disable_session_yolo)(live.route)
+ return {'key': 'yolo', 'value': '1' if enabled else '0', 'scope': 'session'}
+
+
+async def correct(connection, ref, params, *, verb):
+ if (set(params) - {'session_id', 'profile', 'text', 'execution_generation'}
+ or not isinstance(params.get('text'), str) or not params['text'].strip()
+ or type(params.get('execution_generation')) is not int):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control')
+ authority = connection.authority
+ generation = params['execution_generation']
+ live = authority.sessions[ref.session_id]
+ with live.event_stream.lock:
+ authority.check_approval_generation(ref.session_id, generation)
+ # Managed workers have a separate control channel, not a cached owner
+ # agent. Refuse explicitly instead of acknowledging undeliverable text.
+ if ref.session_id in getattr(authority, '_managed_workers', {}):
+ raise RuntimeStoreError('unsupported_control')
+ agent = authority.agent(ref)
+ method = getattr(agent, verb, None)
+ if not callable(method):
+ raise RuntimeStoreError('execution_not_ready')
+ accepted = method(params['text'])
+ return {'status': ({'steer': 'queued', 'redirect': 'redirected'}[verb] if accepted else 'rejected'),
+ 'text': params['text'], 'execution_generation': generation,
+ 'authority_epoch': authority.epoch}
diff --cc tests/gateway/test_yolo_command.py
index bfc9be91e23,3409d226d31..04cf1a57290
--- a/tests/gateway/test_yolo_command.py
+++ b/tests/gateway/test_yolo_command.py
@@@ -60,34 -60,32 +60,90 @@@ async def test_yolo_command_toggles_onl
assert os.environ.get("HERMES_YOLO_MODE") is None
+def test_launch_yolo_revocation_survives_the_next_turn(monkeypatch):
+ """`hermes chat --yolo` seeds the bypass once; a later `/yolo` off is not re-enabled per turn."""
+ from types import SimpleNamespace
+ import gateway.session_policy as session_policy
+ from gateway.run_turn_runner import TurnRunner
+ from gateway.turn_context import TurnContext
+
+ runner = _make_runner()
+ source = SessionSource(platform=Platform.LOCAL, chat_id="launch-yolo", user_id="u", chat_type="dm")
+ key = "agent:main:local:dm:launch-yolo"
+ monkeypatch.setattr(session_policy, "policy_for_source",
+ lambda _runner, _source: SimpleNamespace(yolo=True, platform="cli", max_turns=5))
+
+ def _stop(**_kw):
+ raise RuntimeError("stop after the yolo seam")
+ runner._resolve_session_agent_runtime = _stop
+ runner._pre_agent_fallback_notice = None
+ runner._get_system_prompt_for_channel = lambda *a, **k: ""
+
+ def turn():
+ TurnRunner(runner, TurnContext(source=source, session_key=key))._run_sync_scoped()
+
+ try:
+ turn()
+ assert is_session_yolo_enabled(key) is True
+ disable_session_yolo(key)
+ turn()
+ assert is_session_yolo_enabled(key) is False
+ finally:
+ from tools.approval import clear_session
+ clear_session(key)
++
++
+ @pytest.mark.asyncio
+ async def test_yolo_survives_gateway_restart_and_dies_at_session_boundary(tmp_path):
+ """/yolo is persisted on the routing entry: a fresh process re-arms it on the next turn, and a
+ conversation boundary (/new, /resume) clears both copies so a restart cannot revive it."""
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+
+ def _runner():
+ runner = _make_runner()
+ runner.session_store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
+ runner.session_store._db = None # JSON routing index: the restart reads it back from disk
+ return runner
+
+ event = _make_event("chat-a")
+ first = _runner()
+ key = first._session_key_for_source(event.source)
+ await first._handle_yolo_command(event)
+ assert is_session_yolo_enabled(key) is True
+
+ disable_session_yolo(key) # a new process starts with an empty in-memory approval set
+ second = _runner()
+ second._restore_session_yolo(key, second.session_store.get_or_create_session(event.source))
+ assert is_session_yolo_enabled(key) is True
+
+ second._clear_session_boundary_security_state(key)
+ assert is_session_yolo_enabled(key) is False
+ third = _runner()
+ third._restore_session_yolo(key, third.session_store.get_or_create_session(event.source))
+ assert is_session_yolo_enabled(key) is False
++
++
++async def test_owner_yolo_off_is_not_revived_by_the_persisted_restore(tmp_path):
++ """The owner's `config.set key=yolo` (TUI/Desktop/`hermes chat` /yolo) writes the route's persisted
++ copy too: switching off a persisted /yolo must not be re-armed by the next turn's restore."""
++ from types import SimpleNamespace
++ from gateway.config import GatewayConfig
++ from gateway.session import SessionStore
++ from gateway.session_busy_controls import busy_config
++
++ runner = _make_runner()
++ runner.session_store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
++ runner.session_store._db = None
++ event = _make_event("chat-a")
++ key = runner._session_key_for_source(event.source)
++ await runner._handle_yolo_command(event)
++ authority = SimpleNamespace(authorize=lambda *_a: None, profile_id=str(tmp_path), runner=runner,
++ sessions={"sid": SimpleNamespace(route=key, source=event.source)})
++ connection, ref = SimpleNamespace(actor="a", authority=authority), SimpleNamespace(session_id="sid")
++
++ off = await busy_config(connection, ref, {"session_id": "sid", "key": "yolo", "value": "0"}, write=True)
++ assert off["value"] == "0" and is_session_yolo_enabled(key) is False
++ runner._restore_session_yolo(key, runner.session_store.get_or_create_session(event.source))
++ assert is_session_yolo_enabled(key) is False
diff --cc tui_gateway/agent_factory.py
index 2551e8712fb,00000000000..d6295a68035
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,687 -1,0 +1,691 @@@
+"""TUI agent_factory seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+from .method_ctx import bind_module
+
+def _env_model_seed() -> str:
+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""
+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()
+
+
+def _resolve_model() -> str:
+ if env := _env_model_seed():
+ return env
+ m = _load_cfg().get("model", "")
+ if isinstance(m, dict):
+ return str(m.get("default", "") or "").strip()
+ if isinstance(m, str) and m:
+ return m.strip()
+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.
+ with contextlib.suppress(Exception):
+ from hermes_cli.models import get_preferred_silent_default_model
+ return get_preferred_silent_default_model()
+ return "z-ai/glm-5.2"
+
+
+def _resolve_session_platform() -> str:
+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then
+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""
+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))
+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"
+
+
+def _resolve_session_source(explicit: str | None) -> str:
+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never
+ rewritten; only empty/None falls back to the env-resolved platform."""
+ return explicit or _resolve_session_platform()
+
+
+def _resolve_agent_platform(source: str | None) -> str:
+ return _resolve_session_source(source)
+
+
+def _config_model_target() -> tuple[str, str]:
+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into
+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so
+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""
+ cfg_model = _load_cfg().get("model")
+ if isinstance(cfg_model, dict):
+ provider = str(cfg_model.get("provider") or "").strip()
+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider
+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""
+
+
+def _resolve_startup_runtime() -> tuple[str, str | None]:
+ model = _resolve_model()
+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():
+ return model, explicit_provider
+ if not (explicit_model := _env_model_seed()):
+ return model, None
+ with contextlib.suppress(Exception):
+ from hermes_cli.model_switch import resolve_startup_model_route
+ from hermes_cli.models import detect_static_provider_for_model
+ full_cfg = _load_cfg()
+ cfg = full_cfg.get("model") or {}
+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")
+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")
+ # Same owner as HermesCLI/oneshot: ``custom:<name>:<model>`` selects that provider (#73943).
+ if route := resolve_startup_model_route(
+ explicit_model, current_provider=current_provider,
+ user_providers=full_cfg.get("providers"), custom_providers=full_cfg.get("custom_providers")):
+ return route.model, route.provider
+ if detected := detect_static_provider_for_model(explicit_model, current_provider):
+ provider, detected_model = detected
+ return detected_model, provider
+ return model, None
+
+
+def _is_routable_provider(provider: str) -> bool:
+ with contextlib.suppress(Exception):
+ from hermes_cli.runtime_provider import is_routable_provider
+ return is_routable_provider(provider)
+ return False
+
+
+def _overrides_have_routable_provider(overrides: dict) -> bool:
+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown
+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""
+ provider = str(overrides.get("provider_override") or "").strip()
+ if not provider:
+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()
+ return bool(provider) and _is_routable_provider(provider)
+
+
+def _parse_model_config(raw, *, quiet: bool = False) -> dict:
+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ if not quiet:
+ raise
+ logger.debug("failed to parse stored session model_config", exc_info=True)
+ return {}
+
+
+def _row_follows_profile(row: dict | None) -> bool:
+ """Whether a stored row is a canonical Bot Chat whose runtime follows the member profile's config.
+ Identity is the persisted ``follow_profile_config`` marker; the bare title compare stays ONLY here as
+ the legacy fallback for rows written before the marker existed."""
+ if not row:
+ return False
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ return bool(model_config.get("follow_profile_config") or str(row.get("title") or "").strip() == "Bot Chat")
+
+
+def _stored_session_runtime_overrides(row: dict | None) -> dict:
+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):
+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode
+ sessions normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots
+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit
+ composer pick while the profile model it diverged from remains unchanged."""
+ if not row:
+ return {}
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ _row_title = str(row.get("title") or "").strip()
+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ composer_profile = model_config.get("composer_override_profile")
+ composer_profile_matches = isinstance(composer_profile, dict) and (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) == _config_model_target()
+ if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):
+ return {}
+ overrides: dict = {}
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # Canonical route reader shared with CLI --resume: nested ``gateway_runtime`` (the route the messaging
+ # gateway last ran) before the TUI's top-level keys, then a routable ``billing_provider`` (#125942).
+ from hermes_state import SessionDB
+ route = SessionDB.session_gateway_runtime(row)
+ provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode"))
+ service_tier = str(model_config.get("service_tier") or "").strip()
+ reasoning_config = model_config.get("reasoning_config")
+ from hermes_cli.runtime_provider import is_foreign_provider_endpoint
+ if is_foreign_provider_endpoint(provider, base_url):
+ # The endpoint and its wire belong to the provider this chat left; resolve the stored one's own.
+ base_url = api_mode = ""
+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):
+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.
+ if provider and not _is_routable_provider(provider):
+ healed = None
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)
+ except Exception:
+ logger.debug("custom provider identity recovery failed", exc_info=True)
+ if healed:
+ logger.info("healed stale session provider %r to %r", provider, healed)
+ provider = healed
+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it
+ else:
+ provider = ""
+ if model:
+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint
+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.
+ overrides["model_override"] = {
+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}
+ if provider:
+ overrides["provider_override"] = provider
+ if isinstance(reasoning_config, dict):
+ overrides["reasoning_config_override"] = reasoning_config
+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"
+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier
+ return overrides
+
+
+def _runtime_model_config(agent, existing: dict | None = None) -> dict:
+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent
+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON
+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""
+ config = dict(existing or {})
+ attr = lambda k: str(getattr(agent, k, "") or "").strip()
+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")
+ if provider.lower() == "custom":
+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry
+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider
+ except Exception:
+ logger.debug("custom provider identity lookup failed", exc_info=True)
+ reasoning_config = getattr(agent, "reasoning_config", None)
+ live = {
+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),
+ # An empty dict is still a real (present) reasoning config.
+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,
+ "service_tier": getattr(agent, "service_tier", None),
+ }
+ for key, value in live.items():
+ if value or isinstance(value, dict):
+ config[key] = value
+ else:
+ config.pop(key, None)
+ return config
+
+
+def _persist_live_session_runtime(session: dict | None) -> None:
+ """Persist active session runtime so future resumes restore the same footer."""
+ live = _live_session_agent_db(session)
+ if live is None:
+ return
+ agent, session_key, db = live
+ try:
+ row = db.get_session(session_key) or {}
+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))
+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
+ elif "composer_override_profile" in session:
+ model_config.pop("composer_override_profile", None)
+ if (tier_override := session.get("create_service_tier_override")) is not None:
+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.
+ model_config["service_tier"] = tier_override or "normal"
+ model = str(getattr(agent, "model", "") or "").strip()
+ if hasattr(db, "update_session_meta"):
+ db.update_session_meta(session_key, json.dumps(model_config), model or None)
+ elif model and hasattr(db, "update_session_model"):
+ db.update_session_model(session_key, model)
+ except Exception:
+ logger.debug("failed to persist live session runtime", exc_info=True)
+
+def _load_approval_mode() -> str:
+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the
+ managed overlay and ``${VAR}`` expansion)."""
+ from tools.approval_context import _get_approval_mode
+ mode = _get_approval_mode()
+ return mode if mode in _APPROVAL_MODES else "manual"
+
+
+def _coerce_statusbar(raw) -> str:
+ if raw is False:
+ return "off"
+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"
+
+
+_MOUSE_TRACKING_ALIASES = {
+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",
+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",
+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",
+}
+
+
+def _display_mouse_tracking(display: dict) -> str:
+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC
+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""
+ if not isinstance(display, dict):
+ return "all"
+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)
+ if isinstance(raw, str):
+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")
+ return "off" if raw is False or raw == 0 else "all"
+
+
+def _load_reasoning_config(model: str = "") -> dict | None:
+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >
+ global ``agent.reasoning_effort``; YAML False = disabled).
+
+ Closes #21256.
+ """
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(_load_cfg(), model)
+
+
+def _load_service_tier() -> str | None:
+ from agent.fast_mode import parse_service_tier
+
+ return parse_service_tier((_load_cfg().get("agent") or {}).get("service_tier", ""))
+
+
+def _load_provider_routing() -> dict:
+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""
+ with contextlib.suppress(Exception):
+ return _load_cfg().get("provider_routing", {}) or {}
+ return {}
+
+
+def _load_show_reasoning() -> bool:
+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).
+ return bool(_display_cfg().get("show_reasoning", True))
+
+
+def _load_memory_notifications() -> str:
+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the
+ "💾 Self-improvement review" summary (gateway/CLI parity)."""
+ raw = _display_cfg().get("memory_notifications")
+ if isinstance(raw, bool):
+ return "on" if raw else "off"
+ return str(raw).lower() if raw else "on"
+
+
+_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})
+
+
+def _load_tool_progress_mode() -> str:
+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()
+ if env in _TOOL_PROGRESS_MODES:
+ return env
+ raw = _display_cfg().get("tool_progress", "all")
+ if isinstance(raw, bool):
+ return "all" if raw else "off"
+ mode = str(raw or "all").strip().lower()
+ return mode if mode in _TOOL_PROGRESS_MODES else "all"
+
+
+def _gui_surface_toolsets(platform: str) -> set[str]:
- """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).
++ """Toolsets that exist because of the CLIENT (off ``_HERMES_CORE_TOOLS``; this is the one gate).
+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud
+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""
+ from toolsets import CLIENT_SURFACE_TOOLSETS
+ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}
+
+
+def _with_session_toolsets(selection, platform: str) -> list[str]:
+ """*selection* plus the client surface's toolsets the session carries whatever its config says.
+
+ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,
+ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:
+ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist
+ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a
+ model toolset."""
+ fold_in = _gui_surface_toolsets(platform) - set(selection)
+ disabled = set(_load_disabled_toolsets() or [])
+ if disabled:
+ fold_in -= disabled - {"desktop_ui"}
+ return [*selection, *sorted(fold_in)]
+
+
+def _tui_notice(text: str) -> None:
+ print(text, file=sys.stderr, flush=True)
+
+
+def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:
+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""
+ built_in = [name for name in explicit if validate_toolset(name)]
+ unresolved = [name for name in explicit if name not in built_in]
+ if unresolved:
+ try:
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ plugin_valid = [name for name in unresolved if validate_toolset(name)]
+ except Exception:
+ plugin_valid = []
+ built_in.extend(plugin_valid)
+ unresolved = [name for name in unresolved if name not in plugin_valid]
+ if any(name in {"all", "*"} for name in built_in):
+ if ignored := [name for name in explicit if name not in {"all", "*"}]:
+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")
+ return None
+ if not unresolved:
+ return built_in
+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure
+ from hermes_cli.config import read_raw_config
+ from tools.mcp_tool_common import mcp_server_enabled
+ raw_cfg = read_raw_config()
+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}
+ mcp_names, mcp_disabled = set(), set()
+ for name, server_cfg in mcp_servers.items():
+ if isinstance(server_cfg, dict):
+ on = mcp_server_enabled(server_cfg)
+ (mcp_names if on else mcp_disabled).add(str(name))
+ except Exception:
+ mcp_names, mcp_disabled = set(), set()
+ mcp_valid = [name for name in unresolved if name in mcp_names]
+ disabled = [name for name in unresolved if name in mcp_disabled]
+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]
+ if unknown:
+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")
+ if disabled:
+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "
+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")
+ return (built_in + mcp_valid) or False
+
+
+def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:
+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the
+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);
+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them.
+ An explicitly saved EMPTY list (``platform_toolsets.cli: []`` that resolves to nothing) is a
+ zero-tool state and returns [] — never None, which would mean unrestricted (#82010)."""
+ session_platform = platform or _resolve_session_platform()
+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]
+ fallback_notice = None
+ if not explicit:
+ with contextlib.suppress(Exception):
+ from agent.coding_context import coding_selection
+ selection = coding_selection(platform=session_platform)
+ if selection is not None:
++ from hermes_cli.config import load_config
++ from hermes_cli.tools_config import _get_platform_tools
++ from toolsets import TOOLSET_SESSION_PLATFORMS
++ selection += sorted(_get_platform_tools(load_config(), "cli") & TOOLSET_SESSION_PLATFORMS.keys())
+ return sorted(_with_session_toolsets(selection, session_platform))
+ try:
+ from toolsets import validate_toolset
+ except Exception:
+ validate_toolset = None
+ if explicit and validate_toolset is not None:
+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)
+ if resolved is not False:
+ # An operator pin replaces the surface fold-in.
+ return resolved
+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.tools_config import _get_platform_tools, _platform_toolsets_explicitly_saved
+ cfg = load_config()
+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call
+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.
+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list
+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP
+ # tools silently missing from the TUI. See PR #3252 for the original design split.
+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)
+ if fallback_notice is not None:
+ _tui_notice(fallback_notice)
+ if enabled:
+ return sorted(_with_session_toolsets(enabled, session_platform))
+ # An explicitly saved list that resolves to nothing (``platform_toolsets.cli: []`` with no
+ # enabled MCP servers) is an explicit zero-tool state, not "no filter": fail closed with []
+ # instead of None (#82010). The client-surface fold-in must not resurrect tools the user
+ # explicitly switched off, so [] is returned bare. Only an ABSENT/unset key keeps the
+ # None = "no restriction" default below.
+ if _platform_toolsets_explicitly_saved(cfg, "cli"):
+ return []
+ return None
+ except Exception:
+ if fallback_notice is not None:
+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")
+ return None
+
+
+def _load_disabled_toolsets() -> list[str] | None:
+ """``agent.disabled_toolsets`` from config.yaml, or ``None``.
+
+ The classic CLI (``cli_init_mixin``) and the messaging gateway both forward this list to
+ AIAgent, where ``get_tool_definitions`` strips the named toolsets even out of composite
+ defaults like ``hermes-cli`` (#17309). The desktop/TUI gateway historically dropped it, so
+ e.g. ``disabled_toolsets: [browser]`` silently had no effect on Desktop — the only consumer
+ was ``_get_platform_tools``'s name-level subtraction, which can't reach inside a composite
+ default toolset (#44499).
+ """
+ try:
+ from agent.skill_utils import parse_config_string_list
+
+ from hermes_cli.config import load_config
+
+ agent_cfg = load_config().get("agent") or {}
+ disabled = parse_config_string_list(agent_cfg.get("disabled_toolsets"))
+ return [str(ts) for ts in disabled] or None
+ except Exception:
+ return None
+
+
+def _session_tool_progress_mode(sid: str) -> str:
+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")
+
+
+def _session_verbose(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) == "verbose"
+
+
+def _session_show_reasoning(sid: str) -> bool:
+ """Session display flag. Missing means the config default, not hidden."""
+ session = _sessions.get(sid) or {}
+ if "show_reasoning" in session:
+ return bool(session["show_reasoning"])
+ return _load_show_reasoning()
+
+
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+_TOOL_LIFECYCLE_UI_TOOLS = frozenset({
+ "clarify", "manage_connections", "setup_mcp",
- "image_generate", "manage_catalog", "delegate_task",
++ "image_generate", "manage_catalog", "delegate_task", "setup_choose", "start_chat",
+ # File edits are the turn's deliverable — the diff card the user reviews.
+ "edit_file", "patch", "write_file",
+})
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI / card surfaces, not optional chrome.
+
+ Desktop renders these from the tool-call part itself, so suppressing the
+ lifecycle hides the turn's deliverable entirely (`isCardTool` /
+ `isFileEditTool` in apps/desktop/src/lib/tool-render-class.ts must stay in
+ sync with `_TOOL_LIFECYCLE_UI_TOOLS`): clarify / connection cards are
+ consent surfaces, image_generate / manage_catalog / delegate_task draw the
+ thing the user asked for, and file edits are the diff the user reviews.
+ The start and complete guards both consult this set, so a card's
+ `tool.complete` can never arrive without its `tool.start`.
+ """
+ return name in _TOOL_LIFECYCLE_UI_TOOLS
+
+def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:
+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries
+ are skipped so the unavailable primary model can never leak into a different runtime."""
+ from hermes_cli.auth import AuthError
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ try:
+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)
+ except AuthError as primary_exc:
+ for entry in _load_fallback_model() or []:
+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""
+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""
+ if not fb_provider or not fb_model:
+ continue
+ try:
+ from hermes_cli.fallback_config import effective_runtime_provider, resolve_entry_api_key
+ fb_kwargs: dict = {"requested": fb_provider, "target_model": fb_model,
+ **({"explicit_base_url": entry["base_url"]} if entry.get("base_url") else {})}
+ if fb_api_key := resolve_entry_api_key(entry):
+ fb_kwargs["explicit_api_key"] = fb_api_key
+ runtime = resolve_runtime_provider(**fb_kwargs)
+ # Named custom entries resolve to the bare "custom" billing class; keep the configured
+ # identity so the session/UI shows the provider name, matching the manual-switch path (#98739).
+ runtime["provider"] = effective_runtime_provider(entry, runtime)
+ from hermes_cli.auth import primary_failure_wording
+ logging.getLogger(__name__).warning(
+ "Primary %s (%s), falling back to %s model %s",
+ primary_failure_wording(primary_exc)[0], primary_exc, fb_provider, fb_model)
+ return _RuntimeFallbackResolution(runtime, fb_model, True)
+ except Exception:
+ continue
+ raise
+
+
+def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:
+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted
+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry
+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider
+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""
+ if isinstance(model_override, dict) and model_override.get("model"):
+ model = str(model_override.get("model") or "")
+ requested_provider = model_override.get("provider") or provider_override or None
+ override_base_url = model_override.get("base_url")
+ resolve_kwargs = {}
+ if str(requested_provider or "").strip().lower() == "custom":
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):
+ requested_provider = recovered
+ if override_base_url:
+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.
+ resolve_kwargs["explicit_base_url"] = override_base_url
+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)
+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}
+ else:
+ model, requested_provider = _resolve_startup_runtime()
+ if isinstance(model_override, str) and model_override:
+ model = model_override
+ if provider_override:
+ requested_provider = provider_override
+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}
+ overrides = {}
+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)
+ if resolution.used_fallback:
+ if not resolution.selected_model:
+ raise RuntimeError("Auth fallback resolved without a model")
+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the
+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ # requested_provider=None means resolve_runtime_provider read the persisted config provider;
+ # ``model: <id>`` (string shorthand) names no provider.
+ cfg_model = _load_cfg().get("model")
+ primary_provider = requested_provider or (cfg_model.get("provider") if isinstance(cfg_model, dict) else None)
+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(
+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)
+ return resolution.selected_model, resolution.runtime
+ if resolution.runtime.get("source") == "local-runtime":
+ # Live supervisor beat any persisted loopback URL for this identity.
+ overrides.pop("base_url", None)
+ resolution.runtime.update({k: v for k, v in overrides.items() if v})
+ if any(overrides.values()):
+ _rederive_per_model_route(model, resolution.runtime)
+ return model, resolution.runtime
+
+
+def _rederive_per_model_route(model: str, runtime: dict) -> None:
+ """A row's persisted api_mode/base_url were written for whichever model the session last ran. Providers
+ that pick the wire per model (OpenCode Zen/Go, Copilot, Nous) must re-derive both from the target model,
+ or a resumed opencode-go session keeps a MiniMax-era anthropic_messages route (and its /v1-stripped or
+ other-family relay URL) for a chat_completions model like deepseek-v4-flash-vision-exp (#96066)."""
+ from hermes_cli.model_switch import model_derived_api_mode
+ from hermes_cli.models import normalize_opencode_base_url
+ provider = str(runtime.get("requested_provider") or runtime.get("provider") or "")
+ api_mode = model_derived_api_mode(provider, model)
+ if api_mode is None:
+ return
+ runtime["api_mode"] = api_mode
+ runtime["base_url"] = normalize_opencode_base_url(provider, api_mode, runtime.get("base_url"))
+
+
+def _startup_system_prompt(cfg: dict, task_id: str) -> str:
+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested
+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""
+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config
+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)
+ startup_skills = _parse_tui_skills_env()
+ if not startup_skills:
+ return system_prompt
+ from agent.skill_commands import build_preloaded_skills_prompt, format_missing_skills
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ if not loaded_skills:
+ raise ValueError(format_missing_skills(missing_skills))
+ logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
+ format_missing_skills(missing_skills), ", ".join(loaded_skills))
+ if skills_prompt:
+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()
+ return system_prompt
+
+
+def _make_agent(
+ sid: str, key: str, session_id: str | None = None, session_db=None,
+ model_override: dict | str | None = None, provider_override: str | None = None,
+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,
+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,
+ cwd_override: str | None = None, auth_user_id: str | None = None):
+ # AC-4 test seam: dead unless armed by the isolated certify harness.
+ from tui_gateway.synthetic_turn import maybe_build_synthetic_agent
+ synthetic = maybe_build_synthetic_agent(session_id or key, model_override)
+ if synthetic is not None:
+ return synthetic
+ from run_agent import AIAgent
+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool
+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.
+ for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):
+ with contextlib.suppress(Exception):
+ importlib.import_module(_mod).wait_for_mcp_discovery()
+ cfg = _load_cfg()
+ # Load hooks alongside the same profile config used to construct this agent.
+ from agent.shell_hooks import register_from_config
+ register_from_config(cfg)
+ system_prompt = _startup_system_prompt(cfg, session_id or key)
+ model, runtime = _resolve_agent_model_runtime(model_override, provider_override)
+ fallback_notice = runtime.pop("_fallback_notice", None)
+ _pr = _load_provider_routing()
+ platform = _resolve_agent_platform(platform_override)
+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ agent = AIAgent(
+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),
+ requested_provider=runtime.get("requested_provider"),
+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),
+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),
+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,
+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode
+ reasoning_config=(
+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),
+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),
+ enabled_toolsets=_load_enabled_toolsets(platform),
+ disabled_toolsets=_load_disabled_toolsets(),
+ # OpenRouter provider_routing prefs (gateway + CLI parity).
+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),
+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),
+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,
+ cwd=cwd_override,
+ # The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.
+ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.
+ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),
+ session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,
+ checkpoints_enabled=_resolve_checkpoints_enabled(cfg),
+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),
+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),
+ # The resolved provider's request body (a custom entry's extra_body), as the CLI/cron/gateway pass it.
+ request_overrides=runtime.get("request_overrides"),
+ prefill_messages=_load_prefill_messages() or None, **_agent_cbs(sid))
+ if context_cwd_is_launch_artifact is None:
+ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)
+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)
+ if fallback_notice:
+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.
+ agent._pending_fallback_notice = fallback_notice
+ return agent
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/server.py
index 572407b08d5,0e4f56faecd..a4e689cd899
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -2161,10 -3672,9 +2165,10 @@@ from . import ( # noqa: E40
methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
methods_display as _methods_display, methods_display_watch as _methods_display_watch,
methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n,
- methods_shared_metrics as _methods_shared_metrics)
+ methods_shared_metrics as _methods_shared_metrics, methods_start_chat as _methods_start_chat)
for _m in (
+ _session_registry, _agent_factory,
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
_session_compression, _change_watcher, _tool_progress, _session_notifications,
_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _plugin_inject, _rpc_dispatch,
diff --cc tui_gateway/session_registry.py
index 2124c77aac6,00000000000..7be5efa70c6
mode 100644,000000..100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@@ -1,786 -1,0 +1,789 @@@
+"""TUI session_registry seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+import re
+
+from .method_ctx import bind_module
+
+def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
+ ready = session.get("agent_ready")
+ if ready is not None and not ready.wait(timeout=timeout):
+ return _err(rid, 5032, AGENT_STILL_STARTING)
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+# The deferred prompt path waits in short slices so a cancel is honored promptly and a slow
+# build is reported to the client exactly once.
+_AGENT_BUILD_WAIT_SLICE = 5.0
+_AGENT_BUILD_SLOW_NOTICE_AFTER = 30.0
+_AGENT_BUILD_SLOW_NOTICE_KEY = "agent-build-slow"
+
+
+def _agent_build_wait_cap() -> float:
+ """Seconds a submitted prompt waits for the deferred build before failing; ``agent.build_wait_timeout``
+ overrides the 600s default (raise it for many slow MCP servers / high-latency provider metadata)."""
+ with contextlib.suppress(Exception):
+ raw = (_load_cfg().get("agent") or {}).get("build_wait_timeout")
+ if raw is not None and float(raw) > 0:
+ return float(raw)
+ return 600.0
+
+
+def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:
+ """Patient ``_wait_agent`` for deferred prompt.submit: the client already got ``streaming`` and the
+ first message IS the turn, while a cold build routinely outlives the flat 30s ceiling (timing out
+ silently discarded it). Waits in short slices (cancel honored promptly), notifies once (keyed) past
+ ``_AGENT_BUILD_SLOW_NOTICE_AFTER``, fails only on a dead build thread or the bounded cap.
+ Returns None on success OR cancel mid-wait (the caller's cancel branch owns that messaging).
+
+ The flat 30s ``_wait_agent`` ceiling was a message-eating cliff (#63078): ``prompt.submit`` has already
+ returned ``{"status": "streaming"}``, the user's first message IS the turn in flight, and the deferred
+ agent build (MCP discovery with per-server retry backoff, synchronous model-metadata HTTP, skills
+ scanning) routinely outlives 30 seconds on cold starts. On timeout the old path emitted an error EVENT
+ and returned without ever calling ``_run_prompt_submit`` — the first message was permanently discarded
+ while the build finished successfully in the background, leaving the blank first session.
+ """
+ ready = session.get("agent_ready")
+ if ready is None:
+ return None
+ start, cap, notified_slow = time.monotonic(), _agent_build_wait_cap(), False
+ while not ready.wait(timeout=_AGENT_BUILD_WAIT_SLICE):
+ with session["history_lock"]:
+ cancelled = session.get("_turn_cancel_requested") or not session.get("running")
+ if cancelled:
+ return None
+ waited = time.monotonic() - start
+ if waited >= cap:
+ return _err(rid, 5032, f"agent initialization timed out after {int(waited)}s — "
+ "your message was not sent; retry once the session is ready")
+ build_thread = session.get("_agent_build_thread")
+ if build_thread is not None and not build_thread.is_alive() and not ready.is_set():
+ # _build's finally guarantees ready.set(); dead thread + unset ready = died hard.
+ return _err(rid, 5032, session.get("agent_error") or "agent initialization failed before completing")
+ if not notified_slow and waited >= _AGENT_BUILD_SLOW_NOTICE_AFTER:
+ notified_slow = True # one keyed, replace-in-place notice (toast / status bar)
+ _emit("notification.show", sid, {
+ "text": "Still starting the agent (tool discovery / model setup) — your message will be sent as soon as it's ready.",
+ "level": "info", "kind": "agent", "ttl_ms": None,
+ "key": _AGENT_BUILD_SLOW_NOTICE_KEY, "id": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ if notified_slow:
+ _emit("notification.clear", sid, {"key": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+def _bind_build_profile_scopes(profile_home: "str | None") -> "_TurnScopes | None":
+ """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. ``None`` is the
+ launch profile: its own launch-env secret scope (live env while single-profile, frozen once
+ multiplexing is active — a hosted-room turn for a default member otherwise died at build with
+ ``UnscopedSecretError`` because the launch profile was treated as "no scope"). Fail-open per scope (the build must not die on
+ a scope helper); the terminal installer itself fails closed (malformed policy → refusal scope) so
+ _make_agent's terminal probing / cwd hints resolve the routed profile."""
+ scopes = _TurnScopes()
+ with contextlib.suppress(Exception):
+ return _profile_runtime_scope_tokens(profile_home)
+ if profile_home: # secret/terminal helper failed: keep at least the home + terminal refusal scope
+ scopes.home = set_hermes_home_override(profile_home)
+ with contextlib.suppress(Exception):
+ from tools.terminal_scope import install_profile_terminal_scope
+ scopes.terminal = install_profile_terminal_scope(Path(profile_home))
+ return scopes
+
+
+def _release_build_profile_scopes(scopes: "_TurnScopes | None") -> None:
+ with contextlib.suppress(Exception):
+ _release_profile_runtime_scope_tokens(scopes)
+
+
+def _deferred_build_agent_kwargs(current: dict, session_db) -> dict:
+ """_make_agent kwargs for a deferred (first-prompt) build. A lazy-resumed (watch) session carries the
+ stored conversation id so the upgrade continues it; a cold deferred resume restores the full persisted
+ runtime identity (like the eager resume's overrides splat) so the build can't drop the provider. No
+ stored runtime, or an unroutable provider → this session's picked model/effort/tier, else the default."""
+ kw = {"session_db": session_db, "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(current),
+ "platform_override": _session_source(current), "cwd_override": _session_cwd(current)}
+ if resume_sid := current.get("resume_session_id"):
+ kw["session_id"] = resume_sid
+ resume_overrides = current.get("resume_runtime_overrides")
+ if isinstance(resume_overrides, dict) and resume_overrides and _overrides_have_routable_provider(resume_overrides):
+ kw.update(resume_overrides)
+ else:
+ if override := current.get("model_override"):
+ kw["model_override"] = override
+ kw.update({k: v for k, v in (("reasoning_config_override", current.get("create_reasoning_override")),
+ ("service_tier_override", current.get("create_service_tier_override")))
+ if v is not None})
+ return kw
+
+
+def _wire_session_agent(sid: str, key: str, agent) -> bool:
+ """Post-build wiring; returns whether the approval notify got registered. Approval prompts route to the
+ client; the self-improvement "💾 …" summary is emitted as review.summary (no print surface), honoring
+ display.memory_notifications."""
+ notify_registered = False
+ with contextlib.suppress(Exception):
+ from tools.approval import load_permanent_allowlist, register_gateway_notify
+ register_gateway_notify(key, lambda data: _emit_approval_request(sid, data))
+ notify_registered = True
+ load_permanent_allowlist()
+ _wire_callbacks(sid)
+ with contextlib.suppress(Exception): # bare agents without the attribute must not break startup
+ agent.background_review_callback = lambda message, _sid=sid: _emit("review.summary", _sid, {"text": str(message)})
+ agent.memory_notifications = _load_memory_notifications()
+ return notify_registered
+
+
+def _start_session_services(sid: str, key: str, current: dict) -> None:
+ """Start the notification poller and fire the session-reset boundary hook."""
+ with _sessions_lock:
+ if (rec := _sessions.get(sid)) is not None:
+ rec["_notif_stop"] = _start_notification_poller(sid, rec)
+ _notify_session_boundary("on_session_reset", key, _session_source(current))
+
+
+def _await_resume_history(sid: str, current: dict) -> bool:
+ """Block on a cold resume's transcript hydration; False when this record was replaced meanwhile."""
+ history_ready = current.get("resume_history_ready")
+ if history_ready is None:
+ return True
+ if not history_ready.wait(timeout=300.0):
+ raise TimeoutError("session history hydration timed out")
+ if history_error := current.get("resume_history_error"):
+ raise RuntimeError(str(history_error))
+ with _sessions_lock:
+ return _sessions.get(sid) is current
+
+
+def _attach_built_agent(sid: str, current: dict, agent) -> bool:
+ """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation()).
+ False when ``session.close`` popped this record mid-build: teardown saw ``agent=None`` and closed
+ nothing, so the caller owns closing the orphan (#49852)."""
+ # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at turn START.
+ if _title_hint := str(current.get("pending_title") or "").strip():
+ agent._session_title_hint = _title_hint
+ # Under the same lock session.close takes to pop the record: no window between "still live" and "attached".
+ with _sessions_lock:
+ if _sessions.get(sid) is not current:
+ return False
+ current["agent"] = agent
+ # A workspace move can land while construction is still in flight.
+ _register_session_cwd(current)
+ _session_todo_state(current)
+ # Baseline for the per-turn config sync (profile home override still active).
+ current["config_model_seen"] = _config_model_target()
+ return True
+
+
+def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:
+ """Post-wiring tail of a build: credits seed, session services, session.info, late MCP catch-up."""
+ # Credits notices at session OPEN (notice_callback already wired) so depletion warnings show at "ready".
+ with contextlib.suppress(Exception):
+ from agent.credits_tracker import seed_credits_at_session_start
+ seed_credits_at_session_start(agent)
+ _start_session_services(sid, key, current)
+ info = _session_info(agent, current)
+ if cfg_warn := _probe_config_health(_load_cfg()):
+ info["config_warning"] = cfg_warn
+ logger.warning(cfg_warn)
+ _emit("session.info", sid, info)
+ _schedule_mcp_late_refresh(sid, agent) # servers slower than the bounded discovery wait land here
+
+
+def _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered: bool, scopes, session_db) -> None:
+ """Release build scopes and settle ownership of the late notify registration + dedicated db handle."""
+ if scopes is not None:
+ _release_build_profile_scopes(scopes)
+ # Reaped after the agent was attached: _attach_worker closed the worker; only a late notify
+ # registration can still leak (session.close unregistered before _build registered).
+ with _sessions_lock:
+ replaced = _sessions.get(sid) is not current
+ if replaced and notify_registered:
+ with contextlib.suppress(Exception):
+ from tools.approval import unregister_gateway_notify
+ unregister_gateway_notify(key)
+ # Dedicated profile handle: hand it to the agent that will be torn down, else close it (build
+ # failed, or `replaced`: this agent is discarded and _teardown_session never reaches it).
+ if session_db is not None and not _transfer_db_to_agent(None if replaced else current.get("agent"), session_db):
+ with contextlib.suppress(Exception):
+ session_db.close()
+
+
+def _start_agent_build(sid: str, session: dict) -> None:
+ """Start building the real AIAgent for a TUI session, once. Deferred until the first prompt (or any
+ command needing the agent) so the composer isn't blocked on tool discovery / model metadata;
+ the ready/error event contract is unchanged."""
+ ready = session.get("agent_ready")
+ if ready is None:
+ return
+ # A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps
+ # flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.
+ if session.get("lazy") and _child_run_active(
+ str(session.get("session_key") or ""), session.get("profile_home") or None):
+ return
+ with session.setdefault("agent_build_lock", threading.Lock()):
+ if ready.is_set() or session.get("agent_build_started"):
+ return
+ session["agent_build_started"] = True
+ session.pop("lazy", None) # now genuinely mid-construction: restore the "still starting" eviction exemption
+ key = session["session_key"]
+
+ def _build() -> None:
+ with _sessions_lock:
+ current = _sessions.get(sid)
+ if current is None:
+ # Closed/reaped before the build started: nothing will ever attach an agent to this
+ # record, yet ``agent_ready`` must be set so a prompt waiting on it fails instead of hanging.
+ session["agent_error"] = AGENT_BUILD_ABANDONED
+ ready.set()
+ return
+ notify_registered, scopes, session_db = False, None, None
+ profile_home = current.get("profile_home")
+ try:
+ if not _await_resume_history(sid, current):
+ # Replaced mid-build: the finally still sets ``agent_ready`` with ``agent`` None, so record
+ # why — a turn admitted against this record refuses with the real reason (#111531).
+ current["agent_error"] = AGENT_BUILD_ABANDONED
+ return
+ tokens = _set_session_context(key, cwd=_session_cwd(current))
+ # Global-remote: bind the session profile's HERMES_HOME and hand the agent that profile's db —
+ # DEDICATED and ours until _transfer_db_to_agent in the finally; FAIL CLOSED rather than
+ # binding the launch DB and bleeding rows into the wrong state.db.
+ scopes = _bind_build_profile_scopes(profile_home)
+ if profile_home:
+ session_db = _open_profile_session_db(profile_home)
+ try:
+ from tui_gateway.entry import ensure_mcp_discovery_started
+ ensure_mcp_discovery_started()
+ except Exception:
+ logger.warning("MCP discovery startup failed", exc_info=True)
+ try:
+ agent = _make_agent(sid, key, **_deferred_build_agent_kwargs(current, session_db))
+ finally:
+ _clear_session_context(tokens)
+ # Attach atomically against session teardown: ``session.close`` may have popped this
+ # session while the expensive build was in flight, in which case teardown could not close
+ # an agent that did not exist yet. Release the orphan immediately and do not keep wiring
+ # workers/callbacks for a dead session (#49852).
+ if not _attach_built_agent(sid, current, agent):
+ # Same contract as the replaced-before-attach exit above: a turn admitted against
+ # this record must refuse with the real reason rather than a generic missing agent.
+ current["agent_error"] = AGENT_BUILD_ABANDONED
+ with contextlib.suppress(Exception):
+ if hasattr(agent, "close"):
+ agent.close()
+ return
+ # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio
+ # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.
+ notify_registered = _wire_session_agent(sid, key, agent)
+ _announce_built_agent(sid, key, current, agent)
+ except Exception as e:
+ from agent.auxiliary_unavailable import ProviderNotConfiguredError
+ current["agent_error"] = str(e)
+ # A client can route "no provider is set up" to its setup flow instead of a dead-end
+ # error toast — but only if it can tell. The sentence is for the reader, the code is
+ # for the client; older clients keep matching the text.
+ _emit("error", sid, {
+ "message": agent_init_failed_message(e),
+ **({"code": "provider_not_configured"} if isinstance(e, ProviderNotConfiguredError) else {})})
+ finally:
+ _finish_agent_build(
+ sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)
+ ready.set()
+
+ build_thread = threading.Thread(target=_build, daemon=True)
+ # _wait_agent_for_prompt handle: dead thread + unset agent_ready = died hard; waiters must not sit out the cap.
+ session["_agent_build_thread"] = build_thread
+ build_thread.start()
+
+
+def _sess_nowait(params, rid):
+ sid = params.get("session_id") or ""
+ s = _sessions.get(sid)
+ if s:
+ return (s, None)
+ # Stale runtime id (reaped/evicted/TTL): the client should session.resume the STORED id. Logged so
+ # "message vanished" reads as "arrived and was rejected".
+ logger.warning("session-scoped RPC rejected: method=%s session_id=%r not in memory "
+ # A session-scoped RPC hit a runtime id the gateway no longer holds (detached on WS
+ # disconnect and orphan-reaped, LRU-evicted, or torn down after an idle TTL). The client
+ # is expected to recover via session.resume on the STORED session id, but a plain
+ # stale-id send leaves no trace anywhere when the resume never fires — every RPC in this
+ # class returned a silent 4001. Log it so a "message vanished" report is diagnosable as
+ # "request arrived and was rejected" instead of "request never arrived" (see #90428).
+ "(detached/reaped runtime; client should resume the stored session), rid=%r",
+ _current_rpc_method.get() or "?", sid, rid)
+ return (None, _err(rid, 4001, "session not found"))
+
+
+def _sess(params, rid):
+ s, err = _sess_building(params, rid)
+ return (None, err) if err else (s, _wait_agent(s, rid))
+
+
+def _sess_building(params, rid):
+ """Resolve a session and warm its agent build WITHOUT waiting — for the attach RPCs (image/file/pdf,
+ clipboard.paste, image.detach), which only touch creation-time fields and run inline on the socket
+ reader thread, where waiting on a cold build stalled every RPC behind it ("text is instant, images hang")."""
+ s, err = _sess_nowait(params, rid)
+ if not err:
+ _start_agent_build(params.get("session_id") or "", s)
+ return (None, err) if err else (s, None)
+
+def _init_session(
+ sid: str, key: str, agent, history: list, cols: int = 80, cwd: str | None = None,
+ session_db=None, source: str | None = None, profile_home: str | None = None,
+ explicit_cwd: bool = False):
+ now = time.time()
+ with _sessions_lock:
+ _sessions[sid] = {
+ "agent": agent, "session_key": key, "history": history, "history_lock": threading.Lock(),
+ "history_version": 0, "inflight_turn": None, "created_at": now, "last_active": now,
+ "running": False, "attached_images": [], "image_counter": 0, "cwd": cwd or _completion_cwd(),
+ "explicit_cwd": bool(explicit_cwd), "cols": cols, "slash_worker": None,
+ "show_reasoning": _load_show_reasoning(), "source": _resolve_session_source(source),
+ "tool_progress_mode": _load_tool_progress_mode(), "edit_snapshots": {}, "tool_started_at": {},
+ # Profile-scoped HERMES_HOME (None = launch); SessionBranch copies the parent's (same state.db).
+ "profile_home": profile_home,
+ # In-session /model switch, honored on rebuild (/new, resume) — never leaks to siblings via env vars.
+ "model_override": None,
+ # Async events go to the transport that created the session (stdio for Ink, WS for the dashboard).
+ "transport": current_transport() or _stdio_transport,
+ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+ _session_todo_state(_sessions[sid])
+ _hydrate_session_cwd(sid, key, session_db, profile_home)
+ _register_session_cwd(_sessions[sid])
+ _wire_session_agent(sid, key, agent) # no eager slash-worker pre-warm (see _start_agent_build)
+ _start_session_services(sid, key, _sessions.get(sid, {}))
+ _emit("session.info", sid, _session_info(agent, _sessions.get(sid, {})))
+ _schedule_mcp_late_refresh(sid, agent)
+
+
+def _new_session_key() -> str:
+ return new_session_id()
+
+
+# Server-minted session keys are ``%Y%m%d_%H%M%S_`` + 6 hex chars (see
+# ``_new_session_key``). session.resume uses this shape as the fail-closed gate
+# for materializing a row for a minted-but-never-persisted key: only keys the
+# server itself could have produced qualify — arbitrary strings and 8-hex
+# runtime session ids (``uuid4().hex[:8]``) are rejected.
+_MINTED_SESSION_KEY_RE = re.compile(r"^\d{8}_\d{6}_[0-9a-f]{6}$")
+
+
+def _is_server_minted_key(value: str | None) -> bool:
+ return bool(value and _MINTED_SESSION_KEY_RE.fullmatch(value))
+
+
+def _any_live_session_claims_key(target: str) -> bool:
+ """True if any live registry record claims this stored key (any profile).
+
+ Fail-closed gate for minted-key materialization: a key claimed by a live
+ session — even one scoped to a different profile — is owned, so an
+ unscoped resume must not mint a phantom row in the launch store (#93296
+ cross-profile rule: routing guesses are forbidden).
+ """
+ for record in list(_sessions.values()):
+ if not isinstance(record, dict):
+ continue
+ if str(record.get("session_key") or "") == target:
+ return True
+ return False
+
+
+def _with_checkpoints(session, fn):
+ return fn(session["agent"]._checkpoint_mgr, _session_cwd(session))
+
+
+def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:
+ try:
+ checkpoints = mgr.list_checkpoints(cwd)
+ idx = int(ref) - 1
+ except ValueError:
+ return ref
+ if 0 <= idx < len(checkpoints):
+ return checkpoints[idx].get("hash", ref)
+ raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")
+
+
+# ── Methods: session ─────────────────────────────────────────────────
+
+
+def _lazy_resume_info(cwd: str, *, model: str = "", provider: str = "", profile: str | None = None) -> dict:
+ """session.info for a not-yet-built session (session.create's shape); tools/skills land with the deferred build."""
++ if not model:
++ model, default_provider = _session_default_route({"profile_home": _profile_home(profile)})
++ provider = provider or default_provider
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),
+ **_lazy_info_route({"profile_home": _profile_home(profile)}, {"model": model, "provider": provider} if model else {}),
+ "tools": {}, "skills": {}, "lazy": True,
+ "desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),
+ }
+
+
+def _deferred_session_record(
+ session_key: str, *, cols: int, cwd: str, history: list, lease, source: str = "tui",
+ close_on_disconnect: bool = False, display_history_prefix: list | None = None,
+ profile_home: Path | None = None, lazy: bool = False, model_override=None,
+ resume_runtime_overrides: dict | None = None, todo_state: dict | None = None,
+ explicit_cwd: bool = False) -> dict:
+ """A live-session record whose AIAgent is built later (lazy watch / cold resume) — _init_session's shape minus the agent."""
+ now = time.time()
+ return {
+ "agent": None, "agent_error": None, "agent_ready": threading.Event(), "attached_images": [],
+ "close_on_disconnect": close_on_disconnect, "active_session_lease": lease, "cols": cols,
+ "created_at": now, "cwd": cwd, "display_history_prefix": display_history_prefix or [],
+ "edit_snapshots": {}, "explicit_cwd": bool(explicit_cwd), "history": history,
+ "history_lock": threading.Lock(), "history_version": 0, "image_counter": 0,
+ "inflight_turn": None, "last_active": now, "lazy": lazy, "model_override": model_override,
+ "pending_title": None,
+ "profile_home": str(profile_home) if profile_home is not None else None,
+ "resume_runtime_overrides": resume_runtime_overrides, "resume_session_id": session_key,
+ "running": False, "session_key": session_key, "show_reasoning": _load_show_reasoning(),
+ "slash_worker": None, "source": source, "tool_progress_mode": _load_tool_progress_mode(),
+ "tool_started_at": {}, "todo_state": todo_state,
+ "transport": current_transport() or _stdio_transport,
+ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+
+
+_ANY_PROFILE = object() # default: match a live session regardless of profile
+
+
+def _live_profile_matches(session: dict, profile_home) -> bool:
+ """True when ``session`` belongs to ``profile_home`` (None = launch profile; a record with no
+ ``profile_home`` is the launch profile's). ``_ANY_PROFILE`` disables the check."""
+ if profile_home is _ANY_PROFILE:
+ return True
+ return (session.get("profile_home") or None) == (str(profile_home) if profile_home else None)
+
+
+def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tuple[str, dict] | None:
+ """Register ``record`` as the live session for ``session_key`` under the resume lock, or — if a
+ concurrent resume already won — release ``lease`` and return the winner for the caller to reuse."""
+ # A live runtime of the same stored id under ANOTHER profile is not a winner to reuse.
+ # See #100029.
+ profile_home = record.get("profile_home")
+ with _session_resume_lock:
+ live = _find_live_session_by_key(session_key, profile_home)
+ if live is not None:
+ if lease is not None:
+ lease.release()
+ # The reap is cancelled by the guarded reuse (_reattach_refusal), not here: a rejected
+ # reattach must leave an in-flight orphan interrupt polling.
+ return live
+ with _sessions_lock:
+ _sessions[sid] = record
+ _register_session_cwd(_sessions[sid])
+ # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed; cancel +
+ # finalize it quietly so the reap doesn't broadcast session.reclaimed (storm).
+ _cancel_ws_orphan_reap(sid)
+ stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)
+ _finalize_superseded_runtimes(stale) # slow finalization stays OUTSIDE _session_resume_lock
+ return None
+
+
+def _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE) -> list[tuple[str, dict]]:
+ """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: cancel their orphan-reap
+ Timer and pop them here (under the caller's _session_resume_lock); the caller finalizes after release."""
+ stale: list[tuple[str, dict]] = []
+ with _sessions_lock:
+ candidates = [
+ (old_sid, old) for old_sid, old in list(_sessions.items())
+ if old_sid != keep_sid and not old.get("_finalized")
+ and _session_lookup_key(old, fallback=old_sid) == session_key
+ and _live_profile_matches(old, profile_home) and old.get("transport") is _detached_ws_transport]
+ for old_sid, _old in candidates:
+ _cancel_ws_orphan_reap(old_sid)
+ if (popped := _pop_session_by_id(old_sid)) is not None:
+ stale.append((old_sid, popped))
+ return stale
+
+
+def _finalize_superseded_runtimes(stale: list[tuple[str, dict]]) -> None:
+ """end_reason ``superseded_by_resume`` is deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``
+ broadcast → no reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS (Bot Chat resurrection applies)."""
+ for old_sid, popped in stale:
+ try:
+ _teardown_popped_session(popped, end_reason="superseded_by_resume")
+ except Exception:
+ logger.exception("superseded runtime teardown failed sid=%s", old_sid)
+
+
+def _schedule_agent_build(sid: str, delay: float = 0.05) -> None:
+ """Pre-warm a deferred session's agent off the response path (session.create + cold resume; _sess() also builds on demand)."""
+
+ def _run():
+ if (session := _sessions.get(sid)) is not None:
+ _start_agent_build(sid, session)
+ timer = threading.Timer(delay, _run)
+ timer.daemon = True
+ timer.start()
+
+
+def _load_resume_transcript(db, stored_id: str, *, model_history_only: bool = False) -> tuple[list, list, list]:
+ """(raw_history, display_history, ancestor_prefix) for a cold resume. The full lineage is materialized
+ only while it fits sessions.max_resume_messages (the transcript is REST-paginated), else the tip alone."""
+ from hermes_state import SessionResumeTooLargeError
+ if model_history_only:
+ raw_history = db.get_messages_as_conversation(
+ stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, [], []
+ prefix_fits = True
+ guard = getattr(db, "assert_resume_safe", None)
+ if callable(guard):
+ try:
+ guard(stored_id)
+ except SessionResumeTooLargeError as exc:
+ prefix_fits = False
+ logger.info("resume %s: compression lineage exceeds the resume limit (%s); hydrating the tip segment only",
+ stored_id, exc)
+ except Exception:
+ logger.debug("resume lineage guard failed; loading full lineage", exc_info=True)
+ if prefix_fits:
+ raw_history, display_history = db.get_resume_conversations(stored_id)
+ return raw_history, display_history, db.get_ancestor_display_prefix(stored_id)
+ raw_history = db.get_messages_as_conversation(stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, raw_history, []
+
+
+def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool = False,
+ model_history_only: bool = False) -> None:
+ """Load a cold resume's transcript off the JSON-RPC response path."""
+
+ def _run() -> None:
+ session = _sessions.get(sid)
+ try:
+ if session is None:
+ return
+ _emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})
+ # Read-only mount (#85303): hydration is a read; an ended row stays ended —
+ # the first real turn (prompt.submit) reopens it. But a restart discarded the
+ # busy-queue, so retire never-drained accept rows (#125577) before the read —
+ # with #128508 the reopen (and its retire) no longer runs on this path.
+ # Best-effort like the resume guard: a handle without the method skips it.
+ retire = getattr(db, "retire_undrained_queue_rows", None)
+ if callable(retire):
+ retire(stored_id)
+ raw_history, display_history, prefix = _load_resume_transcript(
+ db, stored_id, model_history_only=model_history_only)
+ # Display keeps the full transcript; the model-fed history uses the
+ # same canonicalization as gateway resume and the send path.
+ history = canonicalize_replay_history(raw_history)
+ if _sessions.get(sid) is not session:
+ return
+ with session["history_lock"]:
+ session.update(history=history, display_history_prefix=prefix, resume_hydrating=False)
+ if not model_history_only:
+ session["resume_message_count"] = len(display_history)
+ # Deferred resumes answered before the transcript existed; cache the derived todo snapshot now.
+ todo_state = _todo_state_from_history(history)
+ if todo_state is not None and session.get("todo_state") is None:
+ session["todo_state"] = todo_state
+ session["resume_history_ready"].set()
+ _emit("session.resume_progress", sid,
+ {"message_count": session["resume_message_count"], "phase": "history", "status": "complete"})
+ _maybe_schedule_auto_continue(sid, session, stored_id)
+ _start_agent_build(sid, session)
+ except Exception as exc:
+ if _sessions.get(sid) is not session:
+ return
+ message = resume_failed_message(exc)
+ session.update(resume_hydrating=False, resume_history_error=message, agent_error=message)
+ session["resume_history_ready"].set()
+ session["agent_ready"].set()
+ _emit("session.resume_progress", sid, {"message": message, "phase": "history", "status": "failed"})
+ _emit("error", sid, {"message": message})
+ with _sessions_lock:
+ discarded = _sessions.pop(sid, None) if _sessions.get(sid) is session else None
+ if (lease := (discarded or {}).get("active_session_lease")) is not None:
+ lease.release()
+ finally:
+ if close_db and hasattr(db, "close"):
+ try:
+ db.close()
+ except Exception:
+ logger.debug("failed to close resume db for %s", sid, exc_info=True)
+ threading.Thread(target=_run, daemon=True).start()
+
+
+def _session_pending_kind(sid: str) -> str:
+ """Method of the server→client request *sid* is blocked on ("" when none)."""
+ from tui_gateway import server_requests
+ return server_requests.pending_kind(sid)
+
+
+def _session_live_status(sid: str, session: dict) -> str:
+ if _session_pending_kind(sid):
+ return "waiting"
+ ready = session.get("agent_ready")
+ # Unset + build never started = a lazy watch session idling, not one stuck mid-construction.
+ if ready is not None and not ready.is_set() and session.get("agent_build_started"):
+ return "starting"
+ return "working" if session.get("running") else "idle"
+
+
+def _session_live_title(session: dict, key: str) -> str:
+ title = str(session.get("pending_title") or "").strip()
+ with contextlib.suppress(Exception), _session_db(session) as db:
+ title = str(db.get_session_title(key) or title or "").strip() if db is not None else title
+ return title
+
+
+def _session_live_item(sid: str, session: dict, current_sid: str = "") -> dict:
+ key = _session_lookup_key(session, fallback=sid)
+ agent = session.get("agent")
+ history = list(session.get("history") or [])
+ status = _session_live_status(sid, session)
+ inflight = _inflight_snapshot(session)
+ queued = _queued_prompt_snapshot(session)
+ preview = next((" ".join(text.split())[:160] for msg in reversed(history)
+ if (text := _content_display_text(msg.get("content", msg.get("text", ""))).strip())), "")
+ if queued:
+ preview = " ".join(str(queued.get("user") or preview).split())[:160]
+ elif inflight:
+ preview = " ".join(str(inflight.get("assistant") or inflight.get("user") or preview).split())[:160]
+ now = time.time()
+ return {
+ "current": sid == current_sid, "id": sid,
+ "last_active": float(session.get("last_active") or session.get("created_at") or now),
+ "message_count": len(history),
+ "model": str(getattr(agent, "model", "") or _resolve_model()), "preview": preview,
+ "session_key": key, "started_at": float(session.get("created_at") or now), "status": status,
+ "title": _session_live_title(session, key),
+ }
+
+
+def _session_lookup_key(session: dict, *, fallback: str = "") -> str:
+ return str(getattr(session.get("agent"), "session_id", None) or session.get("session_key") or fallback or "")
+
+
+def _find_live_session_by_key(session_key: str, profile_home=_ANY_PROFILE) -> tuple[str, dict] | None:
+ # Timestamp-based stored ids can exist in several profiles' stores; a bare-id match would hand
+ # profile B's resume profile A's runtime, so profile-aware callers match on (profile_home, key).
+ # Profile-aware callers pass the home they resolved; the match must then be on (profile_home,
+ # session_key). See #100029.
+ for sid, session in list(_sessions.items()):
+ if (not session.get("_finalized") and _session_lookup_key(session, fallback=sid) == session_key
+ and _live_profile_matches(session, profile_home)):
+ return sid, session
+ return None
+
+
+def _fallback_session_info(session: dict) -> dict:
+ agent = session.get("agent")
+ if agent is not None:
+ return _session_info(agent)
+ # The SESSION's own workspace, not the launch dir (wrong project in the desktop Files pane). `branch` is
+ # always emitted ("" outside git) so a stale label clears; `desktop_contract` missing reads as "out of date".
+ # Reporting `_default_session_cwd()` here told a lazily-resumed session's client that its workspace was
+ # wherever the gateway process happened to start, so the desktop Files pane painted the wrong project
+ # even after the renderer rebound correctly (#71254). `branch` is always emitted ("" outside a git repo)
+ # so a client can clear a stale label instead of retaining it — the same contract `_lazy_session_info`
+ # above already follows.
+ cwd = _session_cwd(session)
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,
+ **_lazy_info_route(session, {}), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,
+ }
+
+
+def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict]) -> list[dict]:
+ """Merge the persisted DISPLAY lineage with the in-memory live history: ``db_display`` is verbatim and
+ candidate-inclusive (verification rows the model history collapses out) but can lag by a flush;
+ ``in_memory`` is the recency authority but the collapsed *model* projection. Keep the DB display as base,
+ append only the in-memory tail past the last DB row's ``(role, text)`` anchor — the verification answer
+ survives a warm switch AND a not-yet-flushed live turn is kept."""
+ if not db_display:
+ return in_memory
+ if not in_memory:
+ return db_display
+
+ def _key(msg: dict) -> tuple:
+ return (msg.get("role"), _coerce_message_text(msg.get("content")))
+ anchor = _key(db_display[-1])
+ last_shared = max((idx for idx, msg in enumerate(in_memory) if isinstance(msg, dict) and _key(msg) == anchor), default=-1)
+ if last_shared == -1:
+ return db_display # DB tail not in memory (DB ahead, or diverged) — trust it over duplicating
+ return list(db_display) + list(in_memory[last_shared + 1 :])
+
+
+def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:
+ """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same read as
+ resume/REST so the payloads agree) reconciled with the in-memory tail; in-memory when the DB is unavailable."""
+ key = session.get("session_key")
+ if db is not None and key:
+ try:
+ # include_compacted: a compacted session's archived turns are still the user's
+ # conversation; without them a warm switch repainted the chat as summary + tail only.
+ display = db.get_messages_as_conversation(
+ key, include_ancestors=True, include_row_ids=True, include_compacted=True)
+ # See #92080.
+ return _reconcile_display_with_live(display, in_memory_fallback)
+ except Exception:
+ logger.debug("live display projection read failed", exc_info=True)
+ return in_memory_fallback
+
+
+def _live_session_payload(
+ sid: str, session: dict, *, cols: int | None = None, touch: bool = False,
+ transport: Transport | None = None, omit_messages: bool = False, inline_images: bool = True) -> dict:
+ with session["history_lock"]:
+ if cols is not None:
+ session["cols"] = cols
+ if transport is not None:
+ _rebind_live_transport(sid, session, transport)
+ if touch:
+ # #84417: do not re-fire the live turn's original user text from a stale server-queue
+ # self-duplicate after settle.
+ session["last_active"] = time.time()
+ in_memory_history = list(session.get("display_history_prefix") or []) + list(session.get("history") or [])
+ inflight, queued = _inflight_snapshot(session), _queued_prompt_snapshot(session)
+ running, turn_started_at = bool(session.get("running")), _turn_started_at(session)
+ # Persisted display lineage via the session's profile-aware DB (not the launch ``_get_db()``), read
+ # outside the history lock (the DB has its own). ``omit_messages`` skips the read (fast path).
+ if omit_messages:
+ history = in_memory_history
+ else:
+ with _session_db(session) as db:
+ history = _live_visible_history(session, db, in_memory_history)
+ # message_count follows _resume_response: the stored size when messages are omitted, else the wire count
+ # (a hidden seed row is in ``history`` but never on the wire).
+ messages = ([] if omit_messages else
+ _history_to_messages(history, profile_home=session.get("profile_home"), image_urls=inline_images))
+ payload = {
+ "info": _fallback_session_info(session), "message_count": len(history) if omit_messages else len(messages),
+ "messages": messages,
+ "messages_omitted": omit_messages, "running": running, "turn_started_at": turn_started_at,
+ "session_id": sid, "session_key": _session_lookup_key(session, fallback=sid),
+ "started_at": float(session.get("created_at") or time.time()),
+ "status": _session_live_status(sid, session),
+ }
+ for key, value in (("inflight", inflight), ("queued", queued),
+ ("pending_approval", _pending_approval_request_payload(str(session.get("session_key") or ""))),
+ ("open_requests", _open_requests(sid)),
+ ("pending_connection", _pending_connection_request_payload(sid))):
+ if value:
+ payload[key] = value
+ return _attach_todo_state(payload, session)
+
+
+def _main_runtime_from_agent(agent) -> dict | None:
+ """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's runtime."""
+ if agent is None:
+ return None
+ runtime: dict = {}
+ # ``session_id`` rides along so a session-bound ``llm.oneshot`` (title, approval) on an OpenCode
+ # route sends the conversation's ``x-opencode-session`` like the main turn does (#112717).
+ for field in ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode", "session_id"):
+ value = getattr(agent, field, None)
+ if isinstance(value, str) and value.strip():
+ runtime[field] = value.strip()
+ elif field == "api_key" and callable(value):
+ runtime[field] = value
+ return runtime or None
+
+
+def register(server):
+ bind_module(globals(), server)