Skip to content

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

TypeScript

fix: let sdk-only Codex prompts reserve and finalize through the dual ledger

Alfredo Lopez8e6e68cb44c5
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 6074729cd..b77601d73 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -225,7 +225,8 @@ jobs:
services.llmProviderAttemptAuthorization.realPostgres.integration \
services.llmProviderAttemptStore.realPostgres.integration \
services.llmProviderAttemptRedemption.realPostgres.integration \
- services.llmProviderAttemptFinalization.realPostgres.integration
+ services.llmProviderAttemptFinalization.realPostgres.integration \
+ pluginWorkloadSdkCodexDualLedger.realPostgres.integration
do
grep -Fq "$suite" "$normalized_log" || {
echo "real-Postgres control-api lane omitted Codex suite ${suite}" >&2
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d55acd55d..5d430cb4d 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"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 738922c09..fa90332bd 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index b172e91c5..356106f62 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -22,6 +22,7 @@ import {
import {
applyLlmProviderAttemptConnectionIdSchema,
applyLlmProviderAttemptSchema,
+ applyLlmProviderAttemptSdkLinkSchema,
applyLlmProviderAttemptTicketSchema,
} from './services/llmProviderAttemptStore.js'
import { applyMemberRegistrationCredentialsSchema } from './services/memberRegistrationCredentialsSchema.js'
@@ -6004,6 +6005,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
],
apply: applyOAuthGrantsOwnerGeneralization,
},
+ {
+ version: '0107_llm_provider_attempts_sdk_link',
+ apply: applyLlmProviderAttemptSdkLinkSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
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 f5c03695c..1ee6f18b8 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'
@@ -193,7 +194,8 @@ function parsePromptBridgeFinalizationBody(
!targetRef ||
!provider ||
!model ||
- !credentialSlot
+ (!(isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker') &&
+ !credentialSlot)
) {
res.status(400).json({
error:
@@ -217,8 +219,9 @@ function parsePromptBridgeFinalizationBody(
const outputTokens = Number.isInteger(rawUsage.outputTokens)
? Number(rawUsage.outputTokens)
: -1
+ const oauthBroker = isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker'
if (
- !llmSecretName ||
+ (!oauthBroker && !llmSecretName) ||
!callerRef ||
typeof rawUsage.fallbackUsed !== 'boolean' ||
attemptCount < 1 ||
@@ -722,7 +725,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
const primaryTarget = grant?.promptTargets[0] ?? null
res.status(200).json({
contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,
- supportedContractVersions: [2],
+ supportedContractVersions: [2, 3],
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -732,6 +735,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
defaultTargetRef: grant?.defaultTargetRef ?? null,
defaultProvider: primaryTarget?.provider ?? null,
defaultModel: primaryTarget?.model ?? null,
+ defaultConnectionRef: primaryTarget?.connectionRef ?? null,
v2Ready,
clientNotificationsPolicyState: clientNotificationsGrant?.policyState ?? 'missing',
clientNotificationsReady,
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 8576c8209..5228ef56c 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -23,6 +23,7 @@ import {
insertLlmProviderAttempt,
} from './llmProviderAttemptStore.js'
import { issueRegisteredCodexExecutionTicket } from './llmProviderAttemptTicket.js'
+import { getPluginWorkloadSdkProviderAttempt } from './pluginWorkloadSdkDb.js'
const log = rootLogger.child({ module: 'llm-provider-attempt-authorizer' })
const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'
@@ -41,7 +42,9 @@ const AUTHORIZE_BODY_KEYS = new Set([
'recipeNamespace',
'recipeName',
'userId',
+ 'pluginWorkloadSdkProviderAttemptId',
])
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export type LlmProviderAttemptAuthorizeErrorCode =
| 'disabled'
@@ -356,6 +359,38 @@ export async function authorizeLlmProviderAttempt(
budgetReservationId = budget.reservationIds?.[0] ?? 'unbudgeted'
}
+ const pluginWorkloadSdkProviderAttemptId =
+ typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
+ ? body.pluginWorkloadSdkProviderAttemptId.trim()
+ : ''
+ if (pluginWorkloadSdkProviderAttemptId) {
+ if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'invalid_request',
+ 'pluginWorkloadSdkProviderAttemptId must be a UUID'
+ )
+ }
+ const sdkAttempt = await getPluginWorkloadSdkProviderAttempt(
+ pluginWorkloadSdkProviderAttemptId,
+ db
+ )
+ if (
+ !sdkAttempt ||
+ sdkAttempt.invocationId !== invocationId ||
+ sdkAttempt.attemptGeneration !== attemptGeneration ||
+ sdkAttempt.attemptIndex !== providerAttemptIndex ||
+ sdkAttempt.recipeNamespace !== caller.recipeNamespace ||
+ sdkAttempt.recipeName !== caller.recipeName ||
+ sdkAttempt.provider !== PROVIDER ||
+ !['reserved', 'in_progress'].includes(sdkAttempt.status)
+ ) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
+ )
+ }
+ }
+
try {
const attempt = await resolvedDeps.insertAttempt(db, {
callerKind: caller.callerKind,
@@ -372,6 +407,7 @@ export async function authorizeLlmProviderAttempt(
budgetReservationId,
connectionRevision: connection.credentialRevision,
connectionId: connection.id,
+ ...(pluginWorkloadSdkProviderAttemptId ? { pluginWorkloadSdkProviderAttemptId } : {}),
})
const issued = await resolvedDeps.issueTicket(db, {
sub: claims.sub,
diff --git a/control-api/src/services/llmProviderAttemptStore.ts b/control-api/src/services/llmProviderAttemptStore.ts
index 2589af50d..2318a4a9f 100644
--- a/control-api/src/services/llmProviderAttemptStore.ts
+++ b/control-api/src/services/llmProviderAttemptStore.ts
@@ -22,6 +22,7 @@ export type LlmProviderAttemptInsert = {
connectionRevision: number
connectionId?: string | null
correlationId?: string | null
+ pluginWorkloadSdkProviderAttemptId?: string | null
}
export type LlmProviderAttemptRow = LlmProviderAttemptInsert & {
@@ -29,6 +30,8 @@ export type LlmProviderAttemptRow = LlmProviderAttemptInsert & {
provider: typeof LLM_PROVIDER_ATTEMPT_PROVIDER
status: LlmProviderAttemptStatus
outcome: LlmProviderAttemptOutcome | null
+ usageInputTokens?: number | null
+ usageOutputTokens?: number | null
createdAt: Date
}
@@ -90,6 +93,18 @@ export async function applyLlmProviderAttemptConnectionIdSchema(db: DbClient): P
`)
}
+export async function applyLlmProviderAttemptSdkLinkSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE llm_provider_attempts
+ ADD COLUMN IF NOT EXISTS plugin_workload_sdk_provider_attempt_id UUID
+ REFERENCES plugin_workload_sdk_provider_attempts(id);
+
+ CREATE UNIQUE INDEX IF NOT EXISTS llm_provider_attempts_sdk_attempt_uidx
+ ON llm_provider_attempts (plugin_workload_sdk_provider_attempt_id)
+ WHERE plugin_workload_sdk_provider_attempt_id IS NOT NULL;
+ `)
+}
+
export async function applyLlmProviderAttemptTicketSchema(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS llm_provider_attempt_tickets (
@@ -120,15 +135,16 @@ export async function insertLlmProviderAttempt(
caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- connection_id, status, correlation_id
+ connection_id, plugin_workload_sdk_provider_attempt_id, status, correlation_id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, 'codex-subscription', $8, $9, $10, $11, $12, $13,
- $14, 'authorized', $15
+ $14, $15, 'authorized', $16
)
RETURNING id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- connection_id, status, outcome, created_at`,
+ connection_id, plugin_workload_sdk_provider_attempt_id, status, outcome,
+ usage_input_tokens, usage_output_tokens, created_at`,
[
input.callerKind,
input.hostRef,
@@ -144,10 +160,15 @@ export async function insertLlmProviderAttempt(
input.budgetReservationId,
input.connectionRevision,
input.connectionId ?? null,
+ input.pluginWorkloadSdkProviderAttemptId ?? null,
input.correlationId ?? null,
]
)
const row = result.rows[0] as Record<string, unknown>
+ return mapLlmProviderAttemptRow(row)
+}
+
+function mapLlmProviderAttemptRow(row: Record<string, unknown>): LlmProviderAttemptRow {
return {
id: String(row.id),
callerKind: row.caller_kind as 'host' | 'recipe',
@@ -165,8 +186,13 @@ export async function insertLlmProviderAttempt(
budgetReservationId: String(row.budget_reservation_id),
connectionRevision: Number(row.connection_revision),
connectionId: row.connection_id ? String(row.connection_id) : null,
+ pluginWorkloadSdkProviderAttemptId: row.plugin_workload_sdk_provider_attempt_id
+ ? String(row.plugin_workload_sdk_provider_attempt_id)
+ : null,
status: row.status as LlmProviderAttemptStatus,
outcome: (row.outcome as LlmProviderAttemptOutcome | null) ?? null,
+ usageInputTokens: row.usage_input_tokens == null ? null : Number(row.usage_input_tokens),
+ usageOutputTokens: row.usage_output_tokens == null ? null : Number(row.usage_output_tokens),
createdAt: row.created_at instanceof Date ? row.created_at : new Date(String(row.created_at)),
}
}
@@ -199,34 +225,32 @@ export async function loadLlmProviderAttempt(
`SELECT id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- connection_id, status, outcome, created_at
+ connection_id, plugin_workload_sdk_provider_attempt_id, status, outcome,
+ usage_input_tokens, usage_output_tokens, created_at
FROM llm_provider_attempts
WHERE id = $1`,
[id]
)
const row = result.rows[0] as Record<string, unknown> | undefined
- if (!row) return null
- return {
- id: String(row.id),
- callerKind: row.caller_kind as 'host' | 'recipe',
- hostRef: String(row.host_ref),
- recipeNamespace: (row.recipe_namespace as string | null) ?? null,
- recipeName: (row.recipe_name as string | null) ?? null,
- invocationId: String(row.invocation_id),
- attemptGeneration: Number(row.attempt_generation),
- providerAttemptIndex: Number(row.provider_attempt_index),
- provider: LLM_PROVIDER_ATTEMPT_PROVIDER,
- model: String(row.model),
- requestHash: String(row.request_hash),
- policyRevision: Number(row.policy_revision),
- policyHash: String(row.policy_hash),
- budgetReservationId: String(row.budget_reservation_id),
- connectionRevision: Number(row.connection_revision),
- connectionId: row.connection_id ? String(row.connection_id) : null,
- status: row.status as LlmProviderAttemptStatus,
- outcome: (row.outcome as LlmProviderAttemptOutcome | null) ?? null,
- createdAt: row.created_at instanceof Date ? row.created_at : new Date(String(row.created_at)),
- }
+ return row ? mapLlmProviderAttemptRow(row) : null
+}
+
+export async function loadLlmProviderAttemptBySdkAttemptId(
+ db: DbClient,
+ pluginWorkloadSdkProviderAttemptId: string
+): Promise<LlmProviderAttemptRow | null> {
+ const result = await db.query(
+ `SELECT id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
+ attempt_generation, provider_attempt_index, provider, model, request_hash,
+ policy_revision, policy_hash, budget_reservation_id, connection_revision,
+ connection_id, plugin_workload_sdk_provider_attempt_id, status, outcome,
+ usage_input_tokens, usage_output_tokens, created_at
+ FROM llm_provider_attempts
+ WHERE plugin_workload_sdk_provider_attempt_id = $1`,
+ [pluginWorkloadSdkProviderAttemptId]
+ )
+ const row = result.rows[0] as Record<string, unknown> | undefined
+ return row ? mapLlmProviderAttemptRow(row) : null
}
export async function lockLlmProviderAttemptTicket(
diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
index f209c1a65..ff5151c7e 100644
--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
@@ -1,3 +1,4 @@
+import { PROVIDER_AUTH_MODE, isLlmProviderId } from '@clerum/llm-providers'
import { pluginWorkloadSdkAuthDecisionsTotal } from '../observability/metrics.js'
import type { McpHostAccessClaims } from '../utils/auth/mcpHostJwtToken.js'
import {
@@ -514,6 +515,7 @@ export type ReissuedPromptBridgeCredentialTicket = {
providerAttemptId: string
providerAttemptIndex: number
credentialTicket: string
+ reservationOnly?: true
policyRevision: number
policyHash: string
expiresInSeconds: number
@@ -611,6 +613,26 @@ export async function reissuePromptBridgeCredentialTicket(
)
}
+ const reservationOnly =
+ isLlmProviderId(target.provider) && PROVIDER_AUTH_MODE[target.provider] === 'oauth-broker'
+ if (reservationOnly) {
+ return {
+ ok: true,
+ value: {
+ invocationId: invocation.id,
+ targetRef: target.targetRef,
+ attemptGeneration: invocation.attemptGeneration,
+ providerAttemptId: providerAttempt.id,
+ providerAttemptIndex: providerAttempt.attemptIndex,
+ credentialTicket: '',
+ reservationOnly: true,
+ policyRevision: grant.policyRevision,
+ policyHash,
+ expiresInSeconds: PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS,
+ },
+ }
+ }
+
const issued = issuePluginWorkloadSdkCredentialTicketWithClaims({
recipeNamespace: params.claims.recipeNamespace,
recipeName: params.claims.recipeName,
diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.ts
index 6e82d5c89..1330f170b 100644
--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts
+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts
@@ -1,4 +1,6 @@
+import { PROVIDER_AUTH_MODE, isLlmProviderId } from '@clerum/llm-providers'
import type { DbClient } from '../db.js'
+import { loadLlmProviderAttemptBySdkAttemptId } from './llmProviderAttemptStore.js'
import { withTraceIngestTransaction } from './tracing/pools.js'
import { projectAcceptedUsageEvents } from './tracing/usageProjection.js'
import { ingestUsageEventsInTransaction } from './usageEvents.js'
@@ -74,6 +76,10 @@ function requireNonEmpty(value: string, field: string): void {
}
}
+function isOauthBrokerProvider(provider: string): boolean {
+ return isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker'
+}
+
function validateInput(input: PromptBridgeFinalizationInput): void {
requireUuid(input.invocationId, 'invocationId')
requireUuid(input.providerAttemptId, 'providerAttemptId')
@@ -94,7 +100,9 @@ function validateInput(input: PromptBridgeFinalizationInput): void {
requireNonEmpty(input.target.targetRef, 'target.targetRef')
requireNonEmpty(input.target.provider, 'target.provider')
requireNonEmpty(input.target.model, 'target.model')
- requireNonEmpty(input.target.credentialSlot, 'target.credentialSlot')
+ if (!isOauthBrokerProvider(input.target.provider)) {
+ requireNonEmpty(input.target.credentialSlot, 'target.credentialSlot')
+ }
if (input.status === 'complete') {
const usage = input.usage
if (!usage) {
@@ -104,7 +112,9 @@ function validateInput(input: PromptBridgeFinalizationInput): void {
400
)
}
- requireNonEmpty(usage.llmSecretName, 'usage.llmSecretName')
+ if (!isOauthBrokerProvider(input.target.provider)) {
+ requireNonEmpty(usage.llmSecretName, 'usage.llmSecretName')
+ }
requireNonEmpty(usage.callerRef, 'usage.callerRef')
if (!Number.isInteger(usage.attemptCount) || usage.attemptCount < 1 || usage.attemptCount > 4) {
throw new PromptBridgeFinalizationError(
@@ -134,6 +144,53 @@ function validateInput(input: PromptBridgeFinalizationInput): void {
}
}
+function resolvePromptBridgeOutcome(
+ status: PromptBridgeFinalizationStatus,
+ oauthBroker: boolean,
+ linked: {
+ status: string
+ outcome: string | null
+ usageInputTokens?: number | null
+ usageOutputTokens?: number | null
+ } | null
+): 'exact' | 'unknown' | 'not_executed' {
+ if (!oauthBroker) {
+ return status === 'complete' ? 'exact' : status === 'failed' ? 'not_executed' : 'unknown'
+ }
+ if (
+ status === 'complete' &&
+ linked?.outcome === 'success' &&
+ linked.usageInputTokens != null &&
+ linked.usageOutputTokens != null
+ ) {
+ return 'exact'
+ }
+ if (status === 'failed' && !linked) return 'not_executed'
+ return 'unknown'
+}
+
+function replayOutcomeCompatible(
+ input: PromptBridgeFinalizationInput,
+ row: SpendOutcomeRow
+): boolean {
+ const oauthBroker = isOauthBrokerProvider(input.target.provider)
+ if (!oauthBroker) {
+ const expectedOutcome =
+ input.status === 'complete' ? 'exact' : input.status === 'failed' ? 'not_executed' : 'unknown'
+ if (row.outcome !== expectedOutcome) return false
+ return (
+ expectedOutcome !== 'exact' ||
+ (Number(row.input_tokens) === input.usage?.inputTokens &&
+ Number(row.output_tokens) === input.usage?.outputTokens)
+ )
+ }
+ if (input.status === 'complete') return row.outcome === 'exact' || row.outcome === 'unknown'
+ if (input.status === 'failed') {
+ return row.outcome === 'not_executed' || row.outcome === 'unknown'
+ }
+ return row.outcome === 'unknown'
+}
+
type SpendOutcomeRow = {
provider_attempt_id: string
invocation_id: string
@@ -155,8 +212,6 @@ function mapExistingOutcome(
row: SpendOutcomeRow,
input: PromptBridgeFinalizationInput
): PromptBridgeFinalizationResult {
- const expectedOutcome =
- input.status === 'complete' ? 'exact' : input.status === 'failed' ? 'not_executed' : 'unknown'
if (
row.invocation_id !== input.invocationId ||
row.recipe_namespace !== input.recipeNamespace ||
@@ -168,10 +223,7 @@ function mapExistingOutcome(
row.provider !== input.target.provider ||
row.model !== input.target.model ||
row.credential_slot !== input.target.credentialSlot ||
- row.outcome !== expectedOutcome ||
- (expectedOutcome === 'exact' &&
- (Number(row.input_tokens) !== input.usage?.inputTokens ||
- Number(row.output_tokens) !== input.usage?.outputTokens))
+ !replayOutcomeCompatible(input, row)
) {
throw new PromptBridgeFinalizationError(
'conflict',
@@ -185,7 +237,7 @@ function mapExistingOutcome(
status: input.status,
outcome: row.outcome,
idempotent: true,
- usageAccepted: row.outcome === 'exact',
+ usageAccepted: row.outcome === 'exact' && !isOauthBrokerProvider(input.target.provider),
}
}
@@ -322,8 +374,11 @@ export async function finalizePromptBridgeInTransaction(
)
}
- const outcome =
- input.status === 'complete' ? 'exact' : input.status === 'failed' ? 'not_executed' : 'unknown'
+ const oauthBroker = isOauthBrokerProvider(input.target.provider)
+ const linkedCodex = oauthBroker
+ ? await loadLlmProviderAttemptBySdkAttemptId(db, input.providerAttemptId)
+ : null
+ const outcome = resolvePromptBridgeOutcome(input.status, oauthBroker, linkedCodex)
let usageAccepted = false
// Promote the immutable physical and attempt receipts before exact usage is
@@ -436,8 +491,8 @@ export async function finalizePromptBridgeInTransaction(
input.target.credentialSlot,
outcome,
input.reason,
- input.usage?.inputTokens ?? null,
- input.usage?.outputTokens ?? null,
+ oauthBroker ? (linkedCodex?.usageInputTokens ?? null) : (input.usage?.inputTokens ?? null),
+ oauthBroker ? (linkedCodex?.usageOutputTokens ?? null) : (input.usage?.outputTokens ?? null),
input.status === 'complete' ? input.providerAttemptId : null,
]
)
diff --git a/control-api/test/db.llmProviderAttemptMigration.test.ts b/control-api/test/db.llmProviderAttemptMigration.test.ts
index 925b29b0a..5578e273e 100644
--- a/control-api/test/db.llmProviderAttemptMigration.test.ts
+++ b/control-api/test/db.llmProviderAttemptMigration.test.ts
@@ -43,6 +43,22 @@ describe('00a2/00a3 LLM provider-attempt ledger', () => {
)
})
+ it('registers the unique SDK-attempt link after the latest Codex OAuth owner migration', () => {
+ expect(dbSource).toContain("version: '0106_oauth_grants_owner_generalization'")
+ expect(dbSource).toContain("version: '0107_llm_provider_attempts_sdk_link'")
+ expect(dbSource).toContain('apply: applyLlmProviderAttemptSdkLinkSchema')
+ expect(dbSource.indexOf("version: '0106_oauth_grants_owner_generalization'")).toBeLessThan(
+ dbSource.indexOf("version: '0107_llm_provider_attempts_sdk_link'")
+ )
+ expect(storeSource).toContain('plugin_workload_sdk_provider_attempt_id UUID')
+ expect(storeSource).toContain('REFERENCES plugin_workload_sdk_provider_attempts(id)')
+ expect(storeSource).toContain(
+ 'CREATE UNIQUE INDEX IF NOT EXISTS llm_provider_attempts_sdk_attempt_uidx'
+ )
+ expect(storeSource).toContain('WHERE plugin_workload_sdk_provider_attempt_id IS NOT NULL')
+ expect(storeSource).toContain('loadLlmProviderAttemptBySdkAttemptId')
+ })
+
it('persists immutable attempt bindings, lifecycle, safe usage, and redacted correlation', () => {
expect(storeSource).toContain('CREATE TABLE IF NOT EXISTS llm_provider_attempts')
expect(storeSource).toContain(
diff --git a/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
new file mode 100644
index 000000000..dfbcdf40a
--- /dev/null
+++ b/control-api/test/pluginWorkloadSdkCodexDualLedger.realPostgres.integration.test.ts
@@ -0,0 +1,540 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes, randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { evaluateBudgetCheck } from '../src/services/budgets/check.js'
+import { getActiveReservation } from '../src/services/budgets/reservations.js'
+import { getCodexCatalogModelState } from '../src/services/codexSubscriptionCatalog.js'
+import {
+ getSafeCodexSubscriptionConnection,
+ insertInitialCodexSubscriptionConnection,
+ recordCodexCatalogOutcome,
+} from '../src/services/codexSubscriptionConnection.js'
+import {
+ type LlmProviderAttemptAuthorizerDeps,
+ authorizeLlmProviderAttempt,
+ computeCodexPolicyHash,
+} from '../src/services/llmProviderAttemptAuthorizer.js'
+import {
+ type LlmProviderAttemptInsert,
+ getMaxLlmProviderAttemptGeneration,
+ insertLlmProviderAttempt,
+ loadLlmProviderAttemptBySdkAttemptId,
+} from '../src/services/llmProviderAttemptStore.js'
+import { issueRegisteredCodexExecutionTicket } from '../src/services/llmProviderAttemptTicket.js'
+import { finalizePromptBridgeInTransaction } from '../src/services/pluginWorkloadSdkFinalization.js'
+import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
+import './realPostgres.requirement.ts'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+
+const NS = 'sandbox-recipes'
+const RECIPE = 'prompt-notify'
+const MODEL = 'gpt-5.1'
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+const REQUEST = {
+ schemaVersion: 'codex-completion-request.v1' as const,
+ requestId: 'req-sdk-dual-ledger',
+ idempotencyKey: 'idem-sdk-dual-ledger',
+ provider: 'codex-subscription' as const,
+ model: MODEL,
+ messages: [{ role: 'user' as const, content: 'sdk dual ledger' }],
+}
+
+function recipeClaims(): McpHostAccessClaims {
+ return {
+ sub: `${NS}/${RECIPE}`,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRefs: [`${NS}/${RECIPE}`],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: ['llm:codex:execute'],
+ iss: 'control-api',
+ aud: 'workflow-approvals',
+ jti: randomUUID(),
+ exp: Math.floor(Date.now() / 1000) + 60,
+ }
+}
+
+function hostClaims(): McpHostAccessClaims {
+ return {
+ sub: 'default/research-host',
+ recipeNamespace: 'default',
+ recipeName: 'research-host',
+ hostRefs: ['research-host'],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: ['llm:codex:execute'],
+ iss: 'control-api',
+ aud: 'workflow-approvals',
+ jti: randomUUID(),
+ exp: Math.floor(Date.now() / 1000) + 60,
+ }
+}
+
+function attemptInput(overrides: Partial<LlmProviderAttemptInsert> = {}): LlmProviderAttemptInsert {
+ return {
+ callerKind: 'recipe',
+ hostRef: `${NS}/${RECIPE}`,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ invocationId: `invocation-${randomUUID()}`,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ model: MODEL,
+ requestHash: 'c'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'd'.repeat(64),
+ budgetReservationId: 'reservation-1',
+ connectionRevision: 1,
+ ...overrides,
+ }
+}
+
+describeRealPostgres('Plugin Workload SDK Codex dual ledger on real PostgreSQL', () => {
+ const database = `sdk_codex_dual_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? `postgresql://postgres@${['127', '0', '0', '1'].join('.')}/postgres`,
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ function dbClient() {
+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }
+ }
+
+ function testDeps(
+ overrides: Partial<LlmProviderAttemptAuthorizerDeps> = {}
+ ): LlmProviderAttemptAuthorizerDeps {
+ const db = dbClient()
+ return {
+ enabled: true,
+ db,
+ withTransaction: async work => {
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const result = await work(client as never)
+ await client.query('COMMIT')
+ return result
+ } catch (error) {
+ try {
+ await client.query('ROLLBACK')
+ } catch {
+ // keep the original error
+ }
+ throw error
+ } finally {
+ client.release()
+ }
+ },
+ getConnection: getSafeCodexSubscriptionConnection,
+ getModelState: getCodexCatalogModelState,
+ resolveConnectionKey: async () => 'deployment-default',
+ evaluateBudget: evaluateBudgetCheck,
+ getActiveReservation,
+ getMaxGeneration: getMaxLlmProviderAttemptGeneration,
+ insertAttempt: insertLlmProviderAttempt,
+ issueTicket: issueRegisteredCodexExecutionTicket,
+ ...overrides,
+ }
+ }
+
+ async function seedSdkAttempt(
+ input: {
+ invocationId?: string
+ status?: string
+ provider?: string
+ model?: string
+ credentialSlot?: string
+ targetRef?: string
+ } = {}
+ ): Promise<{ invocationId: string; sdkAttemptId: string }> {
+ const invocationId = input.invocationId ?? randomUUID()
+ await pool.query(
+ `INSERT INTO plugin_workload_sdk_invocations (
+ id, recipe_namespace, recipe_name, caller_ref, method, detail,
+ idempotency_key_hash, status, authorization_decision, contract_version,
+ attempt_generation
+ ) VALUES ($1, $2, $3, 'api', 'promptBridge', 'prompt', $4, 'in_progress',
+ 'allow', 2, 1)`,
+ [invocationId, NS, RECIPE, randomBytes(32).toString('hex')]
+ )
+ await pool.query(
+ `INSERT INTO plugin_workload_sdk_invocation_attempts (
+ invocation_id, recipe_namespace, recipe_name, attempt_generation,
+ method, status
+ ) VALUES ($1, $2, $3, 1, 'promptBridge', 'in_progress')`,
+ [invocationId, NS, RECIPE]
+ )
+ const inserted = await pool.query<{ id: string }>(
+ `INSERT INTO plugin_workload_sdk_provider_attempts (
+ invocation_id, recipe_namespace, recipe_name, attempt_generation,
+ attempt_index, target_ref, provider, model, credential_slot, status
+ ) VALUES ($1, $2, $3, 1, 1, $4, $5, $6, $7, $8)
+ RETURNING id::text AS id`,
+ [
+ invocationId,
+ NS,
+ RECIPE,
+ input.targetRef ?? 'codex-primary',
+ input.provider ?? 'codex-subscription',
+ input.model ?? MODEL,
+ input.credentialSlot ?? '',
+ input.status ?? 'reserved',
+ ]
+ )
+ return { invocationId, sdkAttemptId: inserted.rows[0]!.id }
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ const created = await insertInitialCodexSubscriptionConnection(pool, KEY, {
+ refreshToken: 'refresh-sdk-dual',
+ accountFingerprint: 'fp-sdk-dual',
+ })
+ await recordCodexCatalogOutcome(pool, {
+ catalogStatus: 'ready',
+ expectedCredentialRevision: 1,
+ expectedCatalogRevision: 0,
+ })
+ await pool.query(
+ `INSERT INTO codex_catalog_models
+ (connection_id, model, enabled, source, discovered_at, last_seen_at, stale)
+ VALUES ($1, $2, true, 'discovery', NOW(), NOW(), false)`,
+ [created.id, MODEL]
+ )
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ it('adds a unique nullable FK from Codex attempts onto reserved SDK attempts', async () => {
+ const columns = await pool.query<{ column_name: string }>(
+ `SELECT column_name
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ AND table_name = 'llm_provider_attempts'
+ AND column_name = 'plugin_workload_sdk_provider_attempt_id'`
+ )
+ expect(columns.rows).toHaveLength(1)
+
+ const { sdkAttemptId } = await seedSdkAttempt()
+ const first = await insertLlmProviderAttempt(
+ pool,
+ attemptInput({ pluginWorkloadSdkProviderAttemptId: sdkAttemptId })
+ )
+ expect(first.pluginWorkloadSdkProviderAttemptId).toBe(sdkAttemptId)
+ await expect(
+ insertLlmProviderAttempt(
+ pool,
+ attemptInput({
+ invocationId: `invocation-${randomUUID()}`,
+ providerAttemptIndex: 2,
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ })
+ )
+ ).rejects.toThrow(/duplicate|unique/i)
+
+ const host = await insertLlmProviderAttempt(
+ pool,
+ attemptInput({
+ callerKind: 'host',
+ hostRef: 'research-host',
+ recipeNamespace: null,
+ recipeName: null,
+ invocationId: `host-${randomUUID()}`,
+ })
+ )
+ expect(host.pluginWorkloadSdkProviderAttemptId ?? null).toBeNull()
+ })
+
+ it('authorizes a recipe Codex attempt bound to a reserved SDK attempt id', async () => {
+ const current = await getSafeCodexSubscriptionConnection(pool)
+ expect(current?.status).toBe('connected')
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt()
+ const authorized = await authorizeLlmProviderAttempt(
+ recipeClaims(),
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-${invocationId}`,
+ idempotencyKey: `idem-${invocationId}`,
+ },
+ invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: current!.connectionKey,
+ }),
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ },
+ testDeps()
+ )
+ const linked = await loadLlmProviderAttemptBySdkAttemptId(pool, sdkAttemptId)
+ expect(linked?.id).toBe(authorized.providerAttemptId)
+ expect(linked?.pluginWorkloadSdkProviderAttemptId).toBe(sdkAttemptId)
+ expect(linked?.invocationId).toBe(invocationId)
+ expect(JSON.stringify(authorized)).not.toContain('refresh-sdk-dual')
+ })
+
+ it('authorizes a host Codex attempt without an SDK FK', async () => {
+ const current = await getSafeCodexSubscriptionConnection(pool)
+ const invocationId = `host-invocation-${randomUUID()}`
+ const authorized = await authorizeLlmProviderAttempt(
+ hostClaims(),
+ {
+ request: {
+ ...REQUEST,
+ requestId: `req-${invocationId}`,
+ idempotencyKey: `idem-${invocationId}`,
+ },
+ invocationId,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ policyRevision: current!.catalogRevision,
+ policyHash: computeCodexPolicyHash({
+ model: MODEL,
+ catalogRevision: current!.catalogRevision,
+ credentialRevision: current!.credentialRevision,
+ connectionKey: current!.connectionKey,
+ }),
+ },
+ testDeps()
+ )
+ const stored = await pool.query<{ plugin_workload_sdk_provider_attempt_id: string | null }>(
+ `SELECT plugin_workload_sdk_provider_attempt_id
+ FROM llm_provider_attempts
+ WHERE id = $1`,
+ [authorized.providerAttemptId]
+ )
+ expect(stored.rows[0]?.plugin_workload_sdk_provider_attempt_id).toBeNull()
+ })
+
+ it('finalizes complete plus linked Codex success as exact using Codex usage', async () => {
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'in_progress' })
+ const codex = await insertLlmProviderAttempt(
+ pool,
+ attemptInput({
+ invocationId,
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ })
+ )
+ await pool.query(
+ `UPDATE llm_provider_attempts
+ SET status = 'finalized',
+ outcome = 'success',
+ usage_input_tokens = 12,
+ usage_output_tokens = 7,
+ finalized_at = now()
+ WHERE id = $1`,
+ [codex.id]
+ )
+
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'complete',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'provider_completed',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ pool
+ )
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'exact',
+ usageAccepted: false,
+ })
+ const spend = await pool.query<{
+ outcome: string
+ input_tokens: number
+ output_tokens: number
+ credential_slot: string
+ }>(
+ `SELECT outcome, input_tokens, output_tokens, credential_slot
+ FROM plugin_workload_sdk_spend_outcomes
+ WHERE provider_attempt_id = $1`,
+ [sdkAttemptId]
+ )
+ expect(spend.rows[0]).toEqual({
+ outcome: 'exact',
+ input_tokens: 12,
+ output_tokens: 7,
+ credential_slot: '',
+ })
+ })
+
+ it('finalizes a pre-dispatch Codex miss as not_executed', async () => {
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'reserved' })
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'failed',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'codex_execution_binding_missing',
+ },
+ pool
+ )
+ expect(result).toMatchObject({
+ status: 'failed',
+ outcome: 'not_executed',
+ usageAccepted: false,
+ })
+ const spend = await pool.query<{
+ outcome: string
+ input_tokens: number | null
+ output_tokens: number | null
+ }>(
+ `SELECT outcome, input_tokens, output_tokens
+ FROM plugin_workload_sdk_spend_outcomes
+ WHERE provider_attempt_id = $1`,
+ [sdkAttemptId]
+ )
+ expect(spend.rows[0]).toEqual({
+ outcome: 'not_executed',
+ input_tokens: null,
+ output_tokens: null,
+ })
+ expect(await loadLlmProviderAttemptBySdkAttemptId(pool, sdkAttemptId)).toBeNull()
+ })
+
+ it('finalizes complete without a linked Codex success as unknown', async () => {
+ const { invocationId, sdkAttemptId } = await seedSdkAttempt({ status: 'in_progress' })
+ const result = await finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'complete',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'provider_completed',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 4,
+ outputTokens: 2,
+ },
+ },
+ pool
+ )
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'unknown',
+ usageAccepted: false,
+ })
+ const spend = await pool.query<{
+ outcome: string
+ input_tokens: number | null
+ output_tokens: number | null
+ }>(
+ `SELECT outcome, input_tokens, output_tokens
+ FROM plugin_workload_sdk_spend_outcomes
+ WHERE provider_attempt_id = $1`,
+ [sdkAttemptId]
+ )
+ expect(spend.rows[0]).toEqual({
+ outcome: 'unknown',
+ input_tokens: null,
+ output_tokens: null,
+ })
+
+ await expect(
+ finalizePromptBridgeInTransaction(
+ {
+ invocationId,
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ hostRef: `${NS}/${RECIPE}`,
+ attemptGeneration: 1,
+ providerAttemptId: sdkAttemptId,
+ providerAttemptIndex: 1,
+ status: 'complete',
+ target: {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: MODEL,
+ credentialSlot: '',
+ },
+ reason: 'provider_completed',
+ usage: {
+ llmSecretName: '',
+ callerRef: 'scanner',
+ fallbackUsed: false,
+ attemptCount: 1,
+ inputTokens: 4,
+ outputTokens: 2,
+ },
+ },
+ pool
+ )
+ ).resolves.toMatchObject({ idempotent: true, outcome: 'unknown', 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 f4459cb37..02c02804c 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
@@ -217,7 +217,8 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
expect(res.status).toBe(200)
expect(res.body).toMatchObject({
contractVersion: 2,
- supportedContractVersions: [2],
+ supportedContractVersions: [2, 3],
+ defaultConnectionRef: null,
targetAwarePromptBridge: true,
attemptLedger: true,
credentialTickets: true,
@@ -271,6 +272,8 @@ describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {
defaultTargetRef: 'primary-openai',
defaultProvider: 'openai',
defaultModel: 'gpt-5.4-mini',
+ defaultConnectionRef: null,
+ supportedContractVersions: [2, 3],
v2Ready: true,
})
expect(res.body.policyHash).toMatch(/^[a-f0-9]{64}$/)
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index 2925f16d9..a9d42c7c0 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -8,6 +8,18 @@ import {
} from '../src/services/llmProviderAttemptAuthorizer.js'
import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
+const getPluginWorkloadSdkProviderAttempt = vi.hoisted(() => vi.fn())
+
+vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/services/pluginWorkloadSdkDb.js')>(
+ '../src/services/pluginWorkloadSdkDb.js'
+ )
+ return {
+ ...actual,
+ getPluginWorkloadSdkProviderAttempt,
+ }
+})
+
const REQUEST = {
schemaVersion: 'codex-completion-request.v1' as const,
requestId: 'req-001',
@@ -104,6 +116,7 @@ describe('authorizeLlmProviderAttempt', () => {
beforeEach(() => {
current = deps()
+ getPluginWorkloadSdkProviderAttempt.mockReset()
})
it('authorizes a bound attempt and returns a ticket without persisting messages', async () => {
@@ -135,6 +148,7 @@ describe('authorizeLlmProviderAttempt', () => {
})
)
const persisted = vi.mocked(current.insertAttempt).mock.calls[0]?.[1]
+ expect(persisted).not.toHaveProperty('pluginWorkloadSdkProviderAttemptId')
expect(JSON.stringify(persisted)).not.toContain('hello')
expect(JSON.stringify(result)).not.toMatch(/sk-|refresh|Authorization/i)
})
@@ -167,6 +181,76 @@ describe('authorizeLlmProviderAttempt', () => {
).rejects.toMatchObject({ code: 'unknown_field' })
})
+ it('rejects a non-UUID Plugin Workload SDK attempt id', async () => {
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims(),
+ body({ pluginWorkloadSdkProviderAttemptId: 'not-a-uuid' }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'invalid_request' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
+
+ it('binds a reserved Plugin Workload SDK attempt onto the Codex ledger row', async () => {
+ const sdkAttemptId = '44444444-4444-4444-8444-444444444444'
+ getPluginWorkloadSdkProviderAttempt.mockResolvedValue({
+ id: sdkAttemptId,
+ invocationId: 'invocation-1',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ attemptGeneration: 1,
+ attemptIndex: 1,
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ status: 'reserved',
+ credentialJti: null,
+ startedAt: new Date().toISOString(),
+ leaseExpiresAt: null,
+ completedAt: null,
+ usageRequestId: null,
+ })
+ await authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({ pluginWorkloadSdkProviderAttemptId: sdkAttemptId }),
+ current
+ )
+ expect(getPluginWorkloadSdkProviderAttempt).toHaveBeenCalledWith(
+ sdkAttemptId,
+ expect.anything()
+ )
+ expect(current.insertAttempt).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ pluginWorkloadSdkProviderAttemptId: sdkAttemptId,
+ callerKind: 'recipe',
+ hostRef: 'sandbox-recipes/prompt-notify',
+ })
+ )
+ })
+
+ it('rejects a Plugin Workload SDK attempt that does not match the reserved receipt', async () => {
+ getPluginWorkloadSdkProviderAttempt.mockResolvedValue(null)
+ await expect(
+ authorizeLlmProviderAttempt(
+ claims({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ hostRefs: ['sandbox-recipes/prompt-notify'],
+ }),
+ body({ pluginWorkloadSdkProviderAttemptId: '44444444-4444-4444-8444-444444444444' }),
+ current
+ )
+ ).rejects.toMatchObject({ code: 'no_grant' })
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
+
it('rejects a stale requestHash', async () => {
await expect(
authorizeLlmProviderAttempt(claims(), body({ requestHash: 'a'.repeat(64) }), current)
diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
index cabaea353..07d58a7f0 100644
--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts
@@ -447,9 +447,16 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
host_ref: inputBase.hostRef,
provider: 'codex-subscription',
model: 'gpt-5.1',
- credential_slot: 'codex-oauth',
+ credential_slot: '',
status: 'in_progress',
},
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ status: 'finalized',
+ outcome: 'success',
+ usage_input_tokens: 12,
+ usage_output_tokens: 7,
+ },
{ rows: [], rowCount: 1 },
{ rows: [], rowCount: 1 },
{ rows: [], rowCount: 1 },
@@ -463,11 +470,11 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
targetRef: 'codex-primary',
provider: 'codex-subscription',
model: 'gpt-5.1',
- credentialSlot: 'codex-oauth',
+ credentialSlot: '',
},
status: 'complete',
usage: {
- llmSecretName: 'unused-codex-secret',
+ llmSecretName: '',
callerRef: 'scanner',
fallbackUsed: false,
attemptCount: 1,
@@ -485,5 +492,148 @@ describe('Plugin Workload SDK promptBridge finalization', () => {
})
expect(ingest).not.toHaveBeenCalled()
expect(project).not.toHaveBeenCalled()
+ const insert = db.query.mock.calls.find(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ expect(insert?.[1]).toEqual(expect.arrayContaining([IDS.providerAttempt, 'exact', 12, 7]))
+ })
+
+ it('records Codex complete without a linked success as unknown without fabricated tokens', 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',
+ },
+ [],
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 },
+ { rows: [], rowCount: 1 }
+ )
+
+ const result = await 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
+ )
+
+ expect(result).toMatchObject({
+ status: 'complete',
+ outcome: 'unknown',
+ usageAccepted: false,
+ })
+ const insert = db.query.mock.calls.find(([statement]: [string]) =>
+ statement.includes('INSERT INTO plugin_workload_sdk_spend_outcomes')
+ )
+ expect(insert?.[1]).toEqual([
+ IDS.providerAttempt,
+ IDS.invocation,
+ inputBase.recipeNamespace,
+ inputBase.recipeName,
+ 1,
+ 1,
+ 'codex-primary',
+ inputBase.hostRef,
+ 'codex-subscription',
+ 'gpt-5.1',
+ '',
+ 'unknown',
+ 'provider_completed',
+ null,
+ null,
+ IDS.providerAttempt,
+ ])
+ })
+
+ it('replays a Codex unknown complete finalization idempotently', async () => {
+ const row = {
+ provider_attempt_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: '',
+ outcome: 'unknown',
+ input_tokens: null,
+ output_tokens: null,
+ }
+ 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,
+ },
+ },
+ dbWithRows([], row) as never
+ )
+ ).resolves.toMatchObject({
+ idempotent: true,
+ outcome: 'unknown',
+ usageAccepted: false,
+ })
})
})
diff --git a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
index 36d08c04e..9f48d869f 100644
--- a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
@@ -17,6 +17,13 @@ import {
sqlLiteral,
} from './third-party-authn-first-party-mcphost/workflowApprovalJourney'
+/*
+ * E2E_GUARDIAN_IPC_FLOW: Desktop Apps opens the Plugin Workload SDK sandbox UI
+ * through the main-process WebContentsView and EmbeddedContents bridge. The
+ * renderer has no HTTP response to await for that transition; the recipe
+ * precondition, native view title, and persisted promptBridge ledger are the
+ * visible/business signals.
+ */
const RUN_ENABLED = process.env.E2E_PLUGIN_SDK_DESKTOP === '1'
const APP_TITLE = process.env.E2E_PLUGIN_SDK_APP_TITLE || 'Prompt & Notify'
const RECIPE_NAME = process.env.E2E_PLUGIN_SDK_RECIPE_NAME || 'evenfire-prompt-notify-app'
@@ -40,7 +47,7 @@ type NativeLayout = {
embeddedCaptureSize: { width: number; height: number } | null
}
-function assertSteplessSdkRecipePrecondition(): void {
+function assertSteplessSdkRecipePrecondition(): { provider: string; model: string } {
const context =
process.env.E2E_K8S_CONTEXT || process.env.KUBECONTEXT || process.env.K8S_CONTEXT || ''
if (!context) throw new Error('E2E_K8S_CONTEXT is required for the stepless recipe precondition.')
@@ -88,9 +95,9 @@ function assertSteplessSdkRecipePrecondition(): void {
) {
throw new Error('Desktop candidate must declare a resolvable spec.agent bootstrap.')
}
- if (!['openai', 'claude'].includes(spec.agent.provider.toLowerCase())) {
+ if (!['openai', 'claude', 'codex-subscription'].includes(spec.agent.provider.toLowerCase())) {
throw new Error(
- `Desktop T3 candidate must use OpenAI or Claude; received provider ${spec.agent.provider}.`
+ `Desktop T3 candidate must use OpenAI, Claude, or Codex; received provider ${spec.agent.provider}.`
)
}
if (!Array.isArray(spec.workloads) || spec.workloads.length === 0) {
@@ -102,6 +109,7 @@ function assertSteplessSdkRecipePrecondition(): void {
) {
throw new Error('Desktop candidate must declare the pluginWorkloadSdk.promptBridge object.')
}
+ return { provider: spec.agent.provider, model: spec.agent.model }
}
async function findPromptNotifyContents(
@@ -427,6 +435,38 @@ function sdkInvocationCount(method: 'promptBridge' | 'clientNotifications'): num
return Number.parseInt(raw, 10) || 0
}
+function promptBridgeLedgerForRun(startedAt: string): {
+ invocationId: string
+ sdkAttemptId: string
+ codexAttemptId: string
+ spendOutcome: string
+} {
+ const raw = profilesSql(`
+ SELECT inv.id::text || '|' || sdk.id::text || '|' ||
+ coalesce(codex.id::text, '') || '|' || coalesce(spend.outcome, '')
+ FROM plugin_workload_sdk_invocations inv
+ JOIN plugin_workload_sdk_provider_attempts sdk
+ ON sdk.invocation_id = inv.id
+ LEFT JOIN llm_provider_attempts codex
+ ON codex.plugin_workload_sdk_provider_attempt_id = sdk.id
+ LEFT JOIN plugin_workload_sdk_spend_outcomes spend
+ ON spend.provider_attempt_id = sdk.id
+ WHERE inv.recipe_namespace = ${sqlLiteral(RECIPE_NAMESPACE)}
+ AND inv.recipe_name = ${sqlLiteral(RECIPE_NAME)}
+ AND inv.method = 'promptBridge'
+ AND inv.created_at >= ${sqlLiteral(startedAt)}::timestamptz
+ ORDER BY inv.created_at ASC, sdk.attempt_index ASC
+ LIMIT 1;
+ `)
+ const [invocationId, sdkAttemptId, codexAttemptId, spendOutcome] = raw.trim().split('|')
+ return {
+ invocationId: invocationId ?? '',
+ sdkAttemptId: sdkAttemptId ?? '',
+ codexAttemptId: codexAttemptId ?? '',
+ spendOutcome: spendOutcome ?? '',
+ }
+}
+
function latestSdkInvocationStatus(method: 'promptBridge' | 'clientNotifications'): string {
return profilesSql(`
SELECT status
@@ -458,7 +498,7 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
// Read-only setup assertion. Every functional action that follows is through
// the real Desktop UI and its native WebContentsView.
- assertSteplessSdkRecipePrecondition()
+ const recipeAgent = assertSteplessSdkRecipePrecondition()
let app: ElectronApplication | undefined
let page: Page | undefined
@@ -532,6 +572,7 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
}
const marker = `desktop-sdk-${Date.now()}`
+ const runStartedAt = new Date().toISOString()
await test.step('reject an empty prompt without creating an invocation', async () => {
const before = sdkInvocationCount('promptBridge')
@@ -569,6 +610,15 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
})
const promptResult = await embeddedText(app, webContentsId, '#prompt-out')
expect(promptResult).not.toMatch(/"error"|provider_unavailable|requires a resolvable agent/i)
+ const ledger = promptBridgeLedgerForRun(runStartedAt)
+ expect(ledger.invocationId).toMatch(/^[0-9a-f-]{36}$/i)
+ expect(ledger.sdkAttemptId).toMatch(/^[0-9a-f-]{36}$/i)
+ expect(ledger.sdkAttemptId).not.toBe(ledger.invocationId)
+ if (recipeAgent.provider.toLowerCase() === 'codex-subscription') {
+ expect(ledger.codexAttemptId).toMatch(/^[0-9a-f-]{36}$/i)
+ expect(ledger.codexAttemptId).not.toBe(ledger.sdkAttemptId)
+ expect(ledger.spendOutcome).toBe('exact')
+ }
// Business signal for notifications: the real app loaded the grant-backed
// recipient list and the native view selected a visible email handle. The
@@ -671,3 +721,55 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
await finalizeRecording(app, page)
}
})
+
+test('Desktop Apps refuses a Codex prompt when the execution binding is missing', async ({}, testInfo) => {
+ test.skip(
+ process.env.E2E_PLUGIN_SDK_NO_GRANT !== '1',
+ 'Set E2E_PLUGIN_SDK_NO_GRANT=1 to exercise the no-grant Codex guard.'
+ )
+ const recipeAgent = assertSteplessSdkRecipePrecondition()
+ test.skip(
+ recipeAgent.provider.toLowerCase() !== 'codex-subscription',
+ 'No-grant guard requires a Codex SDK-only recipe.'
+ )
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+
+ let app: ElectronApplication | undefined
+ let page: Page | undefined
+ try {
+ const credentials = desktopCredentials()
+ const launched = await launchDesktopApp(testInfo)
+ app = launched.app
+ page = launched.page
+ await login(page, credentials)
+ await page.getByTestId('nav-sandbox-ui').click()
+ const appCard = page
+ .getByRole('main')
+ .getByRole('button', { name: `Open ${APP_TITLE}`, exact: true })
+ await appCard.click()
+ let embedded: EmbeddedContents | null = null
+ await expect
+ .poll(async () => {
+ embedded = await findPromptNotifyContents(app!)
+ return embedded?.url ?? ''
+ })
+ .toContain(
+ `/api/v1/sandbox-ui/${encodeURIComponent(RECIPE_NAMESPACE)}/${encodeURIComponent(RECIPE_NAME)}/view/`
+ )
+ const webContentsId = embedded!.id
+ const runStartedAt = new Date().toISOString()
+ const before = sdkInvocationCount('promptBridge')
+ await typeEmbedded(app, webContentsId, '#prompt', 'This prompt must not dispatch Codex.')
+ await activateEmbedded(app, webContentsId, '#run')
+ await expect
+ .poll(() => embeddedText(app!, webContentsId, '#prompt-out'), { timeout: 60_000 })
+ .toMatch(/provider_unavailable|no_grant|not authorized|policy/i)
+ const ledger = promptBridgeLedgerForRun(runStartedAt)
+ expect(ledger.codexAttemptId).toBe('')
+ expect(ledger.spendOutcome).not.toBe('exact')
+ expect(sdkInvocationCount('promptBridge')).toBeGreaterThanOrEqual(before)
+ } finally {
+ await finalizeRecording(app, page)
+ }
+})
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 79c2c67d1..39de989fe 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.303",
+ "version": "0.1.304",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.303",
+ "version": "0.1.304",
"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 5384b9af6..84c36a4dd 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.303",
+ "version": "0.1.304",
"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/codexSubscription.ts b/mcp-host/src/llm/codexSubscription.ts
index da152b20a..704a57f60 100644
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@ -22,6 +22,7 @@ export type CodexAttemptContext = {
invocationId?: string
attemptGeneration?: number
providerAttemptIndex?: number
+ pluginWorkloadSdkProviderAttemptId?: string
policyRevision: number
policyHash: string
hostRef?: string
@@ -259,6 +260,9 @@ export class CodexSubscriptionProvider implements SingleTurnProvider {
recipeNamespace: context.recipeNamespace,
recipeName: context.recipeName,
userId: context.userId,
+ ...(context.pluginWorkloadSdkProviderAttemptId
+ ? { pluginWorkloadSdkProviderAttemptId: context.pluginWorkloadSdkProviderAttemptId }
+ : {}),
})
if (!('accessToken' in authorized)) {
// Bound: authorize returns ticket material only.
diff --git a/mcp-host/src/llm/index.ts b/mcp-host/src/llm/index.ts
index 972eda63a..668bf24fc 100644
--- a/mcp-host/src/llm/index.ts
+++ b/mcp-host/src/llm/index.ts
@@ -7,6 +7,7 @@ import { ClaudeProvider } from './claude'
import { CodexLlmProxyClient, resolveCodexProxyRuntimeUrl } from './codexLlmProxyClient'
import { readCodexPlatformJwt, refreshCodexPlatformJwt } from './codexPlatformJwt'
import { readLiveCodexPolicyBinding, resolveCodexAttemptPolicy } from './codexPolicyBinding'
+import type { CodexAttemptContext } from './codexSubscription'
import { OpenAIProvider } from './openai'
import { ProviderAttemptAuthorizer, resolveCodexAuthorizeUrl } from './providerAttemptAuthorizer'
import { makeProvider } from './registry'
@@ -21,7 +22,7 @@ export type { ClassifiedError, SingleTurnProvider } from './types'
const DEFAULT_CODEX_AUTHORIZE_GATEWAY =
'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092'
-function createCodexRuntimeDeps() {
+function createCodexRuntimeDeps(captured?: CodexAttemptContext) {
const gateway = (config.mcpHostGatewayUrl ?? '').trim() || DEFAULT_CODEX_AUTHORIZE_GATEWAY
return {
authorizer: new ProviderAttemptAuthorizer({
@@ -34,7 +35,8 @@ function createCodexRuntimeDeps() {
readPlatformJwt: readCodexPlatformJwt,
refreshOnUnauthorized: refreshCodexPlatformJwt,
}),
- attemptContext: ({ model }: { model: string }) => {
+ attemptContext: ({ model }: { model: string }): CodexAttemptContext => {
+ if (captured) return captured
const resolved = resolveCodexAttemptPolicy({
model,
envRevision: config.codexPolicyRevision,
@@ -52,12 +54,17 @@ function createCodexRuntimeDeps() {
}
}
+export type CreateLlmProviderOptions = {
+ capturedCodexAttemptContext?: CodexAttemptContext
+}
+
/**
* Create an LLM provider based on configuration.
*/
export function createLLMProvider(
keys: ApiKeys,
- modelConfig?: ModelConfig
+ modelConfig?: ModelConfig,
+ options?: CreateLlmProviderOptions
): SingleTurnProvider | null {
const provider = modelConfig?.provider || 'openai'
const modelName = modelConfig?.name
@@ -90,7 +97,9 @@ export function createLLMProvider(
provider,
credentials,
modelName,
- provider === 'codex-subscription' ? { codex: createCodexRuntimeDeps() } : undefined
+ provider === 'codex-subscription'
+ ? { codex: createCodexRuntimeDeps(options?.capturedCodexAttemptContext) }
+ : undefined
)
} catch (err) {
console.error('[LLM] failed to construct provider')
diff --git a/mcp-host/src/llm/providerAttemptAuthorizer.ts b/mcp-host/src/llm/providerAttemptAuthorizer.ts
index ba25b0b3c..0320957a0 100644
--- a/mcp-host/src/llm/providerAttemptAuthorizer.ts
+++ b/mcp-host/src/llm/providerAttemptAuthorizer.ts
@@ -25,6 +25,7 @@ export type AuthorizeAttemptBody = {
recipeName?: string
userId?: string
budgetReservationId?: string
+ pluginWorkloadSdkProviderAttemptId?: string
}
export type ProviderAttemptAuthorizerOptions = {
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index d73573c19..4f6a56ea8 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -107,6 +107,7 @@ import {
resolvePluginWorkloadSdkBootstrapCapabilityFamily,
} from './pluginWorkloadSdk/bootstrapIdentity'
import { PluginWorkloadSdkBootstrapServer } from './pluginWorkloadSdk/bootstrapServer'
+import { sdkOnlyBindingAsPolicy } from './pluginWorkloadSdk/sdkOnlyCodexBinding'
import { maybeCreatePluginWorkloadSdkServer } from './pluginWorkloadSdk/server'
import type { PluginWorkloadSdkServer } from './pluginWorkloadSdk/server/sdkServer'
import { sanitizeError } from './progress/intentExtraction'
@@ -3183,6 +3184,7 @@ async function startPluginWorkloadSdkOnlyMode(): Promise<void> {
}
console.log(`[Main] Starting in SDK-ONLY MODE (recipe: ${config.workflowRecipeName})`)
+ setCodexPolicyBindingReader(() => sdkOnlyBindingAsPolicy())
if (!runtimeAuth) runtimeAuth = createMcpHostRuntimeAuth()
if (!runtimeAuth) {
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
index dbb877113..02f4b34ae 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it, vi } from 'vitest'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import {
configurePluginWorkloadSdkBootstrapIdentity,
resolvePluginWorkloadSdkBootstrapCapabilityFamily,
} from './bootstrapIdentity'
+import { readSdkOnlyCodexBinding, replaceSdkOnlyCodexBinding } from './sdkOnlyCodexBinding'
describe('Plugin Workload SDK bootstrap identity', () => {
it('uses the host capability projection instead of a request-selected family', async () => {
@@ -90,4 +92,71 @@ describe('Plugin Workload SDK bootstrap identity', () => {
'clientNotifications'
)
})
+
+ it('keeps Codex identity ready while the v3 execution binding is missing', async () => {
+ replaceSdkOnlyCodexBinding(null)
+ const verify = vi.fn()
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ contractVersion: 2,
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({
+ configured: true,
+ ready: true,
+ contractVersion: 3,
+ policyReady: false,
+ policyReason: 'codex_execution_binding_missing',
+ })
+ expect(verify).not.toHaveBeenCalled()
+ expect(readSdkOnlyCodexBinding()).toBeNull()
+ })
+
+ it('stores a verified v3 Codex binding before identity verification', async () => {
+ const binding = {
+ connectionKey: 'team-plus',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ bindingHash: computeCodexPolicyHash({
+ model: 'gpt-5.6-luna',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ connectionKey: 'team-plus',
+ }),
+ }
+ const verify = vi.fn().mockResolvedValue({
+ ready: true,
+ contractVersion: 3,
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ policyReady: true,
+ policyState: 'active',
+ codexBindingReady: true,
+ })
+ const result = await configurePluginWorkloadSdkBootstrapIdentity(
+ {
+ capabilityFamily: 'promptBridge',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ contractVersion: 3,
+ codexBinding: binding,
+ },
+ { capabilityFamily: 'promptBridge', verify }
+ )
+ expect(result).toMatchObject({
+ configured: true,
+ ready: true,
+ contractVersion: 3,
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ codexBinding: binding,
+ })
+ expect(readSdkOnlyCodexBinding()).toEqual(binding)
+ replaceSdkOnlyCodexBinding(null)
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
index e9637a6ef..498c545a4 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts
@@ -7,6 +7,11 @@ import type {
PluginWorkloadSdkBootstrapProof,
PluginWorkloadSdkClientNotificationsBootstrapProof,
} from './promptBridge/controlApiClient'
+import {
+ isPluginWorkloadSdkCodexBindingProof,
+ replaceSdkOnlyCodexBinding,
+ verifySdkOnlyCodexBindingHash,
+} from './sdkOnlyCodexBinding'
export interface PluginWorkloadSdkBootstrapIdentityDeps {
/**
@@ -86,23 +91,71 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(
if (!isRunnableLlmModelId(model)) {
return { configured: false, message: 'model is required and has an invalid format' }
}
+ if (req.provider === 'codex-subscription') {
+ const binding = req.codexBinding
+ const bindingValid =
+ req.contractVersion === 3 &&
+ isPluginWorkloadSdkCodexBindingProof(binding) &&
+ binding.model === model &&
+ verifySdkOnlyCodexBindingHash(binding)
+ if (!bindingValid) {
+ replaceSdkOnlyCodexBinding(null)
+ return {
+ configured: true,
+ ready: true,
+ capabilityFamily: 'promptBridge',
+ provider: req.provider,
+ model,
+ contractVersion: 3,
+ policyReady: false,
+ policyState: 'binding_missing',
+ policyReason: 'codex_execution_binding_missing',
+ message: 'SDK-only Codex bootstrap requires a live v3 execution binding',
+ }
+ }
+ replaceSdkOnlyCodexBinding(binding)
+ } else {
+ replaceSdkOnlyCodexBinding(null)
+ }
const proof = deps.verify ? await deps.verify(req.provider, model) : null
if (deps.verify && !proof) {
+ if (req.provider === 'codex-subscription') replaceSdkOnlyCodexBinding(null)
return {
configured: false,
ready: false,
- contractVersion: 2,
+ contractVersion: req.provider === 'codex-subscription' ? 3 : 2,
message: 'Plugin Workload SDK identity bootstrap contract is not ready',
}
}
+ if (
+ req.provider === 'codex-subscription' &&
+ proof &&
+ (proof.codexBindingReady === false || proof.policyReason === 'codex_execution_binding_missing')
+ ) {
+ replaceSdkOnlyCodexBinding(null)
+ return {
+ configured: true,
+ ready: true,
+ capabilityFamily: 'promptBridge',
+ provider: req.provider,
+ model,
+ contractVersion: 3,
+ policyReady: false,
+ policyState: proof.policyState,
+ policyReason: 'codex_execution_binding_missing',
+ message: 'Control API rejected the SDK-only Codex execution binding',
+ ...(req.codexBinding ? { codexBinding: req.codexBinding } : {}),
+ }
+ }
deps.onConfigured?.({ provider: req.provider, defaultModel: model })
+ const contractVersion = req.provider === 'codex-subscription' ? 3 : 2
return {
configured: true,
ready: true,
capabilityFamily: 'promptBridge',
provider: req.provider,
model,
- contractVersion: 2,
+ contractVersion,
...(proof ? { policyReady: proof.policyReady, policyState: proof.policyState } : {}),
...(proof?.policyReason ? { policyReason: proof.policyReason } : {}),
...(proof?.policyRevision !== undefined ? { policyRevision: proof.policyRevision } : {}),
@@ -119,5 +172,8 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(
...(proof?.clientNotificationsPolicyReason !== undefined
? { clientNotificationsPolicyReason: proof.clientNotificationsPolicyReason }
: {}),
+ ...(req.provider === 'codex-subscription' && req.codexBinding
+ ? { codexBinding: req.codexBinding }
+ : {}),
}
}
diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts
index 5eb6ad5e1..ac29047a2 100644
--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts
+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts
@@ -85,6 +85,10 @@ export class PluginWorkloadSdkBootstrapServer {
capabilityFamily: raw?.capabilityFamily,
provider: raw?.provider,
model: raw?.model,
+ ...(raw?.contractVersion === 2 || raw?.contractVersion === 3
+ ? { contractVersion: raw.contractVersion }
+ : {}),
+ ...(raw?.codexBinding ? { codexBinding: raw.codexBinding } : {}),
}
try {
const result = await this.opts.configure(request)
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index b9a1326ec..b7ddd9b5e 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -5,6 +5,7 @@ import {
isKnownPluginWorkloadErrorReason,
} from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
+import { readSdkOnlyCodexBinding } from '../sdkOnlyCodexBinding'
/**
* Anti-corruption layer (plan §3.4): encapsulates the HTTP call to
@@ -54,7 +55,7 @@ export interface AuthorizePromptBridgeResponse {
}
export interface PluginWorkloadSdkCapabilities {
- contractVersion: 2
+ contractVersion: 2 | 3
supportedContractVersions: number[]
targetAwarePromptBridge: true
attemptLedger: true
@@ -65,6 +66,7 @@ export interface PluginWorkloadSdkCapabilities {
defaultTargetRef: string | null
defaultProvider: string | null
defaultModel: string | null
+ defaultConnectionRef: string | null
v2Ready: boolean
clientNotificationsPolicyState: string
clientNotificationsReady: boolean
@@ -72,7 +74,7 @@ export interface PluginWorkloadSdkCapabilities {
export interface PluginWorkloadSdkBootstrapProof {
ready: true
- contractVersion: 2
+ contractVersion: 2 | 3
provider: string
model: string
policyReady: boolean
@@ -84,6 +86,9 @@ export interface PluginWorkloadSdkBootstrapProof {
| 'policy_disabled'
| 'bootstrap_target_mismatch'
| 'policy_not_ready'
+ | 'codex_execution_binding_missing'
+ /** Control API attested the live Codex connection against the v3 binding. */
+ codexBindingReady?: boolean
/**
* Policy metadata is deliberately optional at identity bootstrap. A recipe
* may be installed and publish an awaiting-policy SDK runtime before an
@@ -121,6 +126,7 @@ export interface ReissuedPromptBridgeCredentialTicket {
providerAttemptIndex: number
targetRef: string
credentialTicket: string
+ reservationOnly?: true
policyRevision: number
policyHash: string
expiresInSeconds: number
@@ -187,7 +193,7 @@ function isPluginWorkloadSdkCapabilities(v: unknown): v is PluginWorkloadSdkCapa
if (typeof v !== 'object' || v === null) return false
const value = v as Record<string, unknown>
return (
- value.contractVersion === 2 &&
+ (value.contractVersion === 2 || value.contractVersion === 3) &&
Array.isArray(value.supportedContractVersions) &&
value.supportedContractVersions.includes(2) &&
value.targetAwarePromptBridge === true &&
@@ -200,6 +206,9 @@ function isPluginWorkloadSdkCapabilities(v: unknown): v is PluginWorkloadSdkCapa
(value.defaultTargetRef === null || typeof value.defaultTargetRef === 'string') &&
(value.defaultProvider === null || typeof value.defaultProvider === 'string') &&
(value.defaultModel === null || typeof value.defaultModel === 'string') &&
+ (value.defaultConnectionRef === undefined ||
+ value.defaultConnectionRef === null ||
+ typeof value.defaultConnectionRef === 'string') &&
typeof value.v2Ready === 'boolean' &&
typeof value.clientNotificationsPolicyState === 'string' &&
typeof value.clientNotificationsReady === 'boolean'
@@ -221,7 +230,7 @@ function isReissuedPromptBridgeCredentialTicket(
(ticket.providerAttemptIndex as number) >= 1 &&
typeof ticket.targetRef === 'string' &&
typeof ticket.credentialTicket === 'string' &&
- ticket.credentialTicket.length > 0 &&
+ (ticket.credentialTicket.length > 0 || ticket.reservationOnly === true) &&
Number.isInteger(ticket.policyRevision) &&
(ticket.policyRevision as number) >= 1 &&
typeof ticket.policyHash === 'string' &&
@@ -522,7 +531,10 @@ export class PluginWorkloadSdkControlApiClient {
true
)
}
- return result
+ return {
+ ...result,
+ defaultConnectionRef: result.defaultConnectionRef ?? null,
+ }
})
.finally(() => {
if (this.capabilitiesInFlight === request) this.capabilitiesInFlight = null
@@ -561,7 +573,7 @@ export class PluginWorkloadSdkControlApiClient {
): Promise<PluginWorkloadSdkBootstrapProof> {
const capabilities = await this.getPromptBridgeCapabilities()
if (
- capabilities.contractVersion !== 2 ||
+ (capabilities.contractVersion !== 2 && capabilities.contractVersion !== 3) ||
!capabilities.supportedContractVersions.includes(2) ||
capabilities.targetAwarePromptBridge !== true ||
capabilities.attemptLedger !== true ||
@@ -577,6 +589,16 @@ export class PluginWorkloadSdkControlApiClient {
true
)
}
+ const binding = expectedProvider === 'codex-subscription' ? readSdkOnlyCodexBinding() : null
+ const codexBindingReady =
+ expectedProvider !== 'codex-subscription' ||
+ (capabilities.supportedContractVersions.includes(3) &&
+ binding !== null &&
+ capabilities.defaultProvider === expectedProvider &&
+ capabilities.defaultModel === expectedModel &&
+ binding.model === expectedModel &&
+ typeof capabilities.defaultConnectionRef === 'string' &&
+ capabilities.defaultConnectionRef === binding.connectionKey)
const policyReady =
capabilities.v2Ready &&
capabilities.policyRevision >= 1 &&
@@ -584,27 +606,31 @@ export class PluginWorkloadSdkControlApiClient {
/^[a-f0-9]{64}$/.test(capabilities.policyHash) &&
!!capabilities.defaultTargetRef &&
capabilities.defaultProvider === expectedProvider &&
- capabilities.defaultModel === expectedModel
+ capabilities.defaultModel === expectedModel &&
+ codexBindingReady
const policyReason = policyReady
? undefined
- : capabilities.policyState === 'missing'
- ? 'grant_missing'
- : capabilities.policyState === 'legacy_unreviewed'
- ? 'policy_unreviewed'
- : capabilities.policyState === 'revoking'
- ? 'policy_revoking'
- : capabilities.policyState === 'disabled'
- ? 'policy_disabled'
- : capabilities.v2Ready
- ? 'bootstrap_target_mismatch'
- : 'policy_not_ready'
+ : 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.v2Ready
+ ? 'bootstrap_target_mismatch'
+ : 'policy_not_ready'
return {
ready: true,
- contractVersion: 2,
+ contractVersion: expectedProvider === 'codex-subscription' ? 3 : 2,
provider: expectedProvider,
model: expectedModel,
policyReady,
policyState: capabilities.policyState,
+ ...(expectedProvider === 'codex-subscription' ? { codexBindingReady } : {}),
...(policyReason ? { policyReason } : {}),
...(capabilities.v2Ready &&
capabilities.policyRevision >= 1 &&
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
index 358d3669f..9230d0aed 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
@@ -356,6 +356,9 @@ export class PromptBridgeHandler {
maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),
temperature: request.temperature ?? authorized.modelPolicy?.temperature,
timeoutMs: this.deps.promptTimeoutMs,
+ recipeNamespace: this.deps.recipeNamespace,
+ recipeName: this.deps.recipeName,
+ hostRef: `${this.deps.recipeNamespace}/${this.deps.recipeName}`,
})
const providerAttemptAcknowledgement =
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index 4e41286e2..47ae46b74 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { register } from 'prom-client'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
import { LlmErrorCode } from '../../core/errors'
import { FinishReason } from '../../core/types'
import type { SingleTurnProvider, createLLMProvider } from '../../llm'
@@ -8,6 +9,7 @@ import { CircuitBreaker } from '../domain/circuitBreaker'
import { PluginWorkloadError } from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
import { recordCircuitBreakerState } from '../metrics'
+import { replaceSdkOnlyCodexBinding } from '../sdkOnlyCodexBinding'
import { LlmBridge, type PromptBridgeCredentialResolver } from './llmBridge'
const OK = {
@@ -96,6 +98,9 @@ const request = {
}
describe('LlmBridge authorized multi-provider fallback', () => {
+ afterEach(() => {
+ replaceSdkOnlyCodexBinding(null)
+ })
it('redeems credentials per attempt and serves the next authorized provider', async () => {
const first = new FakeProvider(() => Promise.reject(new Error('provider response')))
const second = new FakeProvider(() => Promise.resolve(OK))
@@ -584,6 +589,18 @@ describe('LlmBridge authorized multi-provider fallback', () => {
// not trigger any secret redemption or leak into the result payload.
connectionRef: 'team-plus',
}
+ replaceSdkOnlyCodexBinding({
+ connectionKey: 'team-plus',
+ catalogRevision: 1,
+ credentialRevision: 0,
+ model: 'gpt-5.1',
+ bindingHash: computeCodexPolicyHash({
+ model: 'gpt-5.1',
+ catalogRevision: 1,
+ credentialRevision: 0,
+ connectionKey: 'team-plus',
+ }),
+ })
const provider = new FakeProvider(async () => ({
...OK,
usage_reported: false,
@@ -592,7 +609,13 @@ describe('LlmBridge authorized multi-provider fallback', () => {
providerAttemptIndex: 1,
}))
const { bridge, credentialCalls, resolver } = makeBridge({ 'gpt-5.1': provider })
- const issuer = { issue: vi.fn() }
+ const issuer = {
+ issue: vi.fn(async () => ({
+ credentialTicket: '',
+ providerAttemptId: 'sdk-attempt-1',
+ providerAttemptIndex: 1,
+ })),
+ }
const result = await bridge.complete({
...request,
targets: [{ target: codex }],
@@ -601,14 +624,58 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(result.servedTarget).toEqual(codex)
expect(result.llmSecretName).toBe('')
expect(result.content).toBe('ok')
- expect(issuer.issue).not.toHaveBeenCalled()
+ expect(issuer.issue).toHaveBeenCalledTimes(1)
expect(resolver.resolve).not.toHaveBeenCalled()
expect(credentialCalls).toEqual([])
expect(JSON.stringify(result)).not.toMatch(/ticket|authorization|refreshToken|accessToken/i)
- expect(result.providerAttemptId).toBe('attempt-codex')
+ expect(result.providerAttemptId).toBe('sdk-attempt-1')
expect(result.providerAttemptIndex).toBe(1)
})
+ it('fails over after reserving a Codex target whose execution binding is missing', async () => {
+ const codex: PromptBridgeTarget = {
+ targetRef: 'codex-primary',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ credentialSlot: '',
+ connectionRef: 'team-plus',
+ }
+ const second = new FakeProvider(() => Promise.resolve(OK))
+ const { bridge, providerCalls, credentialCalls } = makeBridge({
+ [fallback.model]: second,
+ })
+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }
+ const issuer = {
+ issue: vi.fn(async ({ target }: { target: PromptBridgeTarget }) => ({
+ credentialTicket:
+ target.provider === 'codex-subscription' ? '' : `fresh-${target.targetRef}`,
+ providerAttemptId: `sdk-${target.targetRef}`,
+ providerAttemptIndex: target.provider === 'codex-subscription' ? 1 : 2,
+ })),
+ }
+
+ const result = await bridge.complete({
+ ...request,
+ targets: [{ target: codex }, { target: fallback }],
+ credentialTicketIssuer: issuer,
+ providerAttemptReporter,
+ })
+
+ expect(issuer.issue).toHaveBeenCalledTimes(2)
+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({
+ providerAttemptId: 'sdk-codex-primary',
+ providerAttemptIndex: 1,
+ status: 'failed',
+ })
+ expect(credentialCalls).toEqual([fallback.targetRef])
+ expect(providerCalls).toEqual([`${fallback.provider}/${fallback.model}`])
+ expect(result).toMatchObject({
+ servedTarget: fallback,
+ fallbackUsed: true,
+ attemptCount: 2,
+ })
+ })
+
it('does not execute a Codex target while its circuit is open', async () => {
const codex: PromptBridgeTarget = {
targetRef: 'codex-primary',
@@ -631,13 +698,29 @@ describe('LlmBridge authorized multi-provider fallback', () => {
undefined,
() => openBreaker
)
+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }
+ const issuer = {
+ issue: vi.fn(async () => ({
+ credentialTicket: '',
+ providerAttemptId: 'sdk-attempt-open',
+ providerAttemptIndex: 1,
+ })),
+ }
await expect(
bridge.complete({
...request,
targets: [{ target: codex }],
+ credentialTicketIssuer: issuer,
+ providerAttemptReporter,
})
).rejects.toMatchObject({ code: 'provider_unavailable' })
+ expect(issuer.issue).toHaveBeenCalledTimes(1)
+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({
+ providerAttemptId: 'sdk-attempt-open',
+ providerAttemptIndex: 1,
+ status: 'skipped',
+ })
expect(providerCalls).toEqual([])
expect(provider.completeSingleTurn).not.toHaveBeenCalled()
})
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index 2f00b11d7..d878fdbd5 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -1,11 +1,13 @@
import { LlmErrorCode } from '../../core/errors'
import { type ChatMessage, FinishReason } from '../../core/types'
import { type SingleTurnProvider, createLLMProvider } from '../../llm'
+import type { CodexAttemptContext } from '../../llm/codexSubscription'
import { type ClassifiedLike, type FailoverClass, classifyFailoverClass } from '../../llm/failover'
import { descriptorFor, isLlmProvider } from '../../llm/registryCore'
import { CircuitBreaker } from '../domain/circuitBreaker'
import { PluginWorkloadError, type PluginWorkloadProviderAttemptContext } from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
+import { readSdkOnlyCodexBinding, verifySdkOnlyCodexBindingHash } from '../sdkOnlyCodexBinding'
import type { BrokeredCredential } from './credentialBrokerClient'
class ClassifiedProviderError extends Error {
@@ -79,6 +81,9 @@ export interface LlmBridgeRequest {
temperature?: number
timeoutMs: number
triggerOn?: FailoverClass[]
+ recipeNamespace?: string
+ recipeName?: string
+ hostRef?: string
}
export interface LlmBridgeResult {
@@ -136,6 +141,34 @@ function remainingTimeoutMs(deadlineAt: number): number {
return deadlineAt - Date.now()
}
+function captureSdkOnlyCodexAttemptContext(
+ request: LlmBridgeRequest,
+ target: PromptBridgeTarget,
+ ticket: { providerAttemptId?: string; providerAttemptIndex?: number }
+): CodexAttemptContext | null {
+ const binding = readSdkOnlyCodexBinding()
+ if (
+ !binding ||
+ !verifySdkOnlyCodexBindingHash(binding) ||
+ binding.model !== target.model ||
+ !ticket.providerAttemptId ||
+ ticket.providerAttemptIndex === undefined
+ ) {
+ return null
+ }
+ return {
+ invocationId: request.invocationId,
+ attemptGeneration: request.attemptGeneration,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ pluginWorkloadSdkProviderAttemptId: ticket.providerAttemptId,
+ policyRevision: binding.catalogRevision,
+ policyHash: binding.bindingHash,
+ ...(request.hostRef ? { hostRef: request.hostRef } : {}),
+ ...(request.recipeNamespace ? { recipeNamespace: request.recipeNamespace } : {}),
+ ...(request.recipeName ? { recipeName: request.recipeName } : {}),
+ }
+}
+
function providerOutcomeUnknownError(
providerAttempt?: PluginWorkloadProviderAttemptContext
): PluginWorkloadError {
@@ -299,58 +332,26 @@ export class LlmBridge {
}
const breaker = this.breakerFor(authorized.target)
- if (
+ const oauthBroker =
isLlmProvider(authorized.target.provider) &&
descriptorFor(authorized.target.provider).authMode === 'oauth-broker'
- ) {
- if (!breaker.allow()) {
- lastProviderError = new ClassifiedProviderError(
- { code: LlmErrorCode.ApiCallFailed, retryable: true },
- new PluginWorkloadError(
- 'provider_unavailable',
- 'LLM provider circuit is open',
- true,
- 'provider_unavailable'
- )
- )
- if (index === request.targets.length - 1) {
- throw lastProviderError.toPluginWorkloadError()
- }
- continue
- }
- try {
- const completion = await this.attempt(
- { target: authorized.target, keys: {}, llmSecretName: '' },
- { ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },
- breaker
- )
- return {
- ...completion,
- servedTarget: authorized.target,
- fallbackUsed: index > 0,
- attemptCount: index + 1,
- llmSecretName: '',
- providerAttemptAcknowledgement: 'owned_by_finalizer',
- }
- } catch (error) {
- if (
- error instanceof ClassifiedProviderError &&
- error.classified.providerCode === 'budget_denied'
- ) {
- throw error.toPluginWorkloadError()
- }
- if (!(error instanceof ClassifiedProviderError)) throw error
- lastProviderError = error
- const failureClass = classifyFailoverClass(
- error.classified.code,
- error.classified.retryable
- )
- const eligible = failureClass !== null && triggerOn.has(failureClass)
- if (!eligible || index === request.targets.length - 1) {
- throw error.toPluginWorkloadError()
+ if (oauthBroker) {
+ const skippedOrReserved = await this.completeOauthBrokerTarget({
+ authorized,
+ index,
+ request,
+ breaker,
+ triggerOn,
+ deadlineAt,
+ })
+ if (skippedOrReserved.kind === 'error') {
+ lastProviderError = skippedOrReserved.error
+ if (skippedOrReserved.terminal) {
+ throw skippedOrReserved.error.toPluginWorkloadError()
}
continue
}
+ return skippedOrReserved.result
}
if (!breaker.allow()) {
// A circuit-open target still consumes an ordered, auditable physical
@@ -573,10 +574,162 @@ export class LlmBridge {
)
}
+ private async completeOauthBrokerTarget(input: {
+ authorized: { target: PromptBridgeTarget }
+ index: number
+ request: LlmBridgeRequest
+ breaker: CircuitBreaker
+ triggerOn: Set<FailoverClass>
+ deadlineAt: number
+ }): Promise<
+ | { kind: 'result'; result: LlmBridgeResult }
+ | { kind: 'error'; error: ClassifiedProviderError; terminal: boolean }
+ > {
+ const { authorized, index, request, breaker, triggerOn, deadlineAt } = input
+ const ticket = await withinDeadline(
+ () =>
+ request.credentialTicketIssuer.issue({
+ invocationId: request.invocationId,
+ attemptGeneration: request.attemptGeneration,
+ target: authorized.target,
+ policyRevision: request.policyRevision,
+ policyHash: request.policyHash,
+ }),
+ remainingTimeoutMs(deadlineAt),
+ 'timeout'
+ )
+ const providerAttemptContext =
+ ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined
+ ? {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ target: authorized.target,
+ attemptCount: index + 1,
+ fallbackUsed: index > 0,
+ }
+ : undefined
+
+ if (!breaker.allow()) {
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status: 'skipped',
+ })
+ }
+ const error = new ClassifiedProviderError(
+ { code: LlmErrorCode.ApiCallFailed, retryable: true },
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'LLM provider is temporarily unavailable',
+ true,
+ 'provider_unavailable',
+ false,
+ providerAttemptContext
+ )
+ )
+ const failureClass = classifyFailoverClass(error.classified.code, error.classified.retryable)
+ const eligible = failureClass !== null && triggerOn.has(failureClass)
+ return { kind: 'error', error, terminal: !eligible || index === request.targets.length - 1 }
+ }
+
+ const captured = captureSdkOnlyCodexAttemptContext(request, authorized.target, ticket)
+ if (!captured) {
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status: 'failed',
+ })
+ }
+ const error = new ClassifiedProviderError(
+ { code: LlmErrorCode.ApiCallFailed, retryable: true },
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'Codex execution binding is missing after reserving the SDK attempt',
+ true,
+ 'provider_unavailable',
+ false,
+ providerAttemptContext
+ )
+ )
+ const failureClass = classifyFailoverClass(error.classified.code, error.classified.retryable)
+ const eligible = failureClass !== null && triggerOn.has(failureClass)
+ return { kind: 'error', error, terminal: !eligible || index === request.targets.length - 1 }
+ }
+
+ try {
+ const completion = await this.attempt(
+ { target: authorized.target, keys: {}, llmSecretName: '' },
+ { ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },
+ breaker,
+ captured
+ )
+ return {
+ kind: 'result',
+ result: {
+ ...completion,
+ servedTarget: authorized.target,
+ fallbackUsed: index > 0,
+ attemptCount: index + 1,
+ llmSecretName: '',
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ providerAttemptAcknowledgement: 'owned_by_finalizer',
+ },
+ }
+ } catch (error) {
+ if (
+ error instanceof ClassifiedProviderError &&
+ (error.classified.providerCode === 'budget_denied' ||
+ error.classified.providerCode === 'no_grant' ||
+ error.classified.providerCode === 'host_binding_mismatch' ||
+ error.classified.providerCode === 'insufficient_scope' ||
+ error.classified.code === LlmErrorCode.AuthenticationFailed)
+ ) {
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status: 'failed',
+ })
+ }
+ return {
+ kind: 'error',
+ error,
+ terminal: true,
+ }
+ }
+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
+ const providerMayHaveExecuted =
+ (error instanceof PluginWorkloadError && error.providerMayHaveExecuted) ||
+ (error instanceof ClassifiedProviderError && error.providerMayHaveExecuted)
+ await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
+ providerAttemptId: ticket.providerAttemptId,
+ providerAttemptIndex: ticket.providerAttemptIndex,
+ status: providerMayHaveExecuted ? 'provider_unavailable' : 'failed',
+ })
+ }
+ if (!(error instanceof ClassifiedProviderError)) {
+ throw providerAttemptContext
+ ? withProviderAttemptContext(error, providerAttemptContext)
+ : error
+ }
+ const failureClass = classifyFailoverClass(error.classified.code, error.classified.retryable)
+ const eligible = failureClass !== null && triggerOn.has(failureClass)
+ return {
+ kind: 'error',
+ error,
+ terminal: !eligible || index === request.targets.length - 1,
+ }
+ }
+ }
+
private async attempt(
credential: BrokeredCredential,
request: LlmBridgeRequest,
- breaker: CircuitBreaker
+ breaker: CircuitBreaker,
+ capturedCodexAttemptContext?: CodexAttemptContext
): Promise<
Pick<
LlmBridgeResult,
@@ -601,10 +754,14 @@ export class LlmBridge {
'configuration'
)
}
- const provider: SingleTurnProvider | null = factory(credential.keys, {
- provider: providerId,
- name: credential.target.model,
- })
+ const provider: SingleTurnProvider | null = factory(
+ credential.keys,
+ {
+ provider: providerId,
+ name: credential.target.model,
+ },
+ capturedCodexAttemptContext ? { capturedCodexAttemptContext } : undefined
+ )
if (!provider) {
throw new PluginWorkloadError(
'provider_unavailable',
diff --git a/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
new file mode 100644
index 000000000..2ad58ada1
--- /dev/null
+++ b/mcp-host/src/pluginWorkloadSdk/sdkOnlyCodexBinding.ts
@@ -0,0 +1,73 @@
+import type { CodexPolicyBinding } from '@clerum/codex-catalog-projection'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
+
+const POLICY_HASH_RE = /^[a-f0-9]{64}$/
+
+/**
+ * Sanitized Codex execution proof carried on Plugin Workload SDK bootstrap
+ * configure v3. No OAuth material, Secret name, or unrestricted catalog.
+ */
+export type PluginWorkloadSdkCodexBindingProof = {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+}
+
+let current: PluginWorkloadSdkCodexBindingProof | null = null
+
+export function replaceSdkOnlyCodexBinding(
+ next: PluginWorkloadSdkCodexBindingProof | null
+): PluginWorkloadSdkCodexBindingProof | null {
+ current = next
+ return current
+}
+
+export function readSdkOnlyCodexBinding(): PluginWorkloadSdkCodexBindingProof | null {
+ return current
+}
+
+export function sdkOnlyBindingAsPolicy(): CodexPolicyBinding | null {
+ if (!current) return null
+ return {
+ catalogRevision: current.catalogRevision,
+ credentialRevision: current.credentialRevision,
+ connectionKey: current.connectionKey,
+ models: [current.model],
+ }
+}
+
+export function isPluginWorkloadSdkCodexBindingProof(
+ value: unknown
+): value is PluginWorkloadSdkCodexBindingProof {
+ if (typeof value !== 'object' || value === null) return false
+ const candidate = value as Record<string, unknown>
+ return (
+ typeof candidate.connectionKey === 'string' &&
+ candidate.connectionKey.trim().length > 0 &&
+ candidate.connectionKey !== 'unassigned' &&
+ Number.isInteger(candidate.catalogRevision) &&
+ Number(candidate.catalogRevision) >= 1 &&
+ Number.isInteger(candidate.credentialRevision) &&
+ Number(candidate.credentialRevision) >= 0 &&
+ typeof candidate.model === 'string' &&
+ candidate.model.trim().length > 0 &&
+ typeof candidate.bindingHash === 'string' &&
+ POLICY_HASH_RE.test(candidate.bindingHash)
+ )
+}
+
+export function verifySdkOnlyCodexBindingHash(
+ binding: PluginWorkloadSdkCodexBindingProof
+): boolean {
+ return (
+ binding.bindingHash ===
+ computeCodexPolicyHash({
+ model: binding.model,
+ catalogRevision: binding.catalogRevision,
+ credentialRevision: binding.credentialRevision,
+ connectionKey: binding.connectionKey,
+ })
+ )
+}
diff --git a/mcp-host/src/workflow/types.ts b/mcp-host/src/workflow/types.ts
index 89ed6501e..8ca5341e5 100644
--- a/mcp-host/src/workflow/types.ts
+++ b/mcp-host/src/workflow/types.ts
@@ -118,7 +118,18 @@ export interface ConfigureResponse {
* is intentionally present only on the SDK bootstrap response; workflow
* `/configure` remains on its legacy response shape.
*/
- contractVersion?: 2
+ contractVersion?: 2 | 3
+ /**
+ * Sanitized Codex execution binding echoed on configure v3. Absent for
+ * non-Codex v2 recipes.
+ */
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ }
ready?: boolean
/** Pod/protocol identity is ready even while operator policy is pending. */
policyReady?: boolean
@@ -140,6 +151,15 @@ export interface PluginWorkloadSdkBootstrapRequest {
capabilityFamily?: 'promptBridge' | 'clientNotifications'
provider?: LlmProvider
model?: string
+ /** Required for Codex; ignored by non-Codex v2 hosts that fail closed. */
+ contractVersion?: 2 | 3
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ }
}
// ─── Internal Tools (clerum__*) ──────────────────────────────────────
diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.sh
index b23df29d4..c4d17f01d 100755
--- a/scripts/tests/test-codex-subscription-t0.sh
+++ b/scripts/tests/test-codex-subscription-t0.sh
@@ -191,6 +191,8 @@ run_group "control-api" "control-api" \
"test/services.llmProviderAttemptFinalization.test.ts" \
"test/services.usageEvents.test.ts" \
"test/services.pluginWorkloadSdkFinalization.test.ts" \
+ "test/routes.mcp-host.plugin-workload-sdk.test.ts" \
+ "test/db.llmProviderAttemptMigration.test.ts" \
"test/routes.usageEvents.test.ts"
run_group "codex-llm-proxy" "codex-llm-proxy" \
@@ -208,6 +210,7 @@ run_group "mcp-host" "mcp-host" \
"src/config/configStore.test.ts" \
"src/llm/failover/__tests__/engine.test.ts" \
"src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts" \
+ "src/pluginWorkloadSdk/bootstrapIdentity.test.ts" \
"src/workflow/__tests__/configureHandler.test.ts" \
"src/workflow/__tests__/workflowServiceUsageReporting.test.ts" \
"src/pluginWorkloadSdk/server/index.test.ts" \
@@ -227,7 +230,10 @@ run_group "workflow-recipes" "workflow-recipes" \
"src/workflow/workflowReconciler.codexScopeProvenance.test.ts" \
"src/workflow/llmAllowedModelsSnapshot.test.ts" \
"src/workflow/networkPolicyFactory.codex.test.ts" \
- "tests/unit/workflow/modelConfigHandler.test.ts"
+ "src/workflow/sdkOnlyCodexBinding.test.ts" \
+ "src/reconciler/pluginWorkloadSdkValidator.test.ts" \
+ "tests/unit/workflow/modelConfigHandler.test.ts" \
+ "tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts"
run_group "control-ui" "control-ui" \
"components/__tests__/CodexSubscriptionHub.test.tsx" \
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 8f868668f..0836e6883 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,17 +1,18 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.319",
+ "version": "0.1.320",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.319",
+ "version": "0.1.320",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
"@clerum/image-policy": "file:../packages/image-policy",
+ "@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
@@ -48,6 +49,11 @@
"version": "0.1.0",
"license": "MIT"
},
+ "../packages/llm-provider-attempt-contract": {
+ "name": "@clerum/llm-provider-attempt-contract",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/llm-providers": {
"name": "@clerum/llm-providers",
"version": "0.1.0",
@@ -584,6 +590,10 @@
"resolved": "../packages/image-policy",
"link": true
},
+ "node_modules/@clerum/llm-provider-attempt-contract": {
+ "resolved": "../packages/llm-provider-attempt-contract",
+ "link": true
+ },
"node_modules/@clerum/llm-providers": {
"resolved": "../packages/llm-providers",
"link": true
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index bf6ead106..aa001334c 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.319",
+ "version": "0.1.320",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
@@ -29,6 +29,7 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
+ "@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
index 52cc2d80d..c1d2ed55e 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
@@ -546,6 +546,54 @@ describe('buildPluginWorkloadSdkStatus', () => {
})
})
+ it('blocks Validated when the Codex execution binding is missing', () => {
+ const projection = buildPluginWorkloadSdkStatus({
+ spec: baseSpec(
+ { promptBridge: {} },
+ { agent: { provider: 'codex-subscription', model: 'gpt-5.6-luna' } }
+ ),
+ existingConditions: undefined,
+ phase: 'active',
+ featureFlagEnabled: true,
+ bootstrapProof: {
+ ready: true,
+ contractVersion: 3,
+ podUid: 'pod-uid-1',
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ policyReady: false,
+ policyState: 'binding_missing',
+ policyReason: 'codex_execution_binding_missing',
+ verifiedAt: NOW,
+ },
+ now: NOW,
+ })
+ expect(projection.conditions).toEqual([
+ {
+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,
+ status: 'False',
+ reason: 'PolicyNotConfigured',
+ message:
+ 'Plugin Workload SDK promptBridge policy is not ready (codex_execution_binding_missing)',
+ lastTransitionTime: NOW,
+ },
+ {
+ type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,
+ status: 'True',
+ reason: 'codex_execution_binding_missing',
+ message:
+ 'Plugin Workload SDK promptBridge policy is not ready (codex_execution_binding_missing)',
+ lastTransitionTime: NOW,
+ },
+ ])
+ expect(projection.capability).toMatchObject({
+ state: 'awaiting_policy',
+ bootstrapContractVersion: 3,
+ bootstrapProvider: 'codex-subscription',
+ validatedAt: null,
+ })
+ })
+
it('does not validate a clientNotifications-only recipe before its grant is proven', () => {
const projection = buildPluginWorkloadSdkStatus({
spec: baseSpec(
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
index 9c532f1eb..4f435fdb9 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
@@ -184,8 +184,15 @@ export interface PluginWorkloadSdkStatusProjection {
export interface PluginWorkloadSdkBootstrapProofInput {
ready: true
- contractVersion: 2
+ contractVersion: 2 | 3
podUid: string
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ }
provider?: string
model?: string
policyReady?: boolean
@@ -338,8 +345,17 @@ export function buildPluginWorkloadSdkStatus(args: {
clientNotifications &&
bootstrapProof?.ready === true &&
bootstrapProof.clientNotificationsPolicyReady !== true
- if (policyPending || clientNotificationsPolicyPending) {
- const family = promptBridge && policyPending ? 'promptBridge' : 'clientNotifications'
+ const codexBindingPending =
+ promptBridge &&
+ bootstrapProof?.provider === 'codex-subscription' &&
+ (bootstrapProof.policyReason === 'codex_execution_binding_missing' ||
+ bootstrapProof.contractVersion !== 3 ||
+ !bootstrapProof.codexBinding)
+ if (policyPending || clientNotificationsPolicyPending || codexBindingPending) {
+ const family =
+ promptBridge && (policyPending || codexBindingPending)
+ ? 'promptBridge'
+ : 'clientNotifications'
const policyReason =
family === 'clientNotifications'
? (bootstrapProof?.clientNotificationsPolicyReason ??
diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.ts
index 282fe76e2..15293e51e 100644
--- a/workflow-recipes/src/types.ts
+++ b/workflow-recipes/src/types.ts
@@ -571,7 +571,7 @@ export interface PluginWorkloadSdkCapabilityStatus {
// explicitly send null so a previous validated record cannot survive a
// later degraded/awaiting-policy transition.
validatedAt?: string | null
- bootstrapContractVersion?: 2 | null
+ bootstrapContractVersion?: 2 | 3 | null
bootstrapPodUid?: string | null
bootstrapProvider?: string | null
bootstrapModel?: string | null
diff --git a/workflow-recipes/src/workflow/httpMcpHostClient.ts b/workflow-recipes/src/workflow/httpMcpHostClient.ts
index 51753ae64..d9874cb1b 100644
--- a/workflow-recipes/src/workflow/httpMcpHostClient.ts
+++ b/workflow-recipes/src/workflow/httpMcpHostClient.ts
@@ -61,6 +61,14 @@ export class HttpMcpHostClient implements McpHostClient {
capabilityFamily?: 'promptBridge' | 'clientNotifications'
provider?: string
model?: string
+ contractVersion?: 2 | 3
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ } | null
}
): Promise<{ status: number; body: Record<string, unknown> }> {
const url = `${endpoint}${PLUGIN_SDK_BOOTSTRAP_PATH}`
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index 302f58bac..9061c9352 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -105,6 +105,14 @@ export interface McpHostClient {
capabilityFamily?: 'promptBridge' | 'clientNotifications'
provider?: string
model?: string
+ contractVersion?: 2 | 3
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ } | null
}
): Promise<{ status: number; body: Record<string, unknown> }>
}
@@ -228,7 +236,14 @@ export class ModelConfigHandler {
model: string | undefined,
mcpHostEndpoint: string,
wrcConfigureToken: string,
- capabilityFamily: 'promptBridge' | 'clientNotifications' = 'promptBridge'
+ capabilityFamily: 'promptBridge' | 'clientNotifications' = 'promptBridge',
+ codexBinding?: {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+ } | null
): Promise<ConfigureModelResult> {
if (
capabilityFamily === 'promptBridge' &&
@@ -247,6 +262,9 @@ export class ModelConfigHandler {
...(capabilityFamily === 'clientNotifications' ? { capabilityFamily } : {}),
...(provider ? { provider } : {}),
...(model ? { model } : {}),
+ ...(provider === 'codex-subscription'
+ ? { contractVersion: 3, ...(codexBinding ? { codexBinding } : {}) }
+ : { contractVersion: 2 }),
}
)
if (result.status >= 400) {
@@ -258,10 +276,11 @@ export class ModelConfigHandler {
typeof result.body.policyReady === 'boolean' &&
typeof result.body.policyState === 'string'
: isBootstrapIdentityProof(result.body)
+ const expectedContractVersion = provider === 'codex-subscription' ? 3 : 2
if (
result.body.configured !== true ||
result.body.ready !== true ||
- result.body.contractVersion !== 2 ||
+ result.body.contractVersion !== expectedContractVersion ||
(capabilityFamily === 'clientNotifications'
? result.body.capabilityFamily !== capabilityFamily
: result.body.capabilityFamily !== undefined &&
@@ -272,7 +291,12 @@ export class ModelConfigHandler {
) {
return {
status: 502,
- body: { error: 'mcp_host bootstrap identity is not Plugin Workload SDK v2' },
+ body: {
+ error:
+ expectedContractVersion === 3
+ ? 'mcp_host bootstrap identity is not Plugin Workload SDK v3'
+ : 'mcp_host bootstrap identity is not Plugin Workload SDK v2',
+ },
}
}
const policyProof = capabilityFamily === 'promptBridge' && isBootstrapPolicyProof(result.body)
@@ -283,8 +307,13 @@ export class ModelConfigHandler {
ready: true,
provider,
model,
- contractVersion: 2,
+ contractVersion: expectedContractVersion,
capabilityFamily,
+ ...(result.body.codexBinding &&
+ typeof result.body.codexBinding === 'object' &&
+ !Array.isArray(result.body.codexBinding)
+ ? { codexBinding: result.body.codexBinding }
+ : {}),
...(typeof result.body.policyReady === 'boolean'
? { policyReady: result.body.policyReady }
: {}),
@@ -735,10 +764,11 @@ function mcpHostConfigureRejected(result: {
}
function isBootstrapIdentityProof(body: Record<string, unknown>): boolean {
+ const expectedVersion = body.provider === 'codex-subscription' ? 3 : 2
return (
body.configured === true &&
body.ready === true &&
- body.contractVersion === 2 &&
+ body.contractVersion === expectedVersion &&
typeof body.provider === 'string' &&
body.provider.length > 0 &&
typeof body.model === 'string' &&
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 2c52fe184..7cc94d23d 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -31,6 +31,11 @@ import {
buildPluginWorkloadSdkTokenSecretName,
} from './resourceNames'
import type { WorkflowRuntimePlan } from './runtimePlan'
+import {
+ type PluginWorkloadSdkCodexBindingProof,
+ isPluginWorkloadSdkCodexBindingProof,
+ verifySdkOnlyCodexBindingHash,
+} from './sdkOnlyCodexBinding'
import { buildPluginWorkloadSdkTokenSecret } from './secretFactory'
import type { WorkflowConfig } from './types'
@@ -43,8 +48,9 @@ export type EagerSdkMcpHostStatus =
export interface EagerSdkBootstrapProof {
ready: true
- contractVersion: 2
+ contractVersion: 2 | 3
podUid: string
+ codexBinding?: PluginWorkloadSdkCodexBindingProof
provider?: string
model?: string
policyReady?: boolean
@@ -175,6 +181,7 @@ export class PluginWorkloadSdkProvisioner {
runtime: WorkflowRuntimePlan,
opts: {
mcpHostPhase: string | undefined
+ codexBinding?: PluginWorkloadSdkCodexBindingProof | null
}
): Promise<EagerSdkMcpHostStatus> {
const log = createLogger('wrc', recipeName)
@@ -331,7 +338,7 @@ export class PluginWorkloadSdkProvisioner {
if (promptBridge && !mcpHostAgent) return 'failed'
const capabilityFamily = promptBridge ? 'promptBridge' : 'clientNotifications'
- const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}`
+ const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}:${opts.codexBinding?.bindingHash ?? 'none'}`
try {
const wrcConfigureToken = await this.deps.tokenFactory.signWrcConfigureToken(
recipeName,
@@ -344,7 +351,9 @@ export class PluginWorkloadSdkProvisioner {
mcpHostAgent!.provider,
mcpHostAgent!.model,
mcpHostEndpoint,
- wrcConfigureToken
+ wrcConfigureToken,
+ 'promptBridge',
+ opts.codexBinding ?? null
)
: await modelConfigHandler.configurePluginWorkloadSdkBootstrap(
undefined,
@@ -373,6 +382,15 @@ export class PluginWorkloadSdkProvisioner {
if (promptBridge && proof.policyReady === false) {
return 'awaiting_policy'
}
+ if (
+ promptBridge &&
+ mcpHostAgent?.provider === 'codex-subscription' &&
+ (proof.contractVersion !== 3 ||
+ !proof.codexBinding ||
+ proof.policyReason === 'codex_execution_binding_missing')
+ ) {
+ return 'awaiting_policy'
+ }
if (clientNotifications && proof.clientNotificationsPolicyReady === false) {
return 'awaiting_policy'
}
@@ -565,7 +583,7 @@ function parseEagerSdkBootstrapProof(
if (
body.configured !== true ||
body.ready !== true ||
- body.contractVersion !== 2 ||
+ (body.contractVersion !== 2 && body.contractVersion !== 3) ||
typeof body.provider !== 'string' ||
typeof body.model !== 'string' ||
body.provider.length === 0 ||
@@ -573,6 +591,29 @@ function parseEagerSdkBootstrapProof(
) {
return null
}
+ if (body.provider === 'codex-subscription' && body.contractVersion !== 3) {
+ return null
+ }
+ const codexBinding = parseCodexBindingProof(body.codexBinding)
+ if (
+ body.provider === 'codex-subscription' &&
+ body.policyReason === 'codex_execution_binding_missing'
+ ) {
+ return {
+ ready: true,
+ contractVersion: 3,
+ podUid,
+ provider: body.provider,
+ model: body.model,
+ policyReady: false,
+ policyState: typeof body.policyState === 'string' ? body.policyState : 'binding_missing',
+ policyReason: 'codex_execution_binding_missing',
+ verifiedAt: new Date().toISOString(),
+ }
+ }
+ if (body.provider === 'codex-subscription' && !codexBinding) {
+ return null
+ }
const hasPolicyProof =
Number.isSafeInteger(body.policyRevision) &&
Number(body.policyRevision) >= 1 &&
@@ -586,11 +627,15 @@ function parseEagerSdkBootstrapProof(
body.defaultModel === body.model
return {
ready: true,
- contractVersion: 2,
+ contractVersion: body.contractVersion === 3 ? 3 : 2,
podUid,
provider: body.provider,
model: body.model,
- policyReady: body.policyReady !== false && hasPolicyProof,
+ ...(codexBinding ? { codexBinding } : {}),
+ policyReady:
+ body.policyReady !== false &&
+ hasPolicyProof &&
+ (body.provider !== 'codex-subscription' || Boolean(codexBinding)),
policyState: typeof body.policyState === 'string' ? body.policyState : 'unknown',
...(typeof body.policyReason === 'string' ? { policyReason: body.policyReason } : {}),
verifiedAt: new Date().toISOString(),
@@ -614,3 +659,9 @@ function parseEagerSdkBootstrapProof(
: {}),
}
}
+
+function parseCodexBindingProof(value: unknown): PluginWorkloadSdkCodexBindingProof | undefined {
+ if (!isPluginWorkloadSdkCodexBindingProof(value)) return undefined
+ if (!verifySdkOnlyCodexBindingHash(value)) return undefined
+ return value
+}
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
new file mode 100644
index 000000000..591874113
--- /dev/null
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
+import {
+ deriveSdkOnlyCodexBinding,
+ isPluginWorkloadSdkCodexBindingProof,
+ verifySdkOnlyCodexBindingHash,
+} from './sdkOnlyCodexBinding'
+
+const HASH = computeCodexPolicyHash({
+ model: 'gpt-5.6-luna',
+ catalogRevision: 3,
+ credentialRevision: 1,
+ connectionKey: 'team-plus',
+})
+
+describe('deriveSdkOnlyCodexBinding', () => {
+ it('returns a hashed v3 proof for an assigned executable catalog', () => {
+ const binding = deriveSdkOnlyCodexBinding({
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ connectionKey: 'team-plus',
+ configMap: {
+ metadata: {
+ annotations: {
+ 'clerum.io/catalog-revision': '3',
+ 'clerum.io/connection-revision': '1',
+ },
+ },
+ },
+ })
+ expect(binding).toEqual({
+ connectionKey: 'team-plus',
+ catalogRevision: 3,
+ credentialRevision: 1,
+ model: 'gpt-5.6-luna',
+ bindingHash: HASH,
+ })
+ expect(verifySdkOnlyCodexBindingHash(binding!)).toBe(true)
+ expect(isPluginWorkloadSdkCodexBindingProof(binding)).toBe(true)
+ })
+
+ it('returns null for non-Codex providers and unassigned grants', () => {
+ expect(
+ deriveSdkOnlyCodexBinding({
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ connectionKey: 'team-plus',
+ configMap: undefined,
+ })
+ ).toBeNull()
+ expect(
+ deriveSdkOnlyCodexBinding({
+ provider: 'codex-subscription',
+ model: 'gpt-5.6-luna',
+ connectionKey: 'unassigned',
+ configMap: undefined,
+ })
+ ).toBeNull()
+ })
+})
diff --git a/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
new file mode 100644
index 000000000..882ccb8b2
--- /dev/null
+++ b/workflow-recipes/src/workflow/sdkOnlyCodexBinding.ts
@@ -0,0 +1,92 @@
+import {
+ CODEX_PROVIDER,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
+ type CodexConfigMapView,
+ toPolicyBinding,
+} from '@clerum/codex-catalog-projection'
+import { computeCodexPolicyHash } from '@clerum/llm-provider-attempt-contract'
+
+const POLICY_HASH_RE = /^[a-f0-9]{64}$/
+
+export type PluginWorkloadSdkCodexBindingProof = {
+ connectionKey: string
+ catalogRevision: number
+ credentialRevision: number
+ model: string
+ bindingHash: string
+}
+
+export function isPluginWorkloadSdkCodexBindingProof(
+ value: unknown
+): value is PluginWorkloadSdkCodexBindingProof {
+ if (typeof value !== 'object' || value === null) return false
+ const candidate = value as Record<string, unknown>
+ return (
+ typeof candidate.connectionKey === 'string' &&
+ candidate.connectionKey.trim().length > 0 &&
+ candidate.connectionKey !== CODEX_UNASSIGNED_CONNECTION_KEY &&
+ Number.isInteger(candidate.catalogRevision) &&
+ Number(candidate.catalogRevision) >= 1 &&
+ Number.isInteger(candidate.credentialRevision) &&
+ Number(candidate.credentialRevision) >= 0 &&
+ typeof candidate.model === 'string' &&
+ candidate.model.trim().length > 0 &&
+ typeof candidate.bindingHash === 'string' &&
+ POLICY_HASH_RE.test(candidate.bindingHash)
+ )
+}
+
+export function verifySdkOnlyCodexBindingHash(
+ binding: PluginWorkloadSdkCodexBindingProof
+): boolean {
+ return (
+ binding.bindingHash ===
+ computeCodexPolicyHash({
+ model: binding.model,
+ catalogRevision: binding.catalogRevision,
+ credentialRevision: binding.credentialRevision,
+ connectionKey: binding.connectionKey,
+ })
+ )
+}
+
+/**
+ * Derive the sanitized v3 Codex execution proof from one WRC snapshot.
+ * Returns null when the grant is unassigned, the catalog is not executable,
+ * or the selected model is not in the assigned connection's model list.
+ */
+export function deriveSdkOnlyCodexBinding(input: {
+ provider: string
+ model: string
+ connectionKey: string | undefined
+ configMap: CodexConfigMapView | undefined
+}): PluginWorkloadSdkCodexBindingProof | null {
+ if (input.provider !== CODEX_PROVIDER) return null
+ const policy = toPolicyBinding(input.configMap, input.connectionKey)
+ if (
+ !policy ||
+ !policy.connectionKey ||
+ policy.connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY ||
+ !Number.isInteger(policy.catalogRevision) ||
+ policy.catalogRevision < 1 ||
+ !Number.isInteger(policy.credentialRevision) ||
+ policy.credentialRevision < 0
+ ) {
+ return null
+ }
+ if (Array.isArray(policy.models) && !policy.models.includes(input.model)) {
+ return null
+ }
+ return {
+ connectionKey: policy.connectionKey,
+ catalogRevision: policy.catalogRevision,
+ credentialRevision: policy.credentialRevision,
+ model: input.model,
+ bindingHash: computeCodexPolicyHash({
+ model: input.model,
+ catalogRevision: policy.catalogRevision,
+ credentialRevision: policy.credentialRevision,
+ connectionKey: policy.connectionKey,
+ }),
+ }
+}
diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.ts
index 69c5a08a3..f41ca9c17 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts
@@ -1578,7 +1578,9 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
'zai',
'glm-4.7',
expect.any(String),
- 'wrc-configure-token'
+ 'wrc-configure-token',
+ 'promptBridge',
+ null
)
})
@@ -1872,7 +1874,9 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
'zai',
'glm-4.7',
expect.any(String),
- 'wrc-configure-token'
+ 'wrc-configure-token',
+ 'promptBridge',
+ null
)
})
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 9b7569c21..19132ecff 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -38,7 +38,7 @@ import type {
WorkflowRecipeSpec,
WorkflowSnippetRunSpec,
} from '../types'
-import { resolveMcpHostAgent } from './agentResolution'
+import { resolveEagerSdkMcpHostAgent, resolveMcpHostAgent } from './agentResolution'
import {
type CodexCatalogSnapshot,
projectRecipeCodexExecution,
@@ -137,6 +137,7 @@ import {
deleteScheduling,
reconcileScheduling,
} from './schedulingHandler'
+import { deriveSdkOnlyCodexBinding } from './sdkOnlyCodexBinding'
import { buildMcpHostRuntimeTokenSecret, createCoordinatorTokens } from './secretFactory'
import { SNIPPET_RUN_KEYS } from './snippetRunSchema'
import {
@@ -1104,6 +1105,19 @@ export class WorkflowReconciler {
throw new Error('SDK-only runtime requires spec.steps to be absent or empty')
}
+ await this.refreshCodexSnapshot()
+ const agent = resolveEagerSdkMcpHostAgent(spec)
+ const context = this.resolveCodexContext(recipeUid, recipeName, runtimeScopeRecipeName)
+ const codexBinding =
+ agent?.provider && agent.model
+ ? deriveSdkOnlyCodexBinding({
+ provider: agent.provider,
+ model: agent.model,
+ connectionKey: context.connectionKey,
+ configMap: this.lastCodexConfigMap,
+ })
+ : null
+
const runtime = deriveWorkflowRuntimePlan(spec, {
recipeName,
runtimeScopeRecipeName,
@@ -1121,7 +1135,7 @@ export class WorkflowReconciler {
runtimeScopeRecipeName,
spec,
runtime,
- { mcpHostPhase }
+ { mcpHostPhase, codexBinding }
)
const bootstrapProof = this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)
switch (status) {
diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
index 0d5516797..3966e4ae7 100644
--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts
@@ -150,7 +150,7 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {
expect(mcpHost.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(
'http://mcp-host:8090',
'wrc-token',
- { provider: 'openai', model: 'gpt-5.4-mini' }
+ { provider: 'openai', model: 'gpt-5.4-mini', contractVersion: 2 }
)
expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()
expect(k8s.readSecret).not.toHaveBeenCalled()
@@ -200,4 +200,60 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {
expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()
expect(k8s.readSecret).not.toHaveBeenCalled()
})
+
+ it('publishes Codex SDK bootstrap as v3 without reading ConfigMaps or Secrets', async () => {
+ const binding = {
+ connectionKey: 'team-plus',
+ catalogRevision: 4,
+ credentialRevision: 1,
+ model: 'gpt-5.1',
+ bindingHash: 'a'.repeat(64),
+ }
+ const mcpHost: McpHostClient = {
+ configure: vi.fn(async () => ({ status: 500, body: {} })),
+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({
+ status: 200,
+ body: {
+ configured: true,
+ ready: true,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ contractVersion: 3,
+ policyReady: true,
+ policyState: 'active',
+ codexBinding: binding,
+ },
+ })),
+ }
+ const k8s = reader()
+ const handler = new ModelConfigHandler(k8s, mcpHost)
+ const result = await handler.configurePluginWorkloadSdkBootstrap(
+ 'codex-subscription',
+ 'gpt-5.1',
+ 'http://mcp-host:8090',
+ 'wrc-token',
+ 'promptBridge',
+ binding
+ )
+
+ expect(result.status).toBe(202)
+ expect(result.body).toMatchObject({
+ contractVersion: 3,
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ codexBinding: binding,
+ })
+ expect(mcpHost.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(
+ 'http://mcp-host:8090',
+ 'wrc-token',
+ {
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ contractVersion: 3,
+ codexBinding: binding,
+ }
+ )
+ expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()
+ expect(k8s.readSecret).not.toHaveBeenCalled()
+ })
})