Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(rpc): preserve scoped wake authorization across held operations
Alfredo Lopez20c86d5ca6b3
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex f5fad84ae..35e07cd19 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.313",+ "version": "0.1.314","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.313",+ "version": "0.1.314","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex ba540b0c3..3c04f428a 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.313",+ "version": "0.1.314","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/appService.hostModels.test.ts b/desktop-app/src/__tests__/appService.hostModels.test.tsindex 086d73423..9451496fa 100644--- a/desktop-app/src/__tests__/appService.hostModels.test.ts+++ b/desktop-app/src/__tests__/appService.hostModels.test.ts@@ -42,8 +42,13 @@ describe('AppService.getHostModels', () => {const result = await service.getHostModels('chatllm', 'chat-1')expect(result).toEqual(payload)- // Reading the list reuses the session-read scope — NOT the write scope.- expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(['host:session:read'], ['chatllm'])+ // Reading the list reuses the session-read scope — NOT the write scope — and+ // (issue #791) additionally requests host:wake:write so loading the list can+ // wake a suspended stateless Host.+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(+ ['host:session:read', 'host:wake:write'],+ ['chatllm']+ )expect(rpcClient.getHostModels).toHaveBeenCalledWith('rpc-token', 'chatllm', 'chat-1')})@@ -54,7 +59,7 @@ describe('AppService.getHostModels', () => {await service.getHostModels('chatllm', 'chat-1', ['chatllm', 'other-host'])expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(- ['host:session:read'],+ ['host:session:read', 'host:wake:write'],['chatllm', 'other-host'])})@@ -101,7 +106,10 @@ describe('AppService.getHostModels', () => {const result = await service.getHostModels('chatllm', '')expect(result?.sessionModel).toBeNull()- expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(['host:session:read'], ['chatllm'])+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(+ ['host:session:read', 'host:wake:write'],+ ['chatllm']+ )expect(rpcClient.getHostModels).toHaveBeenCalledWith('rpc-token', 'chatllm', '')})})@@ -118,8 +126,13 @@ describe('AppService.setHostModel', () => {const result = await service.setHostModel('chatllm', 'chat-1', 'claude-haiku-4-5')expect(result.effective).toBe('next-task')- // The write path is gated by the dedicated write scope only (§8.2).- expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(['host:model:write'], ['chatllm'])+ // The write path is gated by the dedicated write scope (§8.2) and (issue+ // #791) additionally requests host:wake:write so a model swap can wake a+ // suspended stateless Host.+ expect(issueRpcTokenForHostRefs).toHaveBeenCalledWith(+ ['host:model:write', 'host:wake:write'],+ ['chatllm']+ )expect(rpcClient.setHostModel).toHaveBeenCalledWith('rpc-token','chatllm',diff --git a/desktop-app/src/__tests__/appService.wakeConcurrency.issue791.test.ts b/desktop-app/src/__tests__/appService.wakeConcurrency.issue791.test.tsnew file mode 100644index 000000000..f3c13fc3e--- /dev/null+++ b/desktop-app/src/__tests__/appService.wakeConcurrency.issue791.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from 'vitest'+import { AppService } from '../appService.js'+import { ApiError } from '../httpClient.js'++// Controller-level (unit) expression of plan §13.4 "Operation outcomes": when a+// user opens an agent and concurrently lists sessions, loads models, and sends a+// message against a suspended-then-waking stateless Host, every finite operation+// must (a) carry the wake grant so the proxy can bring the Host up bounded, and+// (b) surface the real post-wake result — never a fabricated empty session list+// and never a false success on a still-unavailable Host.+vi.mock('electron', () => ({+ app: {+ getPath: vi.fn(() => '/tmp/clerum-desktop-test'),+ getVersion: vi.fn(() => '0.1.286'),+ isPackaged: false,+ isReady: vi.fn(() => false),+ },+ safeStorage: {+ isEncryptionAvailable: vi.fn(() => false),+ encryptString: vi.fn(),+ decryptString: vi.fn(),+ },+ shell: { openExternal: vi.fn() },+}))++const WAKE = 'host:wake:write'+const HOST = 'chatllm-stateless'++// A finite RPC that only resolves after a microtask, modelling rpc-proxy's+// wake-then-hold-then-retry: the caller's promise settles once the woken Host+// answered. Using a real deferred boundary makes the three concurrent calls+// genuinely interleave rather than resolve synchronously in call order.+function afterWakeHold<T>(value: T): Promise<T> {+ return Promise.resolve().then(() => Promise.resolve().then(() => value))+}++function concurrentHarness() {+ const issueRpcTokenForHostRefs = vi.fn().mockResolvedValue({ token: 'rpc-token' })+ const service = new AppService() as any+ service.sessionToken = 'session-token'+ service.me = { id: 7, teamId: 'team-1' }+ service.issueRpcTokenForHostRefs = issueRpcTokenForHostRefs+ service.rpcClient = {+ listSessions: vi.fn(),+ getHostModels: vi.fn(),+ invokeHostMessage: vi.fn(),+ loadSessionMessages: vi.fn(),+ }+ return { service, issueRpcTokenForHostRefs }+}++function scopesFor(issuer: ReturnType<typeof vi.fn>): unknown[] {+ return issuer.mock.calls.map(call => call[0])+}++describe('issue #791 — concurrent open/list/model/message against a waking stateless Host', () => {+ it('all three finite operations carry wake and return real post-wake results (no false-empty)', async () => {+ const { service, issueRpcTokenForHostRefs } = concurrentHarness()+ const sessions = {+ items: [+ { agent: HOST, chatId: 'chat-a', turnCount: 2, lastActivityAt: '2026-07-22T00:00:00Z' },+ { agent: HOST, chatId: 'chat-b', turnCount: 1, lastActivityAt: '2026-07-22T00:01:00Z' },+ ],+ }+ const models = {+ provider: 'claude',+ hostDefault: 'claude-opus-4-8',+ sessionModel: null,+ degraded: false,+ models: [{ name: 'claude-opus-4-8' }, { name: 'claude-haiku-4-5' }],+ }+ const message = { taskId: 'task-1', status: 'accepted' }+ service.rpcClient.listSessions.mockReturnValue(afterWakeHold(sessions))+ service.rpcClient.getHostModels.mockReturnValue(afterWakeHold(models))+ service.rpcClient.invokeHostMessage.mockReturnValue(afterWakeHold(message))++ // The user opened the agent: list sessions, load models, and send — all at+ // once, exactly as the workspace does on selection.+ const [listed, loaded, sent] = await Promise.all([+ service.listSessions(HOST, [HOST], '33333333-3333-4333-8333-333333333333'),+ service.getHostModels(HOST, 'chat-a', [HOST]),+ service.invokeHostMessage(HOST, { content: 'hello' }, [HOST]),+ ])++ // (a) Bounded waking: every finite op requested the wake grant so a+ // suspended Host could be woken for it.+ const requested = scopesFor(issueRpcTokenForHostRefs)+ expect(requested.length).toBe(3)+ for (const scope of requested) {+ expect(scope).toContain(WAKE)+ }+ // session list + models both ride the session-read family; the message+ // rides the message family — assert the exact families that appeared.+ expect(requested).toContainEqual(['host:session:read', WAKE])+ expect(requested).toContainEqual(['host:message:invoke', 'host:task:read', WAKE])++ // (b) No false-empty session catalog and no navigation loss: both chat+ // identities survive the concurrent wake.+ expect(listed.items).toHaveLength(2)+ expect(listed.items.map((s: { chatId: string }) => s.chatId)).toEqual(['chat-a', 'chat-b'])+ // Real model list + real message result, not a fabricated stand-in.+ expect(loaded.models).toHaveLength(2)+ expect(sent.taskId).toBe('task-1')+ })++ it('a still-unavailable Host fails loud under concurrency instead of fabricating an empty list', async () => {+ const { service } = concurrentHarness()+ const unavailable = new ApiError('runtime unavailable (503)', 503, '')+ // The session read never wakes to Ready; models happens to answer. The list+ // MUST reject — a fabricated `{ items: [] }` would be a false success that+ // silently drops the user's real sessions (plan §13.4).+ service.rpcClient.listSessions.mockReturnValue(afterWakeHold(Promise.reject(unavailable)))+ service.rpcClient.getHostModels.mockReturnValue(+ afterWakeHold({+ provider: 'claude',+ hostDefault: 'claude-opus-4-8',+ sessionModel: null,+ degraded: false,+ models: [{ name: 'claude-opus-4-8' }],+ })+ )++ const results = await Promise.allSettled([+ service.listSessions(HOST, [HOST], '44444444-4444-4444-8444-444444444444'),+ service.getHostModels(HOST, 'chat-a', [HOST]),+ ])++ expect(results[0].status).toBe('rejected')+ expect((results[0] as PromiseRejectedResult).reason).toBe(unavailable)+ // The concurrent model load is independent and still resolves — one waking+ // failure does not poison a sibling operation.+ expect(results[1].status).toBe('fulfilled')+ })+})diff --git a/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts b/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.tsnew file mode 100644index 000000000..75133e673--- /dev/null+++ b/desktop-app/src/__tests__/appService.wakeScopeMatrix.issue791.test.ts@@ -0,0 +1,217 @@+import { describe, expect, it, vi } from 'vitest'+import { AppService } from '../appService.js'++// Electron is mocked so `new AppService()` constructs without Keychain/app+// side-effects; the tests then stub `issueRpcTokenForHostRefs` + `rpcClient`+// to observe the EXACT scope array each operation requests from control-api.+vi.mock('electron', () => ({+ app: {+ getPath: vi.fn(() => '/tmp/clerum-desktop-test'),+ getVersion: vi.fn(() => '0.1.286'),+ isPackaged: false,+ isReady: vi.fn(() => false),+ },+ safeStorage: {+ isEncryptionAvailable: vi.fn(() => false),+ encryptString: vi.fn(),+ decryptString: vi.fn(),+ },+ shell: { openExternal: vi.fn() },+}))++const WAKE = 'host:wake:write'++// Lets the not-awaited stream `connect()` chain run far enough to reach its+// `issueRpcTokenForHostRefs` call without advancing real time (so the 1s+// reconnect backoff timer never fires and no handle leaks).+async function flushAsyncWork(iterations = 16): Promise<void> {+ for (let index = 0; index < iterations; index += 1) {+ await Promise.resolve()+ }+}++/**+ * Wires an AppService with `issueRpcTokenForHostRefs` and `rpcClient` stubbed so+ * a test can assert the exact scope array a finite operation requests. Mirrors+ * the canonical `appService.hostModels.test.ts` / `appService.sessions.issue791`+ * harnesses — no team resolution, no real RPC token manager.+ */+function scopeHarness() {+ const issueRpcTokenForHostRefs = vi.fn().mockResolvedValue({ token: 'rpc-token' })+ const service = new AppService() as any+ service.sessionToken = 'session-token'+ service.me = { id: 7, teamId: 'team-1' }+ service.issueRpcTokenForHostRefs = issueRpcTokenForHostRefs+ service.rpcClient = {+ listSessions: vi.fn().mockResolvedValue({ items: [] }),+ loadSessionMessages: vi.fn().mockResolvedValue({ agent: 'a', chatId: 'c', turns: [] }),+ getContextBreakdown: vi.fn().mockResolvedValue({ breakdown: null }),+ getHostModels: vi.fn().mockResolvedValue({+ provider: 'claude',+ hostDefault: 'claude-opus-4-8',+ sessionModel: null,+ degraded: false,+ models: [{ name: 'claude-opus-4-8' }],+ }),+ setHostModel: vi.fn().mockResolvedValue({+ effective: 'next-task',+ provider: 'claude',+ model: 'claude-haiku-4-5',+ }),+ listArtifacts: vi.fn().mockResolvedValue({ artifacts: [] }),+ downloadArtifact: vi.fn().mockResolvedValue(Buffer.from('x')),+ approveToolCall: vi.fn().mockResolvedValue({ decision: 'approved' }),+ denyToolCall: vi.fn().mockResolvedValue({ decision: 'denied' }),+ getHostStatus: vi.fn().mockResolvedValue({ hostRef: 'chatllm', ready: true }),+ getHostActivity: vi.fn().mockResolvedValue({ events: [] }),+ openHostStatusStream: vi.fn().mockResolvedValue(undefined),+ openHostActivityStream: vi.fn().mockResolvedValue(undefined),+ openTaskProgressStream: vi.fn().mockResolvedValue(undefined),+ }+ return { service, issueRpcTokenForHostRefs }+}++function firstScope(issueRpcTokenForHostRefs: ReturnType<typeof vi.fn>): unknown {+ const calls = issueRpcTokenForHostRefs.mock.calls+ expect(calls.length).toBeGreaterThanOrEqual(1)+ const first = calls[0]+ if (!first) throw new Error('issueRpcTokenForHostRefs was not called')+ return first[0]+}++// ── POSITIVE: the nine finite operations that must request host:wake:write ──+//+// Each entry is one of the exactly-nine on-demand operations from plan §11.4.+// The assertion is the FULL exact scope array, wake scope included — a widening+// that dropped or reordered a scope would fail loudly here.++describe('issue #791 — finite operations request host:wake:write in addition to their scope', () => {+ it('listSessions → host:session:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.listSessions('chatllm', ['chatllm'], '11111111-1111-4111-8111-111111111111')+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:session:read', WAKE])+ })++ it('loadSessionMessages → host:session:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.loadSessionMessages(+ 'chatllm',+ 'agent-a',+ 'chat-a',+ ['chatllm'],+ '22222222-2222-4222-8222-222222222222'+ )+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:session:read', WAKE])+ })++ it('getContextBreakdown → host:session:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.getContextBreakdown('chatllm', 'agent-a', 'chat-a', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:session:read', WAKE])+ })++ it('getHostModels → host:session:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.getHostModels('chatllm', 'chat-1', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:session:read', WAKE])+ })++ it('setHostModel → host:model:write + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.setHostModel('chatllm', 'chat-1', 'claude-haiku-4-5', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:model:write', WAKE])+ })++ it('listArtifacts → host:activity:read + host:task:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.listArtifacts('chatllm', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual([+ 'host:activity:read',+ 'host:task:read',+ WAKE,+ ])+ })++ it('downloadArtifact → host:activity:read + host:task:read + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.downloadArtifact('chatllm', 'report.pdf', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual([+ 'host:activity:read',+ 'host:task:read',+ WAKE,+ ])+ })++ it('approveToolCall → host:approval:write + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.approveToolCall('chatllm', 'task-1', 'call-1', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:approval:write', WAKE])+ })++ it('denyToolCall → host:approval:write + host:wake:write', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.denyToolCall('chatllm', 'task-1', 'call-1', 'nope', ['chatllm'])+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:approval:write', WAKE])+ })+})++// ── NEGATIVE: observability reads and every SSE stream must NEVER request wake ──+//+// A suspended stateless Host must stay suspended under polling and streaming, or+// observability would defeat scale-to-zero. These assert the EXACT non-wake+// scope AND that no issued token on these surfaces carries host:wake:write.+// (The status-stream reconnect lifecycle is additionally guarded by+// appService.prewarm.test.ts.)++describe('issue #791 — streams and observability reads never request host:wake:write', () => {+ it('getHostStatus stays host:status:read only', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.getHostStatus('chatllm', ['chatllm'])+ for (const call of issueRpcTokenForHostRefs.mock.calls) {+ expect(call[0]).not.toContain(WAKE)+ }+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:status:read'])+ })++ it('getHostActivity stays host:activity:read only', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ await service.getHostActivity('chatllm', { hostRefs: ['chatllm'] })+ for (const call of issueRpcTokenForHostRefs.mock.calls) {+ expect(call[0]).not.toContain(WAKE)+ }+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:activity:read'])+ })++ it('startHostStatusStream connect stays host:status:read only', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ service.startHostStatusStream('s-status', 7, 'chatllm', ['chatllm'], () => {})+ await flushAsyncWork()+ for (const call of issueRpcTokenForHostRefs.mock.calls) {+ expect(call[0]).not.toContain(WAKE)+ }+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:status:read'])+ service.stopHostStatusStream('s-status')+ })++ it('startHostActivityStream connect stays host:activity:read only', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ service.startHostActivityStream('s-activity', 7, 'chatllm', ['chatllm'], () => {})+ await flushAsyncWork()+ for (const call of issueRpcTokenForHostRefs.mock.calls) {+ expect(call[0]).not.toContain(WAKE)+ }+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:activity:read'])+ service.stopHostActivityStream('s-activity')+ })++ it('startTaskProgressStream connect stays host:activity:read only', async () => {+ const { service, issueRpcTokenForHostRefs } = scopeHarness()+ service.startTaskProgressStream('s-progress', 7, 'chatllm', 'task-1', ['chatllm'], () => {})+ await flushAsyncWork()+ for (const call of issueRpcTokenForHostRefs.mock.calls) {+ expect(call[0]).not.toContain(WAKE)+ }+ expect(firstScope(issueRpcTokenForHostRefs)).toEqual(['host:activity:read'])+ service.stopTaskProgressStream('s-progress')+ })+})diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex c12948519..26038d662 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -66,21 +66,65 @@ import {WorkflowRunArtifactsResult,} from './types.js'-const HOST_WAKEABLE_OPERATION_SCOPES: RpcScope[] = [- 'host:message:invoke',- 'host:task:read',- 'host:wake:write',-]-const HOST_STATUS_SCOPES: RpcScope[] = ['host:status:read']-const HOST_ACTIVITY_SCOPES: RpcScope[] = ['host:activity:read']-const HOST_SESSION_SCOPES: RpcScope[] = ['host:session:read']-// R2 model selector: reading the model list reuses the session-read scope (GET-// /models); writing the per-session selection (POST /model) is gated by the-// dedicated write scope only — the swap's blast radius is the caller's own-// session, so no broader grant is needed.-const HOST_MODEL_SCOPES: RpcScope[] = ['host:model:write']-const HOST_ARTIFACT_SCOPES: RpcScope[] = ['host:activity:read', 'host:task:read']-const HOST_APPROVAL_SCOPES: RpcScope[] = ['host:approval:write']+// The single wake scope. A finite (non-streaming) Host operation carries this+// IN ADDITION to its functional scope so a suspended stateless Host wakes+// bounded-and-once for that operation (issue #791). control-api intersects the+// requested scopes against the caller's grants before issuance, so requesting+// the wake scope never widens a caller who was not granted it.+const HOST_WAKE_SCOPE: RpcScope = 'host:wake:write'++/**+ * Finite-operation scope matrix — the single source of truth for the exact+ * scope array each finite (single request/response) Host RPC operation requests,+ * keyed by operation family (plan §11.4). EVERY entry carries HOST_WAKE_SCOPE:+ * these are the on-demand, user-driven operations that may legitimately wake a+ * suspended stateless Host. rpc-proxy still enforces each route's own functional+ * `requireScope`; the wake scope here only lets that same operation pull a+ * suspended Host back up.+ *+ * Streams and observability reads are DELIBERATELY absent (see+ * HOST_OBSERVABILITY_SCOPES): they keep narrow read scopes with NO wake scope so+ * background polling and SSE streams can never defeat scale-to-zero. Adding a+ * family here is the ONLY place the wake grant is requested — never append+ * HOST_WAKE_SCOPE at a call site.+ * - `model`: writing the per-session selection (POST /model) is gated by the+ * dedicated write scope (the swap's blast radius is the caller's own+ * session); wake is added so selecting a model on a suspended Host brings it+ * up. Reading the model list (GET /models) rides the `session` family.+ * - `approval`: the tool-call surface only (approveToolCall/denyToolCall).+ * `decideWorkflowApproval` (`host:workflow-approval:decide`) is a separate+ * surface and is intentionally NOT in this matrix.+ */+const HOST_FINITE_OPERATION_SCOPES: Record<+ 'message' | 'session' | 'model' | 'artifact' | 'approval',+ RpcScope[]+> = {+ message: ['host:message:invoke', 'host:task:read', HOST_WAKE_SCOPE],+ session: ['host:session:read', HOST_WAKE_SCOPE],+ model: ['host:model:write', HOST_WAKE_SCOPE],+ artifact: ['host:activity:read', 'host:task:read', HOST_WAKE_SCOPE],+ approval: ['host:approval:write', HOST_WAKE_SCOPE],+}++/**+ * Observability scope matrix — status/activity reads plus every SSE stream.+ * DELIBERATELY never contains HOST_WAKE_SCOPE: a suspended stateless Host must+ * stay suspended under polling/streaming, or observability would defeat+ * scale-to-zero. The negative scope tests assert no entry here carries wake.+ */+const HOST_OBSERVABILITY_SCOPES: Record<'status' | 'activity', RpcScope[]> = {+ status: ['host:status:read'],+ activity: ['host:activity:read'],+}++// Named views onto the matrices so existing call sites stay byte-identical.+const HOST_WAKEABLE_OPERATION_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.message+const HOST_STATUS_SCOPES: RpcScope[] = HOST_OBSERVABILITY_SCOPES.status+const HOST_ACTIVITY_SCOPES: RpcScope[] = HOST_OBSERVABILITY_SCOPES.activity+const HOST_SESSION_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.session+const HOST_MODEL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.model+const HOST_ARTIFACT_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.artifact+const HOST_APPROVAL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.approvalconst MCP_SERVERS_LIST_SCOPES: RpcScope[] = ['mcp:servers:list']const DESKTOP_VIEW_SCOPES: RpcScope[] = ['desktop:view']const SANDBOX_UI_VIEW_SCOPES: RpcScope[] = ['sandbox:ui:view']diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex e49f132d2..e2578d725 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.48",+ "version": "0.1.49","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.48",+ "version": "0.1.49","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex 32120ba83..bbcf3d913 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.48",+ "version": "0.1.49","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/approval-artifacts.test.ts b/rpc-proxy/src/__tests__/approval-artifacts.test.tsindex d0918484b..b3d9accf9 100644--- a/rpc-proxy/src/__tests__/approval-artifacts.test.ts+++ b/rpc-proxy/src/__tests__/approval-artifacts.test.ts@@ -558,8 +558,10 @@ describe('POST /rpc/hosts/:hostRef/tasks/:taskId/cancel', () => {it('returns 502 when upstream fetch rejects and the host is not stateless', async () => {authTokenMock.verifyRpcToken.mockReturnValue({+ // §11.4: cancel is a wake-eligible finite operation, so its token carries+ // host:wake:write; the wake plane is consulted on host-down....VALID_CLAIMS,- scopes: ['host:message:invoke'],+ scopes: ['host:message:invoke', 'host:wake:write'],})serviceMock.forwardCancelToHost.mockRejectedValue(new Error('ECONNREFUSED'))diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.tsindex 814d2bfa8..d97d2d54c 100644--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts@@ -11,12 +11,15 @@ const serviceMock = vi.hoisted(() => ({vi.mock('../authToken.js', () => authTokenMock)vi.mock('../services/mcpProxyService.js', () => serviceMock)+// Issue #791 §11.4: session reads are wake-eligible finite operations, so the+// Desktop-issued token carries host:wake:write alongside host:session:read.+// The route scope guard (host:session:read) is unchanged.const VALID_CLAIMS = {sub: 'user-uuid-123',typ: 'user' as const,accessScope: 'team' as const,teamId: 'team-1',- scopes: ['host:session:read'],+ scopes: ['host:session:read', 'host:wake:write'],hostRefs: ['chatllm'],jti: 'j1',iat: 1,diff --git a/rpc-proxy/src/__tests__/wake-and-hold-route.test.ts b/rpc-proxy/src/__tests__/wake-and-hold-route.test.tsindex 2b872c291..bf37f6bf4 100644--- a/rpc-proxy/src/__tests__/wake-and-hold-route.test.ts+++ b/rpc-proxy/src/__tests__/wake-and-hold-route.test.ts@@ -42,12 +42,15 @@ vi.mock('../authToken.js', () => authTokenMock)vi.mock('../services/mcpProxyService.js', () => serviceMock)vi.mock('../services/controlApiRestService.js', () => controlApiMock)+// Issue #791 §11.4: a wake-eligible finite operation carries host:wake:write in+// addition to its operation scope (Desktop adds it; the route scope guard is+// unchanged). Without wake capability the coordinator no longer triggers a wake.const VALID_CLAIMS = {sub: 'user-uuid-123',typ: 'user' as const,accessScope: 'team' as const,teamId: 'team-1',- scopes: ['host:message:invoke'],+ scopes: ['host:message:invoke', 'host:wake:write'],hostRefs: ['chatllm'],jti: 'j1',iat: 1,@@ -312,7 +315,7 @@ describe('POST /rpc/hosts/:hostRef/messages wake-and-hold triggers', () => {describe('task result and cancel host-down paths', () => {it('GET task result triggers wake on host-down and forwards after active', async () => {- const claims = { ...VALID_CLAIMS, scopes: ['host:message:invoke'] }+ const claims = { ...VALID_CLAIMS, scopes: ['host:message:invoke', 'host:wake:write'] }authTokenMock.verifyRpcToken.mockReturnValue(claims)serviceMock.forwardTaskResultFromHost.mockRejectedValueOnce(hostDownError())diff --git a/rpc-proxy/src/__tests__/wake-route-coverage.test.ts b/rpc-proxy/src/__tests__/wake-route-coverage.test.tsnew file mode 100644index 000000000..eed0e33ba--- /dev/null+++ b/rpc-proxy/src/__tests__/wake-route-coverage.test.ts@@ -0,0 +1,554 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { Response as ExpressResponse } from 'express'+import express from 'express'+import request from 'supertest'+import {+ createRpcRouter,+ respondControlApiHostAccessRejection,+ respondUpstreamUnavailable,+} from '../routes/rpc.js'++// ── Issue #791 §11.4/§11.5 — extend wake-and-hold to the remaining finite+// Desktop routes, and prove terminal-response (duplicate-write) safety in the+// route-level outer catches. Wake capability rides on the token; the route+// scope guards are UNCHANGED.++const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))+const serviceMock = vi.hoisted(() => ({+ listAllowedServersForUser: vi.fn(),+ resolveServerConnectionForUser: vi.fn(),+ resolveHostConnectionForUser: vi.fn(),+ validateRpcRequest: vi.fn(),+ forwardRpcToServer: vi.fn(),+ forwardHostMessageToHost: vi.fn(),+ forwardHostActivity: vi.fn(),+ forwardHostStatus: vi.fn(),+ forwardHostHealth: vi.fn(),+ forwardTaskResultFromHost: vi.fn(),+ forwardCancelToHost: vi.fn(),+ UpstreamHostError: class UpstreamHostError extends Error {+ constructor(+ public readonly status: number,+ public readonly bodySnippet: string+ ) {+ super(`Upstream host returned ${status}: ${bodySnippet}`)+ this.name = 'UpstreamHostError'+ }+ },+}))+const controlApiMock = vi.hoisted(() => ({+ fetchUserAllowedServersFromControlApi: vi.fn(),+ fetchHostConnectionFromControlApi: vi.fn(),+ requestHostWakeFromControlApi: vi.fn(),+}))++vi.mock('../authToken.js', () => authTokenMock)+vi.mock('../services/mcpProxyService.js', () => serviceMock)+vi.mock('../services/controlApiRestService.js', () => controlApiMock)++const HOST_CONNECTION = {+ name: 'chatllm',+ url: 'http://chatllm.mcp-host.svc.cluster.local:8080',+ headers: { 'x-clerum-edge-caller': 'rpc-proxy' },+}++function claims(scopes: string[]) {+ return {+ sub: 'user-uuid-123',+ typ: 'user' as const,+ accessScope: 'team' as const,+ teamId: 'team-1',+ scopes,+ hostRefs: ['chatllm'],+ jti: 'j1',+ iat: 1,+ exp: 9999999999,+ }+}++function makeApp() {+ const app = express()+ app.use(express.json())+ app.use(createRpcRouter())+ app.use(+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {+ res.status(500).json({ error: err instanceof Error ? err.message : 'Internal error' })+ }+ )+ return app+}++function mockFetchResponse(status: number, body: string, headers?: Record<string, string>): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: new Headers(headers),+ text: () => Promise.resolve(body),+ arrayBuffer: () => Promise.resolve(Buffer.from(body).buffer as ArrayBuffer),+ } as unknown as Response+}++function hostDownError(): Error {+ return new TypeError('fetch failed')+}++function drainingResponse(): Response {+ return mockFetchResponse(503, JSON.stringify({ code: 'host_draining', retryAfterMs: 1000 }), {+ 'content-type': 'application/json',+ })+}++const originalFetch = globalThis.fetch++beforeEach(() => {+ vi.clearAllMocks()+ serviceMock.resolveHostConnectionForUser.mockResolvedValue({ ...HOST_CONNECTION })+ controlApiMock.requestHostWakeFromControlApi.mockResolvedValue({ kind: 'active', wakeGeneration: null })+})++afterEach(() => {+ globalThis.fetch = originalFetch+})++describe('§11.4 wake coverage — GET /rpc/hosts/:hostRef/models', () => {+ it('a wake-capable token wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ models: [] }), { 'content-type': 'application/json' })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ models: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('a NON-wake token gets the deterministic legacy result and triggers NO wake', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ const fetchMock = vi.fn().mockRejectedValue(hostDownError())+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/models')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+})++describe('§11.4 wake coverage — POST /rpc/hosts/:hostRef/model', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ effective: 'next-task' })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(200)++ expect(res.body).toEqual({ effective: 'next-task' })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+})++describe('§11.4 wake coverage — context-breakdown honors the draining fence', () => {+ it('a 503 host_draining triggers a wake and re-forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(drainingResponse())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ breakdown: {} }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ breakdown: {} })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ it('a plain upstream 404 is NOT treated as a wake trigger (passes through)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ mockFetchResponse(404, JSON.stringify({ error: 'session not found' }), {+ 'content-type': 'application/json',+ })+ ) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/missing/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(404)++ expect(res.body).toEqual({ error: 'session not found' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+})++describe('§11.4 wake coverage — approvals approve', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ // The approve route relays the upstream body verbatim as a raw string+ // (no JSON content-type is set), so read it via res.text.+ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+})++describe('§11.4 wake coverage — artifacts list and download', () => {+ it('artifacts list wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify([{ filename: 'a.pdf' }])))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(JSON.parse(res.text)).toEqual([{ filename: 'a.pdf' }])+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })++ it('artifact download wakes on host-down and streams after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, 'PDF-BYTES', { 'content-type': 'application/pdf' })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.headers['content-type']).toContain('application/pdf')+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+})++// ── §13.4 row 1 — GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages ──+// sessions-passthrough.test.ts already proves the "wake accepted, host still+// down → host_waking" variant for this transcript route; the "retry after+// readiness → operation result" cell (§13.4 row 1 proper) is proven here.+describe('§13.4 row 1 — session transcript wakes on host-down and re-forwards after active', () => {+ it('a wake-capable token wakes then re-forwards the transcript after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(+ mockFetchResponse(200, JSON.stringify({ agent: 'chatllm', chatId: 'c1', turns: [] }), {+ 'content-type': 'application/json',+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ agent: 'chatllm', chatId: 'c1', turns: [] })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })+})++// ── §11.4 wake coverage — approvals/deny (row 1) ────────────────────────────+// Closes the audit gap: POST approvals/deny had no route-level wake test at+// all. Mirrors the approve row-1 test above; the route stays host:approval:write+// and relays the upstream body verbatim as a raw string.+describe('§11.4 wake coverage — approvals deny', () => {+ it('wakes on host-down and forwards after active', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write', 'host:wake:write']))+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(hostDownError())+ .mockResolvedValueOnce(mockFetchResponse(200, JSON.stringify({ ok: true })))+ globalThis.fetch = fetchMock as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(200)++ expect(JSON.parse(res.text)).toEqual({ ok: true })+ expect(controlApiMock.requestHostWakeFromControlApi).toHaveBeenCalledWith('chatllm', 'tok')+ })+})++// ── §13.4 row 3 — GET /rpc/hosts/:hostRef/tasks/:taskId/result ──────────────+// The other finite routes assert their plain-forward path in their own suites+// (model-selection, approval-artifacts, sessions-passthrough). The task-result+// route only had the wake path, so its active/ready row is proven here: even a+// wake-capable token never touches the wake plane when the host is up.+describe('§13.4 row 3 — task result forwards normally on an active host', () => {+ it('an active host forwards the task result and never touches the wake plane', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(+ claims(['host:message:invoke', 'host:wake:write'])+ )+ serviceMock.forwardTaskResultFromHost.mockResolvedValue({+ status: 'completed',+ response: 'done',+ })++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-7/result')+ .set('authorization', 'Bearer tok')+ .expect(200)++ expect(res.body).toEqual({ status: 'completed', response: 'done' })+ expect(serviceMock.forwardTaskResultFromHost).toHaveBeenCalledTimes(1)+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+})++// ── §13.4 row 2 — suspended host + NON-wake token ───────────────────────────+// A finite operation whose token lacks host:wake:write must return today's+// deterministic legacy availability result (502 Upstream host unavailable) and+// NEVER consult the wake plane — no fallback grant is minted (§11.2, §13.4).+// GET /models already asserts this cell above; the remaining finite routes are+// proven here so every wake-eligible route has an explicit non-wake row.+describe('§13.4 row 2 — NON-wake token gets the deterministic legacy result and triggers NO wake', () => {+ it('POST messages', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardHostMessageToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/messages')+ .set('authorization', 'Bearer tok')+ .send({ content: 'hello' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/approve', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/approve')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST approvals/deny', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:approval:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/approvals/deny')+ .set('authorization', 'Bearer tok')+ .send({ toolCallId: 'tc-1' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/messages (transcript)', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET sessions/:agent/:chatId/context-breakdown', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:session:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/context-breakdown')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST model', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:model:write']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/model')+ .set('authorization', 'Bearer tok')+ .send({ chatId: 'c1', model: 'claude-haiku-4-5' })+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET tasks/:taskId/result', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardTaskResultFromHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/tasks/t-1/result')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('POST tasks/:taskId/cancel', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:message:invoke']))+ serviceMock.forwardCancelToHost.mockRejectedValue(hostDownError())++ const res = await request(makeApp())+ .post('/rpc/hosts/chatllm/tasks/t-1/cancel')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })++ it('GET artifacts/:filename/download', async () => {+ authTokenMock.verifyRpcToken.mockReturnValue(claims(['host:task:read']))+ globalThis.fetch = vi.fn().mockRejectedValue(hostDownError()) as unknown as typeof fetch++ const res = await request(makeApp())+ .get('/rpc/hosts/chatllm/artifacts/report.pdf/download')+ .set('authorization', 'Bearer tok')+ .expect(502)++ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ expect(controlApiMock.requestHostWakeFromControlApi).not.toHaveBeenCalled()+ })+})++// ── §11.5 terminal-response (duplicate-write) safety ────────────────────────+describe('§11.5 route outer-catch responders guard headersSent (one-shot settlement)', () => {+ type FakeRes = {+ headersSent: boolean+ statusCode: number+ body: unknown+ status: (code: number) => FakeRes+ json: (payload: unknown) => FakeRes+ }+ function makeRes(headersSent = false): FakeRes {+ const res: FakeRes = {+ headersSent,+ statusCode: 0,+ body: undefined,+ status(code: number) {+ res.statusCode = code+ return res+ },+ json(payload: unknown) {+ if (res.headersSent) throw new Error('Cannot set headers after they are sent to the client')+ res.headersSent = true+ res.body = payload+ return res+ },+ }+ return res+ }++ it('respondUpstreamUnavailable is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })++ it('respondUpstreamUnavailable still writes 502 when the response is uncommitted', () => {+ const res = makeRes(false)+ respondUpstreamUnavailable(res as unknown as ExpressResponse, new Error('boom'))+ expect(res.statusCode).toBe(502)+ expect(res.body).toEqual({ error: 'Upstream host unavailable' })+ })++ it('respondControlApiHostAccessRejection is a no-op once the response is committed', () => {+ const res = makeRes(true)+ expect(() =>+ respondControlApiHostAccessRejection(res as unknown as ExpressResponse, 403)+ ).not.toThrow()+ expect(res.statusCode).toBe(0)+ })+})diff --git a/rpc-proxy/src/main.ts b/rpc-proxy/src/main.tsindex da49e44d7..f87ef617d 100644--- a/rpc-proxy/src/main.ts+++ b/rpc-proxy/src/main.ts@@ -3,6 +3,14 @@ import type { Socket } from 'net'import { createApp } from './app.js'import { config } from './config.js'import { handleDesktopUpgrade } from './routes/desktopProxy.js'+import { hostWakeCoordinator } from './services/wakeAndHold.js'++/**+ * Bounded deadline for graceful shutdown. After the wake-and-hold coordinator+ * drains, only ordinary in-flight requests remain; if `server.close()` has not+ * completed by then we force exit rather than hang the pod termination.+ */+const SHUTDOWN_DEADLINE_MS = 10_000async function bootstrap(): Promise<void> {if (process.env.NODE_ENV === 'production' && !config.desktopApiToken) {@@ -29,6 +37,38 @@ async function bootstrap(): Promise<void> {}})+ // First graceful-stop path for rpc-proxy (Issue #791 §12.2): on SIGTERM/+ // SIGINT stop accepting new connections, deterministically settle every+ // parked wake-and-hold waiter, then close the server under a bounded+ // deadline. Fail loud on close error or deadline expiry.+ let shuttingDown = false+ const shutdown = (signal: string): void => {+ if (shuttingDown) return+ shuttingDown = true+ console.log(`[RPC_PROXY] ${signal} received — draining wake holds and shutting down`)+ // Settle held requests first so `server.close()` is not blocked waiting on+ // them, then stop accepting new connections.+ hostWakeCoordinator.drain('shutdown')+ const deadline = setTimeout(() => {+ console.error(+ `[RPC_PROXY] graceful shutdown deadline (${SHUTDOWN_DEADLINE_MS}ms) exceeded — forcing exit`+ )+ process.exit(1)+ }, SHUTDOWN_DEADLINE_MS)+ deadline.unref?.()+ server.close(error => {+ clearTimeout(deadline)+ if (error) {+ console.error('[RPC_PROXY] error during server.close:', error)+ process.exit(1)+ }+ console.log('[RPC_PROXY] shutdown complete')+ process.exit(0)+ })+ }+ process.on('SIGTERM', () => shutdown('SIGTERM'))+ process.on('SIGINT', () => shutdown('SIGINT'))+server.listen(config.port, () => {console.log(`[RPC_PROXY] listening on :${config.port}`)})diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex 90e8f1194..e06ad0f9a 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -1,5 +1,5 @@import { Router } from 'express'-import type { Response as ExpressResponse } from 'express'+import type { NextFunction, Response as ExpressResponse } from 'express'import { randomUUID } from 'crypto'import { config } from '../config.js'import {@@ -32,8 +32,23 @@ import { mintOrReuseDirectTraceContext } from '../traceContext.js'const RFC1123_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/-/** Pre-wake host error mapping: AbortError → 504, everything else → 502. */-function respondUpstreamUnavailable(res: ExpressResponse, error: unknown): void {+/**+ * Pre-wake host error mapping: AbortError → 504, everything else → 502.+ *+ * Guards `res.headersSent` (§11.5): this is the terminal responder that+ * route-level outer catches invoke after a held request may already have+ * committed a response. A second write here is the ERR_HTTP_HEADERS_SENT /+ * duplicate-terminal-response bug, so it becomes a loud no-op instead.+ */+export function respondUpstreamUnavailable(res: ExpressResponse, error: unknown): void {+ if (res.headersSent) {+ console.warn(+ `[RPC_PROXY] suppressing duplicate terminal response (upstream-unavailable): ${+ error instanceof Error ? error.message : String(error)+ }`+ )+ return+ }if (error instanceof Error && error.name === 'AbortError') {res.status(504).json({ error: 'Gateway Timeout' })return@@ -41,6 +56,38 @@ function respondUpstreamUnavailable(res: ExpressResponse, error: unknown): voidres.status(502).json({ error: 'Upstream host unavailable' })}+/**+ * Guards a `next(error)` handoff against a committed response (§11.5). Express+ * routes an error to the default handler which, when headers are already sent,+ * aborts the socket; suppress it loudly instead so a held request that already+ * wrote its terminal response is never double-terminated.+ */+function guardedNext(res: ExpressResponse, next: NextFunction, error: unknown): void {+ if (res.headersSent) {+ console.warn(+ `[RPC_PROXY] suppressing post-response route error: ${+ error instanceof Error ? error.message : String(error)+ }`+ )+ return+ }+ next(error)+}++/**+ * A 503 carrying mcp-host's `host_draining` fence is a wake-eligible upstream+ * error, not a client-visible failure: convert it so the finite routes below+ * can hand it to respondWithWakeAndHold.+ */+function sessionDrainingFence(response: Response, body: string): Error | null {+ if (response.status !== 503 || !body.includes('host_draining')) return null+ return Object.assign(new Error('Upstream host returned draining fence'), {+ name: 'UpstreamHostError',+ status: response.status,+ bodySnippet: body,+ })+}+function controlApiHostAccessRejectionStatus(error: unknown): 401 | 403 | 409 | null {if (!(error instanceof Error) || error.name !== 'ControlApiHostAccessRejectedError') {return null@@ -49,7 +96,16 @@ function controlApiHostAccessRejectionStatus(error: unknown): 401 | 403 | 409 |return status === 401 || status === 403 || status === 409 ? status : null}-function respondControlApiHostAccessRejection(res: ExpressResponse, status: 401 | 403 | 409): void {+export function respondControlApiHostAccessRejection(+ res: ExpressResponse,+ status: 401 | 403 | 409+): void {+ if (res.headersSent) {+ console.warn(+ `[RPC_PROXY] suppressing duplicate terminal response (host-access-rejection ${status})`+ )+ return+ }if (status === 401) {res.status(401).json({ error: 'Unauthorized' })return@@ -178,7 +234,7 @@ export function createRpcRouter(): Router {'/rpc/hosts/:hostRef/messages',requireRpcAuth,requireScope('host:message:invoke'),- async (req: AuthedRequest, res, next) => {+ async (req: AuthedRequest, res) => {// Host runtime write path (REST-oriented):// - separate from read-only status stream// - explicitly scoped to host:message:invoke@@ -311,8 +367,8 @@ export function createRpcRouter(): Router {res,hostRef,host,+ claims: auth,rpcAccessToken,- tokenExpMs: auth.exp * 1000,attemptUpstream: async () => {const retried = await forwardHostMessageToHost(host, forwardedBody, {async: isAsync,@@ -467,15 +523,37 @@ export function createRpcRouter(): Router {requestId: parsed.toolCallId || parsed.requestId,alwaysApprove: parsed.alwaysApprove || false,}- const response = await fetch(`${baseUrl}/v1/runtime/approvals/approve`, {- method: 'POST',- headers: { 'content-type': 'application/json', ...host.headers },- body: JSON.stringify(upstreamBody),- })- const body = await response.text()- res.status(response.status).send(body)+ // Wake-eligible finite operation (§11.4): the route scope stays+ // host:approval:write; wake capability rides on the token. A suspended+ // (network-down) or draining Host triggers a wake-and-hold instead of a+ // bare next(error)/passthrough.+ const attempt = async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/approvals/approve`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...host.headers },+ body: JSON.stringify(upstreamBody),+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res.status(response.status).send(body)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -510,15 +588,34 @@ export function createRpcRouter(): Router {userId: auth.sub,requestId: parsed.toolCallId || parsed.requestId,}- const response = await fetch(`${baseUrl}/v1/runtime/approvals/deny`, {- method: 'POST',- headers: { 'content-type': 'application/json', ...host.headers },- body: JSON.stringify(upstreamBody),- })- const body = await response.text()- res.status(response.status).send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:approval:write.+ const attempt = async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/approvals/deny`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...host.headers },+ body: JSON.stringify(upstreamBody),+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res.status(response.status).send(body)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -546,17 +643,45 @@ export function createRpcRouter(): Router {}const baseUrl = host.url.replace(/\/+$/, '')console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)- const response = await fetch(`${baseUrl}/v1/runtime/sessions`, {- method: 'GET',- headers: { ...host.headers },- })- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // 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+ // bare next(error)/passthrough.+ const forwardSessionList = async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/sessions`, {+ method: 'GET',+ headers: { ...host.headers },+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await forwardSessionList()+ } catch (error) {+ // A sanitized session boundary can also wrap local response-body+ // failures. Wake only when its retained cause proves the host is+ // unavailable, or when the host explicitly returned the draining+ // fence; otherwise preserve the ordinary sanitized error path.+ if (!isWakeEligibleHostError(error)) {+ throw error+ }+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: forwardSessionList,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -588,17 +713,40 @@ export function createRpcRouter(): Router {console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`)- const response = await fetch(- `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`,- { method: 'GET', headers: { ...host.headers } }- )- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:session:read.+ const forwardTranscript = async () => {+ const response = await fetch(+ `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`,+ { method: 'GET', headers: { ...host.headers } }+ )+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await forwardTranscript()+ } catch (error) {+ // See the list route above: availability recovery is deliberately+ // narrower than the generic sanitized upstream-error boundary.+ if (!isWakeEligibleHostError(error)) {+ throw error+ }+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: forwardTranscript,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -633,17 +781,36 @@ export function createRpcRouter(): Router {console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-context-breakdown agent=${agent} chatId=${chatId}`)- const response = await fetch(- `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/context-breakdown`,- { method: 'GET', headers: { ...host.headers } }- )- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:session:read.+ const attempt = async () => {+ const response = await fetch(+ `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/context-breakdown`,+ { method: 'GET', headers: { ...host.headers } }+ )+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -678,17 +845,36 @@ export function createRpcRouter(): Router {? `${baseUrl}/v1/runtime/models?chatId=${encodeURIComponent(chatId)}`: `${baseUrl}/v1/runtime/models`console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-models`)- const response = await fetch(upstreamUrl, {- method: 'GET',- headers: { ...host.headers },- })- const body = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:session:read.+ const attempt = async () => {+ const response = await fetch(upstreamUrl, {+ method: 'GET',+ headers: { ...host.headers },+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(body)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -723,18 +909,37 @@ export function createRpcRouter(): Router {}const baseUrl = host.url.replace(/\/+$/, '')console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=set-model`)- const response = await fetch(`${baseUrl}/v1/runtime/model`, {- method: 'POST',- headers: { 'content-type': 'application/json', ...host.headers },- body: JSON.stringify(body),- })- const upstreamBody = await response.text()- res- .status(response.status)- .type(response.headers.get('content-type') || 'application/json')- .send(upstreamBody)+ // Wake-eligible finite operation (§11.4): scope stays host:model:write.+ const attempt = async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/model`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...host.headers },+ body: JSON.stringify(body),+ })+ const upstreamBody = await response.text()+ const draining = sessionDrainingFence(response, upstreamBody)+ if (draining) throw draining+ res+ .status(response.status)+ .type(response.headers.get('content-type') || 'application/json')+ .send(upstreamBody)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -743,7 +948,7 @@ export function createRpcRouter(): Router {'/rpc/hosts/:hostRef/tasks/:taskId/result',requireRpcAuth,requireScope('host:message:invoke'),- async (req: AuthedRequest, res, next) => {+ async (req: AuthedRequest, res) => {try {const auth = req.auth!const rpcAccessToken = extractAuthToken(req)@@ -788,8 +993,8 @@ export function createRpcRouter(): Router {res,hostRef,host,+ claims: auth,rpcAccessToken,- tokenExpMs: auth.exp * 1000,attemptUpstream: attemptTaskResult,respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),})@@ -810,7 +1015,7 @@ export function createRpcRouter(): Router {'/rpc/hosts/:hostRef/tasks/:taskId/cancel',requireRpcAuth,requireScope('host:message:invoke'),- async (req: AuthedRequest, res, next) => {+ async (req: AuthedRequest, res) => {try {const auth = req.auth!const rpcAccessToken = extractAuthToken(req)@@ -859,8 +1064,8 @@ export function createRpcRouter(): Router {res,hostRef,host,+ claims: auth,rpcAccessToken,- tokenExpMs: auth.exp * 1000,attemptUpstream: attemptCancel,respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),})@@ -903,13 +1108,32 @@ export function createRpcRouter(): Router {return}const baseUrl = host.url.replace(/\/+$/, '')- const response = await fetch(`${baseUrl}/v1/runtime/artifacts`, {- headers: { ...host.headers },- })- const body = await response.text()- res.status(response.status).send(body)+ // Wake-eligible finite operation (§11.4): scope stays host:task:read.+ const attempt = async () => {+ const response = await fetch(`${baseUrl}/v1/runtime/artifacts`, {+ headers: { ...host.headers },+ })+ const body = await response.text()+ const draining = sessionDrainingFence(response, body)+ if (draining) throw draining+ res.status(response.status).send(body)+ }+ try {+ await attempt()+ } catch (error) {+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attempt,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })+ }} catch (error) {- next(error)+ guardedNext(res, next, error)}})@@ -951,36 +1175,57 @@ export function createRpcRouter(): Router {return}const baseUrl = host.url.replace(/\/+$/, '')- const response = await fetch(- `${baseUrl}/v1/runtime/artifacts/${encodeURIComponent(filename)}/download`,- {- headers: { ...host.headers },+ // Wake-eligible finite operation (§11.4): scope stays host:task:read.+ // The success path only commits (`res.send`) at the very end, so a+ // wake retry before that point is safe from duplicate delivery.+ const attemptDownload = async () => {+ const response = await fetch(+ `${baseUrl}/v1/runtime/artifacts/${encodeURIComponent(filename)}/download`,+ {+ headers: { ...host.headers },+ }+ )+ if (!response.ok) {+ const errBody = await response.text()+ const draining = sessionDrainingFence(response, errBody)+ if (draining) throw draining+ res.status(response.status).send(errBody)+ return}- )- if (!response.ok) {- const errBody = await response.text()- res.status(response.status).send(errBody)- return+ const contentType = response.headers.get('content-type') || 'application/octet-stream'+ const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '_')+ const redaction = response.headers.get('x-clerum-redaction')+ let buffer: Buffer+ try {+ buffer = await readArtifactResponseBuffer(response)+ } catch (error) {+ if (error instanceof ProxyArtifactTooLargeError) {+ res.status(413).json({ error: 'Artifact too large to download' })+ return+ }+ throw error+ }+ res.setHeader('Content-Type', contentType)+ res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`)+ if (redaction) res.setHeader('X-Clerum-Redaction', redaction)+ res.send(buffer)}- const contentType = response.headers.get('content-type') || 'application/octet-stream'- const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '_')- const redaction = response.headers.get('x-clerum-redaction')- let buffer: Buffertry {- buffer = await readArtifactResponseBuffer(response)+ await attemptDownload()} catch (error) {- if (error instanceof ProxyArtifactTooLargeError) {- res.status(413).json({ error: 'Artifact too large to download' })- return- }- throw error+ if (!isWakeEligibleHostError(error)) throw error+ await respondWithWakeAndHold({+ res,+ hostRef,+ host,+ claims: auth,+ rpcAccessToken,+ attemptUpstream: attemptDownload,+ respondLegacy: legacyError => respondUpstreamUnavailable(res, legacyError),+ })}- res.setHeader('Content-Type', contentType)- res.setHeader('Content-Disposition', `attachment; filename="${safeFilename}"`)- if (redaction) res.setHeader('X-Clerum-Redaction', redaction)- res.send(buffer)} catch (error) {- next(error)+ guardedNext(res, next, error)}})diff --git a/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts b/rpc-proxy/src/services/__tests__/probeHostHealth.test.tsnew file mode 100644index 000000000..07b34521b--- /dev/null+++ b/rpc-proxy/src/services/__tests__/probeHostHealth.test.ts@@ -0,0 +1,74 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ResolvedServerConnection } from '../../types.js'++// The wake-and-hold readiness probe must use mcp-host's UNAUTHENTICATED+// /v1/runtime/health endpoint (Issue #791 §11.3), which comes up before MCP+// background init and is the same signal the Pod readiness probe uses — not+// /v1/runtime/status (edge-guarded). We mock the REST module so the probe's+// dependency is observable.+const restMock = vi.hoisted(() => ({+ forwardHostHealth: vi.fn(),+ forwardHostStatus: vi.fn(),+}))++vi.mock('../mcpHostRestService.js', () => restMock)++// vi.mock is hoisted above imports, so the static import resolves the mock.+import { probeHostReadyViaHealth } from '../wakeAndHold.js'++const HOST: ResolvedServerConnection = {+ name: 'chatllm',+ url: 'http://chatllm.mcp-host.svc.cluster.local:8080',+ headers: {},+}++beforeEach(() => {+ restMock.forwardHostHealth.mockReset()+ restMock.forwardHostStatus.mockReset()+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('probeHostReadyViaHealth', () => {+ it('probes /v1/runtime/health (not /v1/runtime/status) and returns true on a healthy answer', async () => {+ restMock.forwardHostHealth.mockResolvedValue({+ hostRef: 'chatllm',+ status: 'ok',+ observedAt: new Date().toISOString(),+ })++ const ready = await probeHostReadyViaHealth(HOST)++ expect(ready).toBe(true)+ expect(restMock.forwardHostHealth).toHaveBeenCalledTimes(1)+ expect(restMock.forwardHostHealth).toHaveBeenCalledWith(HOST)+ expect(restMock.forwardHostStatus).not.toHaveBeenCalled()+ })++ it('returns false when the health endpoint times out (AbortError)', async () => {+ const abort = new Error('The operation was aborted')+ abort.name = 'AbortError'+ restMock.forwardHostHealth.mockRejectedValue(abort)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the connection is refused (pod still suspended)', async () => {+ restMock.forwardHostHealth.mockRejectedValue(new TypeError('fetch failed'))++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })++ it('returns false when the health endpoint answers non-2xx (throws UpstreamHostError)', async () => {+ const upstream = Object.assign(new Error('Upstream host returned 503'), {+ name: 'UpstreamHostError',+ status: 503,+ bodySnippet: '',+ })+ restMock.forwardHostHealth.mockRejectedValue(upstream)++ expect(await probeHostReadyViaHealth(HOST)).toBe(false)+ })+})diff --git a/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts b/rpc-proxy/src/services/__tests__/wakeAndHold.test.tsindex 6cacf721f..9fbdd5b2c 100644--- a/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts+++ b/rpc-proxy/src/services/__tests__/wakeAndHold.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Response as ExpressResponse } from 'express'-import type { ResolvedServerConnection } from '../../types.js'+import type { ResolvedServerConnection, RpcAccessClaims, RpcScope } from '../../types.js'import type { HostWakeApiResponse } from '../controlApiRestService.js'import {WakeAndHoldCoordinator,@@ -39,12 +39,32 @@ function makeCoordinator(overrides?: Partial<WakeCoordinatorDeps>): {return { coordinator, requestWake, probeReady }}-function holdParams(overrides?: { hostRef?: string; tokenExpMs?: number }) {+// Wake-capable by default (§11.2): the branch-matrix below asserts a wake IS+// triggered, which now requires the caller to carry host:wake:write + the+// target hostRef. `tokenExpMs` drives claims.exp so the token-TTL cases still+// exercise the hold budget.+function holdClaims(hostRef: string, tokenExpMs: number, scopes?: RpcScope[]): RpcAccessClaims {return {- hostRef: overrides?.hostRef ?? 'chatllm',+ sub: 'user-1',+ typ: 'user',+ accessScope: 'team',+ teamId: 'team-1',+ scopes: scopes ?? ['host:wake:write', 'host:message:invoke'],+ hostRefs: [hostRef],+ jti: 'jti-1',+ iat: 1,+ exp: Math.floor(tokenExpMs / 1000),+ }+}++function holdParams(overrides?: { hostRef?: string; tokenExpMs?: number; scopes?: RpcScope[] }) {+ const hostRef = overrides?.hostRef ?? 'chatllm'+ const tokenExpMs = overrides?.tokenExpMs ?? Date.now() + 3_600_000+ return {+ hostRef,host: HOST,+ claims: holdClaims(hostRef, tokenExpMs, overrides?.scopes),rpcAccessToken: 'rpc-token',- tokenExpMs: overrides?.tokenExpMs ?? Date.now() + 3_600_000,}}@@ -429,12 +449,13 @@ describe('post-resolution re-forward hardening (respondWithWakeAndHold)', () =>respondLegacy?: (error: unknown) => void}) {+ const hostRef = overrides?.hostRef ?? 'chatllm'return {res: res as unknown as ExpressResponse,- hostRef: overrides?.hostRef ?? 'chatllm',+ hostRef,host: overrides?.host ?? HOST,+ claims: holdClaims(hostRef, Date.now() + 3_600_000),rpcAccessToken: 'rpc-token',- tokenExpMs: Date.now() + 3_600_000,attemptUpstream,respondLegacy:overrides?.respondLegacy ??diff --git a/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.tsnew file mode 100644index 000000000..956b14569--- /dev/null+++ b/rpc-proxy/src/services/__tests__/wakeCoordinator.principal.test.ts@@ -0,0 +1,347 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ResolvedServerConnection, RpcAccessClaims, RpcScope } from '../../types.js'+import {+ WakeAndHoldCoordinator,+ type WakeCoordinatorDeps,+ wakeCoordinationKey,+} from '../wakeAndHold.js'++// ── Issue #791 §11.1/§11.2/§13.3/§13.4 — principal-scoped wake coordination ──+//+// The old coordinator grouped by hostRef and picked the "latest by expiry"+// authorization with NO principal/scope check. This suite pins the corrected+// contract: coordination is keyed by principal + Host, only a same-principal+// wake-capable authorization may occupy/replace the wake slot, non-wake tokens+// never trigger a wake nor displace the wake authorization, and different+// principals never share a group.++const MAX_HOLD_MS = 90_000+const POLL_MS = 2_000+const RETRIGGER_MS = 15_000++function conn(name = 'chatllm', url?: string): ResolvedServerConnection {+ return { name, url: url ?? `http://${name}:8080`, headers: {} }+}++function makeClaims(+ overrides: Partial<Omit<RpcAccessClaims, 'exp'>> & { expMs?: number } = {}+): RpcAccessClaims {+ const expMs = overrides.expMs ?? Date.now() + 3_600_000+ return {+ sub: overrides.sub ?? 'user-a',+ typ: overrides.typ ?? 'user',+ accessScope: overrides.accessScope ?? 'user',+ teamId: overrides.teamId ?? null,+ scopes: overrides.scopes ?? (['host:wake:write', 'host:message:invoke'] as RpcScope[]),+ hostRefs: overrides.hostRefs ?? ['chatllm'],+ jti: overrides.jti ?? 'jti-1',+ iat: 1,+ exp: Math.floor(expMs / 1000),+ }+}++function makeCoordinator(overrides?: Partial<WakeCoordinatorDeps>): {+ coordinator: WakeAndHoldCoordinator+ requestWake: ReturnType<typeof vi.fn>+ probeReady: ReturnType<typeof vi.fn>+} {+ const requestWake = vi.fn().mockResolvedValue({ kind: 'wake-requested', wakeGeneration: 1 })+ const probeReady = vi.fn().mockResolvedValue(false)+ const coordinator = new WakeAndHoldCoordinator({+ requestWake,+ probeReady,+ maxHoldMs: MAX_HOLD_MS,+ pollMs: POLL_MS,+ retriggerMs: RETRIGGER_MS,+ maxTrackedHosts: 1_000,+ ...overrides,+ })+ return { coordinator, requestWake, probeReady }+}++function hold(+ coordinator: WakeAndHoldCoordinator,+ claims: RpcAccessClaims,+ token: string,+ host: ResolvedServerConnection = conn(),+ hostRef = 'chatllm'+) {+ return coordinator.hold({ hostRef, host, claims, rpcAccessToken: token })+}++let warnSpy: ReturnType<typeof vi.spyOn>+let debugSpy: ReturnType<typeof vi.spyOn>+let infoSpy: ReturnType<typeof vi.spyOn>++beforeEach(() => {+ vi.useFakeTimers()+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => {})+ infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})+})++afterEach(() => {+ expect(vi.getTimerCount()).toBe(0) // no dangling timers, ever+ vi.useRealTimers()+ warnSpy.mockRestore()+ debugSpy.mockRestore()+ infoSpy.mockRestore()+})++describe('wakeCoordinationKey', () => {+ it('excludes jti/exp/role/scopes and is stable across token rotation for one principal', () => {+ const a = makeClaims({ jti: 'j1', expMs: Date.now() + 1_000_000, scopes: ['host:wake:write'] })+ const b = makeClaims({ jti: 'j2', expMs: Date.now() + 9_000_000, scopes: ['host:session:read'] })+ expect(wakeCoordinationKey(a, 'chatllm')).toBe(wakeCoordinationKey(b, 'chatllm'))+ })++ it('separates user, team, and service principals and never contains bearer material', () => {+ const user = makeClaims({ typ: 'user', accessScope: 'user', teamId: null, sub: 'u1' })+ const team = makeClaims({ typ: 'user', accessScope: 'team', teamId: 't1', sub: 'u1' })+ const service = makeClaims({ typ: 'service', accessScope: 'service', teamId: 't1', sub: 'svc' })+ const keys = [+ wakeCoordinationKey(user, 'chatllm'),+ wakeCoordinationKey(team, 'chatllm'),+ wakeCoordinationKey(service, 'chatllm'),+ ]+ expect(new Set(keys).size).toBe(3)+ for (const key of keys) expect(key).not.toContain('bearer')+ })+})++describe('§13.3 wake coordination matrix', () => {+ it('row 1: wake-capable A + non-wake A (later expiry) → retain A wake auth; add waiter only', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ scopes: ['host:wake:write', 'host:session:read'] })+ const pA = hold(coordinator, a, 'tok-wake')+ expect(requestWake).toHaveBeenCalledTimes(1)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-wake')++ const nonWakeLater = makeClaims({+ scopes: ['host:session:read'],+ expMs: Date.now() + 7_200_000,+ })+ const pB = hold(coordinator, nonWakeLater, 'tok-nonwake')++ expect(coordinator.trackedHostCount()).toBe(1) // same principal group+ expect(requestWake).toHaveBeenCalledTimes(1) // the non-wake waiter triggered NO new wake+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-nonwake')++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ const [oA, oB] = await Promise.all([pA, pB])+ expect(oA.kind).toBe('proceed')+ expect(oB.kind).toBe('proceed')+ })++ it('row 2: wake-capable A + fresher wake-capable A → replace wake authorization + connection', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims({ expMs: Date.now() + 1_000_000 })+ const pA = hold(coordinator, a, 'tok-a', conn('chatllm', 'http://chatllm-old:8080'))++ const fresher = makeClaims({ expMs: Date.now() + 2_000_000 })+ const freshHost = conn('chatllm', 'http://chatllm-fresh:8080')+ const pA2 = hold(coordinator, fresher, 'tok-a2', freshHost)++ // Readiness probe now uses the fresher connection.+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect(probeReady).toHaveBeenCalledWith(freshHost)+ // The next wake retrigger uses the fresher wake token.+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS)+ expect(requestWake).toHaveBeenCalledWith('chatllm', 'tok-a2')++ coordinator.drain()+ await Promise.all([pA, pA2])+ })++ it('row 3: user A / team 1 vs user A / team 2 → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const t1 = makeClaims({ accessScope: 'team', teamId: 'team-1' })+ const t2 = makeClaims({ accessScope: 'team', teamId: 'team-2' })+ const p1 = hold(coordinator, t1, 'tok-t1')+ const p2 = hold(coordinator, t2, 'tok-t2')+ expect(coordinator.trackedHostCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([p1, p2])+ })++ it('row 4: user A vs user B → separate groups', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const a = makeClaims({ sub: 'user-a' })+ const b = makeClaims({ sub: 'user-b' })+ const pa = hold(coordinator, a, 'tok-a')+ const pb = hold(coordinator, b, 'tok-b')+ expect(coordinator.trackedHostCount()).toBe(2)+ expect(requestWake).toHaveBeenCalledTimes(2)+ coordinator.drain()+ await Promise.all([pa, pb])+ })++ it('row 5: no wake authorization + non-wake authorization → no unauthorized wake attempt', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const nonWake = makeClaims({ scopes: ['host:session:read'] })+ const outcome = await hold(coordinator, nonWake, 'tok-nonwake')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedHostCount()).toBe(0)+ })++ it('key is delimiter-safe: boundary-shifting identifiers cannot collide two principals', () => {+ const p1 = makeClaims({ sub: 'a|team', accessScope: 'team', teamId: 'x' })+ const p2 = makeClaims({ sub: 'a', accessScope: 'team', teamId: 'team|x' })+ expect(wakeCoordinationKey(p1, 'chatllm')).not.toBe(wakeCoordinationKey(p2, 'chatllm'))+ })++ it('drain() is a terminal fence: a hold arriving after drain settles immediately and parks nothing', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ coordinator.drain('shutdown')+ const outcome = await hold(coordinator, makeClaims(), 'tok-after-drain')+ expect(outcome).toEqual({+ kind: 'waking',+ retryAfterMs: POLL_MS,+ reason: 'shutting-down',+ lastKnownState: 'unknown',+ })+ expect(requestWake).not.toHaveBeenCalled()+ expect(coordinator.trackedHostCount()).toBe(0)+ })++ it('row 6: expired wake authorization + non-wake waiter → deterministic terminal, no wake', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ // Wake-capable token with a short budget (~2s) creates the group.+ const shortWake = makeClaims({+ scopes: ['host:wake:write', 'host:session:read'],+ expMs: Date.now() + 4_000,+ })+ const pShort = hold(coordinator, shortWake, 'tok-short')+ // A long-lived non-wake waiter keeps the entry alive after the wake token dies.+ const longNonWake = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const pLong = hold(coordinator, longNonWake, 'tok-long')++ await vi.advanceTimersByTimeAsync(2_000) // short wake token budget expires+ expect((await pShort).kind).toBe('waking')+ expect(coordinator.trackedHostCount()).toBe(1) // entry persists for the long waiter++ await vi.advanceTimersByTimeAsync(2_000) // now past the wake token's exp+ const late = makeClaims({ scopes: ['host:session:read'], expMs: Date.now() + 3_600_000 })+ const oLate = await hold(coordinator, late, 'tok-late')+ expect(oLate.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalledWith('chatllm', 'tok-late')++ coordinator.drain()+ await pLong+ })++ it('row 7: wake succeeds, health pending, several same-principal waiters → one wake, each proceeds', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ const a = makeClaims()+ const pendings = [+ hold(coordinator, a, 'tok-1'),+ hold(coordinator, a, 'tok-2'),+ hold(coordinator, a, 'tok-3'),+ ]+ expect(coordinator.trackedHostCount()).toBe(1)+ expect(requestWake).toHaveBeenCalledTimes(1) // one wake sequence for the principal group++ probeReady.mockResolvedValue(true)+ await vi.advanceTimersByTimeAsync(POLL_MS)+ for (const outcome of await Promise.all(pendings)) {+ expect(outcome.kind).toBe('proceed')+ }+ expect(coordinator.trackedHostCount()).toBe(0)+ })++ it('row 8: waiter settles, a later probe failure does not re-settle', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ probeReady.mockResolvedValueOnce(true) // first probe: ready → settle proceed+ const pending = hold(coordinator, makeClaims(), 'tok-1')+ await vi.advanceTimersByTimeAsync(POLL_MS)+ expect((await pending).kind).toBe('proceed')+ expect(coordinator.trackedHostCount()).toBe(0)++ // Advancing past every window makes NO further probe/settle — group is gone.+ const probeCalls = probeReady.mock.calls.length+ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS * 2)+ expect(probeReady.mock.calls.length).toBe(probeCalls)+ expect(coordinator.trackedHostCount()).toBe(0)+ })+})++describe('§13.4 operation outcomes (unit level)', () => {+ it('active runtime → proceed immediately, no hold loop', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'active', wakeGeneration: null })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'proceed', lastKnownState: 'active' })+ expect(probeReady).not.toHaveBeenCalled()+ })++ it('stateful unavailable (not-stateless) → legacy, never a stateless wake hold', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'not-stateless' })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'not-stateless' })+ expect(coordinator.trackedHostCount()).toBe(0)+ })++ it('suspended + no wake grant → no fallback grant; deterministic legacy result', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ const outcome = await hold(coordinator, makeClaims({ scopes: ['host:session:read'] }), 'tok')+ expect(outcome.kind).toBe('legacy')+ expect(requestWake).not.toHaveBeenCalled()+ })+})++describe('a mid-hold wake auth rejection distinguishes initial from retrigger', () => {+ it('an initial wake 403 settles the group legacy', async () => {+ const { coordinator, requestWake } = makeCoordinator()+ requestWake.mockResolvedValue({ kind: 'auth', status: 403 })+ const outcome = await hold(coordinator, makeClaims(), 'tok')+ expect(outcome).toEqual({ kind: 'legacy', reason: 'wake-auth-403' })+ expect(coordinator.trackedHostCount()).toBe(0)+ })++ it('a retrigger wake 403 does NOT collapse still-valid waiters (initial guard)', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ requestWake+ .mockResolvedValueOnce({ kind: 'wake-requested', wakeGeneration: 1 })+ .mockResolvedValue({ kind: 'auth', status: 403 }) // retrigger rejected+ probeReady.mockResolvedValue(false)++ const pending = hold(coordinator, makeClaims(), 'tok')+ await vi.advanceTimersByTimeAsync(RETRIGGER_MS) // fire one retrigger (auth 403)+ // The group is still held (bounded by deadlines), not collapsed to legacy.+ expect(coordinator.trackedHostCount()).toBe(1)++ await vi.advanceTimersByTimeAsync(MAX_HOLD_MS)+ const outcome = await pending+ expect(outcome).toMatchObject({ kind: 'waking' })+ expect(coordinator.trackedHostCount()).toBe(0)+ })+})++describe('shutdown drain', () => {+ it('settles every parked waiter deterministically and leaves no dangling timers', async () => {+ const { coordinator, requestWake, probeReady } = makeCoordinator()+ void requestWake+ void probeReady+ const a = hold(coordinator, makeClaims({ sub: 'user-a' }), 'tok-a', conn('chatllm'), 'chatllm')+ const b = hold(+ coordinator,+ makeClaims({ sub: 'user-b', hostRefs: ['other'] }),+ 'tok-b',+ conn('other'),+ 'other'+ )+ expect(coordinator.trackedHostCount()).toBe(2)++ coordinator.drain()++ const [oa, ob] = await Promise.all([a, b])+ expect(oa.kind).toBe('waking')+ expect(ob.kind).toBe('waking')+ expect(coordinator.trackedHostCount()).toBe(0)+ })+})diff --git a/rpc-proxy/src/services/wakeAndHold.ts b/rpc-proxy/src/services/wakeAndHold.tsindex 2a8d12c92..c65f804cf 100644--- a/rpc-proxy/src/services/wakeAndHold.ts+++ b/rpc-proxy/src/services/wakeAndHold.ts@@ -1,17 +1,26 @@import type { Response as ExpressResponse } from 'express'import { config } from '../config.js'-import type { ResolvedServerConnection } from '../types.js'+import type { ResolvedServerConnection, RpcAccessClaims } from '../types.js'import { type HostWakeApiResponse, requestHostWakeFromControlApi } from './controlApiRestService.js'-import { forwardHostStatus } from './mcpHostRestService.js'+import { forwardHostHealth } from './mcpHostRestService.js'/**- * Stateless wake-and-hold (Stage 5).+ * Stateless wake-and-hold (Stage 5, Issue #791 §11).** When a request targets a stateless Host whose pod is suspended (network* failure) or draining (upstream 503 {code:'host_draining'}), rpc-proxy calls* the control-api wake endpoint and — for a 202 — parks the request while the* pod comes up, instead of surfacing the generic 502.*+ * Coordination is keyed by PRINCIPAL + Host (§11.1), not by Host alone. Only a+ * same-principal wake-capable authorization (unexpired, carrying+ * `host:wake:write` AND the target hostRef) may occupy or replace the wake+ * slot. A non-wake token can ride an existing wake but can never trigger one+ * nor displace the wake authorization, and different principals never share a+ * group — so a non-wake or foreign token can no longer displace the only+ * wake-capable authorization and drive an unauthorized 403 that collapses+ * every waiter on the Host.+ ** Fleet note: rpc-proxy runs with replicas:2, so the in-memory dedup map here* is per-instance best effort. The fleet-level authority for wake dedup and* rate limiting is control-api (Postgres-backed generation + token bucket).@@ -19,14 +28,21 @@ import { forwardHostStatus } from './mcpHostRestService.js'const TOKEN_EXP_SAFETY_MARGIN_MS = 2_000const ENTRY_TTL_MARGIN_MS = 5_000-const MAX_TRACKED_HOSTS = 1_000+/**+ * Capacity of the coordination map. Entries are per (principal, host) — a+ * fleet of H hosts with P concurrently-holding principals per host consumes+ * up to H×P slots (review F2). Oldest-first eviction settles the victim+ * retryable (503 host_waking), so overflow degrades politely.+ */+const MAX_TRACKED_PRINCIPAL_HOSTS = 1_000+const WAKE_SCOPE = 'host:wake:write' as const/** Short upstream retry schedule after a wake reports the host is up. */const PROCEED_RETRY_DELAYS_MS = [0, 250, 1_000]export type WakeHoldOutcome =/** Host is (or just became) reachable — re-issue the upstream request now. */| { kind: 'proceed'; lastKnownState: string }- /** Host is not stateless / wake plane failed — keep today's error behavior. */+ /** Host is not stateless / wake plane failed / not wake-capable — keep today's error behavior. */| { kind: 'legacy'; reason: string }/** Host CR is gone — 404 to the caller. */| { kind: 'not-found' }@@ -37,16 +53,33 @@ type Waiter = {id: numberresolve: (outcome: WakeHoldOutcome) => voidtimer: NodeJS.Timeout+ /** Per-waiter one-shot latch: the deadline timer and a group settle can race. */+ settled: boolean+}++/**+ * The single same-principal wake-capable authorization used to drive the wake+ * plane. Only replaced by a later-expiry same-principal wake-capable token;+ * never by a non-wake token.+ */+type WakeAuthorization = {+ token: string+ tokenExpMs: number}type HostWakeEntry = {+ /** Principal+Host coordination key (never logged — see §11.1). */+ key: string+ /** Sanitized logical Host reference — the only identity allowed in logs. */hostRef: stringcreatedAt: number/** Last state reported by the wake endpoint — surfaced as diagnostics. */lastKnownState: stringwaiters: Map<number, Waiter>- /** Freshest credentials/connection among held requests, used by loops. */- latest: { host: ResolvedServerConnection; token: string; tokenExpMs: number }+ /** Same-principal wake-capable authorization used for the wake plane. */+ wakeAuthorization: WakeAuthorization+ /** Current resolved Host connection used by the readiness probe. */+ connection: ResolvedServerConnectionpollTimer: NodeJS.Timeout | nullretriggerTimer: NodeJS.Timeout | nullttlTimer: NodeJS.Timeout | null@@ -59,6 +92,7 @@ export type WakeCoordinatorDeps = {maxHoldMs: numberpollMs: numberretriggerMs: number+ /** Capacity in (principal, host) entries — see MAX_TRACKED_PRINCIPAL_HOSTS. */maxTrackedHosts: numbernow?: () => number}@@ -66,14 +100,45 @@ export type WakeCoordinatorDeps = {export type WakeHoldParams = {hostRef: stringhost: ResolvedServerConnection+ /** Parsed claims of the caller — used for principal keying + wake capability. */+ claims: RpcAccessClaims+ /** Raw bearer forwarded to the wake plane when this caller is wake-capable. */rpcAccessToken: string- /** Absolute expiry of the caller's rpc token (JWT `exp` in milliseconds). */- tokenExpMs: number+}++/**+ * Stable in-memory coordination key from existing claims + hostRef (§11.1):+ * `{ typ, sub, accessScope, teamId ?? '', hostRef }`. Excludes jti/exp/role/+ * scopes (they rotate per token and would fragment one principal), and never+ * contains bearer material.+ */+export function wakeCoordinationKey(claims: RpcAccessClaims, hostRef: string): string {+ // Delimiter-safe encoding (adversarial review F4): sub/teamId are+ // server-assigned UUIDs today, but principal isolation must not silently+ // depend on ID format — JSON framing makes boundary-shifting collisions+ // impossible regardless of future identifier shapes.+ return JSON.stringify([claims.typ, claims.sub, claims.accessScope, claims.teamId ?? '', hostRef])+}++/**+ * "Wake-capable" (§11.2) = unexpired claims that contain `host:wake:write` AND+ * the target hostRef in `hostRefs`. Expiry uses the same safety margin as the+ * hold budget so a token that cannot survive the wake call is not treated as+ * usable for it.+ */+function isWakeCapable(claims: RpcAccessClaims, hostRef: string, now: number): boolean {+ const tokenExpMs = claims.exp * 1000+ if (tokenExpMs - TOKEN_EXP_SAFETY_MARGIN_MS <= now) return false+ if (!claims.scopes.includes(WAKE_SCOPE)) return false+ if (!claims.hostRefs.includes(hostRef)) return false+ return true}export class WakeAndHoldCoordinator {private readonly entries = new Map<string, HostWakeEntry>()private waiterSeq = 0+ /** Set once by drain(); permanently fences new holds during shutdown. */+ private draining = falseconstructor(private readonly deps: WakeCoordinatorDeps) {}@@ -83,8 +148,20 @@ export class WakeAndHoldCoordinator {}async hold(params: WakeHoldParams): Promise<WakeHoldOutcome> {+ if (this.draining) {+ // Shutdown fence (review F1): drain() already settled the map; a hold+ // arriving from an in-flight request after SIGTERM must not park past+ // server.close(). The client retries against a live replica.+ return {+ kind: 'waking',+ retryAfterMs: this.deps.pollMs,+ reason: 'shutting-down',+ lastKnownState: 'unknown',+ }+ }const now = this.now()- const tokenBudgetMs = params.tokenExpMs - TOKEN_EXP_SAFETY_MARGIN_MS - now+ const tokenExpMs = params.claims.exp * 1000+ const tokenBudgetMs = tokenExpMs - TOKEN_EXP_SAFETY_MARGIN_MS - nowif (tokenBudgetMs <= 0) {// Never park a request that could only be forwarded with an expired// token. The client re-issues with a fresh token and retries.@@ -99,23 +176,42 @@ export class WakeAndHoldCoordinator {const deadlineReason =holdBudgetMs < this.deps.maxHoldMs ? 'token-expiring' : 'max-hold-exceeded'- let entry = this.entries.get(params.hostRef)+ const key = wakeCoordinationKey(params.claims, params.hostRef)+ const wakeCapable = isWakeCapable(params.claims, params.hostRef, now)++ let entry = this.entries.get(key)if (!entry) {- entry = this.createEntry(params)- } else if (params.tokenExpMs >= entry.latest.tokenExpMs) {- // Keep the freshest token/connection so retriggers and the eventual- // forward never run on the stalest credentials in the pack.- entry.latest = {- host: params.host,- token: params.rpcAccessToken,- tokenExpMs: params.tokenExpMs,+ if (!wakeCapable) {+ // No wake-capable authorization exists for this principal+Host, so+ // calling the wake plane would only earn a deterministic 403. Return+ // today's pre-wake availability result instead (§11.2, §13.4). No+ // fallback grant is minted.+ return { kind: 'legacy', reason: 'no-wake-authorization' }+ }+ entry = this.createEntry(key, params, tokenExpMs)+ } else if (wakeCapable) {+ if (tokenExpMs > entry.wakeAuthorization.tokenExpMs) {+ // Same principal, wake-capable, later valid expiry → replace the wake+ // authorization and the connection the probe uses.+ entry.wakeAuthorization = { token: params.rpcAccessToken, tokenExpMs }+ entry.connection = params.host}+ // Same principal, wake-capable, earlier/equal expiry → retain current.+ } else if (entry.wakeAuthorization.tokenExpMs - TOKEN_EXP_SAFETY_MARGIN_MS <= now) {+ // Not wake-capable and the group's wake authorization has itself expired:+ // there is no valid authorization to ride, so no wake is possible.+ return { kind: 'legacy', reason: 'wake-authorization-expired' }}+ // Otherwise (not wake-capable, valid wake authorization present) the caller+ // rides the existing wake as a waiter only — never replacing the auth.const activeEntry = entryreturn await new Promise<WakeHoldOutcome>(resolve => {const id = ++this.waiterSeq- const timer = setTimeout(() => {+ const waiter: Waiter = { id, resolve, timer: null as unknown as NodeJS.Timeout, settled: false }+ waiter.timer = setTimeout(() => {+ if (waiter.settled) return+ waiter.settled = trueactiveEntry.waiters.delete(id)resolve({kind: 'waking',@@ -125,37 +221,52 @@ export class WakeAndHoldCoordinator {})this.releaseIfEmpty(activeEntry)}, holdBudgetMs)- activeEntry.waiters.set(id, { id, resolve, timer })+ activeEntry.waiters.set(id, waiter)})}+ /**+ * Deterministically settles every parked waiter AND permanently fences new+ * holds (terminal `waking`/`shutting-down`) — used by the service's graceful+ * shutdown path so no held request hangs across `server.close()`.+ */+ drain(reason = 'shutdown-drain'): void {+ this.draining = true+ for (const entry of [...this.entries.values()]) {+ this.settle(entry, {+ kind: 'waking',+ retryAfterMs: this.deps.pollMs,+ reason,+ lastKnownState: entry.lastKnownState,+ })+ }+ }+private now(): number {return this.deps.now ? this.deps.now() : Date.now()}- private createEntry(params: WakeHoldParams): HostWakeEntry {+ private createEntry(key: string, params: WakeHoldParams, tokenExpMs: number): HostWakeEntry {this.enforceCapacity()const entry: HostWakeEntry = {+ key,hostRef: params.hostRef,createdAt: this.now(),lastKnownState: 'unknown',waiters: new Map(),- latest: {- host: params.host,- token: params.rpcAccessToken,- tokenExpMs: params.tokenExpMs,- },+ wakeAuthorization: { token: params.rpcAccessToken, tokenExpMs },+ connection: params.host,pollTimer: null,retriggerTimer: null,ttlTimer: null,settled: false,}- this.entries.set(params.hostRef, entry)+ this.entries.set(key, entry)// Safety net: even if a waiter bookkeeping bug ever left the entry behind,// it self-destructs loudly instead of leaking timers forever.entry.ttlTimer = setTimeout(() => {console.warn(- `[RPC_PROXY] wake-hold entry TTL exceeded host=${entry.hostRef} waiters=${entry.waiters.size} — evicting`+ `[RPC_PROXY] wake-hold entry TTL exceeded (principal-scoped entry) host=${entry.hostRef} waiters=${entry.waiters.size} — evicting`)this.settle(entry, {kind: 'waking',@@ -176,7 +287,7 @@ export class WakeAndHoldCoordinator {}if (!oldest) returnconsole.warn(- `[RPC_PROXY] wake-hold capacity exceeded (max=${this.deps.maxTrackedHosts}) — evicting oldest host=${oldest.hostRef} waiters=${oldest.waiters.size}`+ `[RPC_PROXY] wake-hold capacity exceeded (max=${this.deps.maxTrackedHosts} principal-scoped entries) — evicting oldest entry host=${oldest.hostRef} waiters=${oldest.waiters.size}`)this.settle(oldest, {kind: 'waking',@@ -189,7 +300,7 @@ export class WakeAndHoldCoordinator {private async issueWake(entry: HostWakeEntry, options: { initial: boolean }): Promise<void> {let response: HostWakeApiResponsetry {- response = await this.deps.requestWake(entry.hostRef, entry.latest.token)+ response = await this.deps.requestWake(entry.hostRef, entry.wakeAuthorization.token)} catch (error) {console.warn(`[RPC_PROXY] wake call failed host=${entry.hostRef} initial=${options.initial} error=${@@ -242,12 +353,19 @@ export class WakeAndHoldCoordinator {// next retrigger tick retries, so keep holding for readiness.returncase 'auth':- // The caller's token passed rpc-proxy auth for this host, so a wake- // 401/403 is unexpected — log loudly and keep today's behavior.+ // The wake plane rejected the wake-capable authorization. Distinguish+ // initial from retrigger deliberately (§11.2): an INITIAL rejection is+ // terminal for this principal group, but a mid-hold RETRIGGER rejection+ // (token rotated/revoked after the wake was already recorded) must NOT+ // collapse the still-valid waiters — keep holding, bounded by the+ // per-waiter deadlines and the entry TTL. Because coordination is+ // principal-scoped, this only ever affects this principal's group.console.warn(- `[RPC_PROXY] wake call rejected host=${entry.hostRef} status=${response.status}`+ `[RPC_PROXY] wake call rejected host=${entry.hostRef} status=${response.status} initial=${options.initial}`)- this.settle(entry, { kind: 'legacy', reason: `wake-auth-${response.status}` })+ if (options.initial) {+ this.settle(entry, { kind: 'legacy', reason: `wake-auth-${response.status}` })+ }return}}@@ -257,10 +375,10 @@ export class WakeAndHoldCoordinator {entry.pollTimer = setTimeout(async () => {let ready = falsetry {- ready = await this.deps.probeReady(entry.latest.host)+ ready = await this.deps.probeReady(entry.connection)} catch (error) {// A failed probe is "not ready yet" — the hold stays bounded by the- // per-waiter deadlines, so a broken poll source cannot hang callers.+ // per-waiter deadlines, so a broken probe source cannot hang callers.console.warn(`[RPC_PROXY] wake-hold readiness probe failed host=${entry.hostRef} error=${error instanceof Error ? error.message : String(error)@@ -314,8 +432,10 @@ export class WakeAndHoldCoordinator {}entry.settled = truethis.clearEntryTimers(entry)- this.entries.delete(entry.hostRef)+ this.entries.delete(entry.key)for (const waiter of entry.waiters.values()) {+ if (waiter.settled) continue+ waiter.settled = trueclearTimeout(waiter.timer)waiter.resolve(outcome)}@@ -326,7 +446,7 @@ export class WakeAndHoldCoordinator {if (entry.settled || entry.waiters.size > 0) returnentry.settled = truethis.clearEntryTimers(entry)- this.entries.delete(entry.hostRef)+ this.entries.delete(entry.key)}}@@ -370,6 +490,7 @@ function respondHostWaking(res: ExpressResponse,details: { hostRef: string; retryAfterMs: number; lastKnownState: string }): void {+ if (res.headersSent) returnres.setHeader('Retry-After', String(Math.max(1, Math.ceil(details.retryAfterMs / 1000))))res.status(503).json({code: 'host_waking',@@ -380,34 +501,52 @@ function respondHostWaking(})}+/**+ * Readiness probe (§11.3): mcp-host's UNAUTHENTICATED `/v1/runtime/health`.+ * It comes up before MCP background init and is the same signal the Pod+ * readiness probe uses. `forwardHostHealth` throws on non-2xx / network+ * failure, so a resolved value means the pod is answering runtime traffic —+ * the retried operation still enforces its own authorization/business+ * contract. Bounded by `config.upstreamTimeoutMs` (AbortController inside the+ * REST helper); on shutdown `drain()` stops the poll loop and any late result+ * is ignored via the entry `settled` latch.+ *+ * Rollout-skew note (review F5): an old mcp-host image without+ * `/v1/runtime/health` makes this probe return false until the hold deadline;+ * holds still settle because the retrigger wake's `active` response — derived+ * by control-api from replica/endpoint state, not from this endpoint — settles+ * `proceed`. Readiness latency degrades from ~pollMs to ~retriggerMs in that+ * skew window.+ */+export async function probeHostReadyViaHealth(host: ResolvedServerConnection): Promise<boolean> {+ try {+ await forwardHostHealth(host)+ return true+ } catch {+ // Unreachable/erroring health endpoint == not ready yet. Bounded by the+ // hold deadline — never a silent success.+ return false+ }+}+/** Singleton wired to production dependencies. Tests construct their own. */export const hostWakeCoordinator = new WakeAndHoldCoordinator({requestWake: requestHostWakeFromControlApi,- probeReady: async (host: ResolvedServerConnection) => {- // Same readiness source the host-status SSE stream polls: a parseable- // /v1/runtime/status snapshot proves the pod answers runtime traffic.- try {- const status = await forwardHostStatus(host)- return status !== null- } catch {- // Unreachable/erroring status endpoint == not ready yet. Bounded by the- // hold deadline — never a silent success.- return false- }- },+ probeReady: probeHostReadyViaHealth,maxHoldMs: config.wakeMaxHoldMs,pollMs: config.wakePollMs,retriggerMs: config.wakeRetriggerMs,- maxTrackedHosts: MAX_TRACKED_HOSTS,+ maxTrackedHosts: MAX_TRACKED_PRINCIPAL_HOSTS,})export type RespondWithWakeAndHoldOptions = {res: ExpressResponsehostRef: stringhost: ResolvedServerConnection+ /** Parsed claims of the caller — principal keying + wake capability (§11.1). */+ claims: RpcAccessClaims+ /** Raw bearer forwarded to the wake plane when the caller is wake-capable. */rpcAccessToken: string- /** JWT `exp` of the caller's rpc token, in milliseconds. */- tokenExpMs: number/** Re-issues the original upstream request and writes the success response. */attemptUpstream: () => Promise<void>/** Writes today's error response (502/504) — the pre-wake behavior. */@@ -419,7 +558,8 @@ export type RespondWithWakeAndHoldOptions = {* Drives one held request through the wake flow and always writes a response:* - proceed → short upstream retry schedule (draining bounces clear in ~1-2s),* then structured host_waking if the pod is still not answering.- * - legacy → today's 502 path (409 not-stateless, wake plane failure).+ * - legacy → today's 502 path (409 not-stateless, wake plane failure, or a+ * non-wake-capable caller with no wake authorization to ride).* - not-found→ 404.* - waking → structured 503 {code:'host_waking'} + Retry-After.*/@@ -438,8 +578,8 @@ export async function respondWithWakeAndHold(const outcome = await coordinator.hold({hostRef: options.hostRef,host: options.host,+ claims: options.claims,rpcAccessToken: options.rpcAccessToken,- tokenExpMs: options.tokenExpMs,})switch (outcome.kind) {@@ -521,5 +661,6 @@ export async function respondWithWakeAndHold(}function res404(res: ExpressResponse): void {+ if (res.headersSent) returnres.status(404).json({ error: 'Host not found or not accessible' })}