Skip to content

The agent that grows with you

fix(gateway): typed /reasoning and Move to project edit the owner's frozen policy

Teknium3cd782be3e30
diff --git a/apps/desktop/src/api/canonical-producer-contract.test.ts b/apps/desktop/src/api/canonical-producer-contract.test.ts
index dd5441e76d0..7c5da20fa8d 100644
--- a/apps/desktop/src/api/canonical-producer-contract.test.ts
+++ b/apps/desktop/src/api/canonical-producer-contract.test.ts
@@ -80,6 +80,13 @@ function answer(frame: { method: string; params: Record<string, unknown> }): Rec
return { status: 'settled', delivery_id: p.id, value: 'x' }
}
+// The owner edit each mutating site must send (fenced by the attached snapshot's revision/generation).
+const MUTATIONS: Record<string, Record<string, unknown>> = {
+ rewind: { operation: 'rewind', payload: { target_message_id: 9 } },
+ reasoning: { operation: 'reasoning', payload: { effort: 'high' } },
+ workspace: { operation: 'workspace', payload: { cwd: '/repo' } }
+}
+
// [label, Desktop method, exact producer params, expected: wire methods sent (after attach) or a named refusal]
const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]> = [
[
@@ -102,9 +109,15 @@ const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]>
/reasoning .*not available/
],
[
- 'reasoning-step.ts keybind step',
+ 'reasoning-step.ts keybind step (B14)',
'config.set',
{ key: 'reasoning', session_id: 's', value: 'high' },
+ ['session.mutate']
+ ],
+ [
+ 'reasoning-slash.ts /reasoning show (display word, config.yaml)',
+ 'config.set',
+ { key: 'reasoning', session_id: 's', value: 'show' },
/reasoning is not available/
],
['model-presets.ts fast', 'config.set', { key: 'fast', session_id: 's', value: 'fast' }, /fast is not available/],
@@ -169,7 +182,7 @@ const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]>
'projects.ts moveSessionToProject (B21 / C-hx-2)',
'session.workspace.move',
{ cwd: '/repo', session_key: 's' },
- /Moving a chat to another project is not available/
+ ['session.mutate']
],
[
'connector-tool.tsx in-chat connect',
@@ -211,6 +224,12 @@ test.each(SITES)('%s: the canonical frame fits the generated contract', async (_
try {
const address = server.address() as { port: number }
await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
+
+ // Typed /reasoning and the keybind act on the open (attached) session, as the model picker does.
+ if (method === 'config.set' && params.key === 'reasoning') {
+ await client.request('session.resume', { session_id: 's' })
+ }
+
const call = client.request(method, params)
if (expected instanceof RegExp) {
@@ -231,10 +250,12 @@ test.each(SITES)('%s: the canonical frame fits the generated contract', async (_
}
if (Array.isArray(expected) && expected[0] === 'session.mutate') {
+ const edit =
+ MUTATIONS[method === 'prompt.submit' ? 'rewind' : method === 'config.set' ? 'reasoning' : 'workspace']
+
expect(sent.find(frame => frame.method === 'session.mutate').params).toMatchObject({
session_id: 's',
- operation: 'rewind',
- payload: { target_message_id: 9 },
+ ...edit,
expected_revision: 4,
expected_generation: 2
})
diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.ts
index f791dee4b20..1af3d725bdb 100644
--- a/apps/desktop/src/api/canonical-protocol.ts
+++ b/apps/desktop/src/api/canonical-protocol.ts
@@ -145,18 +145,12 @@ const CANONICAL_CONFIG_KEYS = new Set(['busy', 'verbose', 'yolo', 'model'])
// The one guard between a Desktop producer and the owner's closed contracts: translate a legacy
// shape the owner has a canonical form for, refuse by name what it does not serve.
function canonicalProducerFrame(method: string, params: Record<string, unknown>): Record<string, unknown> {
- // No verb for other settings (reasoning, fast, approvals.mode, voice, display.*) nor a global
- // scope: refuse before the wire, like Ink, instead of a bare invalid_params.
+ // No verb for other settings (reasoning display words, fast, approvals.mode, voice, display.*)
+ // nor a global scope: refuse before the wire, like Ink, instead of a bare invalid_params.
if (method === 'config.set' && (!CANONICAL_CONFIG_KEYS.has(String(params.key)) || 'scope' in params)) {
throw new Error(`Changing ${params.key}${'scope' in params ? ` (${params.scope})` : ''} is not available on the shared gateway yet`)
}
- // The sidecar's move rewrites only the stored row: the owner's frozen policy (execution cwd,
- // TERMINAL_CWD, resume) would stay on the old folder while the sidebar showed the new one.
- if (method === 'session.workspace.move') {
- throw new Error('Moving a chat to another project is not available on the shared gateway yet')
- }
-
if (SIDECAR_SESSION_VERBS.has(method) || (method.startsWith('connect') && (params.owner as { type?: unknown } | undefined)?.type === 'session')) {
throw new Error(`${method} is not available on the shared gateway yet`)
}
@@ -168,9 +162,26 @@ function canonicalProducerFrame(method: string, params: Record<string, unknown>)
return method === 'bot_relay.deliver' ? canonicalBotDelivery(params) : params
}
+// The levels `hermes_constants.parse_reasoning_effort` accepts: a session `/reasoning <level>` is the
+// owner's `reasoning` mutation; the display words (show/hide/full/clamp) are config.yaml writes.
+const REASONING_EFFORTS = new Set(['none', 'false', 'disabled', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'])
+
+// Frozen-policy edits: a session-scope `/reasoning <level>` (`--global` stays the named refusal, no
+// owner config-write verb) and Move to project, which re-homes the execution cwd and TERMINAL_CWD
+// with the row (`session_key` names the sidebar row).
+function policyEdit(method: string, params: Record<string, unknown>): { session: unknown; operation: string; payload: Record<string, unknown> } | null {
+ const effort = String(params.value ?? '').trim().toLowerCase()
+
+ if (method === 'config.set' && params.key === 'reasoning' && params.scope !== 'global' && REASONING_EFFORTS.has(effort)) {
+ return { session: params.session_id, operation: 'reasoning', payload: { effort } }
+ }
+
+ return method === 'session.workspace.move' ? { session: params.session_key, operation: 'workspace', payload: { cwd: params.cwd } } : null
+}
+
const BRANCH_METHODS = new Set(['session.branch', 'session.branch_stored', 'session.branch_whole'])
// Value-setting mutations: re-applying one is harmless, so a later acknowledged edit retires it.
-const VALUE_OPERATIONS = new Set(['rename', 'archive', 'model'])
+const VALUE_OPERATIONS = new Set(['rename', 'archive', 'model', 'reasoning', 'workspace'])
const MUTATION_METHODS = new Set(['session.title', 'session.archive', 'session.compress', 'session.rewind', ...BRANCH_METHODS])
export class CanonicalDesktopProtocol {
@@ -200,8 +211,8 @@ export class CanonicalDesktopProtocol {
// failure carries no reason; its outcome is unknown and the token stays for the exact retry.
if (typeof reason === 'string') { this.settleModelConfirmation(params) }
- // A typed busy refusal of a rewind wrote nothing either; the caller interrupts and retries at the new revision.
- if (reason !== 'revision_conflict' && !(reason === 'session_busy' && params.operation === 'rewind')) { return }
+ // A typed busy refusal of a rewind or a move wrote nothing either; the retry is a new request at the new revision.
+ if (reason !== 'revision_conflict' && !(reason === 'session_busy' && ['rewind', 'workspace'].includes(params.operation as string))) { return }
// A confirmed CAS refusal did not mutate. Ambiguous transport failures keep
// the original revision/id so a retry cannot overwrite another user's edit.
@@ -219,7 +230,7 @@ export class CanonicalDesktopProtocol {
// rebinds the live event transport and returns the same snapshot shape.
if (method === 'session.activate') { return 'session.resume' }
- return (method === 'slash.exec' || method === 'config.set') && typeof prepared.operation === 'string' ? 'session.mutate' : method
+ return (method === 'slash.exec' || method === 'config.set' || method === 'session.workspace.move') && typeof prepared.operation === 'string' ? 'session.mutate' : method
}
private retainedMutation(sessionId: unknown, profile: unknown, operation: string, payload: Record<string, unknown>, withGeneration: boolean): Record<string, unknown> {
@@ -314,6 +325,10 @@ export class CanonicalDesktopProtocol {
return this.retainedMutation(parent, params.profile, 'branch', payload, true)
}
+ const policy = policyEdit(method, params)
+
+ if (policy) { return this.retainedMutation(policy.session, params.profile, policy.operation, policy.payload, true) }
+
if (method === 'config.set' && params.key === 'model') {
const pick = pickerModelMutation(params.value)
@@ -459,7 +474,7 @@ export class CanonicalDesktopProtocol {
result(method: string, params: Record<string, unknown>, value: any): any {
if (!value || typeof value !== 'object') { return value }
- const mutation = MUTATION_METHODS.has(method) || ((method === 'slash.exec' || method === 'config.set') && typeof params.operation === 'string')
+ const mutation = MUTATION_METHODS.has(method) || ((method === 'slash.exec' || method === 'config.set' || method === 'session.workspace.move') && typeof params.operation === 'string')
this.adoptRevision(params, value, mutation)
if (mutation) { return this.mutationReceipt(method, params, value) }
@@ -527,7 +542,8 @@ export class CanonicalDesktopProtocol {
if (method === 'slash.exec') { return { ...value, type: 'exec', output: mutationSummary(params.operation as string, value) } }
- return { ...value, ok: true }
+ // The legacy config.set answer every reasoning caller reads (`result.value`).
+ return params.operation === 'reasoning' ? { ...value, ok: true, value: value.effort } : { ...value, ok: true }
}
// An acknowledged mutation at revision R settles every older retained value-setting request of
diff --git a/apps/desktop/src/api/canonical-reasoning-config-set.test.ts b/apps/desktop/src/api/canonical-reasoning-config-set.test.ts
index 24e327e6e53..3dc4116c1db 100644
--- a/apps/desktop/src/api/canonical-reasoning-config-set.test.ts
+++ b/apps/desktop/src/api/canonical-reasoning-config-set.test.ts
@@ -3,11 +3,10 @@ import { expect, test } from 'vitest'
import { HermesGateway } from './client'
-// The canonical config.set key set (tui_gateway/contracts/canonical_projections.py::
-// CanonicalConfigSetParams); the real owner answers any other key with 4001 invalid_params.
-const CANONICAL_CONFIG_KEYS = new Set(['busy', 'verbose', 'yolo', 'model'])
-
-test('typed /reasoning on a canonical dial is refused by name and never sent as a bare invalid_params', async () => {
+// B14: main's Desktop /reasoning <level> changed the session's reasoning through legacy config.set.
+// On the shared owner the session scope is the revision-fenced `session.mutate operation=reasoning`;
+// `--global` (a config.yaml write the owner has no verb for) stays a named refusal.
+test('typed /reasoning sets the session level through the owner mutation; --global is refused by name', async () => {
const wsPackage = 'ws'
const { WebSocketServer } = await import(wsPackage)
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
@@ -17,17 +16,32 @@ test('typed /reasoning on a canonical dial is refused by name and never sent as
socket.on('message', (bytes: Buffer) => {
const frame = JSON.parse(bytes.toString())
sent.push(frame)
- const refused = frame.method === 'config.set' && !CANONICAL_CONFIG_KEYS.has(frame.params.key)
+ const p = frame.params
+
+ const result =
+ frame.method === 'session.resume'
+ ? { session_id: 's', revision: 4, execution_generation: 2, running: false, messages: [], prompts: [] }
+ : frame.method === 'session.mutate'
+ ? {
+ session_id: p.session_id,
+ operation: p.operation,
+ revision: 5,
+ execution_generation: 3,
+ effort: p.payload.effort
+ }
+ : frame.method === 'config.set'
+ ? null
+ : { value: 'medium' }
socket.send(
JSON.stringify(
- refused
- ? {
+ result
+ ? { jsonrpc: '2.0', id: frame.id, result }
+ : {
jsonrpc: '2.0',
id: frame.id,
- error: { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params', fields: ['key'] } }
+ error: { code: 4001, message: 'invalid_params', data: { reason: 'invalid_params' } }
}
- : { jsonrpc: '2.0', id: frame.id, result: { value: 'medium' } }
)
)
})
@@ -37,15 +51,31 @@ test('typed /reasoning on a canonical dial is refused by name and never sent as
try {
const address = server.address() as { port: number }
await client.connect(`ws://127.0.0.1:${address.port}/api/ws?native_dial=fixture&ticket=one-use`)
+ await client.request('session.resume', { session_id: 's' })
- // reasoningSlashParams('high --global', 's') — the Desktop /reasoning write.
- for (const params of [
- { key: 'reasoning', session_id: 's', value: 'high' },
- { key: 'reasoning', session_id: 's', value: 'high', scope: 'global' }
- ]) {
- await expect(client.request('config.set', params)).rejects.toThrow(/not available on the shared gateway yet/)
- }
+ // reasoningSlashParams('high', 's') and ('high --session', 's'): the result's `value` is what
+ // applyReasoningSlashResult / writeSessionReasoningEffort read.
+ await expect(
+ client.request('config.set', { key: 'reasoning', session_id: 's', value: 'high' })
+ ).resolves.toMatchObject({ value: 'high' })
+ await expect(
+ client.request('config.set', { key: 'reasoning', session_id: 's', value: 'low', scope: 'session' })
+ ).resolves.toMatchObject({ value: 'low' })
+ await expect(
+ client.request('config.set', { key: 'reasoning', session_id: 's', value: 'high', scope: 'global' })
+ ).rejects.toThrow(/reasoning \(global\) is not available on the shared gateway yet/)
+ const mutations = sent.filter(frame => frame.method === 'session.mutate').map(frame => frame.params)
+ expect(mutations).toMatchObject([
+ {
+ session_id: 's',
+ operation: 'reasoning',
+ payload: { effort: 'high' },
+ expected_revision: 4,
+ expected_generation: 2
+ },
+ { session_id: 's', operation: 'reasoning', payload: { effort: 'low' }, expected_revision: 5 }
+ ])
expect(sent.filter(frame => frame.method === 'config.set')).toEqual([])
// The bare form's read still reaches the owner.
await expect(client.request('config.get', { key: 'reasoning', session_id: 's' })).resolves.toEqual({
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.ts
index 8255a4e8651..b2c9790a19c 100644
--- a/apps/desktop/src/api/client.ts
+++ b/apps/desktop/src/api/client.ts
@@ -45,8 +45,9 @@ const CANONICAL_PROMPT_EVENTS: Record<string, 'approval' | 'clarify'> = { 'appro
const ATTACH_REQUIRED = new Set(['prompt.submit', 'approval.respond', 'clarify.respond', 'session.interrupt', 'prompt.cancel', 'session.rewind'])
// A branch is a CAS mutation on the PARENT: an un-attached parent (right-click on a sidebar row
-// that was never opened) has no cached revision, so attach it first to learn one.
-const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole'])
+// that was never opened) has no cached revision, so attach it first to learn one. Move to project
+// (`session_key`) is the same CAS mutation on a sidebar row.
+const PARENT_ATTACH_REQUIRED = new Set(['session.branch_stored', 'session.branch_whole', 'session.workspace.move'])
// Canonical-only identity keys. The legacy `hermes serve` contract refuses an unknown key as
// version skew (4000), so they are stripped on a non-canonical dial. `prompt.submit` keeps its
@@ -401,7 +402,7 @@ export class HermesGateway extends JsonRpcGatewayClient {
await resume(sid)
}
- const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id : null
+ const parent = PARENT_ATTACH_REQUIRED.has(method) ? params.parent_session_id ?? params.session_id ?? params.session_key : null
if (typeof parent === 'string' && parent && !this.attached.has(canonicalSessionKey(parent, params.profile))) {
await resume(parent)
diff --git a/apps/desktop/src/i18n/de_projects.ts b/apps/desktop/src/i18n/de_projects.ts
index db4927e5616..9f9d4a120d5 100644
--- a/apps/desktop/src/i18n/de_projects.ts
+++ b/apps/desktop/src/i18n/de_projects.ts
@@ -33,6 +33,7 @@ export const deProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
movedTo: name => `In ${name} verschoben`,
moveFailed: 'Session konnte nicht verschoben werden',
moveNoFolder: 'Dieses Projekt hat keinen Ordner, in den verschoben werden kann',
+ moveBusy: 'Beende zuerst den laufenden Durchgang und verschiebe dann den Chat',
moveNoProjects: 'Keine anderen Projekte',
reveal: 'Im Ordner anzeigen',
copyPath: 'Pfad kopieren',
diff --git a/apps/desktop/src/i18n/en_projects.ts b/apps/desktop/src/i18n/en_projects.ts
index 06fef35cd20..b5220ab2a65 100644
--- a/apps/desktop/src/i18n/en_projects.ts
+++ b/apps/desktop/src/i18n/en_projects.ts
@@ -33,6 +33,7 @@ export const enProjects: Translations['sidebar']['projects'] = {
movedTo: name => `Moved to ${name}`,
moveFailed: 'Could not move session',
moveNoFolder: 'That project has no folder to move into',
+ moveBusy: 'Stop the running turn, then move the chat',
moveNoProjects: 'No other projects',
reveal: 'Reveal in folder',
copyPath: 'Copy path',
diff --git a/apps/desktop/src/i18n/es_projects.ts b/apps/desktop/src/i18n/es_projects.ts
index 27d23d2178d..0f3f06136ba 100644
--- a/apps/desktop/src/i18n/es_projects.ts
+++ b/apps/desktop/src/i18n/es_projects.ts
@@ -33,6 +33,7 @@ export const esProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
movedTo: name => `Movido a ${name}`,
moveFailed: 'No se pudo mover la sesión',
moveNoFolder: 'Ese proyecto no tiene carpeta a la que mover',
+ moveBusy: 'Detén el turno en curso y luego mueve el chat',
moveNoProjects: 'No hay otros proyectos',
reveal: 'Revelar en carpeta',
copyPath: 'Copiar ruta',
diff --git a/apps/desktop/src/i18n/fr_projects.ts b/apps/desktop/src/i18n/fr_projects.ts
index 971abefec48..e892cfcfbaa 100644
--- a/apps/desktop/src/i18n/fr_projects.ts
+++ b/apps/desktop/src/i18n/fr_projects.ts
@@ -33,6 +33,7 @@ export const frProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
movedTo: name => `Déplacée vers ${name}`,
moveFailed: 'Impossible de déplacer la session',
moveNoFolder: "Ce projet n'a aucun dossier vers lequel effectuer le déplacement",
+ moveBusy: 'Arrêtez le tour en cours, puis déplacez la discussion',
moveNoProjects: 'Aucun autre projet',
reveal: 'Afficher dans le dossier',
copyPath: 'Copier le chemin',
diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.json
index 568ed8efc40..3faaf6d46d6 100644
--- a/apps/desktop/src/i18n/overlay-gaps.json
+++ b/apps/desktop/src/i18n/overlay-gaps.json
@@ -1894,6 +1894,7 @@
"sidebar.projects.branchOff": ["ar"],
"sidebar.projects.moveFailed": ["ar","ja","zh-hant"],
"sidebar.projects.moveNoFolder": ["ar","ja","zh-hant"],
+ "sidebar.projects.moveBusy": ["ar","ja","zh-hant"],
"sidebar.projects.moveNoProjects": ["ar","ja","zh-hant"],
"sidebar.projects.moveToProject": ["ar","ja","zh-hant"],
"sidebar.projects.movedTo": ["ar","ja","zh-hant"],
diff --git a/apps/desktop/src/i18n/ru_projects.ts b/apps/desktop/src/i18n/ru_projects.ts
index 9284a037db7..d1e5a7276e1 100644
--- a/apps/desktop/src/i18n/ru_projects.ts
+++ b/apps/desktop/src/i18n/ru_projects.ts
@@ -32,6 +32,7 @@ export const ruProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
movedTo: name => `Перемещено в ${name}`,
moveFailed: 'Не удалось переместить сеанс',
moveNoFolder: 'У этого проекта нет папки для перемещения',
+ moveBusy: 'Остановите текущий ход, затем переместите чат',
moveNoProjects: 'Нет других проектов',
reveal: 'Показать в папке',
copyPath: 'Копировать путь',
diff --git a/apps/desktop/src/i18n/types_projects.ts b/apps/desktop/src/i18n/types_projects.ts
index 4d6514a2922..e3e0d868710 100644
--- a/apps/desktop/src/i18n/types_projects.ts
+++ b/apps/desktop/src/i18n/types_projects.ts
@@ -32,6 +32,7 @@ export interface SidebarProjectsTranslations {
movedTo: (name: string) => string
moveFailed: string
moveNoFolder: string
+ moveBusy: string
moveNoProjects: string
reveal: string
copyPath: string
diff --git a/apps/desktop/src/i18n/zh_projects.ts b/apps/desktop/src/i18n/zh_projects.ts
index 453b34ff976..aa7f648cb8e 100644
--- a/apps/desktop/src/i18n/zh_projects.ts
+++ b/apps/desktop/src/i18n/zh_projects.ts
@@ -33,6 +33,7 @@ export const zhProjects: NonNullable<TranslationOverrides['sidebar']>['projects'
movedTo: name => `已移动到 ${name}`,
moveFailed: '无法移动会话',
moveNoFolder: '该项目没有可移入的文件夹',
+ moveBusy: '请先停止正在运行的回合,再移动该聊天',
moveNoProjects: '没有其他项目',
reveal: '在文件夹中显示',
copyPath: '复制路径',
diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts
index 4bbc5e3ade3..917f47ca2d5 100644
--- a/apps/desktop/src/store/projects.ts
+++ b/apps/desktop/src/store/projects.ts
@@ -799,10 +799,15 @@ export async function moveSessionToProject(
throw new Error(translateNow('sidebar.projects.moveNoFolder'))
}
+ // The shared owner refuses a move while a turn runs (its frozen policy would change under it).
const res = await gatewayRequest<WorkspaceMovePayload>('session.workspace.move', {
cwd,
session_key: sessionId,
...(profile ? { profile } : {})
+ }).catch((err: unknown) => {
+ throw (err as { data?: { reason?: string } })?.data?.reason === 'session_busy'
+ ? new Error(translateNow('sidebar.projects.moveBusy'))
+ : err
})
const moved = res.cwd || cwd
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 575de0600ea..82b156dc116 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4472,7 +4472,7 @@ export interface PromptResolveUnknownParams {
admission_id: string
execution_generation: number
}
-/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress. */
+/** ``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``; ``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace. ``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project. */
export interface SessionMutateParams {
session_id: string
request_id: string
@@ -6396,7 +6396,7 @@ export interface CanonicalRpcMethods {
'session.info': { params: CanonicalSessionInfoParams; result: CanonicalSessionInfo }
'session.interrupt': { params: CanonicalControlParams; result: CanonicalSessionHandle }
'session.list': { params: CanonicalListParams; result: CanonicalListResult }
- /** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, compress, import). */
+ /** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import). */
'session.mutate': { params: SessionMutateParams; result: SessionMutateResult }
/** Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners. */
'session.prune': { params: SessionPruneParams; result: SessionPruneResult }
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index b4474a5c5cd..fbb1065c562 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -35123,7 +35123,7 @@
},
"SessionMutateParams": {
"additionalProperties": false,
- "description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress.",
+ "description": "``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;\n``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.\n``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite\nthe session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project.",
"properties": {
"session_id": {
"title": "Session Id",
@@ -44448,7 +44448,7 @@
},
{
"name": "session.mutate",
- "summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, compress, import).",
+ "summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import).",
"params": [
{
"name": "params",
diff --git a/gateway/session_mutation_policy.py b/gateway/session_mutation_policy.py
new file mode 100644
index 00000000000..35225ff2632
--- /dev/null
+++ b/gateway/session_mutation_policy.py
@@ -0,0 +1,54 @@
+"""Prepare the policy-only session edits: session-scope reasoning and the workspace (Move to project).
+
+Both rewrite the frozen LocalSessionPolicy the next turn runs under, re-bound like a model switch
+(policy identity covers config/cwd, so its config-secret reference is re-fingerprinted).
+"""
+import asyncio
+import json
+from dataclasses import asdict, replace
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+def _rebind(authority, prepared, old, policy, **extra):
+ from gateway.session_policy import bind_launch_key, launch_key
+ from gateway.session_policy_credentials import recover_config_secrets
+ secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}
+ policy = bind_launch_key(authority, prepared['snapshot']['receipt']['session_id'], policy,
+ launch_key(authority, old), config_secrets=secrets)
+ return dict(prepared, policy=asdict(policy), **extra)
+
+
+async def prepare_reasoning(authority, live, payload, prepared):
+ """``/reasoning <level>`` for this session: the level ``build_policy`` freezes at creation."""
+ from gateway.session_policy import restore_policy
+ old = restore_policy(prepared['snapshot']['receipt']['policy'])
+ frozen = old.config()
+ frozen.setdefault('agent', {})['reasoning_effort'] = payload['effort']
+ # An explicit session level wins over a per-model default, as at creation.
+ frozen['agent'].pop('reasoning_overrides', None)
+ return _rebind(authority, prepared, old, replace(old, config_json=json.dumps(frozen)))
+
+
+async def prepare_workspace(authority, live, payload, prepared):
+ """Move to project: execution cwd and TERMINAL_CWD move together (restore_policy's invariant)."""
+ import os
+ from gateway.session_policy import restore_policy
+ from hermes_constants import translate_cwd_for_wsl_backend
+ from tui_gateway import git_probe
+ old = restore_policy(prepared['snapshot']['receipt']['policy'])
+
+ def probe():
+ # Off-loop: a stat and up to three `git` spawns.
+ cwd = os.path.abspath(os.path.expanduser(translate_cwd_for_wsl_backend(payload['cwd'])))
+ if not os.path.isdir(cwd):
+ raise RuntimeStoreError('invalid_params')
+ return cwd, git_probe.branch(cwd), git_probe.common_repo_root(cwd)
+ cwd, branch, root = await asyncio.to_thread(probe)
+ terminal = json.loads(old.terminal_json)
+ terminal['TERMINAL_CWD'] = cwd
+ policy = replace(old, cwd=cwd, terminal_json=json.dumps(terminal))
+ return _rebind(authority, prepared, old, policy, git={'branch': branch, 'root': root})
+
+
+PREPARE = {'reasoning': prepare_reasoning, 'workspace': prepare_workspace}
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index f11b65fb2ec..7025b6c74d1 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -10,6 +10,8 @@ from contextlib import nullcontext
from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
_METADATA = frozenset({'rename', 'archive', 'sidebar'})
+# Prepared off the commit like model, then published as a new frozen policy.
+_POLICY = frozenset({'model', 'reasoning', 'workspace'})
_FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})
@@ -73,7 +75,7 @@ async def mutate_session(authority, actor, ref, params):
async def _owned_mutation(authority, actor, ref, params):
- if (params.get('operation') in {'model', 'compress', 'reset', 'rewind'}
+ if (params.get('operation') in {*_POLICY, 'compress', 'reset', 'rewind'}
and ref.session_id not in authority.sessions and 'request_id' in params):
_authorize_control(authority, actor, ref, params)
live = authority.sessions.get(_owner_ref(authority, ref, params).session_id)
@@ -90,7 +92,7 @@ async def _owned_mutation(authority, actor, ref, params):
else:
async with live.mutation_lock:
result = await _mutate_session(authority, actor, ref, params)
- if params.get('operation') in {'model', 'compress', 'reset'}:
+ if params.get('operation') in {*_POLICY, 'compress', 'reset'}:
authority._schedule(ref)
return result
@@ -100,7 +102,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
or params['session_id'] != ref.session_id):
raise RuntimeStoreError('invalid_params')
operation = params['operation']
- if not isinstance(operation, str):
+ if not isinstance(operation, str) or (operation in _POLICY and params.get('expected_generation') is None):
raise RuntimeStoreError('invalid_params')
cold_history = False
imported_ids = None
@@ -140,7 +142,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
raise RuntimeStoreError('permission_denied')
prepared = None
- if operation in {'model', 'compress'}:
+ if operation in {*_POLICY, 'compress'}:
# Its own BEGIN IMMEDIATE, so off the loop like the commit below.
prepared = await asyncio.to_thread(mutate_runtime_session, authority.db, epoch=authority.epoch,
principal_id=actor.subject, session_id=ref.session_id, request_id=params['request_id'],
@@ -149,7 +151,8 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
if 'snapshot' in prepared:
from gateway.session_mutation_model import prepare_model
from gateway.session_mutation_compress import prepare_compress
- prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]
+ from gateway.session_mutation_policy import PREPARE
+ prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE}[operation]
prepared = await prepare(authority, live, params['payload'], prepared)
applied = False
if prepared.get('status') in {'preview', 'confirmation_required'}:
@@ -175,7 +178,7 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
current = authority.db.get_session(ref.session_id)
owns_projection = current is not None and (
current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))
- if operation not in {'model', 'reset', 'compress', 'rewind'} or owns_projection:
+ if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:
_project_committed(authority, ref, operation, result)
if live is not None:
if operation == 'rewind' and owns_projection:
@@ -192,13 +195,25 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
def _project_committed(authority, ref, operation, result):
"""Publish a committed receipt's runtime projections (safe to repeat on exact retry)."""
- if operation == 'model':
+ if operation in _POLICY:
from gateway.session_local import publish_local_policy
publish_local_policy(authority, ref.session_id)
# A drain that ran while the receipt committed off-loop saw the new stored policy beside
# the old live one and paused; with both now equal, queued input must run, not wait for
# the next submit or restart.
authority._schedule(ref)
+ if operation in {'reasoning', 'workspace'}:
+ # Every viewer repaints its reasoning pill / workspace from the published policy, as main's
+ # _emit_session_info did after the live change.
+ from gateway.session_local import local_session_info
+ authority.sessions[ref.session_id].event_stream.publish(
+ ref.session_id, local_session_info(authority, ref), event_type='session.info')
+ if operation == 'workspace':
+ # Main's move drops the terminal environment so the next command starts in the new folder.
+ from hermes_state_local import local_receipt
+ from tools.terminal_tool_lifecycle import cleanup_vm
+ for sid in {ref.session_id, local_receipt(authority.db, ref.session_id)['entry']['session_id']}:
+ cleanup_vm(sid)
if operation == 'branch':
from gateway.session_local_recovery import restore_local_session
restore_local_session(authority, result['branched_session_id'])
diff --git a/hermes_state_mutation_prepared.py b/hermes_state_mutation_prepared.py
index 1aa7aa2b083..d6fc1df22af 100644
--- a/hermes_state_mutation_prepared.py
+++ b/hermes_state_mutation_prepared.py
@@ -26,12 +26,21 @@ def validate_prepared(db, conn, session_id, prepared):
return current
-def model_in_transaction(db, conn, session_id, payload, prepared):
+def _commit_policy(db, conn, session_id, prepared):
+ """Write the prepared policy over the snapshot it was derived from and bump the generation."""
from hermes_state_runtime import _json
snapshot = validate_prepared(db, conn, session_id, prepared)
saved = snapshot['receipt']
saved['policy'] = prepared['policy']
conn.execute('UPDATE state_meta SET value=? WHERE key=?', (_json(saved), POLICY_PREFIX + session_id))
+ conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
+ generation = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
+ return snapshot, generation
+
+
+def model_in_transaction(db, conn, session_id, payload, prepared):
+ from hermes_state_runtime import _json
+ snapshot, generation = _commit_policy(db, conn, session_id, prepared)
model = prepared['policy']['model']
config = json.loads(prepared['policy']['config_json'])['model']
target = snapshot['target']
@@ -41,6 +50,28 @@ def model_in_transaction(db, conn, session_id, payload, prepared):
model_config = json.loads(row[0] or '{}')
model_config['provider'] = config['provider']
conn.execute('UPDATE sessions SET model=?,model_config=? WHERE id=?', (model, _json(model_config), target))
- conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))
- generation = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()[0]
return {session_id, target}, {'model': model, 'provider': config['provider'], 'execution_generation': generation}
+
+
+def reasoning_in_transaction(db, conn, session_id, payload, prepared):
+ snapshot, generation = _commit_policy(db, conn, session_id, prepared)
+ return {session_id, snapshot['target']}, {'effort': payload['effort'], 'execution_generation': generation}
+
+
+def workspace_in_transaction(db, conn, session_id, payload, prepared):
+ """The policy (execution cwd + TERMINAL_CWD) and every row of the conversation move together:
+ the sidebar groups by the row's cwd/git identity, which a move REPLACES (main's update_session_cwd
+ with replace_git_meta), never merges."""
+ from hermes_state_local import local_conversation_ids
+ snapshot, generation = _commit_policy(db, conn, session_id, prepared)
+ cwd, git = prepared['policy']['cwd'], prepared['git']
+ rows = list(dict.fromkeys([*local_conversation_ids(conn, session_id), snapshot['target']]))
+ conn.executemany('UPDATE sessions SET cwd=?, git_branch=?, git_repo_root=?, '
+ 'git_metadata_generation=COALESCE(git_metadata_generation, 0)+1 WHERE id=?',
+ [(cwd, git['branch'] or None, git['root'] or None, sid) for sid in rows])
+ return {session_id, snapshot['target']}, {'cwd': cwd, 'branch': git['branch'] or None,
+ 'git_repo_root': git['root'] or None, 'execution_generation': generation}
+
+
+POLICY_HANDLERS = {'model': model_in_transaction, 'reasoning': reasoning_in_transaction,
+ 'workspace': workspace_in_transaction}
diff --git a/hermes_state_mutations.py b/hermes_state_mutations.py
index 83215aece95..b3e7a71ea3b 100644
--- a/hermes_state_mutations.py
+++ b/hermes_state_mutations.py
@@ -14,6 +14,14 @@ def validate_action(operation, payload):
return
if operation == 'branch' and _valid_branch_payload(payload):
return
+ # Session-scope ``/reasoning <level>`` and Desktop's Move to project: revision-fenced edits of
+ # the frozen policy (gateway/session_mutation_policy.py).
+ if operation == 'reasoning' and set(payload) == {'effort'} and isinstance(payload['effort'], str):
+ from hermes_constants import parse_reasoning_effort
+ if parse_reasoning_effort(payload['effort']) is not None:
+ return
+ if operation == 'workspace' and set(payload) == {'cwd'} and isinstance(payload['cwd'], str) and payload['cwd'].strip():
+ return
if operation == 'compress' and _valid_compress_payload(payload):
return
if operation in {'delete', 'reset'} and not payload:
@@ -62,9 +70,9 @@ def apply_action(db, conn, session_id, operation, payload, *, prepared=None):
if operation == 'compress':
from hermes_state_mutation_compress import compress_in_transaction
return compress_in_transaction(db, conn, session_id, payload, prepared)
- if operation == 'model':
- from hermes_state_mutation_prepared import model_in_transaction
- return model_in_transaction(db, conn, session_id, payload, prepared)
+ if operation in {'model', 'reasoning', 'workspace'}:
+ from hermes_state_mutation_prepared import POLICY_HANDLERS
+ return POLICY_HANDLERS[operation](db, conn, session_id, payload, prepared)
from hermes_state_mutation_reset import reset_in_transaction
from hermes_state_mutation_branch import branch_in_transaction
handlers = {'delete': _delete, 'import': _import, 'rewind': _rewind, 'reset': reset_in_transaction,
diff --git a/tests/gateway/test_session_policy_verbs.py b/tests/gateway/test_session_policy_verbs.py
new file mode 100644
index 00000000000..ef2a174dacb
--- /dev/null
+++ b/tests/gateway/test_session_policy_verbs.py
@@ -0,0 +1,119 @@
+"""Desktop's typed /reasoning and Move to project on the shared owner (B14, B21 / C-hx-2).
+
+Main applied both to the live sidecar session. On the owner the next turn runs under the frozen
+LocalSessionPolicy, so each is a revision-fenced ``session.mutate`` that rewrites that policy.
+"""
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+
+
+def _owner(tmp_path, monkeypatch, handle):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ import hermes_state_runtime as rt
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,
+ _handle_message=handle, _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,
+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))
+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ start = tmp_path / 'project-a'
+ start.mkdir()
+ ref = create_local_session(authority, owner.actor, dict(request_id='m', source='gui', cwd=str(start),
+ model='frozen', toolsets=[], reasoning='low'))
+ return store, db, authority, owner, ref
+
+
+def _mutation(db, ref, request_id, operation, payload):
+ snap = db.get_session(ref.session_id)
+ return {'id': request_id, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': request_id, 'operation': operation, 'payload': payload,
+ 'expected_revision': snap['runtime_revision'], 'expected_generation': snap['runtime_generation']}}
+
+
+async def test_session_reasoning_mutation_is_the_next_turns_reasoning(tmp_path, monkeypatch):
+ from gateway.session_policy import policy_for_source
+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, None)
+ live = authority.sessions[ref.session_id]
+ try:
+ before = db.get_session(ref.session_id)
+ frozen_prompt = before['system_prompt']
+ response = await owner.dispatch(_mutation(db, ref, 'r1', 'reasoning', {'effort': 'high'}))
+ assert 'result' in response, response
+ assert response['result']['effort'] == 'high'
+ # The policy the next turn executes under, and what every viewer's session.info reports.
+ assert policy_for_source(authority.runner, live.source).reasoning_config == {'enabled': True, 'effort': 'high'}
+ info = await owner.dispatch({'id': 2, 'method': 'session.info', 'params': {'session_id': ref.session_id}})
+ assert info['result']['reasoning_effort'] == 'high'
+ after = db.get_session(ref.session_id)
+ assert after['runtime_revision'] > before['runtime_revision']
+ assert after['runtime_generation'] == before['runtime_generation'] + 1
+ assert after['system_prompt'] == frozen_prompt
+ # Durable: a restarted owner restores the new level from the receipt.
+ from hermes_state_local import local_receipt
+ assert json.loads(local_receipt(db, ref.session_id)['policy']['config_json'])['agent']['reasoning_effort'] == 'high'
+ bad = await owner.dispatch(_mutation(db, ref, 'r2', 'reasoning', {'effort': 'hgih'}))
+ assert bad['error']['data']['reason'] == 'invalid_params'
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+
+
+async def test_move_to_project_rehomes_the_policy_and_row_and_refuses_mid_turn(tmp_path, monkeypatch):
+ from gateway.session_contract import Submission
+ from gateway.session_policy import policy_for_source
+ from hermes_state_local import local_receipt
+ import hermes_state_runtime as rt
+ started, release, seen = asyncio.Event(), asyncio.Event(), []
+
+ async def handle(event):
+ seen.append(policy_for_source(authority.runner, event.source).cwd)
+ started.set()
+ await release.wait()
+ return 'ok'
+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
+ target = tmp_path / 'project-b'
+ target.mkdir()
+ try:
+ queued = await authority.submit(owner.actor, Submission('turn-1', ref, {'text': 'one'}, 'queue'))
+ await asyncio.wait_for(started.wait(), 10)
+ busy = await owner.dispatch(_mutation(db, ref, 'mv-busy', 'workspace', {'cwd': str(target)}))
+ assert busy['error']['data']['reason'] == 'session_busy', busy
+ assert db.get_session(ref.session_id)['cwd'] == str(tmp_path / 'project-a')
+ release.set()
+ async with asyncio.timeout(10):
+ while rt.get_session_admission(db, admission_id=queued.admission_id)['status'] != 'terminal':
+ await asyncio.sleep(0.02)
+ moved = await owner.dispatch(_mutation(db, ref, 'mv', 'workspace', {'cwd': str(target)}))
+ assert moved['result']['cwd'] == str(target), moved
+ policy = local_receipt(db, ref.session_id)['policy']
+ assert policy['cwd'] == str(target) and json.loads(policy['terminal_json'])['TERMINAL_CWD'] == str(target)
+ assert db.get_session(ref.session_id)['cwd'] == str(target)
+ info = await owner.dispatch({'id': 3, 'method': 'session.info', 'params': {'session_id': ref.session_id}})
+ assert info['result']['cwd'] == str(target)
+ started.clear()
+ second = await authority.submit(owner.actor, Submission('turn-2', ref, {'text': 'two'}, 'queue'))
+ await asyncio.wait_for(started.wait(), 10)
+ async with asyncio.timeout(10):
+ while rt.get_session_admission(db, admission_id=second.admission_id)['status'] != 'terminal':
+ await asyncio.sleep(0.02)
+ assert seen == [str(tmp_path / 'project-a'), str(target)]
+ missing = await owner.dispatch(_mutation(db, ref, 'mv-missing', 'workspace', {'cwd': str(tmp_path / 'nope')}))
+ assert missing['error']['data']['reason'] == 'invalid_params'
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index 0c784ef3018..c17992b66d2 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -79,7 +79,9 @@ canonical_method("prompt.resolve_unknown", params=PromptResolveUnknownParams, re
class SessionMutateParams(Params):
"""``operation`` + ``payload`` are validated by ``hermes_state_mutations.validate_action``;
- ``expected_generation`` is required for delete/rewind/reset/branch/model/compress."""
+ ``expected_generation`` is required for delete/rewind/reset/branch/model/compress/reasoning/workspace.
+ ``reasoning`` (``{effort}``) and ``workspace`` (``{cwd}``, refused ``session_busy`` mid-turn) rewrite
+ the session's frozen policy: session-scope ``/reasoning`` and Desktop's Move to project."""
session_id: str
request_id: str
@@ -101,7 +103,7 @@ class SessionMutateResult(OpenModel):
canonical_method("session.mutate", params=SessionMutateParams, result=SessionMutateResult,
doc="Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, "
- "delete, rewind, reset, model, compress, import).")
+ "delete, rewind, reset, model, reasoning, workspace, compress, import).")
class SessionPruneParams(Params):
diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.py
index f4078bbc408..680a5ddbe3d 100644
--- a/tui_gateway/ws_legacy_fallback.py
+++ b/tui_gateway/ws_legacy_fallback.py
@@ -25,14 +25,13 @@ _connection_profile_home: contextvars.ContextVar[str | None] = contextvars.Conte
# The authority owns every session, its transcript and its admissions: a legacy handler in these
# namespaces would write the same state.db behind its receipts and revision fence (a legacy
# ``session.delete`` dropped a row the authority still held live; ``session.branch_stored`` built a
-# second, legacy-owned runtime). Kept: store-wide reads, foreign-history import (new rows only), and
-# Desktop's project move (``session.workspace.move``), which rewrites only the row's cwd/git grouping
-# and has no authority verb yet.
+# second, legacy-owned runtime; ``session.workspace.move`` rewrote only the row, never the frozen
+# policy: Desktop sends ``session.mutate operation=workspace``). Kept: store-wide reads and
+# foreign-history import (new rows only).
_SESSION_NAMESPACES = ("session.", "prompt.", "message.")
_SESSION_FALLBACK_ALLOWED = frozenset({
"session.most_recent", "session.active_list", "session.events.stats",
"session.foreign.list", "session.foreign.preview", "session.foreign.import",
- "session.workspace.move",
})
# Sidecar verbs whose handler acts on PROCESS-global state. In a TUI's own sidecar that state was
# that TUI's alone; on the shared owner it is every chat's, Desktop window's and served profile's:
diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
index 43e927a8941..6764f2b5d06 100644
--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts
@@ -39,6 +39,10 @@ function harness() {
}
}
+ if (method === 'session.mutate' && params.operation === 'reasoning') {
+ return { session_id: 'owner', operation: 'reasoning', revision: 8, execution_generation: 4, effort: params.payload.effort }
+ }
+
if (method === 'prompt.receipt') {
return { status: 'terminal', result: { model: 'm', input_tokens: 5, output_tokens: 7, total_tokens: 12, api_calls: 1 } }
}
@@ -202,7 +206,7 @@ it('setting writes the shared gateway has no verb for say so instead of a bare i
const { request, slash, sys } = harness()
// dokterdok P3: the canonical config.set accepts only busy / verbose / yolo / model.
- for (const cmd of ['/theme dark', '/skin mono', '/indicator ascii', '/reasoning high', '/fast fast', '/personality pirate', '/skin']) {
+ for (const cmd of ['/theme dark', '/skin mono', '/indicator ascii', '/reasoning high --global', '/fast fast', '/personality pirate', '/skin']) {
slash(cmd)
}
@@ -219,3 +223,22 @@ it('setting writes the shared gateway has no verb for say so instead of a bare i
expect(notices.some(line => /skin: default/.test(line))).toBe(true)
})
+
+it('session /reasoning <level> is the owner\'s fenced reasoning mutation (B14); display words still refuse', async () => {
+ const { request, slash, sys } = harness()
+
+ slash('/reasoning high')
+ await flush()
+ slash('/reasoning show')
+ await flush()
+
+ expect(request).toHaveBeenCalledWith('session.mutate', expect.objectContaining({
+ session_id: 'owner', operation: 'reasoning', payload: { effort: 'high' }, expected_revision: 7, expected_generation: 3
+ }))
+ expect(request.mock.calls.map(([method]) => method)).not.toContain('config.set')
+
+ const notices = sys.mock.calls.map(([text]) => String(text))
+
+ expect(notices.some(line => /high/.test(line))).toBe(true)
+ expect(notices).toContain('/reasoning is not available on the shared gateway yet')
+})
diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.ts
index 73f636c2e22..308e94c5e66 100644
--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts
+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts
@@ -78,6 +78,39 @@ export async function renameCanonicalSession(
return mutation?.result ? String(mutation.result.title ?? title).trim() : undefined
}
+// The levels `hermes_constants.parse_reasoning_effort` accepts; the display words are config.yaml writes.
+const REASONING_EFFORTS = new Set([
+ 'none',
+ 'false',
+ 'disabled',
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max',
+ 'ultra'
+])
+
+/** Session-scope `/reasoning <level>`: the owner's revision-fenced `reasoning` mutation of the frozen
+ * policy. False when the shared gateway has no verb for it (`--global`, a display word). */
+export function canonicalReasoning(payload: { scope?: string; value: string }, ctx: SlashRunCtx): boolean {
+ const effort = payload.value.trim().toLowerCase()
+
+ if (payload.scope === 'global' || !REASONING_EFFORTS.has(effort)) {
+ return false
+ }
+
+ void mutateCanonical(ctx.gateway.gw, ctx.sid!, 'reasoning', { effort }, ctx.stale)
+ .then(
+ mutation =>
+ mutation?.result && !ctx.stale() && ctx.transcript.sys(t('slashCmd.session.reasoning.current', effort))
+ )
+ .catch(ctx.guardedErr)
+
+ return true
+}
+
/** `/undo` and `/retry`: rewind to before the newest user turn; `/retry` then resubmits its text. */
export function canonicalRewind(intent: 'retry' | 'undo', ctx: SlashRunCtx) {
const sid = ctx.sid!
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index aa5c7e88aff..264ad52f71f 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -45,7 +45,7 @@ function modelPayload(arg: string) {
return payload
}
-export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'rewind'
+export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'rewind' | 'reasoning'
/** The snapshot a mutation's CAS tuple was read from; `payload` may derive its target from it. */
export interface MutationSnapshot {
diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.ts
index 1151e93f327..f330a9f9079 100644
--- a/ui-tui/src/app/slash/commands/session.ts
+++ b/ui-tui/src/app/slash/commands/session.ts
@@ -20,7 +20,7 @@ import { applyConfiguredTuiTheme } from '../../createGatewayEventHandler.js'
import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '../../interfaces.js'
import { patchOverlayState } from '../../overlayStore.js'
import { getUiState, patchUiState } from '../../uiStore.js'
-import { canonicalUsage } from '../canonicalSessionCommands.js'
+import { canonicalReasoning, canonicalUsage } from '../canonicalSessionCommands.js'
import { runCanonicalSessionControl } from '../canonicalSessionControls.js'
import type { SlashCommand, SlashRunCtx } from '../types.js'
@@ -665,13 +665,15 @@ export const sessionCommands: SlashCommand[] = [
)
}
- // The shared owner serves this setting's read, not its write (a config.yaml / per-session
- // setting it has no frozen-policy verb for yet): say so instead of a bare invalid_params.
+ const payload = reasoningConfigPayload(arg, ctx.sid ?? '')
+
+ // The shared owner sets a session level through its frozen-policy mutation; it has no verb for
+ // the config.yaml writes (`--global`, the display words): say so instead of a bare invalid_params.
if (ctx.gateway.gw?.isCanonical) {
- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'reasoning'))
+ return canonicalReasoning(payload, ctx) || ctx.transcript.sys(t('canonical.controls.notAvailable', 'reasoning'))
}
- ctx.gateway.rpc<ConfigSetResponse>('config.set', reasoningConfigPayload(arg, ctx.sid ?? '')).then(
+ ctx.gateway.rpc<ConfigSetResponse>('config.set', payload).then(
ctx.guarded<ConfigSetResponse>(r => {
if (!r.value) {
return