Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(mcp-host): add session rename endpoint (spec 15 Phase B)
Diego Zacarias1731e763d3fc
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 229cf9981..7847c178f 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.319",+ "version": "0.1.320","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.319",+ "version": "0.1.320","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 21dcbdfcc..d0c0c6a19 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.319",+ "version": "0.1.320","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/__tests__/sessionTitle.test.ts b/mcp-host/src/agent/__tests__/sessionTitle.test.tsnew file mode 100644index 000000000..b5c3d8585--- /dev/null+++ b/mcp-host/src/agent/__tests__/sessionTitle.test.ts@@ -0,0 +1,213 @@+import { describe, expect, it, vi } from 'vitest'+import { ConversationManager } from '../../core/conversation/conversation'+import { InMemoryConversationStore } from '../../core/conversation/conversationStore'+import { makeSqliteStore } from '../../core/conversation/persistence/__tests__/testHelpers'+import { serializeSessionKey } from '../../session'+import { applySessionTitle } from '../sessionTitle'++const USER = 'u-1'+const AGENT = 'agent-x'+const CHAT = 'chat-1'++function rpcKey(user = USER, agent = AGENT, chat = CHAT): string {+ return serializeSessionKey({+ userId: user,+ channelType: 'rpc',+ channelId: agent,+ threadId: chat,+ })+}++async function seedRpcSession(manager: ConversationManager, user = USER): Promise<void> {+ await manager.getOrCreate(rpcKey(user), {+ userId: user,+ channelType: 'rpc',+ channelId: AGENT,+ threadId: CHAT,+ source: 'rpc',+ })+}++describe('applySessionTitle — validation + sanitization (spec 15 §5)', () => {+ it('renames an existing owned session and sets the sanitized title in RAM', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)++ const res = await applySessionTitle(+ { convManager: manager },+ USER,+ AGENT,+ CHAT,+ ' Quarterly plan '+ )+ expect(res).toEqual({ ok: true, title: 'Quarterly plan' })+ const conv = await manager.getSessionByKeyForUserAsync(rpcKey(), USER)+ expect(conv?.title).toBe('Quarterly plan')+ })++ it('strips bidi/zero-width from the rename (shared sanitizer, D4)', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)++ const res = await applySessionTitle({ convManager: manager }, USER, AGENT, CHAT, 'abcde')+ expect(res.ok).toBe(true)+ if (res.ok) expect(/\p{C}/u.test(res.title)).toBe(false)+ })++ it('rejects an empty-after-sanitize title (400/invalid_title)', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)++ for (const raw of ['', ' ', '', '\n\t']) {+ const res = await applySessionTitle({ convManager: manager }, USER, AGENT, CHAT, raw)+ expect(res).toEqual({ ok: false, reason: 'invalid_title' })+ }+ })++ it('rejects a title over the 120 code-point cap', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)++ const res = await applySessionTitle(+ { convManager: manager },+ USER,+ AGENT,+ CHAT,+ 'x'.repeat(121)+ )+ expect(res).toEqual({ ok: false, reason: 'invalid_title' })+ // Exactly 120 is allowed.+ const ok = await applySessionTitle({ convManager: manager }, USER, AGENT, CHAT, 'y'.repeat(120))+ expect(ok.ok).toBe(true)+ })++ it('accepts 120 astral (4-byte) code points; the byte cap is a backstop the cp cap makes unreachable', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)+ // 120 astral code points = 480 UTF-8 bytes, within both caps. Since 120 cp+ // can be at most 480 bytes (< 512), the 512-byte cap can never bind before+ // the code-point cap — it is a defensive backstop, not a reachable branch.+ const title = '𝕏'.repeat(120)+ const within = await applySessionTitle({ convManager: manager }, USER, AGENT, CHAT, title)+ expect(within.ok).toBe(true)+ if (within.ok) expect(Buffer.byteLength(within.title, 'utf8')).toBe(480)+ })+})++describe('applySessionTitle — ownership + anti-enumeration (uniform 404)', () => {+ it('returns not_found for a session owned by another user (no oracle)', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager, USER)++ const res = await applySessionTitle({ convManager: manager }, 'u-2', AGENT, CHAT, 'Hijack')+ expect(res).toEqual({ ok: false, reason: 'not_found' })+ // Original owner's title untouched.+ const conv = await manager.getSessionByKeyForUserAsync(rpcKey(USER), USER)+ expect(conv?.title).toBeUndefined()+ })++ it('returns the SAME not_found for a session that does not exist', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ const res = await applySessionTitle({ convManager: manager }, USER, AGENT, 'ghost', 'X')+ expect(res).toEqual({ ok: false, reason: 'not_found' })+ })++ it('does not create a row (no getOrCreate) on a missing session', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await applySessionTitle({ convManager: manager }, USER, AGENT, 'ghost', 'X')+ expect(+ await manager.getSessionByKeyForUserAsync(rpcKey(USER, AGENT, 'ghost'), USER)+ ).toBeUndefined()+ })++ it('does not rename a channel session (not renamable by this route)', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ // A telegram session keyed under channelType 'telegram' — the rpc-shaped key+ // this route builds can never resolve it.+ const chanKey = serializeSessionKey({+ userId: USER,+ channelType: 'telegram',+ channelId: 'tg-chan',+ threadId: CHAT,+ })+ const chan = await manager.getOrCreate(chanKey, {+ userId: USER,+ channelType: 'telegram',+ channelId: 'tg-chan',+ threadId: CHAT,+ source: 'telegram',+ })++ const res = await applySessionTitle(+ { convManager: manager },+ USER,+ 'tg-chan',+ CHAT,+ 'Rename me'+ )+ expect(res).toEqual({ ok: false, reason: 'not_found' })+ expect(chan.title).toBeUndefined()+ })+})++describe('applySessionTitle — no-op when unchanged (§5, shared persistQueue)', () => {+ it('does not re-persist when the incoming title equals the current one', async () => {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await seedRpcSession(manager)+ await applySessionTitle({ convManager: manager }, USER, AGENT, CHAT, 'Stable Name')++ const setTitle = vi.spyOn(manager, 'setTitle')+ const res = await applySessionTitle(+ { convManager: manager },+ USER,+ AGENT,+ CHAT,+ ' Stable Name '+ )+ expect(res).toEqual({ ok: true, title: 'Stable Name' })+ expect(setTitle).not.toHaveBeenCalled()+ })+})++describe('applySessionTitle — durable persistence (SQLite, real producer T1)', () => {+ it('overwrites sessions.title and rehydrates on cold-load', async () => {+ const handle = makeSqliteStore()+ try {+ const manager = new ConversationManager(handle.store)+ // Seed with a turn-1 auto-title, then rename overwrites it (unlike COALESCE).+ const conv = await manager.getOrCreate(rpcKey(), {+ userId: USER,+ channelType: 'rpc',+ channelId: AGENT,+ threadId: CHAT,+ source: 'rpc',+ })+ await manager.startTurn(conv, 'first message', 'task-1', null, 'Auto Title')+ await manager.completeTurn(conv, 'ok')++ const res = await applySessionTitle(+ { convManager: manager },+ USER,+ AGENT,+ CHAT,+ 'User Renamed'+ )+ expect(res).toEqual({ ok: true, title: 'User Renamed' })+ await handle.persistQueue.drainSessionKey(rpcKey())++ const row = handle.worker.db+ .prepare('SELECT title FROM sessions WHERE id = ?')+ .get(conv.id) as { title: string }+ expect(row.title).toBe('User Renamed')++ // Cold-load rehydrates the renamed title.+ handle.store['cache'].delete(rpcKey())+ handle.store['ordinals'].clear()+ handle.store['sessionKeyById'].clear()+ const reloaded = await handle.store.getOrLoad(rpcKey())+ expect(reloaded?.title).toBe('User Renamed')+ } finally {+ await handle.shutdown()+ }+ })+})diff --git a/mcp-host/src/agent/sessionTitle.ts b/mcp-host/src/agent/sessionTitle.tsnew file mode 100644index 000000000..778875c33--- /dev/null+++ b/mcp-host/src/agent/sessionTitle.ts@@ -0,0 +1,86 @@+/**+ * Spec 15 Fase B — per-session rename core. Shared, dependency-injected so it is+ * unit-testable outside `main.ts`. Wired by the `PATCH /v1/runtime/sessions/+ * :agent/:chatId/name` route (`handleSetTitleRoute`).+ *+ * Behaviour: sanitize + validate the caller-supplied title (§5), resolve the+ * session by exact key scoped to `userSub`, and overwrite `sessions.title`.+ * Key-derivation contract mirrors the session-read routes: the "agent" slot is+ * the desktop's rpc `channelId` and `chatId` maps to `threadId`, so this renames+ * the SAME row the catalog/messages routes read.+ *+ * Ownership + anti-enumeration: uses `getSessionByKeyForUserAsync` (NOT+ * `getOrCreate` — a rename must never create a row), which collapses "does not+ * exist" and "owned by another user" into `undefined` → a UNIFORM 404. Channel+ * sessions (Slack/Telegram) are not renamable by construction: their key carries+ * a non-`rpc` channelType, so the rpc-shaped key built here can never resolve one+ * (→ 404). No secret handling here; the title is user content, logged only by+ * length (§5).+ */+import type { ConversationManager } from '../core/conversation/conversation'+import {+ MAX_TITLE_BYTES,+ MAX_TITLE_CODE_POINTS,+ normalizeTitleText,+} from '../core/conversation/sessionTitle'+import type { SetTitleResult } from '../server/types'+import { serializeSessionKey } from '../session'++export interface SessionTitleDeps {+ convManager: ConversationManager+}++export async function applySessionTitle(+ deps: SessionTitleDeps,+ userSub: string,+ agent: string,+ chatId: string,+ rawTitle: string+): Promise<SetTitleResult> {+ const { convManager } = deps++ // §5 — sanitize with the SAME core as the auto-title (D4), then enforce the+ // rename policy: non-empty after sanitize, capped at 120 code points / 512+ // bytes. Reject over-cap (400) rather than silently truncating so the user's+ // stored name is never a surprise.+ const title = normalizeTitleText(rawTitle)+ if (+ title.length === 0 ||+ Array.from(title).length > MAX_TITLE_CODE_POINTS ||+ Buffer.byteLength(title, 'utf8') > MAX_TITLE_BYTES+ ) {+ return { ok: false as const, reason: 'invalid_title' as const }+ }++ const key = serializeSessionKey({+ userId: userSub,+ channelType: 'rpc',+ channelId: agent,+ threadId: chatId,+ })+ // Uniform 404 for missing / foreign / channel sessions (no existence oracle).+ const conversation = await convManager.getSessionByKeyForUserAsync(key, userSub)+ if (!conversation) {+ return { ok: false as const, reason: 'not_found' as const }+ }++ // No-op if unchanged (§5): there is no rate limit and every rename is an op on+ // the persistQueue shared with turn persistence, so skip the write when the+ // title already matches (the client already holds this canonical value).+ if (conversation.title === title) {+ return { ok: true as const, title }+ }++ convManager.setTitle(conversation, title)+ // NEVER log the raw title (user content, §5) — only its length + the chatId.+ console.info(+ JSON.stringify({+ level: 'info',+ event: 'set_session_title',+ userId: userSub,+ chatId,+ titleLength: title.length,+ })+ )+ return { ok: true as const, title }+}diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.tsindex 5c7e2e715..35951b871 100644--- a/mcp-host/src/core/conversation/conversation.ts+++ b/mcp-host/src/core/conversation/conversation.ts@@ -658,6 +658,19 @@ export class ConversationManager {void Promise.resolve(this.store.persistModelSelections?.(conversation))}+ /**+ * Spec 15 Fase B — overwrite the session title from an explicit user rename+ * and write it through to the durable `sessions.title` column. Unlike the+ * auto-title (`??=` on turn 1), a rename always wins. Caller+ * (`applySessionTitle`) has already sanitized + validated `title`. Does NOT+ * bump `updated_at`: a rename must not reorder the catalog (mirrors+ * `setModelSelection`).+ */+ setTitle(conversation: Conversation, title: string): void {+ conversation.title = title+ void Promise.resolve(this.store.persistTitle?.(conversation))+ }+/*** Build the ChatMessage[] history from conversation turns.* Used to reconstruct messages for the ReasoningPort.diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex 6b10a71a7..43146579f 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -323,6 +323,14 @@ export interface ConversationStore {*/persistModelSelections?(conv: Conversation): Promise<void> | void+ /**+ * Spec 15 Fase B — persist a user rename (`sessions.title` overwrite). Async+ * (enqueued via the worker), keyed by sessionKey. In-memory stores no-op (the+ * title already lives on the Conversation object). Optional so legacy stores+ * don't have to implement it.+ */+ persistTitle?(conv: Conversation): Promise<void> | void+/*** Accumulate the token usage of ONE LLM call into the durable per-session* counters. Additive (`col = col + delta`). Async (enqueued via the worker);@@ -500,6 +508,10 @@ export class InMemoryConversationStore implements ConversationStore {/* no-op — RAM-only store keeps the selection on the Conversation object */}+ persistTitle(_conv: Conversation): void {+ /* no-op — RAM-only store keeps the title on the Conversation object */+ }+persistSessionUsage(_conv: Conversation, _usage: SessionTokenUsage): void {/* no-op — RAM-only store does not persist counters */}diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex f6d98a9e2..de33ee306 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -998,6 +998,22 @@ export class SqliteConversationStore implements ConversationStore {})}+ /**+ * Spec 15 Fase B — persist a user rename. Enqueued (async) and keyed by+ * sessionKey so it chains AFTER the session's own writes on the FIFO chain.+ * `ConversationManager.setTitle` sets `conv.title` (a validated non-empty+ * string) before calling this; the op overwrites `sessions.title` verbatim.+ */+ persistTitle(conv: Conversation): void {+ const sessionKey = this.sessionKeyById.get(conv.id)+ if (!sessionKey) return+ this.persistQueue.enqueueAsync(sessionKey, {+ kind: 'update_session_title',+ sessionId: conv.id,+ title: conv.title ?? '',+ })+ }+async persistSuspend(conv: Conversation, approval: PendingApproval): Promise<void> {const sessionKey = this.sessionKeyById.get(conv.id)if (!sessionKey) returndiff --git a/mcp-host/src/core/conversation/sessionTitle.ts b/mcp-host/src/core/conversation/sessionTitle.tsindex ec5d60d6c..742a353c3 100644--- a/mcp-host/src/core/conversation/sessionTitle.ts+++ b/mcp-host/src/core/conversation/sessionTitle.ts@@ -29,6 +29,39 @@ export const AUTO_TITLE_SUFFIX = '…' // … (U+2026 HORIZONTAL ELLIPSIS)*/export const AUTO_TITLE_MAX_CODE_POINTS = 60+/** Rename caps (spec 15 §5). Code-point cap for BMP text; byte cap binds first+ * for astral-heavy titles (up to 4 bytes/code point). */+export const MAX_TITLE_CODE_POINTS = 120+export const MAX_TITLE_BYTES = 512++/**+ * Shared text-sanitization core for BOTH the auto-title derivation and the+ * user rename (spec 15 §5, D4 — one implementation of the rule). Normalizes+ * and folds whitespace, strips invisible control/format code points, and+ * collapses/trims. Does NOT truncate and does NOT redact (the caller owns+ * redaction and any length policy).+ *+ * Order matters: fold `\s+` → space BEFORE stripping `\p{C}`, because `\n`/`\t`+ * are themselves `\p{C}` — a strip-before-collapse order would delete them and+ * glue two words together. A second collapse removes a double space left when a+ * stripped format char sat between two spaces.+ */+export function normalizeTitleText(input: string): string {+ return (+ input+ .normalize('NFC')+ // Fold every whitespace variant (newline, tab, NBSP, line/para separators).+ .replace(/\s+/g, ' ')+ // Strip bidi overrides, zero-width, and any other invisible control/format+ // code point (`\p{C}`) that `\s` does not cover. Spaces are `\p{Zs}`, not+ // `\p{C}`, so word boundaries survive; valid astral chars (emoji) are their+ // own category, so only lone surrogates are dropped.+ .replace(/\p{C}/gu, '')+ .replace(/\s+/g, ' ')+ .trim()+ )+}+/*** Derive a short session title from a (already-redacted) user input.*@@ -41,21 +74,7 @@ export const AUTO_TITLE_MAX_CODE_POINTS = 60* is no space, cut at 60 hard. Append the suffix in both cases.*/export function deriveAutoTitle(userInput: string): string {- const collapsed = userInput- .normalize('NFC')- // Fold every whitespace variant (newline, tab, NBSP, line/para separators)- // to a single space FIRST, so the control-char strip below never joins two- // words across a newline — `\n` is itself a `\p{C}` control char, so a- // strip-before-collapse order would delete it and glue the words together.- .replace(/\s+/g, ' ')- // Strip bidi overrides, zero-width, and any other invisible control/format- // code point (`\p{C}`) that `\s` does not cover. Spaces are `\p{Zs}`, not- // `\p{C}`, so word boundaries survive; valid astral chars (emoji) are their- // own category, so only lone surrogates are dropped.- .replace(/\p{C}/gu, '')- // A stripped format char sitting between two spaces leaves a double space.- .replace(/\s+/g, ' ')- .trim()+ const collapsed = normalizeTitleText(userInput)// Code points, not UTF-16 units — Array.from iterates by code point.const codePoints = Array.from(collapsed)if (codePoints.length <= AUTO_TITLE_MAX_CODE_POINTS) return collapseddiff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex 459931125..c025c6bcb 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -26,6 +26,7 @@ export interface PreparedStatements {updateSessionPromptStableHash: StatementupdateSessionModelSelections: StatementsetSessionTitleIfAbsent: Statement+ updateSessionTitle: StatementselectSessionBySessionKey: StatementselectSessionsByPrefix: StatementselectSessionSummariesByPrefix: Statement@@ -184,6 +185,14 @@ export function prepareStatements(db: Database): PreparedStatements {SET title = COALESCE(title, @title)WHERE id = @id`),+ // Spec 15 Fase B — unconditional overwrite of the user-set title (rename).+ // Independent of `setSessionTitleIfAbsent` (COALESCE, auto-title) and of+ // `updateSessionState` (shared with persistTurnFail; must not gain @title).+ updateSessionTitle: db.prepare(`+ UPDATE sessions+ SET title = @title+ WHERE id = @id+ `),updateSessionCounters: db.prepare(`UPDATE sessionsSET message_count = message_count + @message_count_delta,diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex 91a1a55d2..de6895de2 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -425,6 +425,16 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unknreturn { ok: true }})+ case 'update_session_title':+ // Spec 15 Fase B — unconditional overwrite (rename wins over the auto-title).+ return withBusyRetry(() => {+ const tx = db.transaction(() => {+ s.updateSessionTitle.run({ id: op.sessionId, title: op.title })+ })+ tx.immediate()+ return { ok: true }+ })+case 'insert_message':return withBusyRetry(() => {const tx = db.transaction(() => {diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.tsindex 0bde5e0ea..63857137c 100644--- a/mcp-host/src/db/worker/protocol.ts+++ b/mcp-host/src/db/worker/protocol.ts@@ -220,6 +220,14 @@ export type WorkerOp =sessionId: stringmodelSelections: string}+ | {+ /** Spec 15 Fase B — overwrite the user-set session title (rename). Unlike+ * the Fase A auto-title (COALESCE, turn 1 only), this UNCONDITIONALLY+ * overwrites: an explicit rename always wins. */+ kind: 'update_session_title'+ sessionId: string+ title: string+ }| { kind: 'insert_message'; payload: MessageRow }| {/**@@ -331,6 +339,7 @@ export function isWriteOp(op: WorkerOp): boolean {case 'update_session_counters':case 'update_session_prompt_stable_hash':case 'update_session_model_selections':+ case 'update_session_title':case 'insert_message':case 'persist_turn_boundary':case 'replace_messages':diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 04f86e6a2..ace4ce076 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -19,6 +19,7 @@ import type { ResolvedTaskModel } from './agent'import { agentToolEnvProvider } from './agent/agentToolEnv'import type { PendingCronResult } from './agent/cronDispatch'import { applySessionModelSelection as applySessionModelSelectionCore } from './agent/sessionModelSelection'+import { applySessionTitle as applySessionTitleCore } from './agent/sessionTitle'import { BudgetClient } from './budget/budgetClient'// Structured JSON logging — must be first importimport { config } from './config'@@ -129,6 +130,7 @@ import {RPCServer,RuntimeCallerContext,SetModelResult,+ SetTitleResult,StatusResponse,TelegramWorkflowApprovalVerification,WorkflowApprovalMediumEnrollment,@@ -1884,6 +1886,25 @@ function applySessionModelSelection()}+// Spec 15 Fase B — thin wrapper that injects the conversation manager into the+// shared `applySessionTitleCore` (sanitize/validate title, resolve by exact key+// scoped to the user, overwrite `sessions.title`). `agentName` is the rpc+// channelId slot (matches the session-read routes), not the Agent instance.+function applySessionTitle(+ userSub: string,+ agentName: string,+ chatId: string,+ title: string+): Promise<SetTitleResult> {+ return applySessionTitleCore(+ { convManager: agent!.getConversationManager() },+ userSub,+ agentName,+ chatId,+ title+ )+}+/*** Handle incoming message from channel-reader.*@@ -2659,6 +2680,10 @@ async function startRPCServer(): Promise<void> {const handleSetModel = (userSub: string, hostRef: string, chatId: string, model: string) =>applySessionModelSelection(userSub, hostRef, chatId, model)+ // Spec 15 Fase B — PATCH /v1/runtime/sessions/:agent/:chatId/name rename adapter.+ const handleSetTitle = (userSub: string, agentName: string, chatId: string, title: string) =>+ applySessionTitle(userSub, agentName, chatId, title)+rpcServer.onMessage(handleIncomingMessage)rpcServer.setArtifactSecretEntriesProvider(() => configStore?.listSecretEntries() ?? [])rpcServer.onStatus(getStatus)@@ -2683,6 +2708,7 @@ async function startRPCServer(): Promise<void> {rpcServer.onContextBreakdown(handleContextBreakdown)rpcServer.onModelsList(handleModelsList)rpcServer.onSetModel(handleSetModel)+ rpcServer.onSetTitle(handleSetTitle)// T3.1 — session search REST endpoint. Only wired when the feature is// enabled and the SQLite backend is live; otherwise the route returns 501// through `handleSessionSearchRoute`.diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.tsindex 7d094f1a5..c7039bcea 100644--- a/mcp-host/src/server.ts+++ b/mcp-host/src/server.ts@@ -35,6 +35,7 @@ import {handleSessionSearchRoute,handleSessionsListRoute,handleSetModelRoute,+ handleSetTitleRoute,handleStatusRoute,handleTaskResultRoute,handleTelegramWorkflowApprovalVerificationRoute,@@ -63,6 +64,7 @@ import type {SessionSearchHandler,SessionsListHandler,SetModelHandler,+ SetTitleHandler,StatusHandler,TaskResultHandler,TelegramWorkflowApprovalVerificationHandler,@@ -123,6 +125,7 @@ export type {SessionSearchRequest,SessionSearchResponse,SetModelResult,+ SetTitleResult,} from './server/types'export class RPCServer {@@ -160,6 +163,7 @@ export class RPCServer {private compactionHandler: CompactionHandler | null = nullprivate modelsListHandler: ModelsListHandler | null = nullprivate setModelHandler: SetModelHandler | null = null+ private setTitleHandler: SetTitleHandler | null = nullprivate workflowRouter: ReturnType<typeof createWorkflowRouter> | null = nullprivate artifactSecretEntriesProvider: (() => ArtifactSecretEntry[]) | null = nullprivate lifecycleGate: RuntimeLifecycleGate | null = null@@ -437,6 +441,15 @@ export class RPCServer {this.app.post('/v1/runtime/model', runtimeEdgeGuard(['rpc-proxy']), async (req, res) => {await handleSetModelRoute(req, res, this.routeDeps())})+ // Spec 15 Fase B — per-session rename. Behind the same edge guard: rpc-proxy+ // has enforced host:session:write and injects the verified edge user + hostRef.+ this.app.patch(+ '/v1/runtime/sessions/:agent/:chatId/name',+ runtimeEdgeGuard(['rpc-proxy']),+ async (req, res) => {+ await handleSetTitleRoute(req, res, this.routeDeps())+ }+ )this.app.get('/v1/runtime/cron/results', runtimeEdgeGuard(['channel-reader']), (req, res) => {handleCronResultsRoute(req, res, this.routeDeps())@@ -695,6 +708,10 @@ export class RPCServer {this.setModelHandler = handler}+ onSetTitle(handler: SetTitleHandler): void {+ this.setTitleHandler = handler+ }+/** Activate workflow mode — mounts /api/v1/workflow/* routes. */setWorkflowService(service: WorkflowService): void {this.workflowRouter = createWorkflowRouter(service)@@ -736,6 +753,7 @@ export class RPCServer {compactionHandler: this.compactionHandler,modelsListHandler: this.modelsListHandler,setModelHandler: this.setModelHandler,+ setTitleHandler: this.setTitleHandler,}}diff --git a/mcp-host/src/server/__tests__/setTitleRoute.test.ts b/mcp-host/src/server/__tests__/setTitleRoute.test.tsnew file mode 100644index 000000000..03ba3b899--- /dev/null+++ b/mcp-host/src/server/__tests__/setTitleRoute.test.ts@@ -0,0 +1,159 @@+import { describe, expect, it, vi } from 'vitest'+import type { Request, Response } from 'express'+import { applySessionTitle } from '../../agent/sessionTitle'+import { ConversationManager } from '../../core/conversation/conversation'+import { InMemoryConversationStore } from '../../core/conversation/conversationStore'+import { serializeSessionKey } from '../../session'+import { handleSetTitleRoute } from '../routes'+import type { SetTitleHandler } from '../types'+import { makeHandlers } from './testHelpers'++function makeRes() {+ const captured: { statusCode?: number; jsonBody?: unknown } = {}+ const res = {+ writeHead: vi.fn().mockImplementation((status: number) => {+ captured.statusCode = status+ return res+ }),+ end: vi.fn().mockImplementation((body?: string) => {+ if (typeof body === 'string') {+ try {+ captured.jsonBody = JSON.parse(body)+ } catch {+ captured.jsonBody = body+ }+ }+ return res+ }),+ } as unknown as Response+ return {+ get statusCode() {+ return captured.statusCode+ },+ get jsonBody() {+ return captured.jsonBody+ },+ res,+ }+}++function makeReq(opts: {+ caller?: { caller: string; userId?: string; hostRef?: string }+ agent?: string+ chatId?: string+ body?: unknown+}): Request {+ return {+ runtimeCaller: opts.caller,+ params: { agent: opts.agent ?? 'agent-x', chatId: opts.chatId ?? 'chat-1' },+ body: opts.body,+ query: {},+ } as unknown as Request+}++const RPC_CALLER = { caller: 'rpc-proxy', userId: 'u-1', hostRef: 'agent-x' }++async function managerWithSession(user = 'u-1'): Promise<ConversationManager> {+ const manager = new ConversationManager(new InMemoryConversationStore())+ await manager.getOrCreate(+ serializeSessionKey({+ userId: user,+ channelType: 'rpc',+ channelId: 'agent-x',+ threadId: 'chat-1',+ }),+ { userId: user, channelType: 'rpc', channelId: 'agent-x', threadId: 'chat-1', source: 'rpc' }+ )+ return manager+}++/** Wire the REAL core (T1) behind the route so 404-uniform / validation are genuine. */+function realHandler(manager: ConversationManager): SetTitleHandler {+ return (userSub, agent, chatId, title) =>+ applySessionTitle({ convManager: manager }, userSub, agent, chatId, title)+}++describe('handleSetTitleRoute (spec 15 Fase B)', () => {+ it('401 when the caller is not rpc-proxy', async () => {+ const manager = await managerWithSession()+ const captured = makeRes()+ await handleSetTitleRoute(+ makeReq({ caller: { caller: 'channel-reader', userId: 'u-1' }, body: { title: 'x' } }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(401)+ })++ it('400 invalid title for an empty/whitespace body', async () => {+ const manager = await managerWithSession()+ const captured = makeRes()+ await handleSetTitleRoute(+ makeReq({ caller: RPC_CALLER, body: { title: ' ' } }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(400)+ expect(captured.jsonBody).toEqual({ error: 'invalid title' })+ })++ it('404 (uniform) for a non-existent session', async () => {+ const manager = await managerWithSession()+ const captured = makeRes()+ await handleSetTitleRoute(+ makeReq({ caller: RPC_CALLER, chatId: 'ghost', body: { title: 'New' } }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(404)+ expect(captured.jsonBody).toEqual({ error: 'session not found' })+ })++ it('404 (SAME shape) for a session owned by another user — no oracle', async () => {+ const manager = await managerWithSession('u-1')+ const captured = makeRes()+ await handleSetTitleRoute(+ // caller is u-2, session belongs to u-1+ makeReq({+ caller: { caller: 'rpc-proxy', userId: 'u-2', hostRef: 'agent-x' },+ body: { title: 'New' },+ }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(404)+ expect(captured.jsonBody).toEqual({ error: 'session not found' })+ })++ it('200 with the sanitized canonical title on success', async () => {+ const manager = await managerWithSession()+ const captured = makeRes()+ await handleSetTitleRoute(+ makeReq({ caller: RPC_CALLER, body: { title: ' Quarterly plan ' } }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(200)+ expect(captured.jsonBody).toEqual({ ok: true, title: 'Quarterly plan' })+ })++ it('never logs the raw title — only titleLength (T4)', async () => {+ const manager = await managerWithSession()+ const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})+ try {+ const captured = makeRes()+ const secretish = 'MyPrivateBoardName'+ await handleSetTitleRoute(+ makeReq({ caller: RPC_CALLER, body: { title: secretish } }),+ captured.res,+ makeHandlers({ setTitleHandler: realHandler(manager) })+ )+ expect(captured.statusCode).toBe(200)+ const allLogs = infoSpy.mock.calls.map(args => args.join(' ')).join('\n')+ expect(allLogs).not.toContain(secretish)+ expect(allLogs).toContain('titleLength')+ } finally {+ infoSpy.mockRestore()+ }+ })+})diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex dbe368d3e..fb5354394 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -28,6 +28,7 @@ import type {SessionSearchHandler,SessionsListHandler,SetModelHandler,+ SetTitleHandler,StatusHandler,TaskResultHandler,TelegramWorkflowApprovalVerificationHandler,@@ -63,6 +64,7 @@ export type RouteHandlers = {compactionHandler?: CompactionHandler | nullmodelsListHandler?: ModelsListHandler | nullsetModelHandler?: SetModelHandler | null+ setTitleHandler?: SetTitleHandler | null}function isSessionOwnershipError(error: unknown): boolean {@@ -164,6 +166,8 @@ export function runtimeApiInfo() {'DELETE /v1/runtime/cron/results/:id': 'Acknowledge cron result delivery','GET /v1/runtime/sessions': 'List active sessions for the authenticated user','GET /v1/runtime/sessions/:agent/:chatId/messages': 'Get message history for a session',+ 'PATCH /v1/runtime/sessions/:agent/:chatId/name':+ 'Rename a session (server-authoritative title)','GET /v1/runtime/sessions/search':'Full-text search across past messages of the authenticated user','GET /v1/runtime/models': 'List selectable models for the session (per-session selection)',@@ -194,6 +198,7 @@ export function runtimeApiInfo() {'DELETE /v1/runtime/cron/results/:id': 'onCronResultAck(handler)','GET /v1/runtime/sessions': 'onSessionsList(handler)','GET /v1/runtime/sessions/:agent/:chatId/messages': 'onSessionMessages(handler)',+ 'PATCH /v1/runtime/sessions/:agent/:chatId/name': 'onSetTitle(handler)','GET /v1/runtime/sessions/search': 'onSessionSearch(handler)','GET /v1/runtime/models': 'onModelsList(handler)','POST /v1/runtime/model': 'onSetModel(handler)',@@ -1431,6 +1436,55 @@ export async function handleSetModelRoute(}}+/**+ * Spec 15 Fase B — PATCH /v1/runtime/sessions/:agent/:chatId/name `{ title }`.+ * Overwrites the session title from an explicit user rename. `:agent`/`:chatId`+ * come from the path (same key derivation as the read routes); the title comes+ * from the body and is sanitized + validated by the shared core. Uniform 404 for+ * missing / foreign / channel sessions (anti-enumeration). The raw title is NEVER+ * logged — user content (§5).+ */+export async function handleSetTitleRoute(+ req: Request,+ res: Response,+ handlers: RouteHandlers+): Promise<void> {+ try {+ const caller = getRuntimeCallerContext(req)+ if (caller?.caller !== 'rpc-proxy' || !caller.userId) {+ json(res, 401, { error: 'Missing rpc edge caller context' })+ return+ }+ const agent = String(req.params.agent || '').trim()+ const chatId = String(req.params.chatId || '').trim()+ if (!isSafeAgentRouteSegment(agent) || !isSafeRouteSegment(chatId)) {+ badRequest(res, 'Invalid agent or chatId')+ return+ }+ if (!handlers.setTitleHandler) {+ json(res, 501, { error: 'Set title handler not configured' })+ return+ }+ const body = (req.body as Record<string, unknown>) || {}+ // All title-validity logic (sanitize, non-empty, cap) lives in the core so+ // it stays single-sourced (D4); a non-string body.title becomes '' → invalid.+ const rawTitle = typeof body.title === 'string' ? body.title : ''+ const result = await handlers.setTitleHandler(caller.userId, agent, chatId, rawTitle)+ if (!result.ok) {+ if (result.reason === 'not_found') {+ json(res, 404, { error: 'session not found' })+ return+ }+ json(res, 400, { error: 'invalid title' })+ return+ }+ json(res, 200, { ok: true, title: result.title })+ } catch (error) {+ console.error('[Server] Error setting session title:', error)+ json(res, 500, { error: error instanceof Error ? error.message : 'Unknown error' })+ }+}+export async function handleProgressStreamRoute(req: Request,res: Response,diff --git a/mcp-host/src/server/types.ts b/mcp-host/src/server/types.tsindex 63e18787e..cafb9fa5d 100644--- a/mcp-host/src/server/types.ts+++ b/mcp-host/src/server/types.ts@@ -660,3 +660,22 @@ export type SetModelHandler = (chatId: string,model: string) => SetModelResult | Promise<SetModelResult>++/**+ * Result of `PATCH /v1/runtime/sessions/:agent/:chatId/name` (spec 15 Fase B).+ * `ok` → 200 `{ ok:true, title }` (the server's sanitized canonical title, which+ * the client adopts). `invalid_title` → 400 (empty after sanitize, or over the+ * 120-code-point / 512-byte cap). `not_found` → **uniform 404** for a session+ * that does not exist, is owned by another user, OR is a channel session (not+ * renamable) — no cross-user existence oracle.+ */+export type SetTitleResult =+ | { ok: true; title: string }+ | { ok: false; reason: 'invalid_title' | 'not_found' }++export type SetTitleHandler = (+ userSub: string,+ agent: string,+ chatId: string,+ title: string+) => SetTitleResult | Promise<SetTitleResult>