Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: close desktop session follow-up gaps
Josué10f4b5736be2
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex e30f2070b..1471ca9c2 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.339",+ "version": "0.1.340","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.339",+ "version": "0.1.340","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex cc1b7d741..5c98cc43c 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.339",+ "version": "0.1.340","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.tsindex 071dcf843..5ef06dca6 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -129,7 +129,7 @@ describe('AppService invitation configuration lookup', () => {// chat:* IPC throws "Not authenticated" until something else re-binds.expect(bindChatStoreForUser).toHaveBeenCalledWith('user-1',- resolveEnvKey('https://api.example.com')+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com'))expect(config.externalRestApiBaseUrl).toBe('https://api.example.com')expect(config.rpcProxyBaseUrl).toBe('https://rpc.example.com')@@ -424,7 +424,9 @@ describe('AppService invitation configuration lookup', () => {await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })- expect(clearSessionToken).toHaveBeenCalledWith(resolveEnvKey('https://api.example.com'))+ expect(clearSessionToken).toHaveBeenCalledWith(+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com')+ )})it('clears a saved token when startup session restore is forbidden', async () => {diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 95cee58c5..35f88b8a0 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -1308,7 +1308,8 @@ describe('corrupt/missing files', () => {await fs.writeFile(agentPath(`${chatId}.json`), '{"version":2,"messages":[')await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([])- const quarantined = await fs.readdir(agentPath('.corrupt'))+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ const quarantined = await fs.readdir(agentPath('.corrupt', encodedChatId))expect(quarantined).toHaveLength(1)await expect(fs.stat(agentPath(`${chatId}.json`))).rejects.toMatchObject({ code: 'ENOENT' })@@ -1353,16 +1354,30 @@ describe('corrupt/missing files', () => {it('deletes matching quarantined legacy files with the chat', async () => {const chatId = 'deleted-corrupt'+ const otherChatId = `${chatId}-other`await store.createChat('agent-1', chatId)const corruptDir = agentPath('.corrupt')- await fs.mkdir(corruptDir, { recursive: true })const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')- await fs.writeFile(join(corruptDir, `${encodedChatId}-fixture.json`), '{}')- await fs.writeFile(join(corruptDir, 'another-chat-fixture.json'), '{}')+ const otherEncodedChatId = Buffer.from(otherChatId, 'utf8').toString('base64url')+ const legacyUuid = '00000000-0000-4000-8000-000000000000'+ await fs.mkdir(join(corruptDir, encodedChatId), { recursive: true })+ await fs.writeFile(join(corruptDir, encodedChatId, 'nested.json'), '{}')+ await fs.writeFile(join(corruptDir, `${encodedChatId}-${legacyUuid}.json`), '{}')+ await fs.writeFile(join(corruptDir, `${otherEncodedChatId}-${legacyUuid}.json`), '{}')await store.deleteChat('agent-1', chatId)- expect(await fs.readdir(corruptDir)).toEqual(['another-chat-fixture.json'])+ await expect(fs.access(join(corruptDir, encodedChatId))).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ fs.access(join(corruptDir, `${encodedChatId}-${legacyUuid}.json`))+ ).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ fs.access(join(corruptDir, `${otherEncodedChatId}-${legacyUuid}.json`))+ ).resolves.toBeUndefined()})})diff --git a/desktop-app/src/__tests__/config.envKey.test.ts b/desktop-app/src/__tests__/config.envKey.test.tsindex a142d2659..6eaba6926 100644--- a/desktop-app/src/__tests__/config.envKey.test.ts+++ b/desktop-app/src/__tests__/config.envKey.test.ts@@ -12,7 +12,7 @@ vi.mock('electron', () => ({},}))-let resolveEnvKey: (url: string) => string+let resolveEnvKey: (url: string, rpcProxyBaseUrl?: string) => stringbeforeEach(async () => {const mod = await import('../config.js')@@ -53,6 +53,12 @@ describe('resolveEnvKey (spec §5.1, D1)', () => {)})+ it('keys apart when the external REST origin matches but the RPC origin differs', () => {+ expect(resolveEnvKey('https://api.example.com', 'https://rpc.dev.example.com')).not.toBe(+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com')+ )+ })+it('produces a valid, stable key for the Localhost sentinel origin', () => {const key = resolveEnvKey('http://127.0.0.1:8091')expect(key).toMatch(/^http_127_0_0_1_8091-[0-9a-f]{12}$/)diff --git a/desktop-app/src/__tests__/config.runtimeConfig.test.ts b/desktop-app/src/__tests__/config.runtimeConfig.test.tsindex 4226fa011..69dabdf1e 100644--- a/desktop-app/src/__tests__/config.runtimeConfig.test.ts+++ b/desktop-app/src/__tests__/config.runtimeConfig.test.ts@@ -98,6 +98,42 @@ describe('desktop runtime config', () => {expect(config.rpcProxyBaseUrl).toBe('http://127.0.0.1:8094')})+ it('ignores CLERUM_DESKTOP_CONFIG_PATH in packaged builds', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ const explicitConfigPath = path.join(tempUserDataDir, 'explicit-runtime-config.json')+ await fsp.writeFile(+ explicitConfigPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'https://explicit-api.example.com',+ rpcProxyBaseUrl: 'https://explicit-rpc.example.com',+ appName: 'Explicit',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = explicitConfigPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://packaged-api.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://packaged-rpc.example.com'++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { config, getDesktopRuntimeConfigState } = await import('../config.js')++ expect(config.externalRestApiBaseUrl).toBe('https://packaged-api.example.com')+ expect(config.rpcProxyBaseUrl).toBe('https://packaged-rpc.example.com')+ expect(getDesktopRuntimeConfigState().storagePath).toBe(+ path.join(tempUserDataDir, 'runtime-configs')+ )+ })+it('selects localhost for the packaged development app used by npm run ui', async () => {tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))const runtimeConfigDir = path.join(tempUserDataDir, 'runtime-configs')diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 903e7efc8..57c380db8 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1,6 +1,6 @@import { createHash, randomUUID } from 'node:crypto'import { promises as fs } from 'node:fs'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.js'import type {ChatFile,@@ -137,6 +137,19 @@ function assertSafeSegment(label: string, value: string): void {}}+function encodedChatId(chatId: string): string {+ return Buffer.from(chatId, 'utf8').toString('base64url')+}++function legacyCorruptFileBelongsToChat(fileName: string, chatId: string): boolean {+ const encoded = encodedChatId(chatId)+ const match =+ /^(.*)-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/i.exec(+ fileName+ )+ return match?.[1] === encoded+}+function sameReconciledMessage(local: ChatMessage, server: ChatMessage): boolean {if (local.id === server.id) return trueconst localTurn = messageServerTurnNumber(local)@@ -305,8 +318,7 @@ export class ChatStore {private corruptLegacyChatFilePath(agentRef: string, chatId: string): string {assertSafeSegment('chatId', chatId)- const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')- return join(this.agentDir(agentRef), '.corrupt', `${encodedChatId}-${randomUUID()}.json`)+ return join(this.agentDir(agentRef), '.corrupt', encodedChatId(chatId), `${randomUUID()}.json`)}private chatDirPath(agentRef: string, chatId: string): string {@@ -321,14 +333,18 @@ export class ChatStore {token: string): string {assertSafeSegment('chatId', chatId)- const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')- return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId, `${kind}-${token}`)+ return join(+ this.agentDir(agentRef),+ 'chats',+ '.snapshots',+ encodedChatId(chatId),+ `${kind}-${token}`+ )}private chatSnapshotRootPath(agentRef: string, chatId: string): string {assertSafeSegment('chatId', chatId)- const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')- return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId)+ return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId(chatId))}private chatPagesDirPath(agentRef: string, chatId: string): string {@@ -360,8 +376,13 @@ export class ChatStore {private async writeJsonAtomic(filePath: string, value: unknown): Promise<void> {const tmp = `${filePath}.tmp`- await fs.writeFile(tmp, JSON.stringify(value), { mode: 0o600 })- await fs.rename(tmp, filePath)+ try {+ await fs.writeFile(tmp, JSON.stringify(value), { mode: 0o600 })+ await fs.rename(tmp, filePath)+ } catch (err) {+ await fs.rm(tmp, { force: true }).catch(() => undefined)+ throw err+ }}private finalizePagedMeta(meta: PagedChatMeta): PagedChatMeta {@@ -436,14 +457,9 @@ export class ChatStore {// truncated JSON. Quarantine only malformed content; filesystem errors// above still propagate. Returning "no legacy snapshot" lets the server// rehydrate the chat and makes subsequent appends writable again.- await fs.mkdir(join(this.agentDir(agentRef), '.corrupt'), {- recursive: true,- mode: 0o700,- })- await fs.rename(- this.chatFilePath(agentRef, chatId),- this.corruptLegacyChatFilePath(agentRef, chatId)- )+ const corruptPath = this.corruptLegacyChatFilePath(agentRef, chatId)+ await fs.mkdir(dirname(corruptPath), { recursive: true, mode: 0o700 })+ await fs.rename(this.chatFilePath(agentRef, chatId), corruptPath)return null}}@@ -622,12 +638,7 @@ export class ChatStore {pageNumber: number,pagePath: string): Promise<ChatMessage[]> {- let raw: string- try {- raw = await fs.readFile(pagePath, 'utf-8')- } catch (err) {- throw err- }+ const raw = await fs.readFile(pagePath, 'utf-8')try {const parsed = JSON.parse(raw) as ChatPageFile@@ -1338,15 +1349,17 @@ export class ChatStore {await this.saveIndex(agentRef, index)})await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })- const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')const corruptLegacyDir = join(this.agentDir(agentRef), '.corrupt')+ await fs.rm(join(corruptLegacyDir, encodedChatId(chatId)), { recursive: true, force: true })const corruptLegacyEntries = await fs.readdir(corruptLegacyDir).catch(() => [])await Promise.all(corruptLegacyEntries- .filter(name => name.startsWith(`${encodedChatId}-`) && name.endsWith('.json'))+ .filter(name => legacyCorruptFileBelongsToChat(name, chatId)).map(name => fs.rm(join(corruptLegacyDir, name), { force: true })))+ await fs.rm(`${this.chatFilePath(agentRef, chatId)}.tmp`, { force: true })await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })+ await fs.rm(`${this.chatCompatibilitySignaturePath(agentRef, chatId)}.tmp`, { force: true })await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })await this.removePagedChatSnapshotSiblings(agentRef, chatId)const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.tsindex 7d981aafe..108a3ffaa 100644--- a/desktop-app/src/config.ts+++ b/desktop-app/src/config.ts@@ -120,6 +120,11 @@ function loadPackagedEnv(): void {loadPackagedEnv()+function explicitRuntimeConfigPath(): string {+ if (app?.isPackaged) return ''+ return process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim() || ''+}+function requiredOrDefault(name: string, fallback: string): string {const value = process.env[name]?.trim()return value || fallback@@ -164,7 +169,7 @@ function deriveProfileUiBaseUrl(externalRestApiBaseUrl: string): string {}function runtimeConfigDirectoryPath(): string {- const explicit = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicit = explicitRuntimeConfigPath()if (explicit) return path.dirname(explicit)if (app?.isReady()) {@@ -277,7 +282,7 @@ function loadStoredProfilesSync(): {profiles: StoredRuntimeProfile[]activeProfileId: string | null} {- const explicitPath = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicitPath = explicitRuntimeConfigPath()if (explicitPath) {const configFromFile = readRuntimeConfigFileSync(explicitPath)if (!configFromFile) return { profiles: [], activeProfileId: null }@@ -425,7 +430,7 @@ async function persistProfilesIndex(profiles: StoredRuntimeProfile[],activeProfileId: string | null): Promise<void> {- if (process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()) return+ if (explicitRuntimeConfigPath()) returnconst directoryPath = runtimeConfigDirectoryPath()const nextIndex: RuntimeConfigIndex = {version: 1,@@ -609,7 +614,7 @@ export function isDesktopRuntimeConfigured(): boolean {export async function saveDesktopRuntimeConfig(next: DesktopRuntimeConfig): Promise<void> {hydrateDesktopRuntimeConfig()const validated = validateRuntimeConfig(next)- const explicitPath = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicitPath = explicitRuntimeConfigPath()if (explicitPath) {const timestamp = new Date().toISOString()const existing = storedProfiles.find(profile => profile.id === 'custom-file')@@ -667,38 +672,42 @@ export async function saveDesktopRuntimeConfig(next: DesktopRuntimeConfig): Prom/*** Derive the environment namespacing key from a runtime config's external-rest-api- * base URL (spec §5.1, D1). Semantically "one environment = one external-rest-api- * origin": `new URL(url).origin` includes scheme + host + port, so- * `https://api.dev…` and `https://api.prod…` (or `:8091` vs `:8092`) key apart- * automatically, and `rpcProxyBaseUrl` is deliberately NOT mixed in.+ * and rpc-proxy base origins (spec §5.1, D1). Same REST origin + different RPC+ * origin is a different runtime boundary because desktop session tokens are+ * accepted by the RPC proxy, not by external-rest-api alone.*- * The raw origin is not filesystem/keychain-safe (it carries `://`, `:`), so we+ * The raw identity is not filesystem/keychain-safe (it carries `://`, `:`), so we* emit a stable, collision-resistant slug: a lowercase `scheme_host_port`- * fragment for human debuggability, suffixed with a 12-hex sha256 of the origin- * so distinct origins can never collide even when the slug is truncated. Purely a- * function of the origin ⇒ deterministic and stable across restarts.+ * fragment for human debuggability, suffixed with a 12-hex sha256 of the full+ * identity so distinct origins can never collide even when the slug is truncated.*/-export function resolveEnvKey(externalRestApiBaseUrl: string): string {- const raw = String(externalRestApiBaseUrl || '').trim()- let origin: string+function resolveOriginKeyPart(value: string): string {+ const raw = String(value || '').trim()try {- origin = new URL(raw).origin+ return new URL(raw).origin} catch {- origin = raw || 'unknown'+ return raw || 'unknown'}- const slug = origin+}++export function resolveEnvKey(externalRestApiBaseUrl: string, rpcProxyBaseUrl = ''): string {+ const restOrigin = resolveOriginKeyPart(externalRestApiBaseUrl)+ const rpcOrigin = rpcProxyBaseUrl.trim() ? resolveOriginKeyPart(rpcProxyBaseUrl) : ''+ const identity = rpcOrigin ? `${restOrigin}|rpc=${rpcOrigin}` : restOrigin+ const slugSource = rpcOrigin ? `${restOrigin}_${rpcOrigin}` : restOrigin+ const slug = slugSource.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 48)- const hash = createHash('sha256').update(origin).digest('hex').slice(0, 12)+ const hash = createHash('sha256').update(identity).digest('hex').slice(0, 12)return `${slug || 'env'}-${hash}`}/** Env key for the CURRENTLY active runtime config (main-process surfaces). */export function getActiveEnvKey(): string {hydrateDesktopRuntimeConfig()- return resolveEnvKey(config.externalRestApiBaseUrl)+ return resolveEnvKey(config.externalRestApiBaseUrl, config.rpcProxyBaseUrl)}export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {@@ -720,8 +729,8 @@ export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {isLocalhost,selectorVisible,activeOptionId,- envKey: resolveEnvKey(current.externalRestApiBaseUrl),- storagePath: process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim() || runtimeConfigDirectoryPath(),+ envKey: resolveEnvKey(current.externalRestApiBaseUrl, current.rpcProxyBaseUrl),+ storagePath: explicitRuntimeConfigPath() || runtimeConfigDirectoryPath(),options,}}diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 31496c42e..49a5bf60c 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -496,7 +496,7 @@ declare global {messages: ChatMessage[],options?: ReplaceChatMessagesOptions) => Promise<void>- backfillCounters: (+ backfillCounters?: (agentRef: string,chatId: string,messages: ChatMessage[]diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 423c55671..4791f385f 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -111,7 +111,8 @@ export function useChatListController({// Selection requested for an agent before its chats have loaded, consumed by// the parent's agent-selection effect. Ref (not state): imperative, per-agent.const pendingChatSelectionByAgentRef = useRef<Record<string, PendingChatSelection>>({})- const suppressAutoSelectionByAgentRef = useRef<Set<string>>(new Set())+ const suppressAutoSelectionByAgentRef = useRef<Map<string, number>>(new Map())+ const suppressAutoSelectionSequenceRef = useRef(0)const chatListNextCursorByAgentRef = useRef<Record<string, string | null | undefined>>({})const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())const requestGenerationRef = useRef(0)@@ -171,6 +172,7 @@ export function useChatListController({setChatList(merged)const requestGeneration = requestGenerationRef.current+ const suppressionMarkerAtRequest = suppressAutoSelectionByAgentRef.current.get(agentRef)scheduleAfterFirstPaint(async () => {const serverResult = await chatStore.listSessions(agentRef, { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT })@@ -179,6 +181,12 @@ export function useChatListController({selectedAgentRef.current !== agentRef ||requestGenerationRef.current !== requestGeneration) {+ if (+ suppressionMarkerAtRequest !== undefined &&+ suppressAutoSelectionByAgentRef.current.get(agentRef) === suppressionMarkerAtRequest+ ) {+ suppressAutoSelectionByAgentRef.current.delete(agentRef)+ }return}@@ -287,7 +295,17 @@ export function useChatListController({{ force: true }).catch(() => null)- if (!serverResult || requestGenerationRef.current !== requestGeneration) return+ if (!serverResult) {+ if (+ requestGenerationRef.current === requestGeneration &&+ selectedAgentRef.current === agentRef+ ) {+ chatListNextCursorByAgentRef.current[agentRef] = null+ setChatListHasMoreRemoteSessions(false)+ }+ return+ }+ if (requestGenerationRef.current !== requestGeneration) returnconst serverSessions = serverResult.items.filter(s => s.agent === agentRef)if (selectedAgentRef.current !== agentRef) return@@ -306,6 +324,7 @@ export function useChatListController({createdAt: s.lastActivityAt,updatedAt: s.lastActivityAt,messageCount: knownServerMessageCount(s),+ remote: true,}))return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)})@@ -477,8 +496,15 @@ export function useChatListController({const writePendingSelection = useCallback((agentName: string, selection: PendingChatSelection) => {pendingChatSelectionByAgentRef.current[agentName] = selection- if (selection.mode === 'none') suppressAutoSelectionByAgentRef.current.add(agentName)- else suppressAutoSelectionByAgentRef.current.delete(agentName)+ if (selection.mode === 'none') {+ suppressAutoSelectionSequenceRef.current += 1+ suppressAutoSelectionByAgentRef.current.set(+ agentName,+ suppressAutoSelectionSequenceRef.current+ )+ } else {+ suppressAutoSelectionByAgentRef.current.delete(agentName)+ }},[])diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 7b5e742d9..9c81ecb90 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -74,6 +74,14 @@ function hostModelKey(hostRef: string, chatId: string): string {return `${remoteCacheScope}:${hostRef}:${chatId}`}+function pruneExpiredSessionCatalogRequests(now = Date.now()): void {+ for (const [key, cached] of sessionCatalogRequests) {+ if (cached.expiresAt <= now) {+ sessionCatalogRequests.delete(key)+ }+ }+}+/*** Hook providing typed access to the chat persistence IPC layer.* All methods are stable (useCallback) and safe to use in dependency arrays.@@ -152,11 +160,7 @@ export function useChatStore() {)const listSessions = useCallback(- (- hostRef: string,- query: SessionsListQuery = { limit: 50 },- options: { force?: boolean } = {}- ) => {+ (hostRef: string, query: SessionsListQuery = {}, options: { force?: boolean } = {}) => {const source = window.clerum.rpc.listSessionsif (sessionCatalogSource !== source) {sessionCatalogRequests.clear()@@ -169,6 +173,7 @@ export function useChatStore() {query.limit ?? 'all',query.cursor ?? '',].join(':')+ pruneExpiredSessionCatalogRequests()const cached = sessionCatalogRequests.get(key)if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promisediff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex acd624289..d9881a75c 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 576ac3fa7..97668f9f5 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.tsindex ed589e915..9ec26277b 100644--- a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts+++ b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts@@ -157,6 +157,16 @@ describe('InMemoryConversationStore', () => {])})+ it('supports an agent literally named rpc when the scoped agent is explicit', async () => {+ store.set('u-1:rpc:rpc:chat-1', makeConversation('u-1'))++ const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:rpc:', {+ agent: 'rpc',+ })++ expect(summaries.map(session => [session.agent, session.chatId])).toEqual([['rpc', 'chat-1']])+ })+it('counts user and assistant bubbles without counting tool storage rows', async () => {const conversation = makeConversation('u-1')conversation.turns = [diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex 4dd952540..b3929502f 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -66,6 +66,12 @@ export interface SessionListCursor {export interface SessionListQuery {limit?: numbercursor?: SessionListCursor+ /**+ * Explicit scoped agent for prefixes shaped as `${user}:rpc:${agent}:`.+ * This avoids re-inferring scoped intent from ambiguous keys such as+ * `${user}:rpc:rpc:`.+ */+ agent?: string}export interface SessionMessagesQuery {@@ -99,7 +105,6 @@ export interface ConversationSessionMessages extends Omit<totalTurns: numberfirstTurnNumber?: numberlastTurnNumber?: number- updatedAt: Date}function compareSessionSummaries(@@ -160,7 +165,6 @@ function sessionMessagesFromConversation(totalTurns: conversation.turns.length,firstTurnNumber: conversation.turns[0]?.number,lastTurnNumber: conversation.turns.at(-1)?.number,- updatedAt: conversation.updated_at,input_tokens: conversation.input_tokens,output_tokens: conversation.output_tokens,cache_read_tokens: conversation.cache_read_tokens,@@ -374,7 +378,7 @@ export class InMemoryConversationStore implements ConversationStore {): Promise<ConversationSessionSummary[]> {const summaries: ConversationSessionSummary[] = []for (const { key, conversation } of this.listByPrefix(prefix)) {- const parts = sessionPartsFromPrefixedKey(key, prefix)+ const parts = sessionPartsFromPrefixedKey(key, prefix, query.agent)if (!parts) continuesummaries.push({key,diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex 501a4f299..67cb3cb3f 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -327,6 +327,22 @@ describe('SqliteConversationStore — session summary listing', () => {chatId: 'chat:with:colons',})+ const rpcAgentKey = 'u-1:rpc:rpc:chat-rpc'+ const rpcAgentConversation = await manager.getOrCreate(rpcAgentKey)+ await manager.startTurn(rpcAgentConversation, 'rpc agent chat', 'task-rpc-agent')+ await manager.completeTurn(rpcAgentConversation, 'done')+ handle.store['cache'].clear()+ handle.store['ordinals'].clear()+ handle.store['sessionKeyById'].clear()+ const rpcAgentPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:rpc:', {+ agent: 'rpc',+ limit: 10,+ })+ expect(rpcAgentPage.find(session => session.key === rpcAgentKey)).toMatchObject({+ agent: 'rpc',+ chatId: 'chat-rpc',+ })+const secondPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:', {limit: 2,cursor: {diff --git a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts b/mcp-host/src/core/conversation/persistence/dualConversationStore.tsindex 41b0304a0..c7ac63a4e 100644--- a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/dualConversationStore.ts@@ -147,6 +147,9 @@ export class DualConversationStore implements ConversationStore {prefix: string,query: SessionMessagesQuery = {}): Promise<ConversationSessionMessages | undefined> {+ // Transcript pages deliberately return the SQLite result in dual mode.+ // That keeps the durable pagination contract under canary coverage; a+ // memory-only session can read as absent until dual parity is complete.const [memPage, sqlPage] = await Promise.all([this.memory.getSessionMessagesByKey(key, prefix, query),this.sqlite.getSessionMessagesByKey(key, prefix, query),diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 045d16f10..9fd8489ea 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -43,7 +43,7 @@ import {type SessionTokenUsage,boundedTurns,} from '../conversationStore'-import { sessionPartsFromPrefixedKey } from '../sessionKeyParts'+import { scopedAgentFromSessionPrefix, sessionPartsFromPrefixedKey } from '../sessionKeyParts'import type { PersistQueue } from './persistQueue'import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'import {@@ -364,13 +364,14 @@ export class SqliteConversationStore implements ConversationStore {limit: query.limit,cursorUpdatedAt: query.cursor ? query.cursor.updatedAt.getTime() / 1000 : undefined,cursorKey: query.cursor?.key,+ agentScoped: query.agent !== undefined || scopedAgentFromSessionPrefix(prefix) !== null,})const out: ConversationSessionSummary[] = []for (const row of rows) {const key = row.session.session_keyconst cached = this.cache.get(key)- const parts = sessionPartsFromPrefixedKey(key, prefix)+ const parts = sessionPartsFromPrefixedKey(key, prefix, query.agent)if (!parts) continueconst state = cached ? cached.state : conversationStateFromRow(row.session.state)out.push({@@ -431,7 +432,6 @@ export class SqliteConversationStore implements ConversationStore {totalTurns: cached.turns.length,firstTurnNumber: cached.turns[0]?.number,lastTurnNumber: cached.turns.at(-1)?.number,- updatedAt: cached.updated_at,input_tokens: cached.input_tokens,output_tokens: cached.output_tokens,cache_read_tokens: cached.cache_read_tokens,@@ -468,7 +468,6 @@ export class SqliteConversationStore implements ConversationStore {totalTurns: Math.max(0, Math.floor(page.total_turns ?? 0)),firstTurnNumber: page.first_turn_number ?? undefined,lastTurnNumber: page.last_turn_number ?? undefined,- updatedAt: new Date(page.last_activity_at * 1000),input_tokens: page.session.input_tokens,output_tokens: page.session.output_tokens,cache_read_tokens: page.session.cache_read_tokens,diff --git a/mcp-host/src/core/conversation/sessionKeyParts.ts b/mcp-host/src/core/conversation/sessionKeyParts.tsindex 1fd58cbf1..c9a643d31 100644--- a/mcp-host/src/core/conversation/sessionKeyParts.ts+++ b/mcp-host/src/core/conversation/sessionKeyParts.ts@@ -10,7 +10,7 @@ export interface AgentChatSessionParts {* agent and a trailing colon, for example `user:rpc:agent-a:`.*/export function scopedAgentFromSessionPrefix(prefix: string): string | null {- const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')+ const rpcPrefixIndex = prefix.indexOf(':rpc:')if (rpcPrefixIndex < 0) return nullconst suffix = prefix.slice(rpcPrefixIndex + ':rpc:'.length)if (!suffix.endsWith(':')) return null@@ -27,15 +27,18 @@ export function scopedAgentFromSessionPrefix(prefix: string): string | null {*/export function sessionPartsFromPrefixedKey(key: string,- prefix: string+ prefix: string,+ scopedAgent?: string): AgentChatSessionParts | null {if (!key.startsWith(prefix)) return nullconst rest = key.slice(prefix.length)if (!rest) return null- const scopedAgent = scopedAgentFromSessionPrefix(prefix)if (scopedAgent) return { agent: scopedAgent, chatId: rest }+ const inferredScopedAgent = scopedAgentFromSessionPrefix(prefix)+ if (inferredScopedAgent) return { agent: inferredScopedAgent, chatId: rest }+const colonIndex = rest.indexOf(':')if (colonIndex <= 0 || colonIndex === rest.length - 1) return nullreturn {diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex ba3270904..40baf659b 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -249,13 +249,13 @@ export function prepareStatements(db: Database): PreparedStatements {)AND (@cursor_updated_at IS NULL- OR COALESCE(last_activity_at, started_at) < @cursor_updated_at+ OR last_activity_at < @cursor_updated_atOR (- COALESCE(last_activity_at, started_at) = @cursor_updated_at+ last_activity_at = @cursor_updated_atAND session_key > @cursor_key))- ORDER BY COALESCE(last_activity_at, started_at) DESC, session_key ASC+ ORDER BY last_activity_at DESC, session_key ASCLIMIT @limit),ranked_approvals AS (@@ -270,7 +270,7 @@ export function prepareStatements(db: Database): PreparedStatements {JOIN scoped_sessions s ON s.id = pa.session_id)SELECT s.*,- COALESCE(s.last_activity_at, s.started_at) AS summary_last_activity_at,+ s.last_activity_at AS summary_last_activity_at,COALESCE(s.turn_count, 0) AS summary_turn_count,pa.request_id AS pending_request_id,pa.tool_name AS pending_tool_name@@ -281,10 +281,8 @@ export function prepareStatements(db: Database): PreparedStatements {ORDER BY summary_last_activity_at DESC, s.session_key ASC`),selectSessionTurnBounds: db.prepare(`- SELECT COUNT(DISTINCT COALESCE(turn_number, 0)) AS total_turns,- MIN(COALESCE(turn_number, 0)) AS first_turn_number,- MAX(COALESCE(turn_number, 0)) AS last_turn_number,- MAX(timestamp) AS last_activity_at+ SELECT MIN(COALESCE(turn_number, 0)) AS first_turn_number,+ MAX(COALESCE(turn_number, 0)) AS last_turn_numberFROM messagesWHERE session_id = ?`),diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex eea3ccca0..5b68db4f5 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -610,10 +610,8 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn})const bounds = s.selectSessionTurnBounds.get(sessionRow.id) as| {- total_turns: numberfirst_turn_number: number | nulllast_turn_number: number | null- last_activity_at: number | null}| undefinedconst pendingRow = s.selectPendingApprovalBySession.get(sessionRow.id) as@@ -625,10 +623,10 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unknpending_approval: pendingRow? { request_id: pendingRow.request_id, tool_name: pendingRow.tool_name }: null,- total_turns: bounds?.total_turns ?? 0,+ total_turns: sessionRow.turn_count ?? 0,first_turn_number: bounds?.first_turn_number ?? null,last_turn_number: bounds?.last_turn_number ?? null,- last_activity_at: bounds?.last_activity_at ?? sessionRow.started_at,+ last_activity_at: sessionRow.last_activity_at ?? sessionRow.started_at,} satisfies PersistedSessionMessagePage}@@ -650,15 +648,16 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkncase 'list_session_summaries_by_prefix': {const prefixStart = op.sessionKeyPrefix- const finalCodePoint = op.sessionKeyPrefix.codePointAt(op.sessionKeyPrefix.length - 1)+ const prefixCharacters = Array.from(op.sessionKeyPrefix)+ const finalCodePoint = prefixCharacters.at(-1)?.codePointAt(0)if (finalCodePoint === undefined || finalCodePoint >= 0x10ffff) {throw new Error('Session key prefix must have a finite lexicographic upper bound')}- const prefixEnd = `${op.sessionKeyPrefix.slice(- 0,- op.sessionKeyPrefix.length - (finalCodePoint > 0xffff ? 2 : 1)- )}${String.fromCodePoint(finalCodePoint + 1)}`- const agentScoped = scopedAgentFromSessionPrefix(op.sessionKeyPrefix) !== null+ const prefixEnd = `${prefixCharacters+ .slice(0, -1)+ .join('')}${String.fromCodePoint(finalCodePoint + 1)}`+ const agentScoped =+ op.agentScoped === true || scopedAgentFromSessionPrefix(op.sessionKeyPrefix) !== nullconst rows = s.selectSessionSummariesByPrefix.all({prefix_start: prefixStart,prefix_end: prefixEnd,diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.tsindex 9e0302ae9..e330b4271 100644--- a/mcp-host/src/db/worker/protocol.ts+++ b/mcp-host/src/db/worker/protocol.ts@@ -243,6 +243,7 @@ export type WorkerOp =limit?: numbercursorUpdatedAt?: numbercursorKey?: string+ agentScoped?: boolean}| { kind: 'load_all_pending_approvals' }| { kind: 'sweep_expired'; nowEpoch: number; ttlSeconds: number }diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex c34744df6..ab633837b 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2078,6 +2078,7 @@ async function startRPCServer(): Promise<void> {cursor: cursor? { updatedAt: new Date(cursor.updatedAt), key: `${keyPrefix}${cursor.key}` }: undefined,+ agent: query.agent,})const { page, nextCursor } = paginateSessionSummaries(entries,diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.tsindex 992837aa8..dd9942f84 100644--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts@@ -341,6 +341,7 @@ describe('handleSessionMessagesRoute', () => {it.each([['dot agent', '.', 'chat-1'],+ ['colon-bearing agent', 'agent:other', 'chat-1'],['dot-dot chat id', 'agent', '..'],['separator-bearing chat id', 'agent', 'nested/chat'],])('rejects unsafe %s route segments', async (_label, agent, chatId) => {@@ -501,6 +502,15 @@ describe('handleContextBreakdownRoute (F1.5)', () => {expect(captured.statusCode).toBe(400)})+ it('rejects unsafe route segments', async () => {+ const contextBreakdownHandler: ContextBreakdownHandler = vi.fn()+ const req = makeReqWithParams('user-1', 'agent:other', 'c1')+ const captured = makeRes()+ await handleContextBreakdownRoute(req, captured.res, makeHandlers({ contextBreakdownHandler }))+ expect(captured.statusCode).toBe(400)+ expect(contextBreakdownHandler).not.toHaveBeenCalled()+ })+it('returns 501 when contextBreakdownHandler is not configured', async () => {const req = makeReqWithParams('user-1', 'chatllm', 'c1')const captured = makeRes()diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex ceed39c36..7649ee278 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -83,6 +83,10 @@ function isSafeRouteSegment(value: string): boolean {)}+function isSafeAgentRouteSegment(value: string): boolean {+ return isSafeRouteSegment(value) && value.length <= 200 && !value.includes(':')+}+function channelRuntimeSourceMismatch(caller: RuntimeCallerContext | undefined,source: { channelType?: string; channelId?: string; sender?: string }@@ -1214,7 +1218,7 @@ export async function handleSessionMessagesRoute(}const agent = String(req.params.agent || '').trim()const chatId = String(req.params.chatId || '').trim()- if (!isSafeRouteSegment(agent) || !isSafeRouteSegment(chatId)) {+ if (!isSafeAgentRouteSegment(agent) || !isSafeRouteSegment(chatId)) {badRequest(res, 'agent and chatId are required')return}@@ -1298,7 +1302,7 @@ export async function handleContextBreakdownRoute(}const agent = String(req.params.agent || '').trim()const chatId = String(req.params.chatId || '').trim()- if (!isSafeRouteSegment(agent) || !isSafeRouteSegment(chatId)) {+ if (!isSafeAgentRouteSegment(agent) || !isSafeRouteSegment(chatId)) {badRequest(res, 'agent and chatId are required')return}diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 6e78f8eb2..50de89e4a 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.57",+ "version": "0.1.58","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.57",+ "version": "0.1.58","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex d0ca6b303..3d6ea7a95 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.57",+ "version": "0.1.58","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.tsindex 86747ed6e..b5fdec218 100644--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts@@ -119,7 +119,10 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {'/rpc/hosts/chatllm/sessions?limit=1&limit=2','/rpc/hosts/chatllm/sessions?cursor=one&cursor=two','/rpc/hosts/chatllm/sessions?agent=one&agent=two',+ '/rpc/hosts/chatllm/sessions?agent=',+ '/rpc/hosts/chatllm/sessions?agent=%20%20','/rpc/hosts/chatllm/sessions?agent=.',+ '/rpc/hosts/chatllm/sessions?agent=agent:other','/rpc/hosts/chat%2Fllm/sessions',])('rejects malformed session pagination before forwarding upstream: %s', async path => {const fetchMock = vi.fn()@@ -242,6 +245,18 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrouexpect(fetchMock).not.toHaveBeenCalled()})+ it('rejects unsafe transcript route segments before forwarding upstream', async () => {+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/agent%3Aother/c1/messages')+ .set('authorization', 'Bearer user-token')+ .expect(400)++ expect(fetchMock).not.toHaveBeenCalled()+ })+it('returns 404 when the upstream returns 404', async () => {const fetchMock = vi.fn().mockResolvedValue({status: 404,@@ -322,6 +337,18 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/context-breakdown —expect(res.body).toEqual({ error: 'session not found' })})+ it('rejects unsafe route segments before forwarding upstream', async () => {+ const fetchMock = vi.fn()+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/agent%3Aother/c1/context-breakdown')+ .set('authorization', 'Bearer user-token')+ .expect(400)++ expect(fetchMock).not.toHaveBeenCalled()+ })+it('returns 403 if the user cannot access the host', async () => {serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)await request(makeApp())diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex e1dce1961..adc9144b1 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -42,6 +42,10 @@ function isSafeUpstreamPathSegment(value: string): boolean {)}+function isSafeUpstreamAgentSegment(value: string): boolean {+ return isSafeUpstreamPathSegment(value) && value.length <= 200 && !value.includes(':')+}+/*** Pre-wake host error mapping: AbortError → 504, everything else → 502.*@@ -641,42 +645,42 @@ export function createRpcRouter(): Router {const rpcAccessToken = extractAuthToken(req)const hostRef = String(req.params.hostRef || '').trim()if (!isSafeUpstreamPathSegment(hostRef)) {- res.status(400).json({ error: 'hostRef is required' })+ res.status(400).json({ error: 'Invalid hostRef' })return}- const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {- teamId: auth.teamId,- })- if (!host) {- res.status(403).json({ error: 'Forbidden: user cannot access this host' })- return- }- const baseUrl = host.url.replace(/\/+$/, '')- console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)- const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)- const sessionAgent = typeof req.query.agent === 'string' ? req.query.agent.trim() : ''+ const rawSessionAgent = req.query.agent+ const sessionAgent =+ typeof rawSessionAgent === 'string' ? rawSessionAgent.trim() : undefinedconst sessionCursor = typeof req.query.cursor === 'string' ? req.query.cursor : ''const sessionLimit =typeof req.query.limit === 'string' ? Number(req.query.limit) : undefinedif (- (req.query.agent !== undefined && typeof req.query.agent !== 'string') ||+ (rawSessionAgent !== undefined && typeof rawSessionAgent !== 'string') ||(req.query.cursor !== undefined && typeof req.query.cursor !== 'string') ||(req.query.limit !== undefined && typeof req.query.limit !== 'string') ||- (sessionAgent &&- (!isSafeUpstreamPathSegment(sessionAgent) ||- sessionAgent.length > 200 ||- sessionAgent.includes(':'))) ||+ (rawSessionAgent !== undefined &&+ (!sessionAgent || !isSafeUpstreamAgentSegment(sessionAgent))) ||sessionCursor.length > 2048 ||(sessionLimit !== undefined && (!Number.isInteger(sessionLimit) || sessionLimit < 1))) {res.status(400).json({ error: 'Invalid session pagination query' })return}+ const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {+ teamId: auth.teamId,+ })+ if (!host) {+ res.status(403).json({ error: 'Forbidden: user cannot access this host' })+ return+ }+ const baseUrl = host.url.replace(/\/+$/, '')+ const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)if (sessionAgent) upstreamUrl.searchParams.set('agent', sessionAgent)if (sessionLimit !== undefined) {upstreamUrl.searchParams.set('limit', String(Math.min(sessionLimit, 100)))}if (sessionCursor) upstreamUrl.searchParams.set('cursor', sessionCursor)+ console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)// Wake-eligible finite operation (§11.4): the route scope stays// host:session:read; wake capability rides on the token. A suspended// (network-down) or draining Host triggers a wake-and-hold instead of a@@ -734,10 +738,10 @@ export function createRpcRouter(): Router {const chatId = String(req.params.chatId || '').trim()if (!isSafeUpstreamPathSegment(hostRef) ||- !isSafeUpstreamPathSegment(agent) ||+ !isSafeUpstreamAgentSegment(agent) ||!isSafeUpstreamPathSegment(chatId)) {- res.status(400).json({ error: 'hostRef, agent, and chatId are required' })+ res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })return}const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {@@ -748,9 +752,6 @@ export function createRpcRouter(): Router {return}const baseUrl = host.url.replace(/\/+$/, '')- console.info(- `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`- )const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`)@@ -779,6 +780,9 @@ export function createRpcRouter(): Router {upstreamUrl.searchParams.set('beforeTurn', String(beforeTurn))}if (afterTurn !== undefined) upstreamUrl.searchParams.set('afterTurn', String(afterTurn))+ console.info(+ `[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`+ )// Wake-eligible finite operation (§11.4): scope stays host:session:read.const forwardTranscript = async () => {const response = await fetch(upstreamUrl, {@@ -832,8 +836,12 @@ export function createRpcRouter(): Router {const hostRef = String(req.params.hostRef || '').trim()const agent = String(req.params.agent || '').trim()const chatId = String(req.params.chatId || '').trim()- if (!hostRef || !agent || !chatId) {- res.status(400).json({ error: 'hostRef, agent, and chatId are required' })+ if (+ !isSafeUpstreamPathSegment(hostRef) ||+ !isSafeUpstreamAgentSegment(agent) ||+ !isSafeUpstreamPathSegment(chatId)+ ) {+ res.status(400).json({ error: 'Invalid hostRef, agent, or chatId' })return}const host = await resolveHostConnectionForUser(auth.sub, hostRef, rpcAccessToken, {