Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution

teknium1444dd0af3b56
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index 8b45d9193aa,cfd7c5521c7..bed936e9cb3
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -311,23 -308,24 +311,29 @@@ export function useComposerSubmit(
triggerHaptic('submit')
clearDraft()
- // The draft is already cleared, so a refused or failed redirect must keep
- // the only copy: queue it for the next turn, or restore it when there is no
- // queue yet (a new chat is busy before its first session exists).
+ const submittedScope = activeQueueSessionKeyRef.current
+
- const restore = () => {
- loadIntoComposer(text, [])
- stashAt(submittedScope, text, [])
++ // The draft is already cleared, so a refused or failed redirect must keep the only copy
++ // (#68927): the canonical queue when the server owns it, the local queue otherwise, or the
++ // composer itself when there is no queue yet (a new chat busy before its first session).
++ const canonical = serverOwnsComposerQueue(sessionId ?? activeQueueSessionKey)
+ const keep = () => {
- if (activeQueueSessionKey) {
- enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
- } else {
++ if (!activeQueueSessionKey) {
+ loadIntoComposer(text, [])
++ stashAt(submittedScope, text, [])
++ } else if (canonical) {
++ dispatchSubmit(text, [], undefined, { fromQueue: true, sessionId: sessionId ?? null, storedSessionId: activeQueueSessionKey })
++ } else {
++ enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
+ }
}
- const canonical = serverOwnsComposerQueue(sessionId ?? activeQueueSessionKey)
- void Promise.resolve(onSteer(text))
- .then(accepted => {
- if (!accepted) {
- keep()
- }
- })
- .catch(keep)
+ void Promise.resolve().then(() => onSteer(text, mode)).then(accepted => {
- if (!accepted && activeQueueSessionKey) {
- if (canonical) {
- dispatchSubmit(text, [], undefined, { fromQueue: true, sessionId: sessionId ?? null, storedSessionId: activeQueueSessionKey })
- } else {
- enqueueQueuedPrompt(activeQueueSessionKey, { text, attachments: [] })
- }
++ if (!accepted) {
++ keep()
+ }
- }).catch(restore)
++ }).catch(keep)
++
}
const queueDraft = () => {
diff --cc apps/desktop/src/plugins/hermes-bots/i18n.ts
index 2f947194662,878322e5f1d..f7a909d7e32
--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts
+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts
@@@ -36,8 -35,71 +36,72 @@@ import { CANONICAL_GROUP_LOCALES, type
import { getPluginCtx } from './shared'
type BotsMessages = {
+ canonical: { [K in keyof CanonicalGroupMessages]: string }
/** Left rail: the bot + group-chat roster. */
+ editor: {
+ fullConfigHint: string
+ liveCapabilities: string
+ editSoul: string
+ remoteCapabilitiesHint: string
+ skillsEnabled: (enabled: number, total: number) => string
+ toolsetsEnabled: (enabled: number, total: number) => string
+ mcpServers: string
+ providerCustom: string
+ modelCustom: string
+ backToDropdowns: string
+ inheritLaunch: string
+ enterManually: string
+ gatewayDefault: string
+ modelNameExample: string
+ modelSwitchFailed: string
+ newDescription: string
+ name: string
+ title: string
+ description: string
+ createOn: string
+ general: string
+ capabilities: string
+ skills: string
+ tools: string
+ cloneFrom: string
+ freshProfile: string
+ inheritedModel: string
+ soul: string
+ shareKeys: string
+ shareKeysHint: string
+ createEmpty: string
+ nameTakenHint: string
+ nameFirstHint: string
+ newerDesktop: string
+ newerGateway: string
+ emptySkillsHint: string
+ defaultToolsHint: string
+ catalog: string
+ catalogInstalled: string
+ mcpHint: string
+ creating: string
+ createBot: string
+ auto: string
+ autoHint: string
+ unlock: string
+ lockFace: string
+ lockedHint: string
+ unlockedHint: string
+ noImageModel: string
+ checkingImage: string
+ chooseImage: string
+ editDescription: (name: string, profile: string) => string
+ nameTaken: (name: string) => string
+ nameTakenOn: (name: string, target: string) => string
+ currentConnection: (name: string) => string
+ remoteHint: (target: string) => string
+ cloneFromOn: (target: string) => string
+ catalogHint: (source: string) => string
+ sectionsFailed: (sections: string) => string
+ updated: (name: string) => string
+ created: (name: string) => string
+ createdOn: (name: string, target: string) => string
+ }
roster: {
search: string
searchPlaceholder: string
@@@ -365,7 -472,75 +474,76 @@@
}
const en: BotsMessages = {
+ canonical: CANONICAL_GROUP_LOCALES.en,
+ editor: {
+ fullConfigHint: 'Full configuration needs a newer gateway (restart it after updating Hermes).',
+ liveCapabilities: 'Capabilities (applies immediately — skills, tools, MCP)',
+ editSoul: 'SOUL.md (persona + agent-messaging protocol)',
+ remoteCapabilitiesHint:
+ 'Remote capabilities require a newer desktop. Model and SOUL changes remain staged until you save.',
+ skillsEnabled: (enabled, total) => `Skills (${enabled}/${total} enabled)`,
+ toolsetsEnabled: (enabled, total) => `Toolsets (${enabled}/${total} enabled — unchecking all restores the default)`,
+ mcpServers: 'MCP servers',
+ providerCustom: 'Provider (Custom)',
+ modelCustom: 'Model (Custom)',
+ backToDropdowns: '← Back to dropdowns',
+ inheritLaunch: 'Inherit (launch profile)',
+ enterManually: '✏️ Enter manually…',
+ gatewayDefault: 'gateway default',
+ modelNameExample: 'e.g. model name',
+ modelSwitchFailed: 'Model switch failed',
+ newDescription: 'A named teammate with its own memory, skills, and chat. It can message your other agents.',
+ name: 'Name',
+ title: 'Title',
+ description: 'Description',
+ createOn: 'Create on',
+ general: 'General',
+ capabilities: 'Capabilities',
+ skills: 'Skills',
+ tools: 'Tools',
+ cloneFrom: 'Clone from profile',
+ freshProfile: 'Fresh profile (bundled skills)',
+ inheritedModel: 'inherited from launch profile',
+ soul: 'SOUL.md (optional — replaces the generated persona)',
+ shareKeys: 'Share keys & accounts with the main profile',
+ shareKeysHint:
+ 'Subscriptions, OAuth logins, and API keys stay shared (not copied), so token refreshes never invalidate each other. Uncheck for an isolated snapshot copy.',
+ createEmpty: 'Create empty (skip bundled skills)',
+ nameTakenHint: 'That name is taken — pick another before configuring capabilities.',
+ nameFirstHint: 'Name the bot first — a draft profile is created when you open this tab (discarded if you cancel).',
+ newerDesktop: 'Skills need a newer Hermes Desktop.',
+ newerGateway: 'Capability catalog needs a newer gateway (restart it after updating Hermes).',
+ emptySkillsHint: '“Create empty” is checked — no bundled skills will be installed.',
+ defaultToolsHint: 'Leaving all (or none) checked keeps the default toolset behavior.',
+ catalog: 'catalog',
+ catalogInstalled: 'catalog · installed',
+ mcpHint:
+ 'Configured servers copy from the main profile; catalog entries are the bundled MCP menu. Entries needing API keys route through setup first (credentials follow the shared keys setting).',
+ creating: 'Creating…',
+ createBot: 'Create Bot',
+ auto: 'Auto',
+ autoHint: 'Auto — the name decides',
+ unlock: 'Unlock',
+ lockFace: 'Lock face',
+ lockedHint: 'Face locked — renaming won’t change it.',
+ unlockedHint: 'Face follows the name.',
+ noImageModel:
+ 'No image model available. If you just enabled one (or updated Hermes), restart the gateway: Ctrl+K → "Restart gateway".',
+ checkingImage: 'Checking image backend…',
+ chooseImage: 'Choose an image…',
+ editDescription: (name, profile) => `Appearance and role for ${name} (${profile}).`,
+ nameTaken: name => `An agent named "${name}" already exists.`,
+ nameTakenOn: (name, target) => `An agent named "${name}" already exists on ${target}.`,
+ currentConnection: name => `${name} (current)`,
+ remoteHint: target =>
+ `The agent is created on ${target} and appears in the roster as a Connections bot. Chat routes to that machine.`,
+ cloneFromOn: target => `Clone from profile (on ${target})`,
+ catalogHint: source => `Catalog from ${source} — unchecked skills are disabled after creation.`,
+ sectionsFailed: sections => `Some sections failed: ${sections}`,
+ updated: name => `${name} updated`,
+ created: name => `Bot "${name}" created`,
+ createdOn: (name, target) => `Bot "${name}" created on ${target}`
+ },
roster: {
search: 'Search bots and group chats',
searchPlaceholder: 'Search bots and group chats…',
@@@ -676,7 -896,77 +899,78 @@@
}
const ja: BotsMessages = {
+ canonical: CANONICAL_GROUP_LOCALES.ja,
+ editor: {
+ fullConfigHint: 'すべての設定を使うには新しいゲートウェイが必要です(Hermes 更新後に再起動してください)。',
+ liveCapabilities: '機能(即時適用 — スキル、ツール、MCP)',
+ editSoul: 'SOUL.md(人格 + エージェント間メッセージプロトコル)',
+ remoteCapabilitiesHint:
+ 'リモート機能には新しいデスクトップアプリが必要です。モデルと SOUL の変更は保存するまで適用されません。',
+ skillsEnabled: (enabled, total) => `スキル(${enabled}/${total} 有効)`,
+ toolsetsEnabled: (enabled, total) => `ツールセット(${enabled}/${total} 有効 — すべて解除すると既定値に戻ります)`,
+ mcpServers: 'MCP サーバー',
+ providerCustom: 'プロバイダー(カスタム)',
+ modelCustom: 'モデル(カスタム)',
+ backToDropdowns: '← 選択リストに戻る',
+ inheritLaunch: '継承(起動プロファイル)',
+ enterManually: '✏️ 手動入力…',
+ gatewayDefault: 'ゲートウェイの既定値',
+ modelNameExample: '例:モデル名',
+ modelSwitchFailed: 'モデルの切り替えに失敗しました',
+ newDescription:
+ '独自のメモリ、スキル、チャットを持つ名前付きの仲間です。他のエージェントとメッセージをやり取りできます。',
+ name: '名前',
+ title: '表示名',
+ description: '説明',
+ createOn: '作成先',
+ general: '一般',
+ capabilities: '機能',
+ skills: 'スキル',
+ tools: 'ツール',
+ cloneFrom: '複製元のプロファイル',
+ freshProfile: '新規プロファイル(同梱スキル)',
+ inheritedModel: '起動時のプロファイルから継承',
+ soul: 'SOUL.md(任意 — 生成された人格を置き換えます)',
+ shareKeys: 'メインプロファイルとキー・アカウントを共有',
+ shareKeysHint:
+ 'サブスクリプション、OAuth ログイン、API キーをコピーせず共有するため、トークン更新で互いに無効になりません。チェックを外すと独立したスナップショットをコピーします。',
+ createEmpty: '空のプロファイルを作成(同梱スキルを除外)',
+ nameTakenHint: 'その名前は使用済みです。機能を設定する前に別の名前を選んでください。',
+ nameFirstHint:
+ '先にボットに名前を付けてください。このタブを開くと下書きプロファイルが作成されます(キャンセルすると破棄されます)。',
+ newerDesktop: 'スキルには新しい Hermes Desktop が必要です。',
+ newerGateway: '機能カタログには新しいゲートウェイが必要です(Hermes 更新後に再起動してください)。',
+ emptySkillsHint: '「空のプロファイルを作成」が選択されているため、同梱スキルはインストールされません。',
+ defaultToolsHint: 'すべて選択するか、何も選択しない場合は、既定のツールセット動作を維持します。',
+ catalog: 'カタログ',
+ catalogInstalled: 'カタログ · インストール済み',
+ mcpHint:
+ '設定済みサーバーはメインプロファイルからコピーされます。カタログは同梱 MCP メニューです。API キーが必要な項目は先に設定を行います(認証情報はキー共有設定に従います)。',
+ creating: '作成中…',
+ createBot: 'ボットを作成',
+ auto: '自動',
+ autoHint: '自動 — 名前から決定',
+ unlock: 'ロック解除',
+ lockFace: '顔を固定',
+ lockedHint: '顔を固定しました。名前を変えても変化しません。',
+ unlockedHint: '顔は名前に合わせて変わります。',
+ noImageModel:
+ '画像モデルがありません。有効にした直後や Hermes 更新後の場合は、Ctrl+K →「ゲートウェイを再起動」で再起動してください。',
+ checkingImage: '画像バックエンドを確認中…',
+ chooseImage: '画像を選択…',
+ editDescription: (name, profile) => `${name}(${profile})の外観と役割。`,
+ nameTaken: name => `「${name}」というエージェントはすでに存在します。`,
+ nameTakenOn: (name, target) => `${target} には「${name}」というエージェントがすでに存在します。`,
+ currentConnection: name => `${name}(現在)`,
+ remoteHint: target =>
+ `エージェントは ${target} に作成され、接続先のボットとして一覧に表示されます。チャットはそのマシンに送られます。`,
+ cloneFromOn: target => `複製元のプロファイル(${target} 上)`,
+ catalogHint: source => `${source} のカタログです。未選択のスキルは作成後に無効になります。`,
+ sectionsFailed: sections => `一部の設定に失敗しました: ${sections}`,
+ updated: name => `${name} を更新しました`,
+ created: name => `ボット「${name}」を作成しました`,
+ createdOn: (name, target) => `${target} にボット「${name}」を作成しました`
+ },
roster: {
search: 'ボットとグループチャットを検索',
searchPlaceholder: 'ボットとグループチャットを検索…',
@@@ -989,7 -1324,72 +1328,73 @@@
}
const zh: BotsMessages = {
+ canonical: CANONICAL_GROUP_LOCALES.zh,
+ editor: {
+ fullConfigHint: '完整配置需要更新网关(更新 Hermes 后请重启网关)。',
+ liveCapabilities: '功能(立即生效 — 技能、工具、MCP)',
+ editSoul: 'SOUL.md(人格 + 智能体消息协议)',
+ remoteCapabilitiesHint: '远程功能需要更新桌面应用。模型和 SOUL 的更改会在保存后生效。',
+ skillsEnabled: (enabled, total) => `技能(已启用 ${enabled}/${total})`,
+ toolsetsEnabled: (enabled, total) => `工具集(已启用 ${enabled}/${total} — 全部取消勾选可恢复默认值)`,
+ mcpServers: 'MCP 服务器',
+ providerCustom: '提供商(自定义)',
+ modelCustom: '模型(自定义)',
+ backToDropdowns: '← 返回下拉选项',
+ inheritLaunch: '继承(启动配置文件)',
+ enterManually: '✏️ 手动输入…',
+ gatewayDefault: '网关默认值',
+ modelNameExample: '例如:模型名称',
+ modelSwitchFailed: '模型切换失败',
+ newDescription: '拥有独立记忆、技能和聊天的具名队友,可以与你的其他智能体互发消息。',
+ name: '名称',
+ title: '显示名称',
+ description: '描述',
+ createOn: '创建位置',
+ general: '常规',
+ capabilities: '能力',
+ skills: '技能',
+ tools: '工具',
+ cloneFrom: '从配置档案克隆',
+ freshProfile: '新配置档案(内置技能)',
+ inheritedModel: '继承启动时的配置档案',
+ soul: 'SOUL.md(可选,将替换生成的人格)',
+ shareKeys: '与主配置档案共享密钥和账户',
+ shareKeysHint:
+ '订阅、OAuth 登录和 API 密钥保持共享而非复制,令牌刷新不会使另一方失效。取消勾选则创建隔离的快照副本。',
+ createEmpty: '创建空配置(跳过内置技能)',
+ nameTakenHint: '此名称已被占用,请先选择其他名称再配置能力。',
+ nameFirstHint: '请先为机器人命名,打开此标签页时将创建草稿配置档案(取消时会丢弃)。',
+ newerDesktop: '技能功能需要更新的 Hermes Desktop。',
+ newerGateway: '能力目录需要更新的网关(更新 Hermes 后请重启网关)。',
+ emptySkillsHint: '已勾选“创建空配置”,不会安装内置技能。',
+ defaultToolsHint: '全部勾选或全部不选将保留默认工具集行为。',
+ catalog: '目录',
+ catalogInstalled: '目录 · 已安装',
+ mcpHint:
+ '已配置的服务器从主配置档案复制;目录条目来自内置 MCP 菜单。需要 API 密钥的条目先进行设置(凭据遵循共享密钥设置)。',
+ creating: '正在创建…',
+ createBot: '创建机器人',
+ auto: '自动',
+ autoHint: '自动 — 由名称决定',
+ unlock: '解锁',
+ lockFace: '锁定外观',
+ lockedHint: '外观已锁定,重命名不会改变外观。',
+ unlockedHint: '外观随名称变化。',
+ noImageModel: '没有可用的图像模型。如果刚启用模型或更新了 Hermes,请重启网关:Ctrl+K →“重启网关”。',
+ checkingImage: '正在检查图像后端…',
+ chooseImage: '选择图像…',
+ editDescription: (name, profile) => `${name}(${profile})的外观和职责。`,
+ nameTaken: name => `名为“${name}”的智能体已存在。`,
+ nameTakenOn: (name, target) => `${target} 上已存在名为“${name}”的智能体。`,
+ currentConnection: name => `${name}(当前)`,
+ remoteHint: target => `智能体将在 ${target} 上创建,并作为连接机器人显示在名册中。聊天将路由到该机器。`,
+ cloneFromOn: target => `从配置档案克隆(位于 ${target})`,
+ catalogHint: source => `目录来自 ${source},未勾选的技能将在创建后禁用。`,
+ sectionsFailed: sections => `部分设置失败:${sections}`,
+ updated: name => `已更新 ${name}`,
+ created: name => `已创建机器人“${name}”`,
+ createdOn: (name, target) => `已在 ${target} 上创建机器人“${name}”`
+ },
roster: {
search: '搜索机器人和群聊',
searchPlaceholder: '搜索机器人和群聊…',
@@@ -1292,7 -1737,72 +1742,73 @@@
}
const zhHant: BotsMessages = {
+ canonical: CANONICAL_GROUP_LOCALES['zh-hant'],
+ editor: {
+ fullConfigHint: '完整設定需要更新閘道(更新 Hermes 後請重新啟動閘道)。',
+ liveCapabilities: '功能(立即生效 — 技能、工具、MCP)',
+ editSoul: 'SOUL.md(人格 + 智慧代理訊息協定)',
+ remoteCapabilitiesHint: '遠端功能需要更新桌面應用程式。模型和 SOUL 的變更會在儲存後生效。',
+ skillsEnabled: (enabled, total) => `技能(已啟用 ${enabled}/${total})`,
+ toolsetsEnabled: (enabled, total) => `工具集(已啟用 ${enabled}/${total} — 全部取消勾選可還原預設值)`,
+ mcpServers: 'MCP 伺服器',
+ providerCustom: '供應商(自訂)',
+ modelCustom: '模型(自訂)',
+ backToDropdowns: '← 返回下拉選項',
+ inheritLaunch: '繼承(啟動設定檔)',
+ enterManually: '✏️ 手動輸入…',
+ gatewayDefault: '閘道預設值',
+ modelNameExample: '例如:模型名稱',
+ modelSwitchFailed: '模型切換失敗',
+ newDescription: '擁有獨立記憶、技能和聊天的具名隊友,可以與你的其他智慧代理互傳訊息。',
+ name: '名稱',
+ title: '顯示名稱',
+ description: '描述',
+ createOn: '建立位置',
+ general: '一般',
+ capabilities: '功能',
+ skills: '技能',
+ tools: '工具',
+ cloneFrom: '從設定檔複製',
+ freshProfile: '新設定檔(內建技能)',
+ inheritedModel: '繼承啟動時的設定檔',
+ soul: 'SOUL.md(選填,將取代產生的人格)',
+ shareKeys: '與主要設定檔共用金鑰和帳戶',
+ shareKeysHint:
+ '訂閱、OAuth 登入和 API 金鑰保持共用而非複製,權杖更新不會使另一方失效。取消勾選則建立隔離的快照副本。',
+ createEmpty: '建立空白設定(略過內建技能)',
+ nameTakenHint: '此名稱已被使用,請先選擇其他名稱再設定功能。',
+ nameFirstHint: '請先為機器人命名,開啟此分頁時將建立草稿設定檔(取消時會捨棄)。',
+ newerDesktop: '技能功能需要更新的 Hermes Desktop。',
+ newerGateway: '功能目錄需要更新的閘道(更新 Hermes 後請重新啟動閘道)。',
+ emptySkillsHint: '已勾選「建立空白設定」,不會安裝內建技能。',
+ defaultToolsHint: '全部勾選或全部不選將保留預設工具集行為。',
+ catalog: '目錄',
+ catalogInstalled: '目錄 · 已安裝',
+ mcpHint:
+ '已設定的伺服器從主要設定檔複製;目錄項目來自內建 MCP 選單。需要 API 金鑰的項目先進行設定(憑證遵循共用金鑰設定)。',
+ creating: '正在建立…',
+ createBot: '建立機器人',
+ auto: '自動',
+ autoHint: '自動 — 由名稱決定',
+ unlock: '解鎖',
+ lockFace: '鎖定外觀',
+ lockedHint: '外觀已鎖定,重新命名不會改變外觀。',
+ unlockedHint: '外觀隨名稱變化。',
+ noImageModel: '沒有可用的影像模型。如果剛啟用模型或更新了 Hermes,請重新啟動閘道:Ctrl+K →「重新啟動閘道」。',
+ checkingImage: '正在檢查影像後端…',
+ chooseImage: '選擇影像…',
+ editDescription: (name, profile) => `${name}(${profile})的外觀和職責。`,
+ nameTaken: name => `名為「${name}」的智慧代理已存在。`,
+ nameTakenOn: (name, target) => `${target} 上已存在名為「${name}」的智慧代理。`,
+ currentConnection: name => `${name}(目前)`,
+ remoteHint: target => `智慧代理將在 ${target} 上建立,並作為連線機器人顯示在名冊中。聊天將路由到該機器。`,
+ cloneFromOn: target => `從設定檔複製(位於 ${target})`,
+ catalogHint: source => `目錄來自 ${source},未勾選的技能將在建立後停用。`,
+ sectionsFailed: sections => `部分設定失敗:${sections}`,
+ updated: name => `已更新 ${name}`,
+ created: name => `已建立機器人「${name}」`,
+ createdOn: (name, target) => `已在 ${target} 上建立機器人「${name}」`
+ },
roster: {
search: '搜尋機器人和群組聊天',
searchPlaceholder: '搜尋機器人和群組聊天…',
diff --cc gateway/run_shutdown.py
index 6d7697847e7,d555a046160..d70c2b15f99
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@@ -2039,12 -2037,14 +2039,12 @@@ class GatewayShutdownMixin
logger.info("Shutdown phase: SessionDB close done at +%.2fs", ctx.elapsed())
async def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:
- """PID/lock release, clean-shutdown marker, restart markers, terminal runtime status."""
+ """Clean-shutdown marker, restart markers, terminal runtime status; process bootstrap
+ releases PID/lock ownership after the writer drain."""
from gateway.run import _hermes_home, _planned_restart_notification_path, _shutdown_gateway_health_export
from utils import atomic_json_write
- # Clean-shutdown marker skips suspend_recently_active() next boot; a timed-out drain left
- # half-finished sessions, so no marker — the next startup suspends them.
- from gateway.status import remove_pid_file, release_gateway_runtime_lock
- remove_pid_file()
- release_gateway_runtime_lock()
+ # Clean-shutdown marker skips crash-turn recovery next boot; a timed-out drain left
+ # half-finished sessions, so no marker — the next startup recovers their turn markers.
if not ctx.timed_out:
with suppress(Exception):
(_hermes_home / ".clean_shutdown").touch()
diff --cc gateway/run_startup.py
index a9eda264426,743335d9e6b..b64d0969f1b
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@@ -1054,13 -1108,8 +1121,13 @@@ class GatewayStartupMixin
recovered += self._recover_secondary_process_checkpoints(process_registry)
if recovered:
logger.info("Recovered %s background process(es) from previous run", recovered)
+ # The gateway owns delegation state: replay durable completions the previous
+ # process never delivered. Explicit here, never at tools import (clients).
+ with _log_suppressed(logging.WARNING, "Could not restore async delegation completions: %s"):
+ from tools.async_delegation import restore_undelivered_completions
+ restore_undelivered_completions(process_registry.completion_queue)
- # Recover sessions active at last exit (exact turn markers + 120s recency fallback for
- # marker-less older turns). SKIP after a clean exit — the previous process already drained.
+ # Recover the turns the last process left marked (in flight, or reply not yet ledgered).
+ # SKIP after a clean exit — the previous process already drained.
_clean_marker = _hermes_home / ".clean_shutdown"
if _clean_marker.exists():
logger.info("Previous gateway exited cleanly — skipping session suspension")
diff --cc gateway/run_turn_persistence.py
index 7b0f0bf26fc,00000000000..ce9b6509e31
mode 100644,000000..100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@@ -1,573 -1,0 +1,573 @@@
+"""Gateway turn persistence 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.turn_failure_copy import FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE
++from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE
+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.warning_notifications import diagnostic_wake_muted
+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")
+
+
+class GatewayTurnPersistenceMixin:
+ async def _hmwa_shape_agent_response(
+ self, agent_result, source, history, session_entry, session_key,
+ _quick_key, run_generation, _run_start_session_id, _platform_name, _msg_start_time,
+ persist_user_display_kind: Optional[str] = None,
+ ):
+ """Turn the raw agent result into the outbound text: sentinel/silence handling, response
+ logging, resume-pending clear, empty-response normalization, and identity-guarded
+ post-compression session_id propagation. Returns
+ ``(response, _intentional_silence, agent_messages)``."""
+ from gateway.run import (
+ _is_gateway_hidden_reasoning_incomplete_turn, _normalize_empty_agent_response,
+ _sanitize_gateway_final_response, _should_clear_resume_pending_after_turn,
+ )
+ response = agent_result.get("final_response") or ""
+ # Hidden-reasoning-only retry exhaustion: the loop's sentinel text doubles as final_response
+ # and would be delivered verbatim (peer agents would ingest it as a completed turn).
+ if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):
+ response = ""
+ _intentional_silence = self._is_intentional_silence(agent_result, response)
+ # A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that
+ # opened the chain: an internal follow-up may go silent, a human one must not.
+ from gateway.response_filters import is_machinery_display_kind
+ from gateway.run_turn import _UNEXPECTED_SILENCE_REPLY
+ _silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)
+ if _intentional_silence and not is_machinery_display_kind(_silence_kind):
+ logger.warning(
+ "silence marker rejected on a user turn: platform=%s chat=%s",
+ _platform_name, source.chat_id or "unknown",
+ )
+ _intentional_silence = False
+ response = _UNEXPECTED_SILENCE_REPLY
+
+ # "(empty)" = the model produced no visible content after exhausting all retries. One
+ # text with the CLI explainer and the desktop (agent/turn_explainers.py) so the user
+ # reads the same words on every surface.
+ if response == "(empty)" and not _intentional_silence:
+ from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION
+
+ _model = str(agent_result.get("model") or "").strip() or "The model"
+ response = "⚠️ " + EMPTY_RESPONSE_EXPLANATION.format(model=_model)
+ agent_messages = agent_result.get("messages", [])
+ logger.info(
+ "response ready: platform=%s chat=%s session=%s time=%.1fs api_calls=%d response=%d chars",
+ _platform_name, source.chat_id or "unknown", session_key or "unknown",
+ time.time() - _msg_start_time, agent_result.get("api_calls", 0), len(response),
+ )
+
+ # Successful turn: clear the consecutive-restart stuck-loop counter and resume_pending (set
+ # by drain-timeout shutdown) so later messages don't get the restart-interruption note.
+ if session_key and _should_clear_resume_pending_after_turn(agent_result):
+ await self._clear_restart_failure_count(session_key)
+ try:
+ await self.async_session_store.clear_resume_pending(session_key)
+ except Exception as _e:
+ logger.debug("clear_resume_pending failed for %s: %s", session_key, _e)
+
+ # Normalize empty responses: surface errors, partial failures, and work-without-text.
+ # Fix for #18765.
+ if not _intentional_silence:
+ response = _normalize_empty_agent_response(agent_result, response, history_len=len(history))
+ response = _sanitize_gateway_final_response(source.platform, response)
+
+ # The agent thread already updated the contextvar; propagate to SessionEntry + _save() only
+ # if the binding still points at the session this run was launched against.
+ if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:
+ if session_entry.session_id == _run_start_session_id:
+ session_entry.session_id = agent_result["session_id"]
+ # The held turn lease follows the rotation (persistence writes to the NEW id).
+ self._rebind_turn_lease(_quick_key, run_generation, session_entry.session_id)
+ await self.async_session_store._save()
+ await self.async_session_store._record_gateway_session_peer(
+ session_entry.session_id, session_key, source,
+ )
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="agent-result-compression",
+ )
+ else:
+ logger.info(
+ "Skipping agent-result session split sync for %s because the session binding "
+ "moved from %s to %s before compression finished",
+ session_key or "?", _run_start_session_id, session_entry.session_id,
+ )
+ return response, _intentional_silence, agent_messages
+
+ # reasoning_style → (header line, per-line quote prefix for blank / non-blank lines)
+ _REASONING_QUOTE_STYLES = {
+ "subtext": ("-# 💭 Reasoning", "-# ", "-#"), "blockquote": ("> 💭 **Reasoning:**", "> ", ">")
+ }
+
+ def _hmwa_prepend_reasoning(self, agent_result, response, source, _intentional_silence):
+ """Prepend the last reasoning block when show_reasoning is on for this platform. Mattermost
+ requires an explicit per-platform opt-in (scratch text, not final-answer content)."""
+ from gateway.run import _load_gateway_config, _platform_config_key, _resolve_gateway_display_bool
+ try:
+ _show_reasoning_effective = _resolve_gateway_display_bool(
+ _load_gateway_config(), _platform_config_key(source.platform), "show_reasoning",
+ default=bool(getattr(self, "_show_reasoning", False)), platform=source.platform,
+ require_platform_override_for={Platform.MATTERMOST},
+ )
+ except Exception:
+ _show_reasoning_effective = (
+ False if source.platform == Platform.MATTERMOST else getattr(self, "_show_reasoning", False)
+ )
+ last_reasoning = agent_result.get("last_reasoning")
+ if not (_show_reasoning_effective and response and not _intentional_silence and last_reasoning):
+ return response
+ from gateway.stream_consumer_fences import escape_code_fences_for_display
+ # Collapse long reasoning to keep messages readable
+ lines = last_reasoning.strip().splitlines()
+ if len(lines) > 15:
+ display_reasoning = "\n".join(lines[:15]) + f"\n_... ({len(lines) - 15} more lines)_"
+ else:
+ display_reasoning = last_reasoning.strip()
+ # Per-platform render style: Discord defaults to "-# " subtext, others keep the code block.
+ try:
+ from gateway.display_config import resolve_display_setting
+ _reasoning_style = resolve_display_setting(
+ _load_gateway_config(), _platform_config_key(source.platform), "reasoning_style", "code",
+ )
+ except Exception:
+ _reasoning_style = "code"
+ _quote = self._REASONING_QUOTE_STYLES.get(_reasoning_style)
+ if _quote:
+ header, prefix, empty = _quote
+ _quoted = "\n".join(f"{prefix}{ln}" if ln else empty for ln in display_reasoning.splitlines())
+ return f"{header}\n{_quoted}\n\n{response}"
+ # Escape ``` inside reasoning so inner fences don't break the outer code block.
+ display_reasoning = escape_code_fences_for_display(display_reasoning)
+ return f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"
+
+ def _hmwa_runtime_footer_line(self, agent_result, source, _turn_seconds):
+ """Runtime-metadata footer for the FINAL message of the turn; off by default
+ (display.runtime_footer.enabled=false)."""
+ from gateway.run import _load_gateway_config, _platform_config_key, _terminal_scope_cwd
+ try:
+ from gateway.runtime_footer import build_footer_line as _bfl
+ return _bfl(
+ user_config=_load_gateway_config(),
+ platform_key=_platform_config_key(source.platform), model=agent_result.get("model"),
+ context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,
+ context_length=agent_result.get("context_length") or None,
+ cwd=_terminal_scope_cwd(""), turn_seconds=_turn_seconds,
+ requested_model=agent_result.get("requested_model"),
+ served_model=agent_result.get("served_model"),
+ )
+ except Exception as _footer_err:
+ logger.debug("runtime_footer build failed: %s", _footer_err)
+ return ""
+
+ async def _hmwa_post_turn_hooks(self, hook_ctx, agent_result, response):
+ """agent:end hook, process-watcher scheduling, and watch-notification drain."""
+ await self.hooks.emit("agent:end", {
+ **hook_ctx, "response": (response or "")[:500], "model": agent_result.get("model", ""),
+ "provider": agent_result.get("provider", ""),
+ })
+
+ # Pending process watchers (check_interval on background processes)
+ try:
+ from tools.process_registry import process_registry
+ # Detach the batch atomically (reassign, not clear()) so concurrent appends aren't dropped.
+ watchers = process_registry.pending_watchers
+ process_registry.pending_watchers = []
+ for i, watcher in enumerate(watchers):
+ asyncio.create_task(self._run_process_watcher(watcher))
+ if i % 100 == 99:
+ await asyncio.sleep(0)
+ except Exception as e:
+ logger.error("Process watcher setup error: %s", e)
+
+ # Drain watch notifications that arrived during the run; the queue also carries process /
+ # async-delegation completions owned elsewhere — inject only watch-type events.
+ try:
+ from tools.process_registry import process_registry as _pr
+ await self._drain_watch_notifications(_pr.completion_queue)
+ except Exception as e:
+ logger.debug("Watch queue drain error: %s", e)
+
+ # One owner for the boundary copy (agent/turn_failure_copy.py): the core closer in
+ # agent/conversation_loop.py writes the same row on the paths that never reach this layer.
+
+ def _hmwa_add_failed_turn_notice(self, response, notice):
+ """Make failed-turn delivery explicit without replacing the provider-specific guidance."""
+ response = str(response or "").strip()
+ return f"{response}\n\n{notice}" if response else notice
+
+ def _hmwa_failed_turn_notice(self, agent_result):
+ """Choose retry guidance without assuming completed tool effects can be repeated safely."""
+ from gateway.media_repair import _current_turn_messages
+ # Compression during the failed turn can move the slice boundary; the shared helper falls
+ # back to the last user row so tool evidence is not silently dropped.
+ turn_messages = _current_turn_messages(
+ agent_result.get("messages", []) or [], agent_result.get("history_offset", 0),
+ )
+ if any(
+ message.get("role") == "tool"
+ or (message.get("role") == "assistant" and message.get("tool_calls"))
+ for message in turn_messages
+ ):
+ return PARTIAL_FAILED_TURN_NOTICE
+ return FAILED_TURN_NOTICE
+
+ async def _hmwa_close_failed_turn(self, session_id, notice):
+ """Append the gateway-owned assistant boundary iff the durable tail is an open user row.
+
+ The tail, not "did the gateway write the user row", is the key: on the primary path the
+ agent's turn-start flush already persisted the row (so the platform-id dedupe skips the
+ gateway write), and a platform redelivery of an already-closed turn must not stack a
+ second assistant row."""
+ if await self.async_session_store.transcript_tail_role(session_id) != "user":
+ return
+ await self.async_session_store.append_to_transcript(session_id, {
- "role": "assistant", "content": notice, "timestamp": time.time(),
++ "role": "assistant", "content": notice, "timestamp": time.time(), "display_kind": FAILED_TURN_DISPLAY_KIND,
+ })
+
+ def _hmwa_classify_turn_failure(self, agent_result, history, session_entry):
+ """Classify a finished turn for transcript persistence. Returns
+ ``(agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure)``.
+
+ Context-overflow failures must NOT persist the user message (session would grow and
+ reproduce the failure forever); transient failures (429/timeout/5xx) DO."""
+ from gateway.run import _is_gateway_hidden_reasoning_incomplete_turn
+ # Save the full conversation to the transcript, including tool calls. This preserves the complete
+ # agent loop (tool_calls, tool results, intermediate reasoning) so sessions can be resumed with full
+ # context and transcripts are useful for debugging and training data. IMPORTANT: For
+ # context-overflow failures (compression exhausted, generic 400 on large sessions) we must NOT
+ # persist the user's message — doing so would grow the session further and cause the same failure on
+ # the next attempt, an infinite loop. (#1630, #9893) Transient failures (429, timeout, connection
+ # error, provider 5xx) are different: the session is not oversized, and silently dropping the user
+ # message causes severe context loss on retry — the agent forgets what was just asked. Persist the
+ # user turn so the conversation is preserved. (#7100)
+ agent_failed_early = bool(agent_result.get("failed"))
+ hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(agent_result)
+ from gateway.run_turn import is_context_overflow_failure_result
+ is_context_overflow_failure = is_context_overflow_failure_result(agent_result, len(history))
+ if is_context_overflow_failure:
+ logger.info(
+ "Skipping transcript persistence for context-overflow "
+ "failure in session %s to prevent session growth loop.", session_entry.session_id,
+ )
+ elif agent_failed_early:
+ logger.info(
+ "Transient agent failure in session %s — persisting user "
+ "message so conversation context is preserved on retry.", session_entry.session_id,
+ )
+ elif hidden_reasoning_incomplete:
+ logger.warning(
+ "Suppressing hidden-reasoning-only incomplete gateway turn for session %s: %s",
+ session_entry.session_id, agent_result.get("error", "processing incomplete"),
+ )
+ return agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure
+
+ async def _hmwa_compression_exhaustion_reset(
+ self, agent_result, response, session_entry, session_key, source,
+ ):
+ """Auto-reset a permanently oversized session so the next message starts fresh instead of
+ replaying the oversized context forever. Never on a lock-contended defer — that is the
+ OPPOSITE case (a concurrent path holds the lock and is shrinking it). Returns
+ ``(response, session_entry)``."""
+ # When compression is exhausted, the session is permanently too large to process. (#9893) Never wipe
+ # the session for that — retry-next-message semantics apply (#69870 lock-skip consumer; salvaged
+ # from #49874).
+ if agent_result.get("compression_deferred"):
+ logger.info(
+ "Compression deferred for session %s — the compression "
+ "lock is held by a concurrent compressor. Keeping the "
+ "session intact; the next message retries normally.",
+ session_entry.session_id if session_entry else "?",
+ )
+ elif agent_result.get("compression_exhausted") and session_entry and session_key:
+ logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)
+ new_entry = await self.async_session_store.reset_session(session_key)
+ self._evict_cached_agent(session_key)
+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.
+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")
+ if new_entry is not None:
+ # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk
+ # switches the next message back onto the bloated child and re-triggers exhaustion
+ # forever. No-op on non-topic lanes.
+ # Compression rotated session_entry.session_id to the oversized compressed child earlier
+ # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,
+ # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,
+ # but without re-syncing the binding the next inbound message in this topic gets
+ # switch_session'd back onto the bloated child by the binding-heal walk, reloads the
+ # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression
+ # of the #9893/#10063 auto-reset).
+ session_entry = new_entry
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",
+ )
+ response = (response or "") + (
+ "\n\n🔄 Session auto-reset — the conversation exceeded the maximum context size and "
+ "could not be compressed further. Your next message will start a fresh session."
+ )
+ return response, session_entry
+
+ @staticmethod
+ def _hmwa_user_transcript_entry(event, prepared, ts):
+ """Transcript row for the inbound user turn (clean text + event time when captured)."""
+ # Transient failure (429/timeout/5xx): persist only the user message so the next message can load a
+ # transcript that reflects what was said. Skip the assistant error text since it's a
+ # gateway-generated hint, not model output. Hidden- reasoning-only incomplete turns follow the same
+ # persistence rule so peer-agent channels don't ingest them as completed assistant turns. (#7100,
+ # #51628)
+ _user_entry = {
+ "role": "user",
+ "content": (
+ prepared.persist_user_message if prepared.persist_user_message is not None
+ else prepared.message_text
+ ),
+ "timestamp": prepared.persist_user_timestamp if prepared.persist_user_timestamp is not None else ts,
+ }
+ if prepared.persist_user_display_kind:
+ _user_entry["display_kind"] = prepared.persist_user_display_kind
+ if prepared.persistence_owner:
+ _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}
+ if getattr(event, "message_id", None):
+ _user_entry["message_id"] = str(event.message_id)
+ return _user_entry
+
+ async def _hmwa_persist_turn_transcript(
+ self, *, event, source, session_entry, session_key, agent_result, agent_messages,
+ prepared, response, agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure,
+ ):
+ """Persist this turn to the transcript (session_meta on first turn, user-only on transient
+ failure, nothing on context overflow), update last_prompt_tokens, and re-baseline the
+ cached agent's message count."""
+ from gateway.run import _resolve_gateway_model
+ ts = time.time() # Unix epoch float — consistent with DB storage
+ store = self.async_session_store
+ sid = session_entry.session_id
+ history = prepared.history
+ # The agent already persisted this turn's rows (codex app-server reports agent_persisted=True
+ # too); skip the DB write. Default = a session DB exists; non-persisting runtimes pass False.
+ # The agent already persisted these messages to SQLite via _flush_messages_to_session_db(), so skip
+ # the DB write here to prevent the duplicate-write bug (#860 / #42039). This holds for the codex
+ # app-server runtime too: although it early-returns and bypasses conversation_loop's per-step
+ # flushes, it flushes its own projected assistant/tool messages before returning and reports
+ # agent_persisted=True (see agent/codex_runtime.py). Reading the flag (default = self._session_db is
+ # not None) keeps the persistence contract explicit and lets any future non-persisting runtime opt
+ # into a gateway-side write by returning False.
+ agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)
+ _user_row = self._hmwa_user_transcript_entry(event, prepared, ts)
+
+ if is_context_overflow_failure:
+ pass # Skip all transcript writes — don't grow a broken session
+ else:
+ if not history:
+ # Fresh session: the tool definitions (as sent in the API request) make the transcript
+ # self-describing.
+ await store.append_to_transcript(sid, {
+ "role": "session_meta",
+ "tools": agent_result.get("tools", []) or [],
+ "model": _resolve_gateway_model(),
+ "platform": source.platform.value if source.platform else "",
+ "timestamp": ts,
+ })
+ if agent_failed_early or hidden_reasoning_incomplete:
+ # Transient failure / hidden-reasoning incomplete: persist only the user message (the
+ # assistant error text is a gateway hint, not model output). Dedupe on platform
+ # message_id (Telegram retries after transient failures).
+ if event.message_id and await store.has_platform_message_id(sid, str(event.message_id)):
+ logger.info(
+ "Skipping duplicate user turn (message_id=%s) in session %s",
+ event.message_id, sid,
+ )
+ else:
+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)
+ # Close the failed turn: a user-only tail lets alternation repair merge this request
+ # into an unrelated future message and replay stale side effects (#107070).
+ await self._hmwa_close_failed_turn(sid, self._hmwa_failed_turn_notice(agent_result))
+ else:
+ # Only the NEW messages: history_offset (what the agent saw), not len(history), which
+ # counts session_meta entries stripped before the agent saw them.
+ history_len = agent_result.get("history_offset", len(history))
+ new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []
+ if not new_messages:
+ # Edge case: fall back to simple user/assistant rows.
+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)
+ if response:
+ await store.append_to_transcript(
+ sid, {"role": "assistant", "content": response, "timestamp": ts},
+ skip_db=agent_persisted,
+ )
+ else:
+ # Attach the inbound platform message_id to the first user entry so platform-level
+ # quote-resolution (e.g. Yuanbao) can find earlier @bot messages by original id.
+ _user_msg_id_attached = False
+ for msg in new_messages:
+ if msg.get("role") == "system":
+ continue # rebuilt each run
+ entry = {**msg, "timestamp": ts}
+ if (
+ not _user_msg_id_attached
+ and msg.get("role") == "user"
+ and event.message_id
+ and "message_id" not in entry
+ ):
+ entry["message_id"] = str(event.message_id)
+ _user_msg_id_attached = True
+ await store.append_to_transcript(sid, entry, skip_db=agent_persisted)
+
+ # The agent persists token counts/model itself; keep only last_prompt_tokens for hygiene.
+ await store.update_session(
+ session_entry.session_key, last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),
+ touch_activity=not bool(getattr(event, "internal", False)),
+ )
+
+ # Re-baseline the cached agent's message_count now that ALL of this turn's writes are done:
+ # the coherence guard snapshots at agent-BUILD time, so our own writes would otherwise
+ # trigger a rebuild next turn (destroying prompt caching).
+ await self._refresh_agent_cache_message_count(session_key, sid)
+
+ async def _hmwa_deliver_turn_response(
+ self, event, source, session_entry, session_key, run_generation,
+ agent_result, agent_messages, response, _footer_line, _intentional_silence,
+ ):
+ """Final delivery decisions: intentional silence, voice reply, streamed-turn media/footer.
+ Returns the text for the adapter to send, or ``None`` when already delivered."""
+ if diagnostic_wake_muted(event):
+ return None
+ # Intentional silence is a delivery decision: the [SILENT] turn stays persisted (alternation).
+ if _intentional_silence:
+ logger.info("Suppressing intentional silence marker for session %s", session_entry.session_id)
+ response = ""
+
+ adapter = self._delivery_adapter_for(source)
+ # Auto voice reply (TTS audio before the text) unless streaming TTS already delivered audio.
+ _streaming_tts_done = adapter is not None and bool(
+ getattr(adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation)
+ )
+ if not _streaming_tts_done and self._should_send_voice_reply(
+ event, response, agent_messages, already_sent=bool(agent_result.get("already_sent")),
+ ):
+ await self._send_voice_reply(event, response)
+
+ # Streamed responses still need MEDIA: files delivered (chunks carry the tags verbatim). Never
+ # skip when the agent failed: the error text is new content streaming didn't show.
+ if agent_result.get("already_sent") and not agent_result.get("failed"):
+ # The queued-follow-up lane uploads this response's attachments itself; re-scanning here
+ # would upload every file a second time.
+ if response and adapter and not agent_result.get("media_already_delivered"):
+ await self._deliver_media_from_response(response, event, adapter)
+ # Streaming delivered the body, but the footer was held back (`not already_sent` gate).
+ if _footer_line and adapter:
+ try:
+ await adapter.send(source.chat_id, _footer_line, metadata=self._event_thread_metadata(event, source))
+ except Exception as _e:
+ logger.debug("trailing footer send failed: %s", _e)
+ # Return None so the body isn't sent twice; stash the delivered text on the event for the
+ # /loop and /goal hooks that read the return value.
+ with suppress(Exception):
+ event._streamed_final_response = str(response or "")
+ return None
+
+ return response
+
+ # Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own
+ # sign-in, `{relogin}` the profile-aware host equivalent, filled from the turn's agent provider).
+ _STATUS_HINTS = {
+ 401: (" Your sign-in to the AI model service has expired or the API key is wrong. "
+ "Use /login here, or run `{relogin}` on the host."),
+ 402: " Your AI model service balance or quota is used up. Top it up on the service's website, or use /model to switch models.",
+ 529: " The AI model service is temporarily overloaded. Wait a moment, then use /retry.",
+ }
+
+ async def _hmwa_agent_error_reply(self, e, event, source, session_entry, session_key, prepared):
+ """``except Exception`` body of the agent turn: stop typing, log, persist the inbound user
+ turn once, and build the sanitized user-facing error reply."""
+ # Retain Slack thread/workspace routing so a failed turn cannot leave its status visible.
+ await self._hmwa_stop_typing_for_turn(event, source)
+ logger.exception("Agent error in session %s", session_key)
+ status_code = getattr(e, "status_code", None)
+ if status_code in {400, 500} and len(prepared.history) > 50:
+ # Context overflow / payload too large: a deterministic rejection (#107567), and the same
+ # no-grow rule as the persist path (#1630) — nothing is written into an oversized session.
+ from gateway.run import _CONTEXT_OVERFLOW_REPLY
+ return _CONTEXT_OVERFLOW_REPLY
+ # Replay can coalesce inputs; only this input's durable marker establishes ownership.
+ try:
+ if prepared.message_text is not None and session_entry is not None:
+ _owned = await self.async_session_store.has_input_owner(
+ prepared.persistence_session_id, prepared.persistence_owner,
+ )
+ if not _owned:
+ await self.async_session_store.append_to_transcript(
+ session_entry.session_id, self._hmwa_user_transcript_entry(event, prepared, time.time()),
+ )
+ # Tool effects are unknown after an exception.
+ await self._hmwa_close_failed_turn(session_entry.session_id, PARTIAL_FAILED_TURN_NOTICE)
+ except Exception:
+ logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)
+ # Never expose raw exception types/messages to end users (info-leakage risk).
+ status_hint = self._STATUS_HINTS.get(status_code, "")
+ if status_code == 401:
+ from agent.turn_failure_copy import relogin_command_hint
+
+ _turn_agent = getattr(self._session_state(session_key).turn, "agent", None)
+ status_hint = status_hint.format(relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))
+ elif status_code == 429:
+ # Plan usage limit (resets on a schedule) vs a transient rate limit
+ _err_json = {}
+ with suppress(Exception):
+ _err_json = e.response.json().get("error", {})
+ if not isinstance(_err_json, dict):
+ _err_json = {}
+ _resets_in = _err_json.get("resets_in_seconds")
+ if _err_json.get("type") != "usage_limit_reached":
+ status_hint = " You are being rate-limited. Please wait a moment and try again."
+ elif _resets_in and _resets_in > 0:
+ import math
+ status_hint = f" Your plan's usage limit has been reached. It resets in ~{math.ceil(_resets_in / 3600)}h."
+ else:
+ status_hint = " Your plan's usage limit has been reached. Please wait until it resets."
+ elif status_code == 400:
+ status_hint = " The AI model service rejected the request."
+ return self._hmwa_add_failed_turn_notice(
+ f"⚠️ Something went wrong and I couldn't finish this reply.{status_hint}\n"
+ "Use /retry to try again, or /new to start a fresh conversation. "
+ "Technical details are in the gateway log (`hermes logs`).",
+ PARTIAL_FAILED_TURN_NOTICE,
+ )
+
+ def _hmwa_discard_stale_result(self, source, _quick_key, run_generation):
+ """A newer run generation superseded this turn: drop its deferred post-delivery callback."""
+ logger.info(
+ "Discarding stale agent result for %s — generation %d is no longer current",
+ _quick_key or "?", run_generation,
+ )
+ self._pop_post_delivery_callback(self._delivery_adapter_for(source), _quick_key, run_generation)
diff --cc tests/gateway/test_local_session_recovery.py
index 9583a6de47f,00000000000..297e2b637ce
mode 100644,000000..100644
--- a/tests/gateway/test_local_session_recovery.py
+++ b/tests/gateway/test_local_session_recovery.py
@@@ -1,130 -1,0 +1,99 @@@
+"""Local creation is durable before publication and restart never replays a claim."""
+import json
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_local_create_receipt_survives_cold_authority_atomically(tmp_path, monkeypatch):
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+ from gateway import run
+ from hermes_state_runtime import RuntimeStoreError
+
+ config = {'platform_toolsets': {'cli': []}}
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: config)
+ def runner():
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ return SimpleNamespace(session_store=store, _session_db=store._db,
+ adapters={}, _draining=False)
+ first = runner()
+ authority = await initialize_session_authority(first, profile_id='fixture', instance_id='first')
+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read'}), 'socket')
+ params = {'request_id': 'retry', 'source': 'gui', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []}
+ ref = create_local_session(authority, actor, params)
+ policy = first.adapters[Platform.LOCAL].policies[authority.sessions[ref.session_id].source.chat_id]
+ second = runner()
+ cold = await initialize_session_authority(second, profile_id='fixture', instance_id='second')
+ assert ref.session_id in cold.sessions, 'durable creation was lost with process-local registry'
+ config['platform_toolsets']['cli'] = ['terminal']
+ assert create_local_session(cold, actor, params) == ref
+ assert second.adapters[Platform.LOCAL].policies[cold.sessions[ref.session_id].source.chat_id] == policy
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ create_local_session(cold, actor, {**params, 'source': 'tui'})
+ foreign = Principal('other', 'fixture', actor.capabilities, 'other-socket')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ await cold.resolve(foreign, ref)
+
+ db = cold.db
+ write = db._execute_write
+ def abort(callback, **kwargs):
+ def fail(conn):
+ callback(conn)
+ raise RuntimeError('injected transaction abort')
+ return write(fail, **kwargs)
+ before = db.session_count()
+ monkeypatch.setattr(db, '_execute_write', abort)
+ with pytest.raises(RuntimeError, match='injected transaction abort'):
+ create_local_session(cold, actor, {**params, 'request_id': 'aborted'})
+ monkeypatch.setattr(db, '_execute_write', write)
+ assert db.session_count() == before
+ assert set(cold.sessions) == {ref.session_id}
+ with db._read_ctx() as conn:
+ policies = conn.execute("SELECT value FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%'").fetchall()
+ assert len(policies) == 1
+ assert json.loads(policies[0][0])['principal_id'] == actor.subject
+ from hermes_state_runtime import admit_session_input, list_session_admissions
+ admit_session_input(db, epoch=cold.epoch, principal_id=actor.subject,
+ session_id=ref.session_id, request_id='preclaim', payload={'text': 'never run'})
+ db._write_sql('UPDATE state_meta SET value=? WHERE key=?',
+ ('{}', 'gateway.local_policy.v1:' + ref.session_id))
+ await cold._drain(ref)
+ assert list_session_admissions(db, session_id=ref.session_id, pending_only=False)[0]['status'] == 'queued'
+
+
+def test_real_daemon_recovers_only_authorized_never_started_local_work(tmp_path):
+ from tests.gateway.fixtures.local_recovery_probe import probe
+ print(json.dumps(probe(tmp_path)))
+
+
- @pytest.mark.asyncio
- async def test_local_entry_timestamps_keep_fallback_recovery_sweeping_other_routes(tmp_path, monkeypatch):
- """A canonical local entry must not abort the naive-cutoff recovery sweep that marks
- a recent marker-less messaging route ``resume_pending``."""
- from gateway.config import GatewayConfig, Platform
- from gateway.session import SessionSource, SessionStore
- from gateway.session_authority import initialize_session_authority
- from gateway.session_contract import Principal
- from gateway.session_local import create_local_session
- from gateway import run
-
- monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
- store = SessionStore(tmp_path / 'sessions', GatewayConfig())
- runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)
- authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='first')
- actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read'}), 'socket')
- ref = create_local_session(authority, actor, {'request_id': 'r', 'source': 'gui', 'cwd': str(tmp_path),
- 'model': 'frozen', 'toolsets': []})
- from gateway.session_api import bind_api_session
- bind_api_session(authority, 'api-owner')
- telegram = SessionSource(platform=Platform.TELEGRAM, chat_id='7', user_id='7', chat_type='dm')
- entry = store.get_or_create_session(telegram)
- assert not entry.resume_pending
- # Cold store: only the durable index feeds the sweep.
- cold = SessionStore(tmp_path / 'sessions', GatewayConfig())
- assert cold.suspend_recently_active(120) >= 1
- assert cold.lookup_by_session_key(entry.session_key).resume_pending
- # The canonical local route recovers through its durable FIFO, not the legacy marker.
- assert not cold.lookup_by_session_key(authority.sessions[ref.session_id].route).resume_pending
-
-
+def test_messaging_session_history_follows_the_compression_tip(tmp_path, monkeypatch):
+ """The authority keeps a messaging session's admission identity at the compression root,
+ but attach/resume history must come from the current physical transcript."""
+ from gateway.config import Platform
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from gateway.session_contract import SessionRef
+ from gateway.session_local_recovery import local_history
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('root', source='telegram', session_key='agent:telegram:dm:1')
+ db.append_message('root', 'user', 'BEFORE_COMPRESSION')
+ assert db.try_acquire_compression_lock('root', 'holder')
+ db.publish_compression_child(parent_session_id='root', child_session_id='child', source='telegram',
+ messages=[{'role': 'user', 'content': 'SUMMARY'}], compression_lock_holder='holder')
+ db.append_message('child', 'user', 'AFTER_COMPRESSION')
+ authority = SessionAuthority(SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False)),
+ profile_id='owned', instance_id='current', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='current'))
+ source = SimpleNamespace(platform=Platform.TELEGRAM, user_id='human')
+ authority.sessions['root'] = LiveSession(source, 'agent:telegram:dm:1')
+ contents = [m['content'] for m in local_history(authority, SessionRef('owned', 'root'))]
+ assert 'AFTER_COMPRESSION' in contents
+ assert 'BEFORE_COMPRESSION' not in contents
diff --cc tui_gateway/agent_factory.py
index 7fb49ef72c7,00000000000..bc187a491c7
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,632 -1,0 +1,633 @@@
+"""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
+
+
+# Bare billing buckets are not routable provider identities; restoring one as a session provider override
+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).
+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default
+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully
+# routable provider with its own API key and base_url. Sessions that used OpenRouter store
+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom
+# endpoint), which is the wrong provider for the stored model. See #57588.
+
+
+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 = {}
+ field = lambda k: str(model_config.get(k) or "").strip()
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which
+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.
+ provider = field("provider")
+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()
+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
+ provider = billing_provider
+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")
+ 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)
+
+
+_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}
+
+
+def _load_service_tier() -> str | None:
+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()
+ return _SERVICE_TIER_ALIASES.get(raw)
+
+
+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).
+ ``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)."""
- return {"project", "desktop_ui"} if platform == "desktop" else {"project"}
++ from toolsets import CLIENT_SURFACE_TOOLSETS
++ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}
+
+
+def _with_session_toolsets(selection, platform: str | None) -> list[str]:
+ """*selection* plus what the session carries whatever its config says (the client surface's
+ toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written
+ profile.yaml under the session's home override), minus toolsets reserved for another role."""
+ from toolsets import profile_role_toolsets
+ granted, denied = profile_role_toolsets()
+ surface = _gui_surface_toolsets(platform) if platform is not None else set()
+ kept = [name for name in selection if name not in denied]
+ return [*kept, *sorted((surface | granted) - set(kept))]
+
+
+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."""
+ 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:
+ 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 but never strips the profile's own role toolsets.
+ return resolved if resolved is None else _with_session_toolsets(resolved, None)
+ 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
+ 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)
+ return sorted(_with_session_toolsets(enabled, session_platform)) if enabled else 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 _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 _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI, not optional chrome: Desktop renders clarify / connection cards from the tool-call part."""
+ return name in ("clarify", "manage_connections", "setup_mcp")
+
+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.
+ primary_provider = requested_provider or (_load_cfg().get("model") or {}).get("provider")
+ 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
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ missing_display = ", ".join(missing_skills)
+ if not loaded_skills:
+ raise ValueError(f"Unknown skill(s): {missing_display}")
+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "
+ "List available skills with `hermes skills list`.", missing_display, ", ".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),
+ # 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=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),
+ 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(),
+ **_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/session_registry.py
index 28e53180515,00000000000..ef976f0e769
mode 100644,000000..100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@@ -1,723 -1,0 +1,724 @@@
+"""TUI session_registry seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+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(current: dict, agent) -> None:
+ """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation())."""
+ # 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
+ 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()
+
+
+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 mid-build: _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 "")):
+ 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_built_agent(current, agent)
+ # 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:
+ current["agent_error"] = str(e)
+ _emit("error", sid, {"message": agent_init_failed_message(e)})
+ 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()
+
+
+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."""
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),
- "model": model or _resolve_model(), "tools": {}, "skills": {}, "lazy": True,
++ "model": model or _session_default_model({"profile_home": _profile_home(profile)}),
++ "tools": {}, "skills": {}, "lazy": True,
+ "desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),
+ **({"provider": provider} if provider else {}),
+ }
+
+
+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"})
+ db.reopen_session(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,
- "model": _resolve_model(), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,
++ "model": _session_default_model(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) -> 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)
++ messages = [] if omit_messages else _history_to_messages(history, profile_home=session.get("profile_home"))
+ 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)
diff --cc website/docs/user-guide/features/acp.md
index 9c620be1f98,ad4ebb37c7a..27aaae9a0bb
--- a/website/docs/user-guide/features/acp.md
+++ b/website/docs/user-guide/features/acp.md
@@@ -35,26 -35,26 +35,46 @@@ Hermes runs with a curated `hermes-acp
It intentionally excludes things that do not fit typical editor UX, such as messaging delivery and cronjob management.
+ The toolset resolves the same way as on the messaging gateway for the same
+ platform config. That includes the extras the gateway adds on top of the
+ list, such as enabled plugin toolsets, so ACP sessions get those too.
+ `platform_toolsets.acp` replaces the `hermes-acp` default, and
+ `agent.disabled_toolsets` removes toolsets from every ACP session. MCP
+ servers from `mcp_servers` follow the same rules too. By default ACP gets
+ every enabled server. If you list server names in `platform_toolsets.acp`,
+ only those servers are included, and `no_mcp` drops them all. `hermes tools`
+ has no ACP entry, so edit `config.yaml` directly:
+
+ ```yaml
+ platform_toolsets:
+ acp: [file, web, skills, github] # only the github MCP server
+ agent:
+ disabled_toolsets: [code_execution]
+ ```
+
+ MCP servers that the editor sends with `session/new` are separate. The
+ client asks for them per session, and they are always added.
+
+## Editor-provided MCP servers
+
+On gateways advertising `acp-session-mcp-v1`, editor `mcpServers` belong to the
+canonical session, not the ACP viewer process. The gateway uses separate registry
+namespaces even when two editors supply the same server name. Closing an editor
+does not cancel another session's MCP execution.
+
+Discovery is eager and bounded before the first model turn. The selected tool
+schemas remain frozen for the conversation; server tool-list changes require a
+new session. MCP transports are released after each execution, without stopping
+sibling sessions or the shared MCP loop.
+
+The gateway keeps the editor transport specification (including command arguments,
+environment values and HTTP headers) only in memory. Durable session policy holds
+a fingerprint and the selected schemas, not a copy of those credentials. After a
+gateway restart, the editor must supply the same `mcpServers` on load/resume.
+Missing credentials refuse execution; a changed specification or secret refuses
+reattachment rather than silently changing the session. Start a new session when
+changing the server configuration. Commands and paths run on the gateway host.
+
## Installation
Install Hermes normally, then add the ACP extra from the install checkout: