Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge remote-tracking branch 'origin/dev' into feat/grok-subscription-image-input
Alfredo Lopez6526bec7643d
diff --cc codex-llm-proxy/src/server.tsindex f9e9eef02,638500e61..7e924c38d--- a/codex-llm-proxy/src/server.ts+++ b/codex-llm-proxy/src/server.ts@@@ -26,9 -20,10 +26,9 @@@ importlistCodexModels,streamCodexCompletion,testCodexConnection,- UpstreamTimeoutError,} from './codexTransport.js'import type { CodexLlmProxyConfig } from './config.js'- import { ControlApiClient, ControlApiClientError } from './controlApiClient.js'+ import { ControlApiClient, ControlApiClientError, fetchCauseCode } from './controlApiClient.js'import { logger } from './logger.js'import { createProxyMetrics } from './metrics.js'import {diff --cc control-api/package-lock.jsonindex c590eda6b,efe682948..f95b80ddd--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-api",- "version": "0.1.644",- "version": "0.1.637",++ "version": "0.1.645","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.644",- "version": "0.1.637",++ "version": "0.1.645","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --cc control-api/package.jsonindex f6e9dac46,52a7ddeb8..f86280923--- a/control-api/package.json+++ b/control-api/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-api",- "version": "0.1.644",- "version": "0.1.637",++ "version": "0.1.645","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --cc grok-llm-proxy/src/server.tsindex cb945abd2,a2dcd38dc..ebc23ae42--- a/grok-llm-proxy/src/server.ts+++ b/grok-llm-proxy/src/server.ts@@@ -9,22 -9,16 +9,22 @@@ import { rateLimit } from 'express-rateimport { type Server, createServer } from 'node:http'import { Registry, collectDefaultMetrics } from 'prom-client'import { z } from 'zod'-import { verifyAdminPermit } from './auth/adminPermitVerifier.js'import {- isExpiredExecutionTicket,- verifyExecutionTicket,-} from './auth/executionTicketVerifier.js'+ BODY_STRUCTURE_LIMITS,+ LIMITS,+ SCHEMA_VERSION_V2,+ createBodyStructureVerify,+ measureNonImageCompletionBytes,+ requestBodyLimitBytes,+} from '@clerum/grok-provider-attempt-contract'+import { verifyAdminPermit } from './auth/adminPermitVerifier.js'+import { isExpiredExecutionTicket, verifyExecutionTicket } from './auth/executionTicketVerifier.js'import { type PlatformJwtClaims, verifyPlatformJwt } from './auth/platformJwtVerifier.js'import type { GrokLlmProxyConfig } from './config.js'- import { ControlApiClient, ControlApiClientError } from './controlApiClient.js'+ import { ControlApiClient, ControlApiClientError, fetchCauseCode } from './controlApiClient.js'import {GrokTransportError,+ UpstreamTimeoutError,listGrokModels,streamGrokCompletion,testGrokConnection,diff --cc mcp-host/src/llm/__tests__/grokLlmProxyClient.test.tsindex bd2f9eb8b,f167c0951..e6166b844--- a/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts+++ b/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts@@@ -14,7 -8,8 +14,9 @@@ importresolveGrokProxyRuntimeUrl,} from '../grokLlmProxyClient'import { GrokSubscriptionProvider } from '../grokSubscription'+ import { CodexAuthorizeError } from '../providerAttemptAuthorizer'+ import { closedPortUrl, fetchFailure, silentServer } from './connectFailureFixtures'+import { GROK_PNG_2X2_BASE64 } from './grokImageFixtures'const RUNTIME_BASE = 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080'const RUNTIME_URL = `${RUNTIME_BASE}/internal/runtime/v1/grok/completions`diff --cc mcp-host/src/llm/__tests__/grokSubscription.test.tsindex 3a1599095,e11fe0a33..59e5d6e98--- a/mcp-host/src/llm/__tests__/grokSubscription.test.ts+++ b/mcp-host/src/llm/__tests__/grokSubscription.test.ts@@@ -1,23 -1,15 +1,27 @@@- import { describe, expect, it, vi } from 'vitest'+ import { afterEach, describe, expect, it, vi } from 'vitest'-import { LIMITS } from '@clerum/grok-provider-attempt-contract'+import {+ GROK_VISUAL_LIMITS,+ LIMITS,+ hashCanonicalGrokRequest,+} from '@clerum/grok-provider-attempt-contract'import { minifiedMcpResult } from '../../__tests__/fixtures/minifiedMcpResult'import { LlmErrorCode } from '../../core/errors'+import type { ChatMessage, MessageContentPart } from '../../core/types'+import { CodexSubscriptionProvider } from '../codexSubscription'import { classifyFailoverClass } from '../failover/classify'import { GrokProxyError } from '../grokLlmProxyClient'import { GrokSubscriptionProvider } from '../grokSubscription'- import { CodexAuthorizeError } from '../providerAttemptAuthorizer'+ import {+ CodexAuthorizeError,+ ProviderAttemptAuthorizer,+ resolveCodexAuthorizeUrl,+ } from '../providerAttemptAuthorizer'+import {+ GROK_JPEG_2X2_BASE64,+ GROK_PNG_2X2_BASE64,+ GROK_PNG_9000_BASE64,+ grokPngOfDecodedBytesBase64,+} from './grokImageFixtures'const requestHash = 'a'.repeat(64)@@@ -915,484 -838,383 +924,864 @@@ describe('GrokSubscriptionProvider', (})})+// ─── #784 G4b: Grok image input ───────────────────────────────────────────+//+// The Grok twin of the Codex V2 projection (#660) and of R9-11: parts ride on+// user messages only, every image names its source, and a contract image+// budget refusal reaches the Desktop as "Invalid Attachment" with a sentence+// naming the Grok limit.++type ImagePart = Extract<MessageContentPart, { type: 'image' }>++const QUESTION = 'what is on screen?'+const attachmentImage = (+ data: string,+ attachmentId: string,+ mimeType: ImagePart['mimeType'] = 'image/png'+): ImagePart => ({+ type: 'image',+ mimeType,+ data,+ source: { kind: 'attachment', attachmentId, messageId: 'msg-1' },+})+const userWithImages = (parts: ImagePart[], preamble?: string): ChatMessage[] => [+ ...(preamble !== undefined ? [{ role: 'user' as const, content: preamble }] : []),+ {+ role: 'user',+ content: QUESTION,+ contentParts: [{ type: 'text', text: QUESTION }, ...parts],+ },+]++describe('GrokSubscriptionProvider image input (#784)', () => {+ it('T-G4b-1 authorizes an attachment image as a V2 request the contract re-derives', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ await provider.completeSingleTurn(+ userWithImages([attachmentImage(GROK_PNG_2X2_BASE64, 'att-1')])+ )++ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ const body = wired.authorizer.authorize.mock.calls[0][0]+ expect(body.request.schemaVersion).toBe('grok-completion-request.v2')+ expect(body.request.messages).toEqual([+ {+ role: 'user',+ content: QUESTION,+ contentParts: [+ { type: 'text', text: QUESTION },+ {+ type: 'image',+ mimeType: 'image/png',+ data: GROK_PNG_2X2_BASE64,+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: 'msg-1' },+ },+ ],+ },+ ])+ // control-api and the proxy hash the JSON wire copy; the Host must agree.+ const rederived = hashCanonicalGrokRequest(JSON.parse(JSON.stringify(body.request)))+ if (!rederived.ok) throw new Error(rederived.message)+ expect(rederived.value.requestHash).toBe(body.requestHash)+ expect(wired.proxy.stream.mock.calls[0][0].request).toEqual(body.request)+ })++ it('T-G4b-2 carries a tool screenshot on a user message with a tool source', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ await provider.completeSingleTurnWithTools(+ [+ { role: 'user', content: 'take a screenshot' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: 'tc-1', name: 'browser_screenshot', arguments: {} }],+ },+ {+ role: 'tool',+ content: 'screenshot captured',+ tool_call_id: 'tc-1',+ name: 'browser_screenshot',+ },+ {+ role: 'user',+ content: 'Screenshot from browser_screenshot',+ contentParts: [+ { type: 'text', text: 'Screenshot from browser_screenshot' },+ {+ type: 'image',+ mimeType: 'image/jpeg',+ data: GROK_JPEG_2X2_BASE64,+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: 'tc-1' },+ },+ ],+ },+ ],+ [{ name: 'browser_screenshot', description: 'screenshot', parameters: {} }]+ )++ const request = wired.authorizer.authorize.mock.calls[0][0].request+ expect(request.schemaVersion).toBe('grok-completion-request.v2')+ const withParts = request.messages.filter(+ (message: { contentParts?: unknown }) => message.contentParts !== undefined+ )+ // Exactly one message carries parts, and it is the user frame; the+ // assistant and tool messages keep their V1 shape inside the V2 request.+ expect(withParts).toHaveLength(1)+ expect(withParts[0].role).toBe('user')+ expect(withParts[0].contentParts[1]).toEqual({+ type: 'image',+ mimeType: 'image/jpeg',+ data: GROK_JPEG_2X2_BASE64,+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: 'tc-1' },+ })+ expect(request.messages[2]).toEqual({+ role: 'tool',+ content: 'screenshot captured',+ toolCallId: 'tc-1',+ name: 'browser_screenshot',+ })+ })++ it('T-G4b-2b projects a GFS read to its tool-call source on the Grok wire', async () => {+ // The twin of the Codex test #670 added: a GFS image names the read that+ // produced it, and the contract's closed source union carries it as `tool`.+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ await provider.completeSingleTurnWithTools(+ userWithImages([+ {+ type: 'image',+ mimeType: 'image/png',+ data: GROK_PNG_2X2_BASE64,+ source: {+ kind: 'gfs',+ drive: 'main',+ resourceId: 'a'.repeat(32),+ gfsUri: `gfs://main/${'a'.repeat(32)}`,+ version: 7,+ name: 'image.png',+ attachmentId: 'gfs-read-attachment',+ toolCallId: 'gfs-read-call',+ },+ },+ ]),+ []+ )++ const body = wired.authorizer.authorize.mock.calls[0][0]+ expect(body.request.messages[0].contentParts[1].source).toEqual({+ kind: 'tool',+ attachmentId: 'gfs-read-attachment',+ toolCallId: 'gfs-read-call',+ })+ const rederived = hashCanonicalGrokRequest(JSON.parse(JSON.stringify(body.request)))+ if (!rederived.ok) throw new Error(rederived.message)+ expect(rederived.value.requestHash).toBe(body.requestHash)+ })++ it('T-G4b-3 keeps text and image parts in their original order', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ await provider.completeSingleTurn([+ {+ role: 'user',+ content: 'before\nafter',+ contentParts: [+ { type: 'text', text: 'before' },+ attachmentImage(GROK_PNG_2X2_BASE64, 'att-1'),+ { type: 'text', text: 'after' },+ ],+ },+ ])++ const [message] = wired.authorizer.authorize.mock.calls[0][0].request.messages+ expect(message.content).toBe('before\nafter')+ expect(message.contentParts.map((part: { type: string }) => part.type)).toEqual([+ 'text',+ 'image',+ 'text',+ ])+ })++ it('T-G4b-4 sends a 9000x9000 image, since Grok has no dimension limit', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ await provider.completeSingleTurn(+ userWithImages([attachmentImage(GROK_PNG_9000_BASE64, 'att-large')])+ )++ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ const [message] = wired.authorizer.authorize.mock.calls[0][0].request.messages+ expect(message.contentParts[1].data).toBe(GROK_PNG_9000_BASE64)+ })++ it('T-G4b-5 refuses parts on a non-user message instead of dropping them', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const rejected = await provider+ .completeSingleTurn([+ { role: 'user', content: 'hi' },+ {+ role: 'assistant',+ content: 'look',+ contentParts: [{ type: 'text', text: 'look' }, attachmentImage(GROK_PNG_2X2_BASE64, 'a')],+ },+ ])+ .catch((e: unknown) => e)++ expect(rejected).toBeInstanceOf(CodexAuthorizeError)+ expect(rejected).toMatchObject({+ code: 'invalid_request',+ message: 'content parts are only supported on user messages (role=assistant)',+ })+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()++ // Liveness witness: the same provider authorizes and streams a small turn.+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['missing source', { type: 'image', mimeType: 'image/png', data: GROK_PNG_2X2_BASE64 }],+ [+ 'empty attachmentId',+ {+ type: 'image',+ mimeType: 'image/png',+ data: GROK_PNG_2X2_BASE64,+ source: { kind: 'attachment', attachmentId: ' ', messageId: 'msg-1' },+ },+ ],+ [+ 'empty messageId',+ {+ type: 'image',+ mimeType: 'image/png',+ data: GROK_PNG_2X2_BASE64,+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: '' },+ },+ ],+ [+ 'empty toolCallId',+ {+ type: 'image',+ mimeType: 'image/png',+ data: GROK_PNG_2X2_BASE64,+ source: { kind: 'tool', attachmentId: 'shot-1', toolCallId: '' },+ },+ ],+ ] as Array<[string, ImagePart]>)(+ 'T-G4b-6 refuses an image with %s as image_source_invalid before authorize',+ async (detail, part) => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const rejected = await provider+ .completeSingleTurn(userWithImages([part]))+ .catch((e: unknown) => e)++ expect(rejected).toBeInstanceOf(CodexAuthorizeError)+ expect(rejected).toMatchObject({+ code: 'image_source_invalid',+ message: `image part has no usable provenance source (${detail}); host producers must attach the attachment or tool call it came from`,+ })+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()++ const classified = provider.classifyError(rejected)+ expect(classified).toMatchObject({+ code: LlmErrorCode.ApiCallFailed,+ retryable: false,+ providerDispatched: false,+ })+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()++ // Liveness witness: the same provider authorizes a well-sourced image.+ await provider.completeSingleTurn(+ userWithImages([attachmentImage(GROK_PNG_2X2_BASE64, 'att-1')])+ )+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ }+ )++ const gfsSource = (attachmentId: string, toolCallId: string) => ({+ kind: 'gfs' as const,+ drive: 'main',+ resourceId: 'a'.repeat(32),+ gfsUri: `gfs://main/${'a'.repeat(32)}`,+ version: 7,+ name: 'image.png',+ attachmentId,+ toolCallId,+ })+ it.each([+ ['a tool source', 'empty attachmentId', { kind: 'tool', attachmentId: '', toolCallId: 'tc-1' }],+ ['a GFS source', 'empty attachmentId', gfsSource(' ', 'gfs-read-call')],+ ['a GFS source', 'empty toolCallId', gfsSource('gfs-read-attachment', '')],+ ['an unknown source kind', 'unknown source kind', { kind: 'upload', attachmentId: 'att-1' }],+ ])(+ 'T-G4b-6b refuses %s with %s as image_source_invalid before authorize',+ async (_label, detail, source) => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)+ const part = { type: 'image', mimeType: 'image/png', data: GROK_PNG_2X2_BASE64, source }++ const rejected = await provider+ .completeSingleTurn(userWithImages([part as ImagePart]))+ .catch((e: unknown) => e)++ expect(rejected).toMatchObject({+ code: 'image_source_invalid',+ message: `image part has no usable provenance source (${detail}); host producers must attach the attachment or tool call it came from`,+ })+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()++ // Liveness witness: the same provider authorizes a well-sourced image.+ await provider.completeSingleTurn(+ userWithImages([attachmentImage(GROK_PNG_2X2_BASE64, 'att-1')])+ )+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ }+ )++ const MIB = 1024 * 1024+ const GROK_ATTACHMENT_REFUSALS: Array<{+ name: string+ messages: () => ChatMessage[]+ userMessage: string+ }> = [+ {+ name: 'one image over maxImageBytes decoded',+ messages: () =>+ userWithImages([+ attachmentImage(grokPngOfDecodedBytesBase64(GROK_VISUAL_LIMITS.maxImageBytes + 1), 'a'),+ ]),+ userMessage: `An attached image is too large: it exceeds ${GROK_VISUAL_LIMITS.maxImageBytes / MIB} MiB. Reduce its size and send it again.`,+ },+ {+ name: 'images over maxTotalImageBytes together',+ messages: () => {+ const half = grokPngOfDecodedBytesBase64(GROK_VISUAL_LIMITS.maxTotalImageBytes / 2 + 1)+ return userWithImages([attachmentImage(half, 'a'), attachmentImage(half, 'b')])+ },+ userMessage: `The attached images are too large together: they exceed ${GROK_VISUAL_LIMITS.maxTotalImageBytes / MIB} MiB in total. Send fewer or smaller images.`,+ },+ {+ name: 'an image whose encoded bytes alone cross maxVisualRequestBodyBytes',+ // The whole-body ceiling is checked before any part is parsed. With the+ // Grok limits, images within 20 MiB plus text within 8 MiB stay under+ // 35 MiB, so only an image past the per-image limit reaches this check.+ messages: () =>+ userWithImages([+ attachmentImage(+ grokPngOfDecodedBytesBase64((LIMITS.maxVisualRequestBodyBytes / 4) * 3 + 3),+ 'a'+ ),+ ]),+ userMessage: `The message and its attached images are too large together: they exceed ${LIMITS.maxVisualRequestBodyBytes / MIB} MiB. Send fewer or smaller images.`,+ },+ ]++ it.each(GROK_ATTACHMENT_REFUSALS)(+ 'T-G4b-7 refuses $name as attachment_too_large before authorize',+ async ({ messages, userMessage }) => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const rejected = await provider.completeSingleTurn(messages()).catch((e: unknown) => e)++ // The limit-specific sentence is the positive witness that the contract+ // refused this image budget, not an earlier, unrelated guard.+ expect(rejected).toBeInstanceOf(CodexAuthorizeError)+ expect(rejected).toMatchObject({ code: 'attachment_too_large', message: userMessage })+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()++ const classified = provider.classifyError(rejected)+ expect(classified).toEqual({+ code: LlmErrorCode.InvalidAttachment,+ retryable: false,+ message: userMessage,+ providerCode: 'attachment_too_large',+ providerDispatched: false,+ })+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()++ // Liveness witness: the same provider authorizes and streams a small turn.+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ }+ )++ it('T-G4b-8 keeps conversation-volume refusals on a V2 request as context length', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ // A small image plus text over the non-image cap.+ const textOverCap = await provider+ .completeSingleTurn(+ userWithImages(+ [attachmentImage(GROK_PNG_2X2_BASE64, 'a')],+ 'x'.repeat(LIMITS.maxRequestBodyBytes)+ )+ )+ .catch((e: unknown) => e)+ expect(textOverCap).toMatchObject({+ code: 'request_limit_exceeded',+ message: 'request exceeds maxRequestBodyBytes outside image data',+ })+ expect(provider.classifyError(textOverCap).code).toBe(LlmErrorCode.ContextLengthExceeded)++ // A V2 request with no image at all over the whole-body ceiling: the text+ // is what is too large, so it must not be blamed on an attachment. The+ // contract checks the non-image share before the whole body, so this is+ // reported as text too.+ const text = 'x'.repeat(LIMITS.maxVisualRequestBodyBytes)+ const wholeBody = await provider+ .completeSingleTurn([{ role: 'user', content: text, contentParts: [{ type: 'text', text }] }])+ .catch((e: unknown) => e)+ expect(wholeBody).toMatchObject({+ code: 'request_limit_exceeded',+ message: 'request exceeds maxRequestBodyBytes outside image data',+ })+ expect(provider.classifyError(wholeBody).code).toBe(LlmErrorCode.ContextLengthExceeded)+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()++ // Liveness witness: the same provider authorizes and streams a small turn.+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ })++ // #806 review M6, user decision: keep Codex parity. More than maxImages+ // images is `invalid_request`, not an attachment refusal, exactly as Codex+ // classifies it (codexSubscription.ts, "the maxImages count refusal stays+ // invalid_request").+ it('T-G4b-9 refuses more than maxImages images as invalid_request, classified as Codex does', async () => {+ const wired = deps()+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)+ const images = Array.from({ length: GROK_VISUAL_LIMITS.maxImages + 1 }, (_, index) =>+ attachmentImage(GROK_PNG_2X2_BASE64, `att-${index}`)+ )++ const rejected = await provider+ .completeSingleTurn(userWithImages(images))+ .catch((e: unknown) => e)++ // The contract's own sentence is the witness that the canonical-hash path+ // refused the batch, not an earlier guard.+ expect(rejected).toBeInstanceOf(CodexAuthorizeError)+ expect(rejected).toMatchObject({+ code: 'invalid_request',+ message: `request exceeds ${GROK_VISUAL_LIMITS.maxImages} images`,+ })+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()+ expect(wired.proxy.stream).not.toHaveBeenCalled()+ const classified = provider.classifyError(rejected)+ expect(classified).toMatchObject({+ code: LlmErrorCode.ApiCallFailed,+ retryable: false,+ providerCode: 'invalid_request',+ providerDispatched: false,+ })+ expect(classified).toEqual(+ new CodexSubscriptionProvider('gpt-5.3-codex', {} as never).classifyError(rejected)+ )++ // Liveness witness: maxImages images are authorized and streamed.+ await provider.completeSingleTurn(userWithImages(images.slice(1)))+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })+})+ describe('GrokSubscriptionProvider Retry-After retry (G1-9, #720)', () => {+ afterEach(() => {+ vi.useRealTimers()+ })++ const ok = { text: 'after the wait', toolCalls: [], outcome: 'success' }+ const limited = (retryAfterMs?: number) =>+ new GrokProxyError('rate_limited', 'proxy stream failed with 429 (rate_limited)', {+ retryAfterMs,+ })+ const authorizeTwice = () =>+ vi+ .fn()+ .mockResolvedValueOnce({+ providerAttemptId: 'attempt-1',+ requestHash,+ executionTicket: 'ticket-first',+ expiresAt: '2026-08-20T10:00:00.000Z',+ })+ .mockResolvedValueOnce({+ providerAttemptId: 'attempt-2',+ requestHash,+ executionTicket: 'ticket-second',+ expiresAt: '2026-08-20T10:00:00.000Z',+ })++ it('G1-9a: waits the advised delay, re-authorizes with the next index and dispatches again', async () => {+ vi.useFakeTimers()+ const stream = vi.fn().mockRejectedValueOnce(limited(2000)).mockResolvedValueOnce(ok)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await vi.advanceTimersByTimeAsync(1999)+ // The advised delay is honoured: nothing is re-sent before it elapses.+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(1)+ const result = await turn++ expect(result.content).toBe('after the wait')+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ const [first, second] = wired.authorizer.authorize.mock.calls.map(call => call[0])+ expect(second.invocationId).toBe(first.invocationId)+ expect(second.requestHash).toBe(first.requestHash)+ expect(first.providerAttemptIndex).toBe(1)+ expect(second.providerAttemptIndex).toBe(2)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream.mock.calls[1][0].executionTicket).toBe('ticket-second')+ })++ it('G1-9a: retries at exactly the 30 s cap', async () => {+ vi.useFakeTimers()+ const stream = vi.fn().mockRejectedValueOnce(limited(30_000)).mockResolvedValueOnce(ok)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await vi.advanceTimersByTimeAsync(30_000)+ await expect(turn).resolves.toMatchObject({ content: 'after the wait' })+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ })++ it.each([+ ['G1-9b: without Retry-After', undefined],+ ['G1-9c: over the 30 s cap', 31_000],+ // The Host parser never yields these; a non-positive value built directly+ // into the error is treated as absent (@claude review, PR #821).+ ['G1-9j: a zero Retry-After', 0],+ ['G1-9j: a negative Retry-After', -1000],+ ])('%s the 429 is thrown with no retry', async (_label, retryAfterMs) => {+ vi.useFakeTimers()+ const err = limited(retryAfterMs)+ const wired = deps({ stream: vi.fn().mockRejectedValueOnce(err).mockResolvedValueOnce(ok) })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(err)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ // Witness: the first attempt ran; the negative is that no second one did.+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ expect(provider.classifyError(err).code).toBe(LlmErrorCode.RateLimited)+ })++ it('G1-9d: a second 429 is thrown as RateLimited with no third attempt', async () => {+ vi.useFakeTimers()+ const second = limited(1000)+ const stream = vi.fn().mockRejectedValueOnce(limited(1000)).mockRejectedValueOnce(second)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(second)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(2)+ expect(provider.classifyError(second)).toMatchObject({+ code: LlmErrorCode.RateLimited,+ retryable: true,+ })+ })++ it('G1-9e: a caller-pinned attempt index is never retried here', async () => {+ vi.useFakeTimers()+ const err = limited(1000)+ const wired = deps({ stream: vi.fn().mockRejectedValueOnce(err).mockResolvedValueOnce(ok) })+ wired.attemptContext = vi.fn(() => ({+ policyRevision: 1,+ policyHash: 'b'.repeat(64),+ hostRef: 'chatllm',+ providerAttemptIndex: 3,+ }))+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(err)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.authorizer.authorize.mock.calls[0][0].providerAttemptIndex).toBe(3)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })++ it('G1-9f: an abort during the wait rejects with the abort reason and sends nothing more', async () => {+ vi.useFakeTimers()+ const wired = deps({+ authorize: authorizeTwice(),+ stream: vi.fn().mockRejectedValueOnce(limited(5000)).mockResolvedValueOnce(ok),+ })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)+ const controller = new AbortController()+ const reason = new Error('caller gave up')++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {+ signal: controller.signal,+ })+ const settled = expect(turn).rejects.toBe(reason)+ await vi.advanceTimersByTimeAsync(1000)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ controller.abort(reason)+ await settled+ await vi.advanceTimersByTimeAsync(60_000)+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })++ it('G1-9g: control_plane_unavailable is never retried here', async () => {+ vi.useFakeTimers()+ // Carries a delay on purpose, so only the code keeps it from being retried.+ const err = new GrokProxyError('control_plane_unavailable', 'proxy could not be reached', {+ retryAfterMs: 1000,+ })+ const wired = deps({ stream: vi.fn().mockRejectedValueOnce(err).mockResolvedValueOnce(ok) })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(err)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })++ it('G1-9h: a retry whose stream fails with provider_unavailable surfaces that error (review round 2 M5)', async () => {+ vi.useFakeTimers()+ const outage = new GrokProxyError('provider_unavailable', 'proxy stream failed with 503')+ const stream = vi.fn().mockRejectedValueOnce(limited(1000)).mockRejectedValueOnce(outage)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(outage)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ // Witness: the retry ran; the negative is that nothing ran after it.+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(2)+ expect(provider.classifyError(outage).code).toBe(LlmErrorCode.ModelOverloaded)+ })++ it('G1-9h: a retry whose authorize fails with control_plane_unavailable surfaces that error (review round 2 M5)', async () => {+ vi.useFakeTimers()+ const unreachable = new CodexAuthorizeError(+ 'control_plane_unavailable',+ 'authorize could not reach the control plane (ECONNREFUSED)'+ )+ const authorize = vi+ .fn()+ .mockResolvedValueOnce({+ providerAttemptId: 'attempt-1',+ requestHash,+ executionTicket: 'ticket-first',+ expiresAt: '2026-08-20T10:00:00.000Z',+ })+ .mockRejectedValueOnce(unreachable)+ const wired = deps({+ authorize,+ stream: vi.fn().mockRejectedValueOnce(limited(1000)).mockResolvedValueOnce(ok),+ })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const settled = expect(turn).rejects.toBe(unreachable)+ await vi.advanceTimersByTimeAsync(60_000)+ await settled+ // Witness: the second authorize ran; the negative is that it dispatched nothing.+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ expect(provider.classifyError(unreachable)).toMatchObject({+ code: LlmErrorCode.ControlPlaneUnavailable,+ providerDispatched: false,+ })+ })++ it('G1-9i: a successful retry passes the caller signal to the second stream (review round 2 L9)', async () => {+ vi.useFakeTimers()+ const stream = vi.fn().mockRejectedValueOnce(limited(1000)).mockResolvedValueOnce(ok)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)+ const controller = new AbortController()++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {+ signal: controller.signal,+ })+ await vi.advanceTimersByTimeAsync(1000)+ await expect(turn).resolves.toMatchObject({ content: 'after the wait' })+ expect(controller.signal.aborted).toBe(false)+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(2)+ expect(wired.proxy.stream.mock.calls[1][0].signal).toBe(controller.signal)+ })++ // G1-11 (#720, review R1-B1): the 429 that control-api's own limiters answer+ // on authorize, in the shape they send it, takes the same single retry as a+ // proxy 429. The authorizer is the real one; only its fetch is faked.+ const controlApiLimiter429 = (seconds: number) =>+ Response.json(+ { error: 'Too Many Requests', retryAfterSeconds: seconds },+ { status: 429, headers: { 'retry-after': String(seconds) } }+ )+ const authorizedSecond = () =>+ Response.json({+ providerAttemptId: 'attempt-2',+ requestHash,+ executionTicket: 'ticket-second',+ expiresAt: '2026-08-20T10:00:00.000Z',+ })+ const realAuthorize = (fetchFn: ReturnType<typeof vi.fn>) => {+ const authorizer = new ProviderAttemptAuthorizer({+ authorizeUrl: resolveCodexAuthorizeUrl('http://gateway:8092'),+ readPlatformJwt: () => 'platform-jwt',+ fetchFn: fetchFn as unknown as typeof fetch,+ })+ return vi.fn((body, options) => authorizer.authorize(body, options))+ }++ it('G1-11a: a control-api limiter 429 on authorize is retried once after its Retry-After', async () => {+ vi.useFakeTimers()+ const fetchFn = vi+ .fn()+ .mockResolvedValueOnce(controlApiLimiter429(2))+ .mockResolvedValueOnce(authorizedSecond())+ const wired = deps({ authorize: realAuthorize(fetchFn), stream: vi.fn().mockResolvedValue(ok) })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ await vi.advanceTimersByTimeAsync(1999)+ // Witness: the first authorize ran; nothing was dispatched on its 429.+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(0)+ await vi.advanceTimersByTimeAsync(1)+ await expect(turn).resolves.toMatchObject({ content: 'after the wait' })++ expect(fetchFn).toHaveBeenCalledTimes(2)+ const [first, second] = fetchFn.mock.calls.map(call => JSON.parse(call[1].body as string))+ expect(second.invocationId).toBe(first.invocationId)+ expect([first.providerAttemptIndex, second.providerAttemptIndex]).toEqual([1, 2])+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream.mock.calls[0][0].executionTicket).toBe('ticket-second')+ })++ it('G1-11b: a control-api limiter 429 over the cap is thrown as RateLimited with no retry', async () => {+ vi.useFakeTimers()+ const fetchFn = vi+ .fn()+ .mockResolvedValueOnce(controlApiLimiter429(31))+ .mockResolvedValueOnce(authorizedSecond())+ const wired = deps({ authorize: realAuthorize(fetchFn) })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const caught = turn.then(+ () => undefined,+ (e: unknown) => e+ )+ await vi.advanceTimersByTimeAsync(60_000)+ const err = await caught++ expect(err).toBeInstanceOf(CodexAuthorizeError)+ expect(err).toMatchObject({ code: 'rate_limited', retryAfterMs: 31_000 })+ expect(provider.classifyError(err)).toMatchObject({+ code: LlmErrorCode.RateLimited,+ retryable: true,+ providerDispatched: false,+ })+ // Witness: the first authorize ran; the negative is that no second one did.+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(0)+ })++ it('G1-11e: a budget_denied 429 with a short Retry-After is not retried (review round 2 M6)', async () => {+ vi.useFakeTimers()+ const fetchFn = vi+ .fn()+ .mockResolvedValueOnce(+ Response.json({ error: 'budget_denied' }, { status: 429, headers: { 'retry-after': '1' } })+ )+ .mockResolvedValueOnce(authorizedSecond())+ const wired = deps({ authorize: realAuthorize(fetchFn) })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }])+ const caught = turn.then(+ () => undefined,+ (e: unknown) => e+ )+ await vi.advanceTimersByTimeAsync(60_000)+ const err = await caught++ // The delay is within the cap, so only the code keeps it from being retried.+ expect(err).toBeInstanceOf(CodexAuthorizeError)+ expect(err).toMatchObject({ code: 'budget_denied', retryAfterMs: 1000 })+ // Witness: the first authorize ran; the negative is that no second one did.+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(0)+ })++ it('G1-12: an abort after the wait resolves and before the second authorize sends nothing more', async () => {+ vi.useFakeTimers()+ const controller = new AbortController()+ const reason = new Error('caller gave up')+ let abortInGap = false+ const remove = controller.signal.removeEventListener.bind(controller.signal)+ vi.spyOn(controller.signal, 'removeEventListener').mockImplementation(+ (type, listener, opts) => {+ remove(type, listener, opts)+ // The wait drops its abort listener once its timer fired: abort right+ // then, in the gap no listener watches.+ if (abortInGap) {+ abortInGap = false+ controller.abort(reason)+ }+ }+ )+ const stream = vi+ .fn()+ .mockImplementationOnce(async () => {+ abortInGap = true+ throw limited(1000)+ })+ .mockResolvedValueOnce(ok)+ const wired = deps({ authorize: authorizeTwice(), stream })+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)++ const turn = provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {+ signal: controller.signal,+ })+ const settled = expect(turn).rejects.toBe(reason)+ await vi.advanceTimersByTimeAsync(1000)+ await settled+ // Witness: the abort did land in the gap, after the first attempt ran.+ expect(controller.signal.aborted).toBe(true)+ expect(abortInGap).toBe(false)+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)+ expect(wired.proxy.stream).toHaveBeenCalledTimes(1)+ })+ })diff --cc mcp-host/src/llm/grokLlmProxyClient.tsindex 4353b1576,c74595d47..3868c9ac0--- a/mcp-host/src/llm/grokLlmProxyClient.ts+++ b/mcp-host/src/llm/grokLlmProxyClient.ts@@@ -1,8 -1,6 +1,11 @@@+import {+ SCHEMA_VERSION_V2,+ buildGrokProxyEnvelope,+ parseGrokCompletionRequest,+} from '@clerum/grok-provider-attempt-contract'+ import { fetchCauseCode, isConnectPhaseFailure } from './controlPlaneReachability'+ import { rateLimitedCode, retryAfterMs } from './retryAfter'+ import { upstreamRejectedStatus } from './upstreamRejected'export const GROK_PROXY_COMPLETIONS_PATH = '/internal/runtime/v1/grok/completions'@@@ -99,52 -112,36 +117,66 @@@ export class GrokLlmProxyClient},retryOnUnauthorized: boolean): Promise<GrokProxyStreamResult> {+ let body: unknown = {+ executionTicket: input.executionTicket,+ requestHash: input.requestHash,+ request: input.request,+ ...(input.deadlineMs !== undefined ? { deadlineMs: input.deadlineMs } : {}),+ }+ // A V2 request carries its deadline inside the hashed request, and+ // grok-llm-proxy refuses an outer one. The envelope is the contract's own,+ // so a request the proxy would refuse never leaves this process (#784).+ if ((input.request as { schemaVersion?: string } | null)?.schemaVersion === SCHEMA_VERSION_V2) {+ const parsed = parseGrokCompletionRequest(input.request)+ if (!parsed.ok) throw new GrokProxyError('invalid_request', parsed.message, false)+ if (input.deadlineMs !== undefined && input.deadlineMs !== parsed.value.deadlineMs) {+ throw new GrokProxyError(+ 'invalid_request',+ 'Grok deadline must match the authorized request',+ false+ )+ }+ const envelope = buildGrokProxyEnvelope({+ executionTicket: input.executionTicket,+ requestHash: input.requestHash,+ request: parsed.value,+ })+ if (!envelope.ok) {+ const code =+ envelope.code === 'limit'+ ? 'payload_too_large'+ : envelope.code === 'request_hash_mismatch'+ ? 'request_hash_mismatch'+ : 'invalid_request'+ throw new GrokProxyError(code, envelope.message, false)+ }+ body = envelope.value+ }const jwt = this.options.readPlatformJwt()const fetchFn = this.options.fetchFn ?? fetch- const response = await fetchFn(this.options.runtimeUrl, {- method: 'POST',- headers: {- authorization: `Bearer ${jwt}`,- 'content-type': 'application/json',- },- body: JSON.stringify(body),- signal: input.signal,- })+ let response: Response+ try {+ response = await fetchFn(this.options.runtimeUrl, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${jwt}`,+ 'content-type': 'application/json',+ },- body: JSON.stringify({- executionTicket: input.executionTicket,- requestHash: input.requestHash,- request: input.request,- ...(input.deadlineMs !== undefined ? { deadlineMs: input.deadlineMs } : {}),- }),++ body: JSON.stringify(body),+ signal: input.signal,+ })+ } catch (err) {+ // No live proxy process received the request (G1-7, #720). Every other+ // rejection, the caller's abort included, is rethrown unchanged; a+ // failure while the stream is read is never relabelled here.+ if (isConnectPhaseFailure(err, input.signal)) {+ throw new GrokProxyError(+ 'control_plane_unavailable',+ `proxy could not be reached (${fetchCauseCode(err)})`+ )+ }+ throw err+ }if (!response.ok) {if (response.status === 401 && retryOnUnauthorized && this.options.refreshOnUnauthorized) {await this.options.refreshOnUnauthorized()diff --cc mcp-host/src/llm/grokSubscription.tsindex a846881cb,482203597..103618e82--- a/mcp-host/src/llm/grokSubscription.ts+++ b/mcp-host/src/llm/grokSubscription.ts@@@ -25,7 -16,8 +25,8 @@@ importimport { classifyUnknown } from './errorClassification'import { GrokLlmProxyClient, GrokProxyError } from './grokLlmProxyClient'import { CodexAuthorizeError, ProviderAttemptAuthorizer } from './providerAttemptAuthorizer'+ import { rateLimitRetryDelayMs, waitBeforeRetry } from './rateLimitRetry'-import type { LlmProvider } from './registryCore'+import { type LlmProvider, descriptorFor } from './registryCore'import type { ClassifiedError, SingleTurnProvider } from './types'export type GrokAttemptContext = {diff --cc mcp-host/src/llm/providerAttemptAuthorizer.tsindex f36070aa1,a43074aaa..e1d1615a9--- a/mcp-host/src/llm/providerAttemptAuthorizer.ts+++ b/mcp-host/src/llm/providerAttemptAuthorizer.ts@@@ -174,8 -166,9 +205,9 @@@ export class ProviderAttemptAuthorizerthrow new CodexAuthorizeError(code,code === 'payload_too_large'- ? 'Codex request is too large; use fewer or smaller images, or reduce context'+ ? `${contract.label} request is too large; use fewer or smaller images, or reduce context`- : `authorize failed with ${response.status}`+ : `authorize failed with ${response.status}`,+ { retryAfterMs: response.status === 429 ? retryAfterMs(response) : undefined })}for (const key of LEAK_KEYS) {