Skip to content

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

TypeScript

fix: fail closed on stale Codex capabilities and pending ledger races

Alfredo Lopez96f00a1401fb
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 398056d97..a9abdd0fc 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.527",
+ "version": "0.1.528",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.527",
+ "version": "0.1.528",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 83bdec9b4..bf9bbdfef 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.527",
+ "version": "0.1.528",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index a9ac51e8d..fbe2913bf 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -1,5 +1,6 @@
import { type NextFunction, type Request, type Response, Router } from 'express'
import { rateLimit } from 'express-rate-limit'
+import { PROVIDER_AUTH_MODE, isLlmProviderId } from '@clerum/llm-providers'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
@@ -718,8 +719,18 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
(await hasUsableClientNotificationRecipients(clientNotificationsGrant))
)
const primaryTarget = grant?.promptTargets[0] ?? null
+ const reservationOnlyOauthBroker = Boolean(
+ primaryTarget &&
+ isLlmProviderId(primaryTarget.provider) &&
+ PROVIDER_AUTH_MODE[primaryTarget.provider] === 'oauth-broker'
+ )
+ // Old mcp-host/WRC require capabilities.contractVersion === 2. Advertise
+ // 3 only for oauth-broker defaults so those binaries fail at reconcile
+ // instead of Validated-then-empty-ticket. Authorize/grant wire stays 2.
res.status(200).json({
- contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,
+ contractVersion: reservationOnlyOauthBroker
+ ? 3
+ : PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,
supportedContractVersions: [2, 3],
targetAwarePromptBridge: true,
attemptLedger: true,
@@ -732,6 +743,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
defaultModel: primaryTarget?.model ?? null,
defaultConnectionRef: primaryTarget?.connectionRef ?? null,
v2Ready,
+ ...(reservationOnlyOauthBroker ? { reservationOnlyOauthBroker: true } : {}),
clientNotificationsPolicyState: clientNotificationsGrant?.policyState ?? 'missing',
clientNotificationsReady,
})
@@ -1048,17 +1060,18 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
const errorCode =
error.code === 'conflict'
? 'idempotency_conflict'
- : error.code === 'binding_mismatch'
- ? 'provider_policy_denied'
- : error.code === 'stale_attempt'
- ? 'provider_unavailable'
+ : error.code === 'ledger_pending' || error.code === 'stale_attempt'
+ ? 'provider_unavailable'
+ : error.code === 'binding_mismatch'
+ ? 'provider_policy_denied'
: error.code === 'not_found'
? 'invalid_request'
: error.code
res.status(error.httpStatus).json({
error: errorCode,
message: error.message,
- retryable: false,
+ retryable: error.retryable === true,
+ ...(error.code === 'ledger_pending' ? { reason: 'provider_unavailable' } : {}),
})
return
}
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
index bf45da245..7a9f5a6e0 100644
--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -51,13 +51,15 @@ export type PromptBridgeFinalizationErrorCode =
| 'binding_mismatch'
| 'stale_attempt'
| 'conflict'
+ | 'ledger_pending'
| 'invalid_request'
export class PromptBridgeFinalizationError extends Error {
constructor(
readonly code: PromptBridgeFinalizationErrorCode,
message: string,
- readonly httpStatus: 400 | 403 | 404 | 409
+ readonly httpStatus: 400 | 403 | 404 | 409,
+ readonly retryable = false
) {
super(message)
this.name = 'PromptBridgeFinalizationError'
@@ -388,6 +390,24 @@ export async function finalizePromptBridgeInTransaction(
const linkedCodex = oauthBroker
? await loadLlmProviderAttemptBySdkAttemptId(db, input.providerAttemptId)
: null
+ if (oauthBroker && input.status === 'complete' && linkedCodex) {
+ const usageReady =
+ linkedCodex.outcome === 'success' &&
+ linkedCodex.usageInputTokens != null &&
+ linkedCodex.usageOutputTokens != null
+ const inFlight =
+ linkedCodex.status === 'authorized' ||
+ linkedCodex.status === 'redeemed' ||
+ (linkedCodex.status === 'finalized' && linkedCodex.outcome === 'success' && !usageReady)
+ if (!usageReady && inFlight) {
+ throw new PromptBridgeFinalizationError(
+ 'ledger_pending',
+ 'linked Codex attempt has not finalized usage yet',
+ 409,
+ true
+ )
+ }
+ }
const outcome = resolvePromptBridgeOutcome(input.status, oauthBroker, linkedCodex)
let usageAccepted = false
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index 550f82568..e26388e00 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -267,6 +267,7 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
expect(res.status).toBe(200)
expect(res.body).toMatchObject({
+ contractVersion: 2,
policyState: 'active',
policyRevision: 2,
defaultTargetRef: 'primary-openai',
@@ -276,8 +277,55 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
supportedContractVersions: [2, 3],
v2Ready: true,
})
+ expect(res.body.reservationOnlyOauthBroker).toBeUndefined()
expect(res.body.policyHash).toMatch(/^[a-f0-9]{64}$/)
})
+
+ it('advertises contract v3 only when the grant default is oauth-broker', async () => {
+ vi.mocked(sdkDb.findGrant).mockResolvedValue({
+ id: 'grant-codex-capabilities',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ allowedModels: ['gpt-5.1'],
+ allowedEventTypes: [],
+ allowedTargetRefs: [],
+ allowedUserRefs: [],
+ allowedCallers: ['api'],
+ quotaLimits: {},
+ modelPolicies: {},
+ promptTargets: [
+ {
+ targetRef: 'primary-codex',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ },
+ ],
+ defaultTargetRef: 'primary-codex',
+ policyState: 'active',
+ policyRevision: 2,
+ createdAt: '2026-08-03T00:00:00.000Z',
+ updatedAt: '2026-08-03T00:00:00.000Z',
+ })
+
+ const res = await request(buildApp())
+ .get('/mcp-host/plugin-workload-sdk/capabilities')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+
+ expect(res.status).toBe(200)
+ expect(res.body).toMatchObject({
+ contractVersion: 3,
+ supportedContractVersions: [2, 3],
+ reservationOnlyOauthBroker: true,
+ defaultProvider: 'codex-subscription',
+ defaultModel: 'gpt-5.1',
+ defaultConnectionRef: 'team-plus',
+ v2Ready: true,
+ })
+ })
})
describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/v2', () => {
@@ -855,6 +903,27 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/finalize', () => {
expect(res.body).toMatchObject({ error: 'idempotency_conflict', retryable: false })
})
+ it('maps a pending Codex ledger to retryable provider_unavailable', async () => {
+ vi.mocked(finalizer.finalizePromptBridge).mockRejectedValue(
+ new finalizer.PromptBridgeFinalizationError(
+ 'ledger_pending',
+ 'linked Codex attempt has not finalized usage yet',
+ 409,
+ true
+ )
+ )
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send(finalizationBody)
+ expect(res.status).toBe(409)
+ expect(res.body).toMatchObject({
+ error: 'provider_unavailable',
+ retryable: true,
+ reason: 'provider_unavailable',
+ })
+ })
+
it('accepts empty Codex credential fields and defers auth-mode rules to the service', async () => {
vi.mocked(finalizer.finalizePromptBridge).mockResolvedValue({
invocationId: 'inv-1',
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index 44f427fc8..89eef2f17 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -498,6 +498,101 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
expect(insert?.[1]).toEqual(expect.arrayContaining([IDS.providerAttempt, 'exact', 12, 7]))
})
+ it('refuses Codex complete while a linked attempt is still in flight', async () => {
+ ingest.mockReset()
+ project.mockReset()
+ const db = dbWithRows(
+ [],
+ [],
+ {
+ id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ method: 'promptBridge',
+ status: 'in_progress',
+ attempt_generation: 1,
+ },
+ {
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ method: 'promptBridge',
+ status: 'in_progress',
+ },
+ {
+ id: IDS.providerAttempt,
+ invocation_id: IDS.invocation,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ attempt_generation: 1,
+ attempt_index: 1,
+ target_ref: 'codex-primary',
+ host_ref: inputBase.hostRef,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credential_slot: '',
+ status: 'in_progress',
+ },
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ caller_kind: 'recipe',
+ host_ref: inputBase.hostRef,
+ recipe_namespace: inputBase.recipeNamespace,
+ recipe_name: inputBase.recipeName,
+ invocation_id: IDS.invocation,
+ attempt_generation: 1,
+ provider_attempt_index: 1,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ request_hash: 'hash',
+ policy_revision: 1,
+ policy_hash: 'a'.repeat(64),
+ budget_reservation_id: 'budget-1',
+ connection_revision: 1,
+ status: 'authorized',
+ outcome: null,
+ usage_input_tokens: null,
+ usage_output_tokens: null,
+ created_at: new Date('2026-08-03T00:00:00.000Z'),
+ }
+ )
+
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ ...inputBase,
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ },
+ status: 'complete',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 4,
+ outputTokens: 2,
+ },
+ },
+ db as never
+ )
+ ).rejects.toMatchObject({
+ code: 'ledger_pending',
+ httpStatus: 409,
+ retryable: true,
+ })
+ expect(
+ db.query.mock.calls.some(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ ).toBe(false)
+ expect(ingest).not.toHaveBeenCalled()
+ })
+
it('records Codex complete without a linked success as unknown without fabricated tokens', async () => {
ingest.mockReset()
project.mockReset()
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 4649d7587..7a7fa2602 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.306",
+ "version": "0.1.307",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.306",
+ "version": "0.1.307",
"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 aad4c677e..ca5ac84c6 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.306",
+ "version": "0.1.307",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
index 95e1e228d..464f6ef74 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
@@ -1,6 +1,8 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import { CircuitBreaker } from '../domain/circuitBreaker'
import { PluginWorkloadError } from '../domain/errors'
+import { replaceSdkOnlyCodexBinding } from '../sdkOnlyCodexBinding'
import { PluginWorkloadSdkControlApiClient } from './controlApiClient'
const promptBody = {
@@ -54,6 +56,27 @@ function makeClient(fetchImpl: typeof fetch, breaker?: CircuitBreaker) {
})
}
+function installCodexBinding(model = 'gpt-5.1') {
+ const binding = {
+ connectionKey: 'team-plus',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ model,
+ bindingHash: computeCodexPolicyHash({
+ model,
+ catalogRevision: 4,
+ credentialRevision: 1,
+ connectionKey: 'team-plus',
+ }),
+ }
+ replaceSdkOnlyCodexBinding(binding)
+ return binding
+}
+
+afterEach(() => {
+ replaceSdkOnlyCodexBinding(null)
+})
+
describe('PluginWorkloadSdkControlApiClient', () => {
it('posts to the gateway with the mcp-host bearer token', async () => {
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, authorizedBody('inv-1')))
@@ -118,6 +141,75 @@ describe('PluginWorkloadSdkControlApiClient', () => {
)
})
+ it('requires reservation-only Codex capabilities before marking policy ready', async () => {
+ installCodexBinding()
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(200, {
+ contractVersion: 3,
+ supportedContractVersions: [2, 3],
+ reservationOnlyOauthBroker: true,
+ targetAwarePromptBridge: true,
+ attemptLedger: true,
+ credentialTickets: true,
+ policyState: 'active',
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ defaultTargetRef: 'codex-primary',
+ defaultProvider: 'codex-subscription',
+ defaultModel: 'gpt-5.1',
+ defaultConnectionRef: 'team-plus',
+ v2Ready: true,
+ clientNotificationsPolicyState: 'missing',
+ clientNotificationsReady: false,
+ })
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.verifyPromptBridgeBootstrapV2('codex-subscription', 'gpt-5.1')
+ ).resolves.toMatchObject({
+ ready: true,
+ contractVersion: 3,
+ policyReady: true,
+ policyState: 'active',
+ codexBindingReady: true,
+ })
+ })
+
+ it('keeps Codex policy not ready when an old API advertises contract v2', async () => {
+ installCodexBinding()
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(200, {
+ contractVersion: 2,
+ supportedContractVersions: [2, 3],
+ targetAwarePromptBridge: true,
+ attemptLedger: true,
+ credentialTickets: true,
+ policyState: 'active',
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ defaultTargetRef: 'codex-primary',
+ defaultProvider: 'codex-subscription',
+ defaultModel: 'gpt-5.1',
+ defaultConnectionRef: 'team-plus',
+ v2Ready: true,
+ clientNotificationsPolicyState: 'missing',
+ clientNotificationsReady: false,
+ })
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.verifyPromptBridgeBootstrapV2('codex-subscription', 'gpt-5.1')
+ ).resolves.toMatchObject({
+ ready: true,
+ contractVersion: 3,
+ policyReady: false,
+ policyReason: 'codex_execution_binding_missing',
+ codexBindingReady: false,
+ })
+ })
+
it('keeps request-time policy readiness separate from identity bootstrap', async () => {
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(200, {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index b7ddd9b5e..8abe68351 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -68,6 +68,8 @@ export interface PluginWorkloadSdkCapabilities {
defaultModel: string | null
defaultConnectionRef: string | null
v2Ready: boolean
+ /** Present only when the grant default is oauth-broker (reservation-only Codex). */
+ reservationOnlyOauthBroker?: true
clientNotificationsPolicyState: string
clientNotificationsReady: boolean
}
@@ -210,6 +212,7 @@ function isPluginWorkloadSdkCapabilities(v: unknown): v is PluginWorkloadSdkCapa
value.defaultConnectionRef === null ||
typeof value.defaultConnectionRef === 'string') &&
typeof value.v2Ready === 'boolean' &&
+ (value.reservationOnlyOauthBroker === undefined || value.reservationOnlyOauthBroker === true) &&
typeof value.clientNotificationsPolicyState === 'string' &&
typeof value.clientNotificationsReady === 'boolean'
)
@@ -590,9 +593,13 @@ export class PluginWorkloadSdkControlApiClient {
)
}
const binding = expectedProvider === 'codex-subscription' ? readSdkOnlyCodexBinding() : null
+ const reservationOnlyReady = capabilities.reservationOnlyOauthBroker === true
+ const contractReady =
+ capabilities.contractVersion === 3 && capabilities.supportedContractVersions.includes(3)
const codexBindingReady =
expectedProvider !== 'codex-subscription' ||
- (capabilities.supportedContractVersions.includes(3) &&
+ (reservationOnlyReady &&
+ contractReady &&
binding !== null &&
capabilities.defaultProvider === expectedProvider &&
capabilities.defaultModel === expectedModel &&
@@ -610,16 +617,16 @@ export class PluginWorkloadSdkControlApiClient {
codexBindingReady
const policyReason = policyReady
? undefined
- : expectedProvider === 'codex-subscription' && !codexBindingReady
- ? 'codex_execution_binding_missing'
- : capabilities.policyState === 'missing'
- ? 'grant_missing'
- : capabilities.policyState === 'legacy_unreviewed'
- ? 'policy_unreviewed'
- : capabilities.policyState === 'revoking'
- ? 'policy_revoking'
- : capabilities.policyState === 'disabled'
- ? 'policy_disabled'
+ : capabilities.policyState === 'missing'
+ ? 'grant_missing'
+ : capabilities.policyState === 'legacy_unreviewed'
+ ? 'policy_unreviewed'
+ : capabilities.policyState === 'revoking'
+ ? 'policy_revoking'
+ : capabilities.policyState === 'disabled'
+ ? 'policy_disabled'
+ : expectedProvider === 'codex-subscription' && !codexBindingReady
+ ? 'codex_execution_binding_missing'
: capabilities.v2Ready
? 'bootstrap_target_mismatch'
: 'policy_not_ready'
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
index e551017df..ca536da8c 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
@@ -445,6 +445,49 @@ describe('PromptBridgeHandler', () => {
expect(report).not.toHaveBeenCalled()
})
+ it('retries a retryable complete finalization before treating the outcome as unknown', async () => {
+ const finalize = vi
+ .fn<FinalizePromptBridge>()
+ .mockRejectedValueOnce(
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'linked Codex attempt has not finalized usage yet',
+ true,
+ 'provider_unavailable'
+ )
+ )
+ .mockResolvedValueOnce({
+ invocationId: 'inv-1',
+ providerAttemptId: 'attempt-1',
+ status: 'complete',
+ outcome: 'exact',
+ idempotent: false,
+ usageAccepted: false,
+ })
+ const complete = vi.fn().mockResolvedValue({
+ model: fallback.model,
+ servedTarget: fallback,
+ fallbackUsed: true,
+ attemptCount: 2,
+ llmSecretName: 'provider-secret',
+ providerAttemptId: 'attempt-1',
+ providerAttemptIndex: 2,
+ content: 'summary text',
+ usage: { inputTokens: 10, outputTokens: 5 },
+ finishReason: 'complete',
+ })
+ const { handler, report } = makeDeps({ complete, finalize })
+
+ await expect(handler.handle(validBody, 'api')).resolves.toMatchObject({
+ invocationId: 'inv-1',
+ content: 'summary text',
+ })
+ expect(finalize).toHaveBeenCalledTimes(2)
+ expect(finalize).toHaveBeenNthCalledWith(1, expect.objectContaining({ status: 'complete' }))
+ expect(finalize).toHaveBeenNthCalledWith(2, expect.objectContaining({ status: 'complete' }))
+ expect(report).not.toHaveBeenCalled()
+ })
+
it('reconciles an exact-finalization failure into a durable unknown receipt', async () => {
const finalize = vi
.fn<FinalizePromptBridge>()
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
index 9230d0aed..1214fe0da 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
@@ -36,6 +36,32 @@ import type { LlmBridge } from './llmBridge'
const IDEMPOTENCY_KEY_RE = new RegExp(DEFAULT_IDEMPOTENCY_KEY_PATTERN)
const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)
const MAX_METADATA_BYTES = 16 * 1024
+const FINALIZE_LEDGER_RETRIES = 4
+const FINALIZE_LEDGER_DELAY_MS = 50
+
+async function finalizeCompleteWithLedgerRetry(
+ finalize: NonNullable<PromptBridgeHandlerDeps['finalizePromptBridge']>,
+ input: Parameters<NonNullable<PromptBridgeHandlerDeps['finalizePromptBridge']>>[0]
+): Promise<void> {
+ let lastError: unknown
+ for (let attempt = 0; attempt < FINALIZE_LEDGER_RETRIES; attempt++) {
+ try {
+ await finalize(input)
+ return
+ } catch (error) {
+ lastError = error
+ if (
+ !(error instanceof PluginWorkloadError) ||
+ error.retryable !== true ||
+ attempt === FINALIZE_LEDGER_RETRIES - 1
+ ) {
+ throw error
+ }
+ await new Promise(resolve => setTimeout(resolve, FINALIZE_LEDGER_DELAY_MS))
+ }
+ }
+ throw lastError
+}
/**
* A provider response is already potentially billable when this acknowledgement
@@ -388,7 +414,7 @@ export class PromptBridgeHandler {
providerAttemptIndex >= 1
) {
try {
- await this.deps.finalizePromptBridge({
+ await finalizeCompleteWithLedgerRetry(this.deps.finalizePromptBridge, {
invocationId: authorized.invocationId,
attemptGeneration: authorized.attemptGeneration,
providerAttemptId,