Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: hash canonical broker requests and cap nesting depth

Jose Gabriel Ramirez Encinascc26018e3df7
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 86e3b66ff..a521e06e8 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.574",
+ "version": "0.1.575",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.574",
+ "version": "0.1.575",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index ee5e96292..96ca86b36 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.574",
+ "version": "0.1.575",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index c88d7ba99..e428f1a88 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -145,6 +145,33 @@ const defaultDeps = (): LlmProviderAttemptAuthorizerDeps => ({
export { computeCodexPolicyHash }
+// body > request > messages[] > message > toolCalls[] > call > arguments: the
+// deepest free-form tree the contracts accept sits six containers below the
+// body root, and may itself nest maxNestingDepth containers.
+const MAX_AUTHORIZE_BODY_DEPTH = Math.max(LIMITS.maxNestingDepth, GROK_LIMITS.maxNestingDepth) + 6
+
+/**
+ * Reject an over-deep body before anything serializes it. Iterative, so an
+ * attacker-controlled nesting depth cannot overflow the stack here; without it
+ * JSON.stringify throws a RangeError that surfaces as a 500.
+ */
+function assertBodyNestingWithinLimit(body: Record<string, unknown>): void {
+ const stack: Array<[unknown, number]> = [[body, 1]]
+ while (stack.length > 0) {
+ const [node, depth] = stack.pop()!
+ if (depth > MAX_AUTHORIZE_BODY_DEPTH) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'invalid_request',
+ 'request body exceeds the maximum nesting depth'
+ )
+ }
+ const children = Array.isArray(node) ? node : Object.values(node as Record<string, unknown>)
+ for (const child of children) {
+ if (child !== null && typeof child === 'object') stack.push([child, depth + 1])
+ }
+ }
+}
+
function firstUnknownKey(body: Record<string, unknown>): string | null {
for (const key of Object.keys(body)) {
if (!AUTHORIZE_BODY_KEYS.has(key)) return key
@@ -224,6 +251,7 @@ async function authorizeGrokProviderAttempt(
'mcp-host JWT lacks the llm:grok:execute scope'
)
}
+ assertBodyNestingWithinLimit(body)
const serialized = JSON.stringify(body)
if (Buffer.byteLength(serialized, 'utf8') > GROK_LIMITS.maxRequestBodyBytes) {
throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')
@@ -582,6 +610,7 @@ export async function authorizeLlmProviderAttempt(
'mcp-host JWT lacks the llm:codex:execute scope'
)
}
+ assertBodyNestingWithinLimit(body)
const serialized = JSON.stringify(body)
if (Buffer.byteLength(serialized, 'utf8') > LIMITS.maxRequestBodyBytes) {
throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts
new file mode 100644
index 000000000..c48245a90
--- /dev/null
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.depth.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { config } from '../src/config.js'
+import {
+ LlmProviderAttemptAuthorizeError,
+ type LlmProviderAttemptAuthorizerDeps,
+ authorizeLlmProviderAttempt,
+} from '../src/services/llmProviderAttemptAuthorizer.js'
+import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
+
+// B-L6: a deeply nested authorize body must fail closed as invalid_request
+// before the authorizer serializes it. Without the guard, JSON.stringify throws
+// a RangeError that the route maps to a 500.
+
+const PROVIDERS = [
+ {
+ provider: 'codex-subscription',
+ schemaVersion: 'codex-completion-request.v1',
+ model: 'gpt-5.1',
+ scope: 'llm:codex:execute',
+ },
+ {
+ provider: 'grok-subscription',
+ schemaVersion: 'grok-completion-request.v1',
+ model: 'grok-4.6',
+ scope: 'llm:grok:execute',
+ },
+] as const
+
+type ProviderCase = (typeof PROVIDERS)[number]
+
+function claims(scope: string): McpHostAccessClaims {
+ return {
+ sub: 'default/research-host',
+ recipeNamespace: 'default',
+ recipeName: 'research-host',
+ hostRefs: ['research-host'],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [scope],
+ iss: 'control-api',
+ aud: 'workflow-approvals',
+ jti: 'jti-1',
+ exp: Math.floor(Date.now() / 1000) + 60,
+ }
+}
+
+/** Parses JSON text the way express.json does, so the body is a plain tree. */
+function wireBody(p: ProviderCase, parametersJson: string, extra = ''): Record<string, unknown> {
+ const request =
+ `{"schemaVersion":"${p.schemaVersion}","requestId":"req-1","idempotencyKey":"idem-1",` +
+ `"provider":"${p.provider}","model":"${p.model}","messages":[{"role":"user","content":"hi"}],` +
+ `"tools":[{"name":"t","description":"d","parameters":${parametersJson}}]}`
+ return JSON.parse(
+ `{"request":${request},"invocationId":"inv-1","attemptGeneration":1,` +
+ `"policyRevision":1,"policyHash":"${'a'.repeat(64)}"${extra}}`
+ ) as Record<string, unknown>
+}
+
+function nestedArrays(depth: number): string {
+ return `{"x":${'['.repeat(depth)}${']'.repeat(depth)}}`
+}
+
+function nestedObjects(depth: number): string {
+ return `${'{"n":'.repeat(depth - 1)}{}${'}'.repeat(depth - 1)}`
+}
+
+const GUARD_PASSED = new Error('guard passed: assignment lookup reached')
+
+function deps(): Partial<LlmProviderAttemptAuthorizerDeps> {
+ return {
+ enabled: true,
+ resolveAssignment: vi.fn().mockRejectedValue(GUARD_PASSED),
+ }
+}
+
+describe('authorizeLlmProviderAttempt nesting depth guard', () => {
+ const previousGrokFlag = config.grokSubscriptionEnabled
+
+ beforeEach(() => {
+ config.grokSubscriptionEnabled = true
+ })
+
+ afterEach(() => {
+ config.grokSubscriptionEnabled = previousGrokFlag
+ })
+
+ for (const p of PROVIDERS) {
+ for (const depth of [5000, 150000]) {
+ it(`rejects a ${depth}-deep ${p.provider} request with invalid_request, not a RangeError`, async () => {
+ const body = wireBody(p, nestedArrays(depth))
+ // Proves the fixture really is deep enough to overflow serialization.
+ if (depth === 150000) expect(() => JSON.stringify(body)).toThrow(RangeError)
+ const current = deps()
+ const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)
+ await expect(attempt).rejects.toBeInstanceOf(LlmProviderAttemptAuthorizeError)
+ await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })
+ await expect(attempt).rejects.toThrow(/nesting depth/)
+ expect(current.resolveAssignment).not.toHaveBeenCalled()
+ })
+ }
+
+ it(`rejects deep nesting under an unknown ${p.provider} body key before serializing`, async () => {
+ const body = wireBody(p, '{"type":"object"}', `,"extra":${nestedArrays(150000)}`)
+ const current = deps()
+ const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)
+ await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })
+ await expect(attempt).rejects.toThrow(/nesting depth/)
+ })
+
+ it(`lets a ${p.provider} request with 64-deep tool parameters past the guard`, async () => {
+ const body = wireBody(p, nestedObjects(64))
+ const current = deps()
+ await expect(authorizeLlmProviderAttempt(claims(p.scope), body, current)).rejects.toBe(
+ GUARD_PASSED
+ )
+ expect(current.resolveAssignment).toHaveBeenCalledTimes(1)
+ })
+
+ it(`lets a ${p.provider} request with 64-deep assistant tool-call arguments past the guard`, async () => {
+ // The deepest accepted tree: body > request > messages[] > message >
+ // toolCalls[] > call > arguments, then 64 levels inside arguments.
+ const body = wireBody(p, '{"type":"object"}')
+ const request = body.request as Record<string, unknown>
+ request.messages = JSON.parse(
+ `[{"role":"assistant","content":"","toolCalls":[{"id":"c1","name":"t","arguments":${nestedObjects(64)}}]}]`
+ )
+ const current = deps()
+ await expect(authorizeLlmProviderAttempt(claims(p.scope), body, current)).rejects.toBe(
+ GUARD_PASSED
+ )
+ })
+
+ it(`still applies the contract cap to 65-deep ${p.provider} tool parameters`, async () => {
+ const body = wireBody(p, nestedObjects(65))
+ const current = deps()
+ const attempt = authorizeLlmProviderAttempt(claims(p.scope), body, current)
+ await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })
+ await expect(attempt).rejects.toThrow(/nesting depth/)
+ expect(current.resolveAssignment).not.toHaveBeenCalled()
+ })
+ }
+})
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index cd2c9e27c..a91328d01 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.342",
+ "version": "0.1.343",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.342",
+ "version": "0.1.343",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 3e7ba5fc5..b0099c671 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.342",
+ "version": "0.1.343",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts
index 583455635..3ef536074 100644
--- a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts
+++ b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts
@@ -13,7 +13,7 @@ function sse(frames: unknown[]): ReadableStream<Uint8Array> {
}
describe('CodexLlmProxyClient', () => {
- it('streams to the frozen runtime Service URL and never accepts a caller URL', async () => {
+ it('streams only to the server-owned runtime Service URL and ignores a caller-supplied URL', async () => {
const fetchFn = vi.fn().mockResolvedValue({
ok: true,
body: sse([
@@ -33,16 +33,33 @@ describe('CodexLlmProxyClient', () => {
executionTicket: 'ticket-123456',
requestHash: 'a'.repeat(64),
request: { model: 'gpt-5.3-codex' },
- })
+ // Not part of the input type: a caller must not be able to redirect the hop.
+ url: 'https://attacker.example/backend-api/codex/responses',
+ runtimeUrl: 'https://attacker.example/internal/runtime/v1/codex/completions',
+ } as never)
+ expect(fetchFn).toHaveBeenCalledTimes(1)
expect(fetchFn.mock.calls[0][0]).toBe(
'http://codex-llm-proxy.control-plane.svc.cluster.local:8080/internal/runtime/v1/codex/completions'
)
+ const sent = JSON.parse(fetchFn.mock.calls[0][1].body)
+ expect(Object.keys(sent).sort()).toEqual(['executionTicket', 'request', 'requestHash'])
+ expect(JSON.stringify(sent)).not.toContain('attacker.example')
expect(result.text).toBe('hello')
expect(result.toolCalls).toEqual([
{ type: 'tool_call', id: 'c1', name: 'echo', arguments: { x: 1 } },
])
})
+ it('refuses a runtime URL that is not absolute', () => {
+ expect(
+ () =>
+ new CodexLlmProxyClient({
+ runtimeUrl: '/internal/runtime/v1/codex/completions',
+ readPlatformJwt: () => 'platform-jwt',
+ })
+ ).toThrow(/absolute server-owned URL/)
+ })
+
it('fails closed when aborted before the proxy hop', async () => {
const client = new CodexLlmProxyClient({
runtimeUrl:
diff --git a/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts b/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts
index f404e81e1..86b0792b1 100644
--- a/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts
+++ b/mcp-host/src/llm/__tests__/grokLlmProxyClient.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { GrokLlmProxyClient, resolveGrokProxyRuntimeUrl } from '../grokLlmProxyClient'
+const RUNTIME_BASE = 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080'
+const RUNTIME_URL = `${RUNTIME_BASE}/internal/runtime/v1/grok/completions`
+
function sse(frames: unknown[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder()
const payload = frames.map(frame => `data: ${JSON.stringify(frame)}\n\n`).join('')
@@ -12,30 +15,184 @@ function sse(frames: unknown[]): ReadableStream<Uint8Array> {
})
}
+function client(fetchFn: unknown, extra: { refreshOnUnauthorized?: () => Promise<void> } = {}) {
+ return new GrokLlmProxyClient({
+ runtimeUrl: resolveGrokProxyRuntimeUrl(RUNTIME_BASE),
+ readPlatformJwt: () => 'platform-jwt',
+ fetchFn: fetchFn as typeof fetch,
+ ...extra,
+ })
+}
+
+const STREAM_INPUT = {
+ executionTicket: 'ticket-123456',
+ requestHash: 'a'.repeat(64),
+ request: { model: 'grok-4.6' },
+}
+
describe('GrokLlmProxyClient', () => {
- it('streams to the frozen Grok runtime path and never accepts a caller URL', async () => {
+ it('streams only to the server-owned Grok runtime URL and ignores a caller-supplied URL', async () => {
const fetchFn = vi.fn().mockResolvedValue({
ok: true,
body: sse([
{ type: 'text', text: 'hello' },
- { type: 'done', outcome: 'success' },
+ { type: 'tool_call', id: 'c1', name: 'echo', arguments: { x: 1 } },
+ { type: 'done', outcome: 'success', usage: { inputTokens: 3, outputTokens: 5 } },
]),
})
- const client = new GrokLlmProxyClient({
- runtimeUrl: resolveGrokProxyRuntimeUrl(
- 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080'
- ),
- readPlatformJwt: () => 'platform-jwt',
+ const result = await client(fetchFn).stream({
+ ...STREAM_INPUT,
+ // Not part of the input type: a caller must not be able to redirect the hop.
+ url: 'https://attacker.example/v1/responses',
+ runtimeUrl: 'https://attacker.example/internal/runtime/v1/grok/completions',
+ } as never)
+ expect(fetchFn).toHaveBeenCalledTimes(1)
+ expect(fetchFn.mock.calls[0][0]).toBe(RUNTIME_URL)
+ const sent = JSON.parse(fetchFn.mock.calls[0][1].body)
+ expect(Object.keys(sent).sort()).toEqual(['executionTicket', 'request', 'requestHash'])
+ expect(JSON.stringify(sent)).not.toContain('attacker.example')
+ expect(result.text).toBe('hello')
+ expect(result.toolCalls).toEqual([
+ { type: 'tool_call', id: 'c1', name: 'echo', arguments: { x: 1 } },
+ ])
+ expect(result.outcome).toBe('success')
+ expect(result.usage).toEqual({ inputTokens: 3, outputTokens: 5 })
+ })
+
+ it('refuses a runtime URL that is not absolute', () => {
+ expect(
+ () =>
+ new GrokLlmProxyClient({
+ runtimeUrl: '/internal/runtime/v1/grok/completions',
+ readPlatformJwt: () => 'platform-jwt',
+ })
+ ).toThrow(/absolute server-owned URL/)
+ })
+
+ it('fails closed when aborted before the proxy hop', async () => {
+ const fetchFn = vi.fn()
+ await expect(
+ client(fetchFn).stream({ ...STREAM_INPUT, signal: AbortSignal.abort() })
+ ).rejects.toMatchObject({ code: 'canceled', dispatched: false })
+ expect(fetchFn).not.toHaveBeenCalled()
+ })
+
+ it('surfaces the proxy error code with the HTTP status', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 403,
+ json: async () => ({ error: 'origin_denied' }),
+ })
+ await expect(client(fetchFn).stream(STREAM_INPUT)).rejects.toMatchObject({
+ name: 'GrokProxyError',
+ code: 'origin_denied',
+ message: 'proxy stream failed with 403 (origin_denied)',
+ })
+ })
+
+ it('refreshes the platform JWT once and retries the proxy hop after HTTP 401', async () => {
+ let jwt = 'stale-jwt'
+ const refreshOnUnauthorized = vi.fn(async () => {
+ jwt = 'fresh-jwt'
+ })
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: 'Unauthorized' }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ body: sse([
+ { type: 'text', text: 'ok' },
+ { type: 'done', outcome: 'success' },
+ ]),
+ })
+ const grok = new GrokLlmProxyClient({
+ runtimeUrl: resolveGrokProxyRuntimeUrl(RUNTIME_BASE),
+ readPlatformJwt: () => jwt,
+ refreshOnUnauthorized,
fetchFn: fetchFn as unknown as typeof fetch,
})
- const result = await client.stream({
- executionTicket: 'ticket-123456',
- requestHash: 'a'.repeat(64),
- request: { model: 'grok-4.6' },
+ const result = await grok.stream(STREAM_INPUT)
+ expect(refreshOnUnauthorized).toHaveBeenCalledTimes(1)
+ expect(fetchFn).toHaveBeenCalledTimes(2)
+ expect(fetchFn.mock.calls[0][1].headers.authorization).toBe('Bearer stale-jwt')
+ expect(fetchFn.mock.calls[1][1].headers.authorization).toBe('Bearer fresh-jwt')
+ expect(result.text).toBe('ok')
+ })
+
+ it('refreshes at most once when the retried hop is still unauthorized', async () => {
+ const refreshOnUnauthorized = vi.fn(async () => undefined)
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: 'unauthorized' }),
+ })
+ await expect(
+ client(fetchFn, { refreshOnUnauthorized }).stream(STREAM_INPUT)
+ ).rejects.toMatchObject({ code: 'unauthorized' })
+ expect(refreshOnUnauthorized).toHaveBeenCalledTimes(1)
+ expect(fetchFn).toHaveBeenCalledTimes(2)
+ })
+
+ it('fails closed when the proxy emits an SSE error frame after headers', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ body: sse([
+ { type: 'text', text: 'partial' },
+ { type: 'error', code: 'origin_denied' },
+ ]),
+ })
+ await expect(client(fetchFn).stream(STREAM_INPUT)).rejects.toMatchObject({
+ code: 'origin_denied',
+ dispatched: true,
+ })
+ })
+
+ it('reports a missing terminal frame as an unknown outcome', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ body: sse([{ type: 'text', text: 'cut off' }]),
+ })
+ await expect(client(fetchFn).stream(STREAM_INPUT)).resolves.toMatchObject({
+ text: 'cut off',
+ outcome: 'unknown',
+ })
+ })
+
+ it('marks only the pre-stream abort as never dispatched', async () => {
+ await expect(
+ client(vi.fn()).stream({ ...STREAM_INPUT, signal: AbortSignal.abort() })
+ ).rejects.toMatchObject({ code: 'canceled', dispatched: false })
+
+ // The request left the process before the proxy answered, so a denial is
+ // not proof that nothing was billed.
+ const denied = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 403,
+ json: async () => ({ error: 'origin_denied' }),
+ })
+ await expect(client(denied).stream(STREAM_INPUT)).rejects.toMatchObject({
+ code: 'origin_denied',
+ dispatched: true,
+ })
+
+ // An error frame arrives mid-stream: the upstream call is already running.
+ const framed = vi.fn().mockResolvedValue({
+ ok: true,
+ body: sse([{ type: 'error', code: 'rate_limited' }]),
+ })
+ await expect(client(framed).stream(STREAM_INPUT)).rejects.toMatchObject({
+ code: 'rate_limited',
+ dispatched: true,
+ })
+
+ const bodiless = vi.fn().mockResolvedValue({ ok: true, body: null })
+ await expect(client(bodiless).stream(STREAM_INPUT)).rejects.toMatchObject({
+ code: 'provider_unavailable',
+ dispatched: true,
})
- expect(fetchFn.mock.calls[0][0]).toBe(
- 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080/internal/runtime/v1/grok/completions'
- )
- expect(result.text).toBe('hello')
})
})
diff --git a/mcp-host/src/llm/__tests__/grokSubscription.test.ts b/mcp-host/src/llm/__tests__/grokSubscription.test.ts
index 22fdb33d4..de89510d2 100644
--- a/mcp-host/src/llm/__tests__/grokSubscription.test.ts
+++ b/mcp-host/src/llm/__tests__/grokSubscription.test.ts
@@ -3,6 +3,7 @@ import { LlmErrorCode } from '../../core/errors'
import { classifyFailoverClass } from '../failover/classify'
import { GrokProxyError } from '../grokLlmProxyClient'
import { GrokSubscriptionProvider } from '../grokSubscription'
+import { CodexAuthorizeError } from '../providerAttemptAuthorizer'
const requestHash = 'a'.repeat(64)
@@ -121,4 +122,261 @@ describe('GrokSubscriptionProvider', () => {
expect(wired.authorizer.authorize).not.toHaveBeenCalled()
expect(wired.proxy.stream).not.toHaveBeenCalled()
})
+
+ it('authorizes through the gateway and returns proxy tool calls without executing them', async () => {
+ const wired = deps({
+ stream: vi.fn().mockResolvedValue({
+ text: 'use a tool',
+ toolCalls: [{ id: 'c1', name: 'echo', arguments: { x: 1 } }],
+ outcome: 'success',
+ }),
+ })
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ const result = await provider.completeSingleTurnWithTools(
+ [{ role: 'user', content: 'hi' }],
+ [{ name: 'echo', description: 'echo', parameters: {} }]
+ )
+ expect(wired.authorizer.authorize).toHaveBeenCalledTimes(1)
+ const authorizedBody = wired.authorizer.authorize.mock.calls[0][0]
+ expect(authorizedBody.request.provider).toBe('grok-subscription')
+ expect(authorizedBody.request.model).toBe('grok-4.6')
+ expect(authorizedBody.requestHash).toMatch(/^[a-f0-9]{64}$/)
+ expect(wired.proxy.stream).toHaveBeenCalledWith(
+ expect.objectContaining({ executionTicket: 'ticket-123456', requestHash })
+ )
+ expect(result.tool_calls).toEqual([{ id: 'c1', name: 'echo', arguments: { x: 1 } }])
+ expect(result.finish_reason).toBe('tool_use')
+ })
+
+ it('preserves assistant toolCalls and tool results in the authorize request', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ await provider.completeSingleTurnWithTools(
+ [
+ { role: 'user', content: 'hi' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: 'call-1', name: 'echo', arguments: { x: 1 } }],
+ },
+ { role: 'tool', content: 'ok', tool_call_id: 'call-1', name: 'echo' },
+ ],
+ [{ name: 'echo', description: 'echo', parameters: {} }]
+ )
+ expect(wired.authorizer.authorize.mock.calls[0][0].request.messages).toEqual([
+ { role: 'user', content: 'hi' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call-1', name: 'echo', arguments: { x: 1 } }],
+ },
+ { role: 'tool', content: 'ok', toolCallId: 'call-1', name: 'echo' },
+ ])
+ })
+
+ it('does not authorize or call the proxy when aborted before authorize', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ const attempt = provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {
+ signal: AbortSignal.abort(),
+ })
+ await expect(attempt).rejects.toMatchObject({ code: 'canceled', dispatched: false })
+ expect(wired.authorizer.authorize).not.toHaveBeenCalled()
+ expect(wired.proxy.stream).not.toHaveBeenCalled()
+ })
+
+ it('issues a new authorize attempt index and request id on every physical call', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ await provider.completeSingleTurn([{ role: 'user', content: 'one' }])
+ await provider.completeSingleTurn([{ role: 'user', content: 'two' }])
+ const calls = wired.authorizer.authorize.mock.calls
+ expect(calls[0][0].providerAttemptIndex).toBe(1)
+ expect(calls[1][0].providerAttemptIndex).toBe(2)
+ expect(calls[0][0].request.requestId).not.toBe(calls[1][0].request.requestId)
+ })
+
+ it('passes the selected model into attemptContext and uses a captured attempt index', async () => {
+ const wired = deps()
+ wired.attemptContext = vi.fn(() => ({
+ policyRevision: 3,
+ policyHash: 'c'.repeat(64),
+ hostRef: 'chatllm',
+ providerAttemptIndex: 7,
+ invocationId: 'inv-9',
+ pluginWorkloadSdkProviderAttemptId: 'sdk-attempt-9',
+ targetRef: 'grok-primary',
+ }))
+ const provider = new GrokSubscriptionProvider('grok-4.6-mini', wired as never)
+ const result = await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(wired.attemptContext).toHaveBeenCalledWith({ model: 'grok-4.6-mini' })
+ expect(wired.authorizer.authorize.mock.calls[0][0]).toMatchObject({
+ providerAttemptIndex: 7,
+ invocationId: 'inv-9',
+ policyRevision: 3,
+ policyHash: 'c'.repeat(64),
+ pluginWorkloadSdkProviderAttemptId: 'sdk-attempt-9',
+ targetRef: 'grok-primary',
+ })
+ expect(result.providerAttemptIndex).toBe(7)
+ })
+
+ it('keeps unknown usage unknown and forwards reported usage', async () => {
+ const unknownUsage = await new GrokSubscriptionProvider(
+ 'grok-4.6',
+ deps() as never
+ ).completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(unknownUsage.usage_reported).toBe(false)
+ expect(unknownUsage.usage).toEqual({ input_tokens: 0, output_tokens: 0, total_tokens: 0 })
+ expect(unknownUsage.providerAttemptId).toBe('attempt-1')
+
+ const reported = await new GrokSubscriptionProvider(
+ 'grok-4.6',
+ deps({
+ stream: vi.fn().mockResolvedValue({
+ text: 'ok',
+ toolCalls: [],
+ outcome: 'success',
+ usage: { inputTokens: 11, outputTokens: 4 },
+ }),
+ }) as never
+ ).completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(reported.usage_reported).toBe(true)
+ expect(reported.usage).toEqual({ input_tokens: 11, output_tokens: 4, total_tokens: 15 })
+ })
+
+ it.each([1, 83, 250])(
+ 'preserves all %i approved tool definitions through authorization and dispatch',
+ async count => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ const tools = Array.from({ length: count }, (_, i) => ({
+ name: `eventasks__read_${i}`,
+ description: 'read task',
+ parameters: { type: 'object', properties: { key: { type: 'string' } } },
+ }))
+ await provider.completeSingleTurnWithTools([{ role: 'user', content: 'Find a task' }], tools)
+ const authorized = wired.authorizer.authorize.mock.calls[0][0]
+ expect(authorized.request.tools).toEqual(tools)
+ expect(wired.proxy.stream.mock.calls[0][0].request).toEqual(authorized.request)
+ }
+ )
+
+ it('accepts exactly 64 tool calls from a successful batch', async () => {
+ const toolCalls = Array.from({ length: 64 }, (_, index) => ({
+ id: `call-${index}`,
+ name: 'echo',
+ arguments: {},
+ }))
+ const provider = new GrokSubscriptionProvider(
+ 'grok-4.6',
+ deps({
+ stream: vi.fn().mockResolvedValue({ text: '', outcome: 'success', toolCalls }),
+ }) as never
+ )
+ const result = await provider.completeSingleTurnWithTools(
+ [{ role: 'user', content: 'hi' }],
+ [{ name: 'echo', description: 'echo', parameters: {} }]
+ )
+ expect(result.tool_calls).toHaveLength(64)
+ const over = new GrokSubscriptionProvider(
+ 'grok-4.6',
+ deps({
+ stream: vi.fn().mockResolvedValue({
+ text: '',
+ outcome: 'success',
+ toolCalls: [...toolCalls, { id: 'call-64', name: 'echo', arguments: {} }],
+ }),
+ }) as never
+ )
+ await expect(
+ over.completeSingleTurnWithTools(
+ [{ role: 'user', content: 'hi' }],
+ [{ name: 'echo', description: 'echo', parameters: {} }]
+ )
+ ).rejects.toThrow(/tool calls exceed 64/)
+ })
+
+ it('does not treat an unknown empty stream as a successful stop', async () => {
+ const provider = new GrokSubscriptionProvider(
+ 'grok-4.6',
+ deps({
+ stream: vi.fn().mockResolvedValue({ text: '', toolCalls: [], outcome: 'unknown' }),
+ }) as never
+ )
+ await expect(
+ provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ ).rejects.toMatchObject({ code: 'provider_unavailable' })
+ })
+
+ it('classifies authorize denials as non-retryable and never dispatched', () => {
+ const provider = new GrokSubscriptionProvider('grok-4.6', deps() as never)
+ const scope = provider.classifyError(new CodexAuthorizeError('insufficient_scope', 'scope'))
+ expect(scope).toMatchObject({
+ code: LlmErrorCode.AuthenticationFailed,
+ retryable: false,
+ providerCode: 'insufficient_scope',
+ providerDispatched: false,
+ })
+
+ const revoked = provider.classifyError(new CodexAuthorizeError('no_grant', 'revoked'))
+ expect(revoked.code).toBe(LlmErrorCode.AuthenticationFailed)
+ expect(revoked.retryable).toBe(false)
+ expect(revoked.providerDispatched).toBe(false)
+ expect(classifyFailoverClass(revoked.code, revoked.retryable)).toBe('auth')
+
+ const budget = provider.classifyError(new CodexAuthorizeError('budget_denied', 'over'))
+ expect(budget).toMatchObject({ code: LlmErrorCode.InsufficientQuota, retryable: false })
+
+ const model = provider.classifyError(new CodexAuthorizeError('model_not_allowed', 'model'))
+ expect(model).toMatchObject({ code: LlmErrorCode.ModelNotAvailable, retryable: false })
+
+ const transient = provider.classifyError(
+ new CodexAuthorizeError('connection_unavailable', 'catalog unavailable')
+ )
+ expect(transient.code).toBe(LlmErrorCode.ModelOverloaded)
+ expect(transient.retryable).toBe(true)
+ expect(classifyFailoverClass(transient.code, transient.retryable)).toBe('provider_unavailable')
+ })
+
+ it('maps transient proxy failures onto failover-eligible classes as dispatched', () => {
+ const provider = new GrokSubscriptionProvider('grok-4.6', deps() as never)
+ const unavailable = provider.classifyError(
+ new GrokProxyError('provider_unavailable', 'upstream 5xx')
+ )
+ expect(unavailable).toMatchObject({
+ code: LlmErrorCode.ModelOverloaded,
+ retryable: true,
+ providerDispatched: true,
+ })
+ expect(classifyFailoverClass(unavailable.code, unavailable.retryable)).toBe(
+ 'provider_unavailable'
+ )
+
+ const limited = provider.classifyError(new GrokProxyError('rate_limited', 'upstream 429'))
+ expect(limited).toMatchObject({ code: LlmErrorCode.RateLimited, retryable: true })
+ expect(classifyFailoverClass(limited.code, limited.retryable)).toBe('rate_limited')
+
+ expect(
+ provider.classifyError(new GrokProxyError('canceled', 'aborted before authorize', false))
+ .providerDispatched
+ ).toBe(false)
+ expect(provider.classifyError(new Error('who knows')).providerDispatched).toBeUndefined()
+ })
+
+ it('shares the caller deadline with the authorize hop and the proxy stream', async () => {
+ const wired = deps()
+ const provider = new GrokSubscriptionProvider('grok-4.6', wired as never)
+ const controller = new AbortController()
+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {
+ signal: controller.signal,
+ })
+ expect(wired.authorizer.authorize).toHaveBeenCalledWith(expect.any(Object), {
+ signal: controller.signal,
+ })
+ expect(wired.proxy.stream.mock.calls[0][0].signal).toBe(controller.signal)
+
+ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])
+ expect(wired.authorizer.authorize).toHaveBeenNthCalledWith(2, expect.any(Object), {})
+ })
})
diff --git a/mcp-host/src/llm/__tests__/subscriptionRequestHash.test.ts b/mcp-host/src/llm/__tests__/subscriptionRequestHash.test.ts
new file mode 100644
index 000000000..e7b9f01dd
--- /dev/null
+++ b/mcp-host/src/llm/__tests__/subscriptionRequestHash.test.ts
@@ -0,0 +1,169 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ hashGrokCompletionRequestV1,
+ parseGrokCompletionRequestV1,
+} from '@clerum/grok-provider-attempt-contract'
+import {
+ hashCodexCompletionRequestV1,
+ parseCodexCompletionRequestV1,
+} from '@clerum/llm-provider-attempt-contract'
+import { CodexSubscriptionProvider } from '../codexSubscription'
+import { GrokSubscriptionProvider } from '../grokSubscription'
+import { CodexAuthorizeError } from '../providerAttemptAuthorizer'
+
+// B-M1 / C-RP-015: mcp-host must hash exactly what control-api authorize and
+// the proxies hash (the validated projection of the JSON wire request).
+
+const uuid = vi.hoisted(() => ({ next: 0 }))
+vi.mock('node:crypto', async () => {
+ const actual = await vi.importActual<typeof import('node:crypto')>('node:crypto')
+ return {
+ ...actual,
+ randomUUID: () => `00000000-0000-4000-8000-${String(++uuid.next).padStart(12, '0')}`,
+ }
+})
+
+function deps() {
+ const authorize = vi.fn().mockResolvedValue({
+ providerAttemptId: 'attempt-1',
+ requestHash: 'f'.repeat(64),
+ executionTicket: 'ticket-123456',
+ expiresAt: '2026-08-20T10:00:00.000Z',
+ })
+ const stream = vi.fn().mockResolvedValue({ text: 'ok', toolCalls: [], outcome: 'success' })
+ return {
+ authorizer: { authorize },
+ proxy: { stream },
+ attemptContext: vi.fn(() => ({ policyRevision: 1, policyHash: 'b'.repeat(64) })),
+ authorize,
+ stream,
+ }
+}
+
+const PROVIDERS = [
+ {
+ name: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ make: (wired: ReturnType<typeof deps>) =>
+ new CodexSubscriptionProvider('gpt-5.3-codex', wired as never),
+ serverHash: (wire: unknown) => {
+ const parsed = parseCodexCompletionRequestV1(wire)
+ if (!parsed.ok) throw new Error(parsed.message)
+ return hashCodexCompletionRequestV1(parsed.value)
+ },
+ // Captured from the provider at a42dedf8, before canonical hashing.
+ goldenToolsHash: 'ec9146face0ad4024b88c72906b47135e5cc986c64c700e8f1c3377dade3f4f2',
+ goldenHistoryHash: 'e3c5a1f3317dd601c5aeab17c5b4914a180a5b40164059584004725701212cb2',
+ },
+ {
+ name: 'grok-subscription',
+ model: 'grok-4.6',
+ make: (wired: ReturnType<typeof deps>) =>
+ new GrokSubscriptionProvider('grok-4.6', wired as never),
+ serverHash: (wire: unknown) => {
+ const parsed = parseGrokCompletionRequestV1(wire)
+ if (!parsed.ok) throw new Error(parsed.message)
+ return hashGrokCompletionRequestV1(parsed.value)
+ },
+ // Captured from the provider at a42dedf8, before canonical hashing.
+ goldenToolsHash: '507c127d04e04544ce92b2417e6d30c84033aef8609b501bfe305c1e61a526af',
+ goldenHistoryHash: '76e9df10e95d15c489c713aa44a41163d8a346711ee97fdb9e53f4e575929b8e',
+ },
+] as const
+
+/** What control-api computes from the authorize body it receives. */
+function hashOnWire(p: (typeof PROVIDERS)[number], body: { request: unknown }): string {
+ return p.serverHash(JSON.parse(JSON.stringify(body)).request)
+}
+
+const TOOLS = [
+ {
+ name: 'eventasks__read',
+ description: 'Read a record',
+ parameters: {
+ type: 'object',
+ properties: { id: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } },
+ required: ['id'],
+ },
+ },
+]
+
+describe.each(PROVIDERS)('$name request hashing', p => {
+ beforeEach(() => {
+ uuid.next = 0
+ })
+
+ it('keeps the pre-change digest for a well-formed tools + generation request', async () => {
+ const wired = deps()
+ await p.make(wired).completeSingleTurnWithTools([{ role: 'user', content: 'find it' }], TOOLS, {
+ temperature: 0.2,
+ max_tokens: 512,
+ tool_choice: 'auto',
+ })
+ const body = wired.authorize.mock.calls[0][0]
+ expect(body.requestHash).toBe(p.goldenToolsHash)
+ expect(hashOnWire(p, body)).toBe(body.requestHash)
+ })
+
+ it('keeps the pre-change digest for a well-formed tool-call history request', async () => {
+ const wired = deps()
+ await p.make(wired).completeSingleTurnWithTools(
+ [
+ { role: 'system', content: 'be brief' },
+ { role: 'user', content: 'café 漢字 🎵' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: 'call-1', name: 'eventasks__read', arguments: { id: 'A-1' } }],
+ },
+ { role: 'tool', content: '{"ok":true}', tool_call_id: 'call-1', name: 'eventasks__read' },
+ ],
+ TOOLS
+ )
+ const body = wired.authorize.mock.calls[0][0]
+ expect(body.requestHash).toBe(p.goldenHistoryHash)
+ expect(hashOnWire(p, body)).toBe(body.requestHash)
+ })
+
+ it('agrees with the server hash when tool_choice is a tool name (empty generation)', async () => {
+ const wired = deps()
+ await p.make(wired).completeSingleTurnWithTools([{ role: 'user', content: 'hi' }], TOOLS, {
+ tool_choice: 'eventasks__read',
+ })
+ const body = wired.authorize.mock.calls[0][0]
+ expect(body.request).not.toHaveProperty('generation')
+ expect(hashOnWire(p, body)).toBe(body.requestHash)
+ // The proxy receives the same canonical request that was authorized.
+ expect(wired.stream.mock.calls[0][0].request).toEqual(body.request)
+ })
+
+ it('fails an invalid request locally as a never-dispatched invalid_request', async () => {
+ const wired = deps()
+ const provider = p.make(wired)
+ const attempt = provider.completeSingleTurn([{ role: 'user', content: 'hi' }], {
+ temperature: 3,
+ })
+ await expect(attempt).rejects.toBeInstanceOf(CodexAuthorizeError)
+ await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })
+ expect(wired.authorize).not.toHaveBeenCalled()
+ expect(wired.stream).not.toHaveBeenCalled()
+ const classified = provider.classifyError(await attempt.catch(err => err))
+ expect(classified.providerDispatched).toBe(false)
+ expect(classified.retryable).toBe(false)
+ })
+
+ it('fails an over-deep tool schema locally without a stack overflow', async () => {
+ let parameters: Record<string, unknown> = {}
+ for (let i = 0; i < 150000; i++) parameters = { n: parameters }
+ const wired = deps()
+ const attempt = p
+ .make(wired)
+ .completeSingleTurnWithTools(
+ [{ role: 'user', content: 'hi' }],
+ [{ name: 'deep', description: 'deep', parameters }]
+ )
+ await expect(attempt).rejects.toMatchObject({ code: 'invalid_request' })
+ await expect(attempt).rejects.toThrow(/nesting depth/)
+ expect(wired.authorize).not.toHaveBeenCalled()
+ })
+})
diff --git a/mcp-host/src/llm/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index ad98ea4f5..20d85c5f1 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'
import {
type CodexCompletionRequestV1,
LIMITS,
- hashCodexCompletionRequestV1,
+ hashCanonicalCodexRequest,
} from '@clerum/llm-provider-attempt-contract'
import { LlmErrorCode } from '../core/errors'
import {
@@ -253,8 +253,16 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
if (options?.signal?.aborted) {
throw new CodexProxyError('canceled', 'aborted before authorize', false)
}
- const request = this.buildRequest(messages, tools, options)
- const requestHash = hashCodexCompletionRequestV1(request)
+ // Hash and send the validated wire projection — exactly what control-api
+ // authorize and the proxy re-derive. Hashing the locally built object let
+ // shapes the parser normalizes away (an empty `generation` from a
+ // tool-name tool_choice, empty tools/hints) fail authorize with a
+ // requestHash mismatch. An invalid request never leaves the process.
+ const canonical = hashCanonicalCodexRequest(this.buildRequest(messages, tools, options))
+ if (!canonical.ok) {
+ throw new CodexAuthorizeError('invalid_request', canonical.message)
+ }
+ const { request, requestHash } = canonical.value
const context = this.deps.attemptContext({ model: this.model })
if (
!Number.isInteger(context.policyRevision) ||
diff --git a/mcp-host/src/llm/grokSubscription.ts b/mcp-host/src/llm/grokSubscription.ts
index 0f71017ef..3455bf8b4 100644
--- a/mcp-host/src/llm/grokSubscription.ts
+++ b/mcp-host/src/llm/grokSubscription.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'
import {
type GrokCompletionRequestV1,
LIMITS,
- hashGrokCompletionRequestV1,
+ hashCanonicalGrokRequest,
} from '@clerum/grok-provider-attempt-contract'
import { LlmErrorCode } from '../core/errors'
import {
@@ -253,8 +253,16 @@ export class GrokSubscriptionProvider implements SingleTurnProvider {
if (options?.signal?.aborted) {
throw new GrokProxyError('canceled', 'aborted before authorize', false)
}
- const request = this.buildRequest(messages, tools, options)
- const requestHash = hashGrokCompletionRequestV1(request)
+ // Hash and send the validated wire projection — exactly what control-api
+ // authorize and the proxy re-derive. Hashing the locally built object let
+ // shapes the parser normalizes away (an empty `generation` from a
+ // tool-name tool_choice, empty tools/hints) fail authorize with a
+ // requestHash mismatch. An invalid request never leaves the process.
+ const canonical = hashCanonicalGrokRequest(this.buildRequest(messages, tools, options))
+ if (!canonical.ok) {
+ throw new CodexAuthorizeError('invalid_request', canonical.message)
+ }
+ const { request, requestHash } = canonical.value
const context = this.deps.attemptContext({ model: this.model })
if (
!Number.isInteger(context.policyRevision) ||
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
index 031a26508..79eac54da 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
@@ -472,4 +472,119 @@ describe('Plugin Workload SDK bootstrap identity', () => {
expect(readSdkOnlyCodexBinding()).toBeNull()
replaceSdkOnlyGrokBinding(null)
})
+
+ describe('strict provider binding slots (B-L14)', () => {
+ function grokBinding(connectionKey: string) {
+ const fields = { connectionKey, catalogRevision: 5, credentialRevision: 2, model: 'grok-4.6' }
+ return { ...fields, bindingHash: computeGrokPolicyHash(fields) }
+ }
+ function codexBinding(connectionKey: string) {
+ const fields = {
+ connectionKey,
+ catalogRevision: 4,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ }
+ return { ...fields, bindingHash: computeCodexPolicyHash(fields) }
+ }
+ const readyProof = (provider: string, model: string) => ({
+ ready: true,
+ contractVersion: 3,
+ provider,
+ model,
+ policyReady: true,
+ policyState: 'active',
+ bindingReady: true,
+ codexBindingReady: true,
+ })
+
+ it('ignores a hash-valid Grok binding delivered in the Codex slot', async () => {
+ replaceSdkOnlyGrokBinding(null)
+ replaceSdkOnlyCodexBinding(null)
+ const verify = vi.fn()
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ contractVersion: 3,
+ codexBinding: grokBinding('team-grok'),
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({
+ configured: true,
+ policyReady: false,
+ policyReason: 'execution_binding_missing',
+ bindingReady: false,
+ })
+ expect(result).not.toHaveProperty('subscriptionBinding')
+ expect(verify).not.toHaveBeenCalled()
+ expect(readSdkOnlyGrokBinding()).toBeNull()
+ expect(readSdkOnlyCodexBinding()).toBeNull()
+ })
+
+ it('ignores a hash-valid Codex binding delivered in the Grok slot', async () => {
+ replaceSdkOnlyGrokBinding(null)
+ replaceSdkOnlyCodexBinding(null)
+ const verify = vi.fn()
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ contractVersion: 3,
+ subscriptionBinding: codexBinding('team-plus'),
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({
+ configured: true,
+ policyReady: false,
+ policyReason: 'codex_execution_binding_missing',
+ })
+ expect(result).not.toHaveProperty('codexBinding')
+ expect(verify).not.toHaveBeenCalled()
+ expect(readSdkOnlyCodexBinding()).toBeNull()
+ expect(readSdkOnlyGrokBinding()).toBeNull()
+ })
+
+ it('installs the Grok binding from subscriptionBinding even when codexBinding also verifies', async () => {
+ const own = grokBinding('team-grok')
+ const verify = vi.fn().mockResolvedValue(readyProof('grok-subscription', 'grok-4.6'))
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ contractVersion: 3,
+ codexBinding: grokBinding('other-grok'),
+ subscriptionBinding: own,
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({ subscriptionBinding: own, bindingReady: true })
+ expect(readSdkOnlyGrokBinding()).toEqual(own)
+ replaceSdkOnlyGrokBinding(null)
+ })
+
+ it('installs the Codex binding from codexBinding even when subscriptionBinding also verifies', async () => {
+ const own = codexBinding('team-plus')
+ const verify = vi.fn().mockResolvedValue(readyProof('codex-subscription', 'gpt-5.6-luna'))
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ contractVersion: 3,
+ codexBinding: own,
+ subscriptionBinding: codexBinding('other-plus'),
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({ codexBinding: own })
+ expect(readSdkOnlyCodexBinding()).toEqual(own)
+ replaceSdkOnlyCodexBinding(null)
+ })
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
index b54cf9bab..7f78419da 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
@@ -94,10 +94,13 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(
}
// Always integrity-check a supplied binding before the provider protocol
// branch. Request-controlled provider/version must not skip this check.
+ // Each provider reads only its own slot: WRC writes Grok proofs to
+ // `subscriptionBinding` and Codex proofs to `codexBinding`, so a proof in the
+ // other slot is never a fallback for a missing one.
const grok = req.provider === 'grok-subscription'
const verifiedBinding = grok
- ? readVerifiedSdkOnlyGrokBinding(req.subscriptionBinding ?? req.codexBinding, model)
- : readVerifiedSdkOnlyCodexBinding(req.codexBinding ?? req.subscriptionBinding, model)
+ ? readVerifiedSdkOnlyGrokBinding(req.subscriptionBinding, model)
+ : readVerifiedSdkOnlyCodexBinding(req.codexBinding, model)
const missingReason = grok ? 'execution_binding_missing' : 'codex_execution_binding_missing'
if (isOauthBrokerProvider(req.provider)) {
if (!verifiedBinding) {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index d3fa98522..584cad91a 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -991,6 +991,85 @@ describe('LlmBridge oauth-broker terminal accounting', () => {
})
})
+ it.each([
+ {
+ provider: 'grok-subscription' as const,
+ model: 'grok-4.6',
+ connectionKey: 'team-grok',
+ key: 'capturedGrokAttemptContext',
+ otherKey: 'capturedCodexAttemptContext',
+ },
+ {
+ provider: 'codex-subscription' as const,
+ model: 'gpt-5.1',
+ connectionKey: 'team-plus',
+ key: 'capturedCodexAttemptContext',
+ otherKey: 'capturedGrokAttemptContext',
+ },
+ ])(
+ 'hands createLLMProvider exactly the $provider attempt context bound to its own slot',
+ async ({ provider, model, connectionKey, key, otherKey }) => {
+ const target: PromptBridgeTarget = {
+ targetRef: `${provider}-primary`,
+ provider,
+ model,
+ credentialSlot: '',
+ connectionRef: connectionKey,
+ }
+ // Distinct revisions per slot, none equal to the request's own
+ // policyRevision, so a context built from the wrong source is visible.
+ const grokBinding = {
+ connectionKey: 'team-grok',
+ catalogRevision: 9,
+ credentialRevision: 4,
+ model: 'grok-4.6',
+ }
+ const codexBinding = {
+ connectionKey: 'team-plus',
+ catalogRevision: 17,
+ credentialRevision: 6,
+ model: 'gpt-5.1',
+ }
+ const grokHash = computeGrokPolicyHash(grokBinding)
+ const codexHash = computeCodexPolicyHash(codexBinding)
+ replaceSdkOnlyGrokBinding({ ...grokBinding, bindingHash: grokHash })
+ replaceSdkOnlyCodexBinding({ ...codexBinding, bindingHash: codexHash })
+ const fake = new FakeProvider(() => Promise.resolve(OK))
+ const { bridge, capturedCalls } = makeBridge({ [model]: fake })
+ await bridge.complete({
+ ...request,
+ hostRef: 'research-host',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ targets: [{ target }],
+ credentialTicketIssuer: {
+ issue: vi.fn(async () => ({
+ credentialTicket: '',
+ providerAttemptId: `sdk-${provider}`,
+ providerAttemptIndex: 3,
+ })),
+ },
+ providerAttemptReporter: { report: vi.fn().mockResolvedValue(undefined) },
+ })
+ expect(capturedCalls).toHaveLength(1)
+ expect(capturedCalls[0]).not.toHaveProperty(otherKey)
+ expect(capturedCalls[0]).toEqual({
+ [key]: {
+ invocationId: 'inv-1',
+ attemptGeneration: 1,
+ providerAttemptIndex: 3,
+ pluginWorkloadSdkProviderAttemptId: `sdk-${provider}`,
+ targetRef: `${provider}-primary`,
+ policyRevision: provider === 'grok-subscription' ? 9 : 17,
+ policyHash: provider === 'grok-subscription' ? grokHash : codexHash,
+ hostRef: 'research-host',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ },
+ })
+ }
+ )
+
it('keeps a pre-dispatch Codex budget denial revivable and carries its receipt', async () => {
installCodexBinding()
const codex = new FakeProvider(() => Promise.reject(new Error('budget denied')), {
diff --git a/packages/grok-provider-attempt-contract/fixtures/golden-request-hashes.json b/packages/grok-provider-attempt-contract/fixtures/golden-request-hashes.json
new file mode 100644
index 000000000..e85006496
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/fixtures/golden-request-hashes.json
@@ -0,0 +1,156 @@
+{
+ "schemaVersion": "grok-completion-request.v1",
+ "notes": "Golden digests captured from the contract at a42dedf8 before hashCanonical/depth-cap changes. Well-formed requests must keep these exact digests. depthBoundaryDigests are built in index.test.cjs as a single-key chain of 64 nested objects (key n for tool parameters, key a for assistant toolCall arguments).",
+ "cases": [
+ {
+ "name": "minimal",
+ "request": {
+ "schemaVersion": "grok-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "grok-subscription",
+ "model": "grok-4.6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "hello"
+ }
+ ]
+ },
+ "sha256": "e112e859a8e8e424e7285d726273878a7e64b759f1bf10e9407c20b7e2a079d7"
+ },
+ {
+ "name": "tools-and-generation",
+ "request": {
+ "schemaVersion": "grok-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "grok-subscription",
+ "model": "grok-4.6",
+ "messages": [
+ {
+ "role": "system",
+ "content": "be brief"
+ },
+ {
+ "role": "user",
+ "content": "find it"
+ }
+ ],
+ "tools": [
+ {
+ "name": "eventasks__read",
+ "description": "Read a record",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "opts": {
+ "type": "object",
+ "properties": {
+ "deep": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ }
+ }
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "clerum__tool_search",
+ "description": "search",
+ "parameters": {
+ "type": "object"
+ }
+ }
+ ],
+ "generation": {
+ "temperature": 0.2,
+ "maxOutputTokens": 1024,
+ "toolChoice": "auto"
+ }
+ },
+ "sha256": "ed53e249072eab8bf99bd3acd9d20c9e40d66972287440c1c94c9fcc364e2897"
+ },
+ {
+ "name": "tool-history-unicode",
+ "request": {
+ "schemaVersion": "grok-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "grok-subscription",
+ "model": "grok-4.6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "café 漢字 🎵"
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "toolCalls": [
+ {
+ "id": "call-1",
+ "name": "工具@café",
+ "arguments": {
+ "x": 1,
+ "y": [
+ true,
+ null,
+ "z"
+ ],
+ "n": {
+ "m": -0.5
+ }
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "content": "{\"ok\":true}",
+ "toolCallId": "call-1",
+ "name": "工具@café"
+ }
+ ]
+ },
+ "sha256": "8161f8e8cb8b4f536ed2baeb9911f8601d419a7eadd6d3da166c2798b870ab70"
+ },
+ {
+ "name": "deadline-and-hint",
+ "request": {
+ "schemaVersion": "grok-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "grok-subscription",
+ "model": "grok-4.6",
+ "messages": [
+ {
+ "role": "user",
+ "content": "hi"
+ }
+ ],
+ "deadlineMs": 120000,
+ "transportHints": {
+ "promptCacheKey": "cache:key/1"
+ },
+ "generation": {
+ "toolChoice": "none"
+ }
+ },
+ "sha256": "9bb1f851f93dc782a6dc979f9db332a2a5b58547e71a89c7f2d9f3da063f7030"
+ }
+ ],
+ "depthBoundaryDigests": {
+ "parameters-at-max-depth-64": "bc7b8406c4edf0b3b5a7cace94787d354fee6a799847889f8d52840a3eec5057",
+ "arguments-at-max-depth-64": "d8f6e299d3519d6e288493cf45bfd09d03682a4ef2cdba46c7d83b54eac56aa5"
+ }
+}
diff --git a/packages/grok-provider-attempt-contract/index.cjs b/packages/grok-provider-attempt-contract/index.cjs
index 647c61ff4..42e6d7ebb 100644
--- a/packages/grok-provider-attempt-contract/index.cjs
+++ b/packages/grok-provider-attempt-contract/index.cjs
@@ -24,8 +24,18 @@ const LIMITS = Object.freeze({
maxOutputTokens: 16384,
maxDeadlineMs: 300000,
maxIdLength: 128,
+ // Free-form JSON trees (tool parameters, assistant tool-call arguments) may
+ // nest at most this many containers. Bounds recursion before hashing.
+ maxNestingDepth: 64,
})
+// Deepest free-form tree root inside a request: request > messages[] >
+// message > toolCalls[] > call > arguments. A request that nests deeper than
+// this cannot pass the per-tree check, so the whole-request guard (which runs
+// before any recursive JSON work) never rejects an acceptable request.
+const REQUEST_ENVELOPE_DEPTH = 5
+const MAX_REQUEST_DEPTH = LIMITS.maxNestingDepth + REQUEST_ENVELOPE_DEPTH
+
const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
const SHA256_HEX = /^[a-f0-9]{64}$/
const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
@@ -93,6 +103,16 @@ function ok(value) {
* Validation rejects non-finite numbers before this runs.
*/
function stableStringify(value) {
+ return stableStringifyAt(value, 1)
+}
+
+function depthLimitError() {
+ const err = new Error(`value exceeds maximum nesting depth ${MAX_REQUEST_DEPTH}`)
+ err.code = 'limit'
+ return err
+}
+
+function stableStringifyAt(value, depth) {
if (value === null) return 'null'
if (value === undefined) return 'null'
const t = typeof value
@@ -102,8 +122,13 @@ function stableStringify(value) {
if (t === 'string' || t === 'boolean') {
return JSON.stringify(value)
}
+ if (t === 'object' && depth > MAX_REQUEST_DEPTH) {
+ throw depthLimitError()
+ }
if (Array.isArray(value)) {
- const items = value.map(item => (item === undefined ? 'null' : stableStringify(item)))
+ const items = value.map(item =>
+ item === undefined ? 'null' : stableStringifyAt(item, depth + 1)
+ )
return `[${items.join(',')}]`
}
if (t === 'object') {
@@ -111,7 +136,9 @@ function stableStringify(value) {
const keys = Object.keys(obj)
.filter(k => obj[k] !== undefined)
.sort()
- const body = keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')
+ const body = keys
+ .map(k => `${JSON.stringify(k)}:${stableStringifyAt(obj[k], depth + 1)}`)
+ .join(',')
return `{${body}}`
}
return 'null'
@@ -141,7 +168,39 @@ function rejectUnknown(obj, allowed, label) {
return fail('unknown-field', `${label} rejects field '${extra[0]}'`)
}
-function assertFiniteTree(value, label) {
+/**
+ * Iterative structural pre-check, safe on arbitrarily deep or cyclic input.
+ * Returns a failure when containers nest deeper than `maxDepth`, or when the
+ * value holds more elements than a maxRequestBodyBytes JSON document can encode
+ * (every encoded element takes at least one byte, so no acceptable request
+ * reaches that count; shared references are counted per occurrence, as JSON
+ * would serialize them).
+ */
+function checkStructure(value, maxDepth) {
+ if (value === null || typeof value !== 'object') return null
+ const stack = [value, 1]
+ let elements = 1
+ while (stack.length > 0) {
+ const depth = stack.pop()
+ const node = stack.pop()
+ if (depth > maxDepth) {
+ return fail('limit', `request exceeds maximum nesting depth ${LIMITS.maxNestingDepth}`)
+ }
+ const children = Array.isArray(node)
+ ? node
+ : Object.values(node).filter(child => child !== undefined)
+ elements += children.length
+ if (elements > LIMITS.maxRequestBodyBytes) {
+ return fail('limit', 'request exceeds maxRequestBodyBytes')
+ }
+ for (const child of children) {
+ if (child !== null && typeof child === 'object') stack.push(child, depth + 1)
+ }
+ }
+ return null
+}
+
+function assertFiniteTree(value, label, depth = 1) {
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
return fail('non-finite', `${label} must be finite`)
@@ -153,9 +212,12 @@ function assertFiniteTree(value, label) {
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
return fail('invalid', `${label} has an unsupported type`)
}
+ if (depth > LIMITS.maxNestingDepth) {
+ return fail('limit', `${label} exceeds maximum nesting depth ${LIMITS.maxNestingDepth}`)
+ }
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
- const inner = assertFiniteTree(value[i], `${label}[${i}]`)
+ const inner = assertFiniteTree(value[i], `${label}[${i}]`, depth + 1)
if (inner) return inner
}
return null
@@ -163,7 +225,7 @@ function assertFiniteTree(value, label) {
if (typeof value === 'object') {
for (const [k, v] of Object.entries(value)) {
if (v === undefined) continue
- const inner = assertFiniteTree(v, `${label}.${k}`)
+ const inner = assertFiniteTree(v, `${label}.${k}`, depth + 1)
if (inner) return inner
}
}
@@ -318,7 +380,16 @@ function parseTransportHints(raw) {
function parseGrokCompletionRequestV1(input) {
if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
- const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ // Runs before JSON.stringify: a deeply nested body would otherwise throw a
+ // RangeError out of the parser instead of failing closed.
+ const structure = checkStructure(input, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ let encoded
+ try {
+ encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
if (encoded > LIMITS.maxRequestBodyBytes) {
return fail('limit', 'request exceeds maxRequestBodyBytes')
}
@@ -375,6 +446,35 @@ function hashGrokCompletionRequestV1(request) {
return createHash('sha256').update(stableStringify(request)).digest('hex')
}
+/**
+ * Client-side canonical hashing. Serializes `raw` exactly as a JSON peer
+ * receives it, parses that wire form with parseGrokCompletionRequestV1, and
+ * hashes the validated projection — the same steps control-api authorize and
+ * grok-llm-proxy perform. Callers send `value.request` with
+ * `value.requestHash`, so shapes the parser normalizes away (empty
+ * generation/tools/transportHints, undefined leaves) cannot make the two ends
+ * disagree. Never throws; invalid input fails closed.
+ */
+function hashCanonicalGrokRequest(raw) {
+ if (!isPlainObject(raw)) return fail('invalid', 'request must be an object')
+ const structure = checkStructure(raw, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ let wire
+ try {
+ wire = JSON.parse(JSON.stringify(raw))
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
+ const parsed = parseGrokCompletionRequestV1(wire)
+ if (!parsed.ok) return parsed
+ return ok(
+ Object.freeze({
+ request: parsed.value,
+ requestHash: hashGrokCompletionRequestV1(parsed.value),
+ })
+ )
+}
+
/**
* Grant-binding digest for a Grok authorize attempt. connectionKey is
* required; never aliases deployment-default.
@@ -552,6 +652,7 @@ module.exports = {
stableStringify,
parseGrokCompletionRequestV1,
hashGrokCompletionRequestV1,
+ hashCanonicalGrokRequest,
computeGrokPolicyHash,
parseGrokExecutionTicketClaims,
parseAuthorizeAttemptResponse,
diff --git a/packages/grok-provider-attempt-contract/index.d.ts b/packages/grok-provider-attempt-contract/index.d.ts
index 3b37d9e10..8f0af12ed 100644
--- a/packages/grok-provider-attempt-contract/index.d.ts
+++ b/packages/grok-provider-attempt-contract/index.d.ts
@@ -21,6 +21,7 @@ export declare const LIMITS: {
readonly maxOutputTokens: 16384
readonly maxDeadlineMs: 300000
readonly maxIdLength: 128
+ readonly maxNestingDepth: 64
}
export type ContractResult<T> =
@@ -133,6 +134,15 @@ export declare function parseGrokCompletionRequestV1(
input: unknown
): ContractResult<GrokCompletionRequestV1>
export declare function hashGrokCompletionRequestV1(request: GrokCompletionRequestV1): string
+/**
+ * Canonical client hash: JSON wire round-trip, parseGrokCompletionRequestV1,
+ * then hashGrokCompletionRequestV1 of the projection. Send `request` together
+ * with `requestHash`. Never throws; invalid input returns `{ ok: false }`.
+ */
+export declare function hashCanonicalGrokRequest(raw: unknown): ContractResult<{
+ request: GrokCompletionRequestV1
+ requestHash: string
+}>
export declare function computeGrokPolicyHash(input: {
model: string
catalogRevision: number
diff --git a/packages/grok-provider-attempt-contract/index.test.cjs b/packages/grok-provider-attempt-contract/index.test.cjs
index daf5bd58d..46fa306a3 100644
--- a/packages/grok-provider-attempt-contract/index.test.cjs
+++ b/packages/grok-provider-attempt-contract/index.test.cjs
@@ -110,3 +110,223 @@ test('parses Grok ticket claims and rejects Codex typ', () => {
})
assert.equal(wrongTyp.ok, false)
})
+
+// ---------------------------------------------------------------------------
+// Canonical hashing shared by mcp-host (client) and control-api/grok-llm-proxy
+// (server), plus the structural depth cap.
+// ---------------------------------------------------------------------------
+
+const GOLDEN = JSON.parse(
+ fs.readFileSync(path.join(__dirname, 'fixtures/golden-request-hashes.json'), 'utf8')
+)
+
+function nest(depth, key, leaf = {}) {
+ let value = leaf
+ for (let i = 1; i < depth; i++) value = { [key]: value }
+ return value
+}
+
+function nestArrays(depth) {
+ let value = []
+ for (let i = 1; i < depth; i++) value = [value]
+ return value
+}
+
+/** What a JSON peer (control-api authorize, grok-llm-proxy) computes. */
+function serverHash(wireRequest) {
+ const onWire = JSON.parse(JSON.stringify({ request: wireRequest })).request
+ const parsed = contract.parseGrokCompletionRequestV1(onWire)
+ assert.equal(parsed.ok, true, parsed.message)
+ return contract.hashGrokCompletionRequestV1(parsed.value)
+}
+
+test('golden digests: well-formed requests keep their pre-change hashes on every path', () => {
+ const golden = [
+ ...GOLDEN.cases,
+ {
+ name: 'parameters-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [{ role: 'user', content: 'deep' }],
+ tools: [{ name: 'deep', description: 'deep schema', parameters: nest(64, 'n') }],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['parameters-at-max-depth-64'],
+ },
+ {
+ name: 'arguments-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call-deep', name: 'deep', arguments: nest(64, 'a') }],
+ },
+ ],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['arguments-at-max-depth-64'],
+ },
+ ]
+ assert.equal(golden.length, 6)
+ for (const entry of golden) {
+ const parsed = contract.parseGrokCompletionRequestV1(entry.request)
+ assert.equal(parsed.ok, true, `${entry.name}: ${parsed.message}`)
+ assert.equal(contract.hashGrokCompletionRequestV1(parsed.value), entry.sha256, entry.name)
+ const canonical = contract.hashCanonicalGrokRequest(entry.request)
+ assert.equal(canonical.ok, true, entry.name)
+ assert.equal(canonical.value.requestHash, entry.sha256, entry.name)
+ assert.equal(serverHash(canonical.value.request), entry.sha256, entry.name)
+ }
+})
+
+const DIVERGENT_SHAPES = [
+ ['empty generation from a non-enum tool_choice', { generation: {} }],
+ ['empty tools array', { tools: [] }],
+ ['empty transportHints', { transportHints: {} }],
+ ['transportHints with an undefined cache key', { transportHints: { promptCacheKey: undefined } }],
+ [
+ 'undefined optional message fields',
+ { messages: [{ role: 'user', content: 'x', name: undefined, toolCallId: undefined }] },
+ ],
+ [
+ 'undefined leaves in assistant tool-call arguments',
+ {
+ messages: [
+ { role: 'user', content: 'x' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 't', arguments: { a: undefined, b: [undefined] } }],
+ },
+ ],
+ },
+ ],
+ [
+ 'a Date inside tool parameters (serialized by toJSON on the wire)',
+ {
+ tools: [{ name: 't', description: 'd', parameters: { type: 'object', since: new Date(0) } }],
+ },
+ ],
+]
+
+for (const [label, overrides] of DIVERGENT_SHAPES) {
+ test(`hashCanonicalGrokRequest matches the server hash for ${label}`, () => {
+ const raw = { ...BASE, ...overrides }
+ const canonical = contract.hashCanonicalGrokRequest(raw)
+ assert.equal(canonical.ok, true, canonical.message)
+ assert.match(canonical.value.requestHash, /^[a-f0-9]{64}$/)
+ // mcp-host sends the canonical request; a caller that still sent the raw
+ // request must land on the same digest.
+ assert.equal(serverHash(canonical.value.request), canonical.value.requestHash)
+ assert.equal(serverHash(raw), canonical.value.requestHash)
+ })
+}
+
+test('hashCanonicalGrokRequest drops empty optional containers from the canonical request', () => {
+ const canonical = contract.hashCanonicalGrokRequest({
+ ...BASE,
+ generation: {},
+ tools: [],
+ transportHints: {},
+ })
+ assert.equal(canonical.ok, true)
+ assert.deepEqual(Object.keys(canonical.value.request).sort(), Object.keys(BASE).sort())
+})
+
+test('hashCanonicalGrokRequest fails closed without throwing on invalid input', () => {
+ const cases = [
+ [{ ...BASE, generation: { temperature: 3 } }, 'invalid'],
+ [{ ...BASE, provider: 'codex-subscription' }, 'invalid'],
+ [{ ...BASE, headers: { authorization: 'x' } }, 'unknown-field'],
+ [{ ...BASE, deadlineMs: 10n }, 'invalid'],
+ ['not-an-object', 'invalid'],
+ ]
+ for (const [raw, code] of cases) {
+ const result = contract.hashCanonicalGrokRequest(raw)
+ assert.equal(result.ok, false)
+ assert.equal(result.code, code)
+ }
+ const cyclic = { ...BASE, tools: [{ name: 't', description: 'd', parameters: {} }] }
+ cyclic.tools[0].parameters.self = cyclic.tools[0].parameters
+ const cyclicResult = contract.hashCanonicalGrokRequest(cyclic)
+ assert.equal(cyclicResult.ok, false)
+ assert.equal(cyclicResult.code, 'limit')
+})
+
+test('LIMITS publishes the nesting depth cap', () => {
+ assert.equal(contract.LIMITS.maxNestingDepth, 64)
+})
+
+test('tool parameters accept depth 64 and reject depth 65 with a limit failure', () => {
+ const at = contract.parseGrokCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(64, 'n') }],
+ })
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseGrokCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(65, 'n') }],
+ })
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+ assert.match(over.message, /nesting depth/)
+})
+
+test('assistant tool-call arguments accept depth 64 and reject depth 65', () => {
+ const request = depth => ({
+ ...BASE,
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 'deep', arguments: nest(depth, 'a') }],
+ },
+ ],
+ })
+ const at = contract.parseGrokCompletionRequestV1(request(64))
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseGrokCompletionRequestV1(request(65))
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+})
+
+for (const depth of [5000, 150000]) {
+ test(`a ${depth}-deep body returns a limit failure instead of a RangeError`, () => {
+ const viaObjects = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: nest(depth, 'n') }],
+ }
+ const viaArrays = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: { x: nestArrays(depth) } }],
+ }
+ for (const raw of [viaObjects, viaArrays]) {
+ const parsed = contract.parseGrokCompletionRequestV1(raw)
+ assert.equal(parsed.ok, false)
+ assert.equal(parsed.code, 'limit')
+ const canonical = contract.hashCanonicalGrokRequest(raw)
+ assert.equal(canonical.ok, false)
+ assert.equal(canonical.code, 'limit')
+ }
+ })
+}
+
+test('stableStringify rejects over-deep values with a limit error, not a stack overflow', () => {
+ for (const value of [nest(5000, 'n'), nestArrays(150000)]) {
+ assert.throws(
+ () => contract.stableStringify(value),
+ err => err.code === 'limit' && !(err instanceof RangeError)
+ )
+ }
+ // Any request the parser accepts stays serializable.
+ assert.doesNotThrow(() =>
+ contract.stableStringify({
+ tools: [{ parameters: nest(64, 'n') }],
+ m: [[{ a: nest(64, 'a') }]],
+ })
+ )
+})
diff --git a/packages/llm-provider-attempt-contract/fixtures/golden-request-hashes.json b/packages/llm-provider-attempt-contract/fixtures/golden-request-hashes.json
new file mode 100644
index 000000000..6f26c0ed1
--- /dev/null
+++ b/packages/llm-provider-attempt-contract/fixtures/golden-request-hashes.json
@@ -0,0 +1,156 @@
+{
+ "schemaVersion": "codex-completion-request.v1",
+ "notes": "Golden digests captured from the contract at a42dedf8 before hashCanonical/depth-cap changes. Well-formed requests must keep these exact digests. depthBoundaryDigests are built in index.test.cjs as a single-key chain of 64 nested objects (key n for tool parameters, key a for assistant toolCall arguments).",
+ "cases": [
+ {
+ "name": "minimal",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ {
+ "role": "user",
+ "content": "hello"
+ }
+ ]
+ },
+ "sha256": "ea13b97d4dcd9c50f487dc85b6917eae5a41301d3ea24dc300923012696a4c2e"
+ },
+ {
+ "name": "tools-and-generation",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ {
+ "role": "system",
+ "content": "be brief"
+ },
+ {
+ "role": "user",
+ "content": "find it"
+ }
+ ],
+ "tools": [
+ {
+ "name": "eventasks__read",
+ "description": "Read a record",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "opts": {
+ "type": "object",
+ "properties": {
+ "deep": {
+ "type": "array",
+ "items": {
+ "type": "number"
+ }
+ }
+ }
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "clerum__tool_search",
+ "description": "search",
+ "parameters": {
+ "type": "object"
+ }
+ }
+ ],
+ "generation": {
+ "temperature": 0.2,
+ "maxOutputTokens": 1024,
+ "toolChoice": "auto"
+ }
+ },
+ "sha256": "a930f4a9f2e0f3d2d87bd347d4e15c4e23c0e7658bc4752694a7973a40c70ccf"
+ },
+ {
+ "name": "tool-history-unicode",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ {
+ "role": "user",
+ "content": "café 漢字 🎵"
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "toolCalls": [
+ {
+ "id": "call-1",
+ "name": "工具@café",
+ "arguments": {
+ "x": 1,
+ "y": [
+ true,
+ null,
+ "z"
+ ],
+ "n": {
+ "m": -0.5
+ }
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "content": "{\"ok\":true}",
+ "toolCallId": "call-1",
+ "name": "工具@café"
+ }
+ ]
+ },
+ "sha256": "2b72662c0141097576a50b83f123b543be3bbb4330e3ac863a869e39a4428790"
+ },
+ {
+ "name": "deadline-and-hint",
+ "request": {
+ "schemaVersion": "codex-completion-request.v1",
+ "requestId": "req-golden",
+ "idempotencyKey": "idem-golden",
+ "provider": "codex-subscription",
+ "model": "gpt-5.1",
+ "messages": [
+ {
+ "role": "user",
+ "content": "hi"
+ }
+ ],
+ "deadlineMs": 120000,
+ "transportHints": {
+ "promptCacheKey": "cache:key/1"
+ },
+ "generation": {
+ "toolChoice": "none"
+ }
+ },
+ "sha256": "7b2fafda6737b2521b16d911fc48be7a21f52a13395d044afc29228050176dcc"
+ }
+ ],
+ "depthBoundaryDigests": {
+ "parameters-at-max-depth-64": "439517b293d9c78d4c5ca379f360710854ad392dc29154b61a32c89c7475ad63",
+ "arguments-at-max-depth-64": "48b223751703e7198de01e04bd71b64fccb7203fe300735ab68a34c9a9c9ad7c"
+ }
+}
diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjs
index fa7e9bad3..884c5e951 100644
--- a/packages/llm-provider-attempt-contract/index.cjs
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@ -20,8 +20,18 @@ const LIMITS = Object.freeze({
maxOutputTokens: 16384,
maxDeadlineMs: 300000,
maxIdLength: 128,
+ // Free-form JSON trees (tool parameters, assistant tool-call arguments) may
+ // nest at most this many containers. Bounds recursion before hashing.
+ maxNestingDepth: 64,
})
+// Deepest free-form tree root inside a request: request > messages[] >
+// message > toolCalls[] > call > arguments. A request that nests deeper than
+// this cannot pass the per-tree check, so the whole-request guard (which runs
+// before any recursive JSON work) never rejects an acceptable request.
+const REQUEST_ENVELOPE_DEPTH = 5
+const MAX_REQUEST_DEPTH = LIMITS.maxNestingDepth + REQUEST_ENVELOPE_DEPTH
+
const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
const SHA256_HEX = /^[a-f0-9]{64}$/
const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
@@ -88,6 +98,16 @@ function ok(value) {
* Validation rejects non-finite numbers before this runs.
*/
function stableStringify(value) {
+ return stableStringifyAt(value, 1)
+}
+
+function depthLimitError() {
+ const err = new Error(`value exceeds maximum nesting depth ${MAX_REQUEST_DEPTH}`)
+ err.code = 'limit'
+ return err
+}
+
+function stableStringifyAt(value, depth) {
if (value === null) return 'null'
if (value === undefined) return 'null'
const t = typeof value
@@ -97,8 +117,11 @@ function stableStringify(value) {
if (t === 'string' || t === 'boolean') {
return JSON.stringify(value)
}
+ if (t === 'object' && depth > MAX_REQUEST_DEPTH) {
+ throw depthLimitError()
+ }
if (Array.isArray(value)) {
- const items = value.map(item => (item === undefined ? 'null' : stableStringify(item)))
+ const items = value.map(item => (item === undefined ? 'null' : stableStringifyAt(item, depth + 1)))
return `[${items.join(',')}]`
}
if (t === 'object') {
@@ -106,7 +129,7 @@ function stableStringify(value) {
const keys = Object.keys(obj)
.filter(k => obj[k] !== undefined)
.sort()
- const body = keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')
+ const body = keys.map(k => `${JSON.stringify(k)}:${stableStringifyAt(obj[k], depth + 1)}`).join(',')
return `{${body}}`
}
return 'null'
@@ -136,7 +159,37 @@ function rejectUnknown(obj, allowed, label) {
return fail('unknown-field', `${label} rejects field '${extra[0]}'`)
}
-function assertFiniteTree(value, label) {
+/**
+ * Iterative structural pre-check, safe on arbitrarily deep or cyclic input.
+ * Returns a failure when containers nest deeper than `maxDepth`, or when the
+ * value holds more elements than a maxRequestBodyBytes JSON document can encode
+ * (every encoded element takes at least one byte, so no acceptable request
+ * reaches that count; shared references are counted per occurrence, as JSON
+ * would serialize them).
+ */
+function checkStructure(value, maxDepth) {
+ if (value === null || typeof value !== 'object') return null
+ const stack = [value, 1]
+ let elements = 1
+ while (stack.length > 0) {
+ const depth = stack.pop()
+ const node = stack.pop()
+ if (depth > maxDepth) {
+ return fail('limit', `request exceeds maximum nesting depth ${LIMITS.maxNestingDepth}`)
+ }
+ const children = Array.isArray(node) ? node : Object.values(node).filter(child => child !== undefined)
+ elements += children.length
+ if (elements > LIMITS.maxRequestBodyBytes) {
+ return fail('limit', 'request exceeds maxRequestBodyBytes')
+ }
+ for (const child of children) {
+ if (child !== null && typeof child === 'object') stack.push(child, depth + 1)
+ }
+ }
+ return null
+}
+
+function assertFiniteTree(value, label, depth = 1) {
if (typeof value === 'number') {
if (!Number.isFinite(value)) {
return fail('non-finite', `${label} must be finite`)
@@ -148,9 +201,12 @@ function assertFiniteTree(value, label) {
if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
return fail('invalid', `${label} has an unsupported type`)
}
+ if (depth > LIMITS.maxNestingDepth) {
+ return fail('limit', `${label} exceeds maximum nesting depth ${LIMITS.maxNestingDepth}`)
+ }
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
- const inner = assertFiniteTree(value[i], `${label}[${i}]`)
+ const inner = assertFiniteTree(value[i], `${label}[${i}]`, depth + 1)
if (inner) return inner
}
return null
@@ -158,7 +214,7 @@ function assertFiniteTree(value, label) {
if (typeof value === 'object') {
for (const [k, v] of Object.entries(value)) {
if (v === undefined) continue
- const inner = assertFiniteTree(v, `${label}.${k}`)
+ const inner = assertFiniteTree(v, `${label}.${k}`, depth + 1)
if (inner) return inner
}
}
@@ -311,7 +367,16 @@ function parseTransportHints(raw) {
function parseCodexCompletionRequestV1(input) {
if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
- const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ // Runs before JSON.stringify: a deeply nested body would otherwise throw a
+ // RangeError out of the parser instead of failing closed.
+ const structure = checkStructure(input, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ let encoded
+ try {
+ encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
if (encoded > LIMITS.maxRequestBodyBytes) {
return fail('limit', 'request exceeds maxRequestBodyBytes')
}
@@ -368,6 +433,31 @@ function hashCodexCompletionRequestV1(request) {
return createHash('sha256').update(stableStringify(request)).digest('hex')
}
+/**
+ * Client-side canonical hashing. Serializes `raw` exactly as a JSON peer
+ * receives it, parses that wire form with parseCodexCompletionRequestV1, and
+ * hashes the validated projection — the same steps control-api authorize and
+ * codex-llm-proxy perform. Callers send `value.request` with
+ * `value.requestHash`, so shapes the parser normalizes away (empty
+ * generation/tools/transportHints, undefined leaves) cannot make the two ends
+ * disagree. For an already well-formed request the digest is identical to
+ * hashCodexCompletionRequestV1(request). Never throws; invalid input fails closed.
+ */
+function hashCanonicalCodexRequest(raw) {
+ if (!isPlainObject(raw)) return fail('invalid', 'request must be an object')
+ const structure = checkStructure(raw, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ let wire
+ try {
+ wire = JSON.parse(JSON.stringify(raw))
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
+ const parsed = parseCodexCompletionRequestV1(wire)
+ if (!parsed.ok) return parsed
+ return ok(Object.freeze({ request: parsed.value, requestHash: hashCodexCompletionRequestV1(parsed.value) }))
+}
+
/**
* Grant-binding digest for a Codex authorize attempt. Must match
* control-api's expected hash: SHA-256 of lexicographic stableStringify of
@@ -524,6 +614,7 @@ module.exports = {
stableStringify,
parseCodexCompletionRequestV1,
hashCodexCompletionRequestV1,
+ hashCanonicalCodexRequest,
computeCodexPolicyHash,
parseCodexExecutionTicketClaims,
parseAuthorizeAttemptResponse,
diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.ts
index 17acd19f9..c87ee6092 100644
--- a/packages/llm-provider-attempt-contract/index.d.ts
+++ b/packages/llm-provider-attempt-contract/index.d.ts
@@ -20,6 +20,7 @@ export declare const LIMITS: {
readonly maxOutputTokens: 16384
readonly maxDeadlineMs: 300000
readonly maxIdLength: 128
+ readonly maxNestingDepth: 64
}
export type ContractResult<T> =
@@ -138,6 +139,15 @@ export declare function parseCodexCompletionRequestV1(
export declare function hashCodexCompletionRequestV1(
request: CodexCompletionRequestV1
): string
+/**
+ * Canonical client hash: JSON wire round-trip, parseCodexCompletionRequestV1,
+ * then hashCodexCompletionRequestV1 of the projection. Send `request` together
+ * with `requestHash`. Never throws; invalid input returns `{ ok: false }`.
+ */
+export declare function hashCanonicalCodexRequest(raw: unknown): ContractResult<{
+ request: CodexCompletionRequestV1
+ requestHash: string
+}>
export declare function computeCodexPolicyHash(input: {
model: string
catalogRevision: number
diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjs
index 3b9982d90..f19287964 100644
--- a/packages/llm-provider-attempt-contract/index.test.cjs
+++ b/packages/llm-provider-attempt-contract/index.test.cjs
@@ -367,3 +367,236 @@ test('opaque canonical names remain bounded by serialized UTF-8 request bytes',
ok: false, code: 'limit', message: 'request exceeds maxRequestBodyBytes',
})
})
+
+// ---------------------------------------------------------------------------
+// Canonical hashing shared by mcp-host (client) and control-api/codex-llm-proxy
+// (server), plus the structural depth cap.
+// ---------------------------------------------------------------------------
+
+const GOLDEN = JSON.parse(
+ fs.readFileSync(path.join(__dirname, 'fixtures/golden-request-hashes.json'), 'utf8')
+)
+
+function nest(depth, key, leaf = {}) {
+ let value = leaf
+ for (let i = 1; i < depth; i++) value = { [key]: value }
+ return value
+}
+
+function nestArrays(depth) {
+ let value = []
+ for (let i = 1; i < depth; i++) value = [value]
+ return value
+}
+
+/** What a JSON peer (control-api authorize, codex-llm-proxy) computes. */
+function serverHash(wireRequest) {
+ const onWire = JSON.parse(JSON.stringify({ request: wireRequest })).request
+ const parsed = contract.parseCodexCompletionRequestV1(onWire)
+ assert.equal(parsed.ok, true, parsed.message)
+ return contract.hashCodexCompletionRequestV1(parsed.value)
+}
+
+test('golden digests: well-formed requests keep their pre-change hashes on every path', () => {
+ const golden = [
+ ...GOLDEN.cases,
+ {
+ name: 'parameters-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [{ role: 'user', content: 'deep' }],
+ tools: [{ name: 'deep', description: 'deep schema', parameters: nest(64, 'n') }],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['parameters-at-max-depth-64'],
+ },
+ {
+ name: 'arguments-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call-deep', name: 'deep', arguments: nest(64, 'a') }],
+ },
+ ],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['arguments-at-max-depth-64'],
+ },
+ ]
+ assert.equal(golden.length, 6)
+ for (const entry of golden) {
+ const parsed = contract.parseCodexCompletionRequestV1(entry.request)
+ assert.equal(parsed.ok, true, `${entry.name}: ${parsed.message}`)
+ assert.equal(contract.hashCodexCompletionRequestV1(parsed.value), entry.sha256, entry.name)
+ const canonical = contract.hashCanonicalCodexRequest(entry.request)
+ assert.equal(canonical.ok, true, entry.name)
+ assert.equal(canonical.value.requestHash, entry.sha256, entry.name)
+ assert.equal(serverHash(canonical.value.request), entry.sha256, entry.name)
+ }
+})
+
+const DIVERGENT_SHAPES = [
+ ['empty generation from a non-enum tool_choice', { generation: {} }],
+ ['empty tools array', { tools: [] }],
+ ['empty transportHints', { transportHints: {} }],
+ ['transportHints with an undefined cache key', { transportHints: { promptCacheKey: undefined } }],
+ [
+ 'undefined optional message fields',
+ { messages: [{ role: 'user', content: 'x', name: undefined, toolCallId: undefined }] },
+ ],
+ [
+ 'undefined leaves in assistant tool-call arguments',
+ {
+ messages: [
+ { role: 'user', content: 'x' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 't', arguments: { a: undefined, b: [undefined] } }],
+ },
+ ],
+ },
+ ],
+ [
+ 'a Date inside tool parameters (serialized by toJSON on the wire)',
+ {
+ tools: [{ name: 't', description: 'd', parameters: { type: 'object', since: new Date(0) } }],
+ },
+ ],
+]
+
+for (const [label, overrides] of DIVERGENT_SHAPES) {
+ test(`hashCanonicalCodexRequest matches the server hash for ${label}`, () => {
+ const raw = { ...BASE, ...overrides }
+ const canonical = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(canonical.ok, true, canonical.message)
+ assert.match(canonical.value.requestHash, /^[a-f0-9]{64}$/)
+ // mcp-host sends the canonical request; a caller that still sent the raw
+ // request must land on the same digest.
+ assert.equal(serverHash(canonical.value.request), canonical.value.requestHash)
+ assert.equal(serverHash(raw), canonical.value.requestHash)
+ })
+}
+
+test('hashCanonicalCodexRequest drops empty optional containers from the canonical request', () => {
+ const canonical = contract.hashCanonicalCodexRequest({
+ ...BASE,
+ generation: {},
+ tools: [],
+ transportHints: {},
+ })
+ assert.equal(canonical.ok, true)
+ assert.deepEqual(Object.keys(canonical.value.request).sort(), Object.keys(BASE).sort())
+})
+
+test('hashCanonicalCodexRequest fails closed without throwing on invalid input', () => {
+ const cases = [
+ [{ ...BASE, generation: { temperature: 3 } }, 'invalid'],
+ [{ ...BASE, provider: 'grok-subscription' }, 'invalid'],
+ [{ ...BASE, headers: { authorization: 'x' } }, 'unknown-field'],
+ [{ ...BASE, deadlineMs: 10n }, 'invalid'],
+ ['not-an-object', 'invalid'],
+ ]
+ for (const [raw, code] of cases) {
+ const result = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(result.ok, false)
+ assert.equal(result.code, code)
+ }
+ const cyclic = { ...BASE, tools: [{ name: 't', description: 'd', parameters: {} }] }
+ cyclic.tools[0].parameters.self = cyclic.tools[0].parameters
+ const cyclicResult = contract.hashCanonicalCodexRequest(cyclic)
+ assert.equal(cyclicResult.ok, false)
+ assert.equal(cyclicResult.code, 'limit')
+})
+
+test('LIMITS publishes the nesting depth cap', () => {
+ assert.equal(contract.LIMITS.maxNestingDepth, 64)
+})
+
+test('tool parameters accept depth 64 and reject depth 65 with a limit failure', () => {
+ const at = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(64, 'n') }],
+ })
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(65, 'n') }],
+ })
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+ assert.match(over.message, /nesting depth/)
+})
+
+test('assistant tool-call arguments accept depth 64 and reject depth 65', () => {
+ const request = depth => ({
+ ...BASE,
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 'deep', arguments: nest(depth, 'a') }],
+ },
+ ],
+ })
+ const at = contract.parseCodexCompletionRequestV1(request(64))
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseCodexCompletionRequestV1(request(65))
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+})
+
+for (const depth of [5000, 150000]) {
+ test(`a ${depth}-deep body returns a limit failure instead of a RangeError`, () => {
+ const viaObjects = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: nest(depth, 'n') }],
+ }
+ const viaArrays = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: { x: nestArrays(depth) } }],
+ }
+ for (const raw of [viaObjects, viaArrays]) {
+ const parsed = contract.parseCodexCompletionRequestV1(raw)
+ assert.equal(parsed.ok, false)
+ assert.equal(parsed.code, 'limit')
+ const canonical = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(canonical.ok, false)
+ assert.equal(canonical.code, 'limit')
+ }
+ })
+}
+
+test('stableStringify rejects over-deep values with a limit error, not a stack overflow', () => {
+ for (const value of [nest(5000, 'n'), nestArrays(150000)]) {
+ assert.throws(
+ () => contract.stableStringify(value),
+ err => err.code === 'limit' && !(err instanceof RangeError)
+ )
+ }
+ // Any request the parser accepts stays serializable.
+ assert.doesNotThrow(() =>
+ contract.stableStringify({
+ tools: [{ parameters: nest(64, 'n') }],
+ m: [[{ a: nest(64, 'a') }]],
+ })
+ )
+})
+
+test('frozen Codex fixture corpus hashes identically through hashCanonicalCodexRequest', () => {
+ for (const fixture of FIXTURE.cases) {
+ for (const request of [fixture.request, fixture.equivalentRequest].filter(Boolean)) {
+ const canonical = contract.hashCanonicalCodexRequest(request)
+ assert.equal(canonical.ok, true, fixture.name)
+ assert.equal(canonical.value.requestHash, fixture.sha256, fixture.name)
+ }
+ }
+ for (const fixture of FIXTURE.rejects) {
+ assert.equal(contract.hashCanonicalCodexRequest(fixture.request).ok, false, fixture.name)
+ }
+})