Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: close prompt bridge lifecycle and readiness gaps
Alfredo Lopez087183a4bbd1
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 64566c8c1..bee10c909 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.417",+ "version": "0.1.418","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.417",+ "version": "0.1.418","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex a44896878..cea300089 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.417",+ "version": "0.1.418","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.tsindex b30b13a88..0ffaf5bea 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -9,6 +9,7 @@ import { applyMemberRegistrationCredentialsSchema } from './services/memberRegisimport {addPluginWorkloadSdkAttemptLedgerColumns,addPluginWorkloadSdkJitCredentialTicketColumns,+ addPluginWorkloadSdkNotExecutedSpendOutcome,addPluginWorkloadSdkPromptTargetPolicyColumns,addPluginWorkloadSdkProtocolAndRevocation,addPluginWorkloadSdkProviderAttemptLedger,@@ -20,6 +21,7 @@ import {applyPluginWorkloadSdkSchema,dropPluginWorkloadSdkSuperAdminApprovedColumn,relaxPluginWorkloadSdkSpendOutcomeHostRef,+ repairPluginWorkloadSdkLegacyGrantPolicies,} from './services/pluginWorkloadSdkSchema.js'import { applyRegistryConnectionSchema } from './services/registryConnectionSchema.js'@@ -5124,6 +5126,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0085_plugin_workload_sdk_spend_outcome_host_ref_nullable',apply: relaxPluginWorkloadSdkSpendOutcomeHostRef,},+ {+ version: '0086_plugin_workload_sdk_legacy_policy_repair',+ apply: repairPluginWorkloadSdkLegacyGrantPolicies,+ },+ {+ version: '0087_plugin_workload_sdk_not_executed_spend_outcome',+ apply: addPluginWorkloadSdkNotExecutedSpendOutcome,+ },]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.tsindex 8e4020f8c..22ea99e9a 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@@ -184,7 +184,7 @@ function parsePromptBridgeFinalizationBody(attemptGeneration < 1 ||providerAttemptIndex < 1 ||providerAttemptIndex > 4 ||- !['complete', 'provider_unavailable'].includes(String(status)) ||+ !['complete', 'failed', 'provider_unavailable'].includes(String(status)) ||!reason ||reason.length > 128 ||!targetRef ||@@ -695,6 +695,11 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {asyncHandler(async (_req, res) => {const claims = _req.mcpHostJwt!const grant = await findGrant(claims.recipeNamespace, claims.recipeName, 'promptBridge')+ const clientNotificationsGrant = await findGrant(+ claims.recipeNamespace,+ claims.recipeName,+ 'clientNotifications'+ )const v2Ready = Boolean(grant &&grant.policyState === 'active' &&@@ -703,6 +708,12 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {grant.defaultTargetRef !== null &&grant.promptTargets[0]?.targetRef === grant.defaultTargetRef)+ const clientNotificationsReady = Boolean(+ clientNotificationsGrant &&+ clientNotificationsGrant.policyState === 'active' &&+ clientNotificationsGrant.allowedCallers.length > 0 &&+ clientNotificationsGrant.allowedEventTypes.length > 0+ )const primaryTarget = grant?.promptTargets[0] ?? nullres.status(200).json({contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,@@ -717,6 +728,8 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {defaultProvider: primaryTarget?.provider ?? null,defaultModel: primaryTarget?.model ?? null,v2Ready,+ clientNotificationsPolicyState: clientNotificationsGrant?.policyState ?? 'missing',+ clientNotificationsReady,})}))diff --git a/control-api/src/services/pluginWorkloadSdkFinalization.ts b/control-api/src/services/pluginWorkloadSdkFinalization.tsindex c56b0f7d9..6f11f766b 100644--- a/control-api/src/services/pluginWorkloadSdkFinalization.ts+++ b/control-api/src/services/pluginWorkloadSdkFinalization.ts@@ -5,7 +5,7 @@ import { ingestUsageEventsInTransaction } from './usageEvents.js'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 PromptBridgeFinalizationStatus = 'complete' | 'provider_unavailable'+export type PromptBridgeFinalizationStatus = 'complete' | 'failed' | 'provider_unavailable'export type PromptBridgeFinalizationUsage = {llmSecretName: string@@ -39,7 +39,7 @@ export type PromptBridgeFinalizationResult = {invocationId: stringproviderAttemptId: stringstatus: PromptBridgeFinalizationStatus- outcome: 'exact' | 'unknown'+ outcome: 'exact' | 'unknown' | 'not_executed'idempotent: booleanusageAccepted: boolean}@@ -128,7 +128,7 @@ function validateInput(input: PromptBridgeFinalizationInput): void {} else if (input.usage) {throw new PromptBridgeFinalizationError('invalid_request',- 'provider_unavailable finalization cannot claim exact usage',+ 'non-complete finalization cannot claim exact usage',400)}@@ -146,7 +146,7 @@ type SpendOutcomeRow = {provider: stringmodel: stringcredential_slot: string- outcome: 'exact' | 'unknown'+ outcome: 'exact' | 'unknown' | 'not_executed'input_tokens: number | string | nulloutput_tokens: number | string | null}@@ -155,7 +155,8 @@ function mapExistingOutcome(row: SpendOutcomeRow,input: PromptBridgeFinalizationInput): PromptBridgeFinalizationResult {- const expectedOutcome = input.status === 'complete' ? 'exact' : 'unknown'+ const expectedOutcome =+ input.status === 'complete' ? 'exact' : input.status === 'failed' ? 'not_executed' : 'unknown'if (row.invocation_id !== input.invocationId ||row.recipe_namespace !== input.recipeNamespace ||@@ -190,9 +191,10 @@ function mapExistingOutcome(/*** Finalize one physical promptBridge attempt and its logical invocation in a- * single trace-ingest transaction. Exact usage is inserted through the same- * receipt binder as the normal usage endpoint; unknown provider spend gets an- * immutable ledger row instead of disappearing behind provider_unavailable.+ * single trace-ingest transaction. Exact usage is inserted through the same+ * receipt binder as the normal usage endpoint; unknown provider spend and+ * proven no-execution failures get immutable ledger rows instead of+ * disappearing behind a public provider_unavailable response.*/export async function finalizePromptBridge(input: PromptBridgeFinalizationInput@@ -303,9 +305,11 @@ export async function finalizePromptBridgeInTransaction(// unknown ledger entry is then the only honest accounting result and still// prevents replay.const compatibleProviderStatuses =- input.status === 'provider_unavailable'- ? new Set(['in_progress', 'provider_unavailable', 'complete', 'failed'])- : new Set(['in_progress', 'complete'])+ input.status === 'complete'+ ? new Set(['in_progress', 'complete'])+ : input.status === 'failed'+ ? new Set(['reserved', 'in_progress', 'failed'])+ : new Set(['reserved', 'in_progress', 'provider_unavailable', 'complete', 'failed'])if (!compatibleStatuses.has(currentInvocationStatus) ||!compatibleStatuses.has(currentReceiptStatus) ||@@ -318,7 +322,8 @@ export async function finalizePromptBridgeInTransaction()}- const outcome = input.status === 'complete' ? 'exact' : 'unknown'+ const outcome =+ input.status === 'complete' ? 'exact' : input.status === 'failed' ? 'not_executed' : 'unknown'let usageAccepted = false// Promote the immutable physical and attempt receipts before exact usage isdiff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.tsindex f2f3e17a4..beb32b006 100644--- a/control-api/src/services/pluginWorkloadSdkSchema.ts+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts@@ -189,10 +189,11 @@ export async function addPluginWorkloadSdkJitCredentialTicketColumns(db: DbClien}/**- * Monotonic follow-up for the attempt/lease contract. Existing migrations are- * never edited because long-lived databases intentionally skip versions that- * are already recorded. Existing promptBridge rows are marked legacy without- * inferring provider, model, credential slot, default, or ordering.+ * Monotonic attempt/lease migration. A policy written by the ordered-policy+ * writer is already an explicit operator decision and must not be invalidated+ * merely because the attempt ledger is being added. Only rows that cannot+ * prove an ordered, provider-bound policy are moved to the fail-closed+ * legacy state. No policy is reconstructed from the old flat model columns.*/export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): Promise<void> {await db.query(`@@ -201,7 +202,7 @@ export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): PrDO $$ BEGINALTER TABLE plugin_workload_sdk_grantsADD CONSTRAINT plugin_workload_sdk_grants_policy_state_check- CHECK (policy_state IN ('active', 'legacy_unreviewed'));+ CHECK (policy_state IN ('active', 'legacy_unreviewed', 'revoking', 'disabled'));EXCEPTION WHEN duplicate_object THEN NULL;END $$;@@ -298,13 +299,48 @@ export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): Pr)ON CONFLICT (invocation_id, attempt_generation) DO NOTHING;- -- Every promptBridge row that predates this migration is unreviewed. Do- -- not infer a routable policy from legacy provider/model/slot columns;- -- only an explicit operator upsert/resave may move it to active.+ -- Preserve only a policy that proves the complete ordered contract. Do+ -- not infer a routable policy from legacy provider/model columns. Rows+ -- already revoking/disabled remain fenced; malformed/legacy active rows+ -- become explicitly reviewable and fail closed.UPDATE plugin_workload_sdk_grantsSET policy_state = 'legacy_unreviewed',policy_revision = 0- WHERE capability_family = 'promptBridge';+ WHERE capability_family = 'promptBridge'+ AND policy_state = 'active'+ AND NOT (+ policy_revision >= 1+ AND provider IS NOT NULL+ AND btrim(provider) <> ''+ AND default_target_ref IS NOT NULL+ AND btrim(default_target_ref) <> ''+ AND CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN jsonb_array_length(prompt_targets) > 0 ELSE false END+ AND CASE WHEN jsonb_typeof(allowed_callers) = 'array'+ THEN jsonb_array_length(allowed_callers) > 0 ELSE false END+ AND (prompt_targets -> 0 ->> 'targetRef') = default_target_ref+ AND (prompt_targets -> 0 ->> 'provider') = provider+ AND NOT EXISTS (+ SELECT 1+ FROM jsonb_array_elements(+ CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN prompt_targets ELSE '[]'::jsonb END+ ) AS target+ WHERE jsonb_typeof(target) <> 'object'+ OR btrim(COALESCE(target ->> 'targetRef', '')) = ''+ OR btrim(COALESCE(target ->> 'provider', '')) = ''+ OR btrim(COALESCE(target ->> 'model', '')) = ''+ OR btrim(COALESCE(target ->> 'credentialSlot', '')) = ''+ )+ AND (+ SELECT COUNT(DISTINCT target ->> 'targetRef')+ FROM jsonb_array_elements(+ CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN prompt_targets ELSE '[]'::jsonb END+ ) AS target+ ) = CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN jsonb_array_length(prompt_targets) ELSE 0 END+ );CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocations_lease_idxON plugin_workload_sdk_invocations (status, lease_expires_at)@@ -312,6 +348,55 @@ export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): Pr`)}+/**+ * Repairs databases that recorded the original 0078 migration before the+ * non-degrading predicate shipped. The ordered target policy is retained and+ * explicitly re-activated at revision 1; malformed rows remain+ * legacy_unreviewed. The operation is idempotent and never touches+ * clientNotifications or a policy already fenced as revoking/disabled.+ */+export async function repairPluginWorkloadSdkLegacyGrantPolicies(db: DbClient): Promise<void> {+ await db.query(`+ UPDATE plugin_workload_sdk_grants+ SET policy_state = 'active',+ policy_revision = 1,+ updated_at = now()+ WHERE capability_family = 'promptBridge'+ AND policy_state = 'legacy_unreviewed'+ AND policy_revision = 0+ AND provider IS NOT NULL+ AND btrim(provider) <> ''+ AND default_target_ref IS NOT NULL+ AND btrim(default_target_ref) <> ''+ AND CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN jsonb_array_length(prompt_targets) > 0 ELSE false END+ AND CASE WHEN jsonb_typeof(allowed_callers) = 'array'+ THEN jsonb_array_length(allowed_callers) > 0 ELSE false END+ AND (prompt_targets -> 0 ->> 'targetRef') = default_target_ref+ AND (prompt_targets -> 0 ->> 'provider') = provider+ AND NOT EXISTS (+ SELECT 1+ FROM jsonb_array_elements(+ CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN prompt_targets ELSE '[]'::jsonb END+ ) AS target+ WHERE jsonb_typeof(target) <> 'object'+ OR btrim(COALESCE(target ->> 'targetRef', '')) = ''+ OR btrim(COALESCE(target ->> 'provider', '')) = ''+ OR btrim(COALESCE(target ->> 'model', '')) = ''+ OR btrim(COALESCE(target ->> 'credentialSlot', '')) = ''+ )+ AND (+ SELECT COUNT(DISTINCT target ->> 'targetRef')+ FROM jsonb_array_elements(+ CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN prompt_targets ELSE '[]'::jsonb END+ ) AS target+ ) = CASE WHEN jsonb_typeof(prompt_targets) = 'array'+ THEN jsonb_array_length(prompt_targets) ELSE 0 END;+ `)+}+/** Adds the explicit usage source used by SDK-only promptBridge receipts. */export async function addPluginWorkloadSdkUsageSourceKind(db: DbClient): Promise<void> {await db.query(`ALTER TYPE usage_source_kind ADD VALUE IF NOT EXISTS 'plugin_workload_sdk';`)@@ -491,7 +576,7 @@ export async function addPluginWorkloadSdkSpendOutcomeLedger(db: DbClient): Promprovider TEXT NOT NULL,model TEXT NOT NULL,credential_slot TEXT NOT NULL,- outcome TEXT NOT NULL CHECK (outcome IN ('exact', 'unknown')),+ outcome TEXT NOT NULL CHECK (outcome IN ('exact', 'unknown', 'not_executed')),reason TEXT NOT NULL,input_tokens INTEGER NULL CHECK (input_tokens IS NULL OR input_tokens >= 0),output_tokens INTEGER NULL CHECK (output_tokens IS NULL OR output_tokens >= 0),@@ -499,7 +584,8 @@ export async function addPluginWorkloadSdkSpendOutcomeLedger(db: DbClient): Promcreated_at TIMESTAMPTZ NOT NULL DEFAULT now(),CONSTRAINT plugin_workload_sdk_spend_outcomes_token_pair_checkCHECK ((outcome = 'exact' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL)- OR (outcome = 'unknown' AND input_tokens IS NULL AND output_tokens IS NULL))+ OR (outcome IN ('unknown', 'not_executed')+ AND input_tokens IS NULL AND output_tokens IS NULL)));CREATE INDEX IF NOT EXISTS plugin_workload_sdk_spend_outcomes_recipe_idxON plugin_workload_sdk_spend_outcomes (recipe_namespace, recipe_name, created_at DESC);@@ -509,6 +595,28 @@ export async function addPluginWorkloadSdkSpendOutcomeLedger(db: DbClient): Prom`)}+/**+ * Extend the immutable spend ledger for pre-provider failures. Older+ * installations already have the table from 0084; this migration changes only+ * the two constraints and never rewrites existing exact/unknown receipts.+ */+export async function addPluginWorkloadSdkNotExecutedSpendOutcome(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE plugin_workload_sdk_spend_outcomes+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_spend_outcomes_token_pair_check;+ ALTER TABLE plugin_workload_sdk_spend_outcomes+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_spend_outcomes_outcome_check;+ ALTER TABLE plugin_workload_sdk_spend_outcomes+ ADD CONSTRAINT plugin_workload_sdk_spend_outcomes_outcome_check+ CHECK (outcome IN ('exact', 'unknown', 'not_executed'));+ ALTER TABLE plugin_workload_sdk_spend_outcomes+ ADD CONSTRAINT plugin_workload_sdk_spend_outcomes_token_pair_check+ CHECK ((outcome = 'exact' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL)+ OR (outcome IN ('unknown', 'not_executed')+ AND input_tokens IS NULL AND output_tokens IS NULL));+ `)+}+/*** The spend ledger was initially shipped with a required host_ref. Stale* lease recovery has no bearer token from which to prove that binding, sodiff --git a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.tsindex d9326b8be..3f717a2d2 100644--- a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts+++ b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts@@ -1,7 +1,10 @@import { describe, expect, it, vi } from 'vitest'import {+ addPluginWorkloadSdkAttemptLedgerColumns,+ addPluginWorkloadSdkNotExecutedSpendOutcome,addPluginWorkloadSdkProtocolAndRevocation,addPluginWorkloadSdkRuntimeAccess,+ repairPluginWorkloadSdkLegacyGrantPolicies,} from '../src/services/pluginWorkloadSdkSchema.js'describe('plugin workload SDK protocol migration', () => {@@ -29,4 +32,45 @@ describe('plugin workload SDK protocol migration', () => {expect(migrationSql).toContain('plugin_workload_sdk_invocation_attempts')expect(migrationSql).toContain('plugin_workload_sdk_provider_attempts')})++ it('preserves only complete ordered active policies while adding the attempt ledger', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await addPluginWorkloadSdkAttemptLedgerColumns({ query } as never)++ const migrationSql = String(query.mock.calls[0]?.[0])+ expect(migrationSql).toContain(+ "policy_state IN ('active', 'legacy_unreviewed', 'revoking', 'disabled')"+ )+ expect(migrationSql).toContain("jsonb_typeof(prompt_targets) = 'array'")+ expect(migrationSql).toContain("(prompt_targets -> 0 ->> 'targetRef') = default_target_ref")+ expect(migrationSql).toContain("(prompt_targets -> 0 ->> 'provider') = provider")+ expect(migrationSql).toContain("COUNT(DISTINCT target ->> 'targetRef')")+ expect(migrationSql).toContain("policy_state = 'active'")+ })++ it('provides an idempotent forward repair for valid policies already marked legacy', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await repairPluginWorkloadSdkLegacyGrantPolicies({ query } as never)++ const migrationSql = String(query.mock.calls[0]?.[0])+ expect(migrationSql).toContain("SET policy_state = 'active'")+ expect(migrationSql).toContain('policy_revision = 1')+ expect(migrationSql).toContain("policy_state = 'legacy_unreviewed'")+ expect(migrationSql).toContain('policy_revision = 0')+ expect(migrationSql).toContain("capability_family = 'promptBridge'")+ expect(migrationSql).not.toContain('clientNotifications')+ })++ it('keeps no-execution receipts distinct from unknown provider spend', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await addPluginWorkloadSdkNotExecutedSpendOutcome({ query } as never)++ const migrationSql = String(query.mock.calls[0]?.[0])+ expect(migrationSql).toContain("outcome IN ('exact', 'unknown', 'not_executed')")+ expect(migrationSql).toContain("outcome IN ('unknown', 'not_executed')")+ expect(migrationSql).toContain('DROP CONSTRAINT IF EXISTS')+ })})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.tsindex d1817842a..d7af530f3 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@@ -848,6 +848,31 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/finalize', () => {expect(res.status).toBe(409)expect(res.body).toMatchObject({ error: 'idempotency_conflict', retryable: false })})++ it('accepts a failed no-execution finalization without usage claims', async () => {+ vi.mocked(finalizer.finalizePromptBridge).mockResolvedValue({+ invocationId: 'inv-1',+ providerAttemptId: finalizationBody.providerAttemptId,+ status: 'failed',+ outcome: 'not_executed',+ idempotent: false,+ usageAccepted: false,+ })+ const res = await request(buildApp())+ .post('/mcp-host/plugin-workload-sdk/invocations/inv-1/finalize')+ .set('Authorization', `Bearer ${issueSdkToken()}`)+ .send({+ ...finalizationBody,+ status: 'failed',+ reason: 'credential_unavailable',+ usage: undefined,+ })+ expect(res.status).toBe(201)+ expect(res.body).toMatchObject({ status: 'failed', outcome: 'not_executed' })+ expect(finalizer.finalizePromptBridge).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'failed', reason: 'credential_unavailable' })+ )+ })})describe('GET /mcp-host/plugin-workload-sdk/invocations/:recipeRef', () => {diff --git a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts b/control-api/test/services.pluginWorkloadSdkFinalization.test.tsindex b38acc5a6..68c16a8ea 100644--- a/control-api/test/services.pluginWorkloadSdkFinalization.test.ts+++ b/control-api/test/services.pluginWorkloadSdkFinalization.test.ts@@ -206,6 +206,83 @@ describe('Plugin Workload SDK promptBridge finalization', () => {])})+ it('atomically records a pre-provider failure as not_executed without usage', 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: inputBase.target.targetRef,+ provider: inputBase.target.provider,+ model: inputBase.target.model,+ credential_slot: inputBase.target.credentialSlot,+ status: 'reserved',+ },+ { rows: [], rowCount: 1 },+ { rows: [], rowCount: 1 },+ { rows: [], rowCount: 1 },+ { rows: [], rowCount: 1 }+ )++ const result = await finalizePromptBridgeInTransaction(+ { ...inputBase, status: 'failed', reason: 'credential_unavailable' },+ db as never+ )++ expect(result).toMatchObject({+ status: 'failed',+ outcome: 'not_executed',+ idempotent: false,+ usageAccepted: false,+ })+ 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([+ IDS.providerAttempt,+ IDS.invocation,+ inputBase.recipeNamespace,+ inputBase.recipeName,+ 1,+ 1,+ inputBase.target.targetRef,+ inputBase.hostRef,+ inputBase.target.provider,+ inputBase.target.model,+ inputBase.target.credentialSlot,+ 'not_executed',+ 'credential_unavailable',+ null,+ null,+ null,+ ])+ })+it('converts a previously acknowledged physical attempt into a durable unknown outcome', async () => {const db = dbWithRows([],@@ -304,4 +381,34 @@ describe('Plugin Workload SDK promptBridge finalization', () => {)).rejects.toMatchObject<PromptBridgeFinalizationError>({ code: 'conflict', httpStatus: 409 })})++ it('replays a not_executed 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: inputBase.target.targetRef,+ host_ref: inputBase.hostRef,+ provider: inputBase.target.provider,+ model: inputBase.target.model,+ credential_slot: inputBase.target.credentialSlot,+ outcome: 'not_executed',+ input_tokens: null,+ output_tokens: null,+ }+ await expect(+ finalizePromptBridgeInTransaction(+ { ...inputBase, status: 'failed', reason: 'credential_unavailable' },+ dbWithRows([], row) as never+ )+ ).resolves.toMatchObject({+ status: 'failed',+ outcome: 'not_executed',+ idempotent: true,+ usageAccepted: false,+ })+ })})diff --git a/control-api/test/services.pluginWorkloadSdkSchema.test.ts b/control-api/test/services.pluginWorkloadSdkSchema.test.tsindex 603f9671d..e30bb0cea 100644--- a/control-api/test/services.pluginWorkloadSdkSchema.test.ts+++ b/control-api/test/services.pluginWorkloadSdkSchema.test.ts@@ -64,14 +64,14 @@ describe('pluginWorkloadSdkSchema', () => {expect(source).toMatch(/addPluginWorkloadSdkJitCredentialTicketColumns/)})- it('persists exact or unknown provider spend as an immutable attempt ledger', () => {+ it('persists exact, unknown, and no-execution provider spend outcomes as an immutable attempt ledger', () => {const schemaPath = join(dirname(fileURLToPath(import.meta.url)),'../src/services/pluginWorkloadSdkSchema.ts')const source = readFileSync(schemaPath, 'utf8')expect(source).toMatch(/plugin_workload_sdk_spend_outcomes/)- expect(source).toMatch(/outcome IN \('exact', 'unknown'\)/)+ expect(source).toMatch(/outcome IN \('exact', 'unknown', 'not_executed'\)/)expect(source).toMatch(/plugin_workload_sdk_spend_outcomes_token_pair_check/)expect(source).toMatch(/addPluginWorkloadSdkSpendOutcomeLedger/)})diff --git a/control-ui/app/plugin-workload-sdk/Views.tsx b/control-ui/app/plugin-workload-sdk/Views.tsxindex 44308d74b..736bfd790 100644--- a/control-ui/app/plugin-workload-sdk/Views.tsx+++ b/control-ui/app/plugin-workload-sdk/Views.tsx@@ -9,6 +9,7 @@ import type {PluginWorkloadSdkFamily,PluginWorkloadSdkGrant,PluginWorkloadSdkInvocation,+ PluginWorkloadSdkLegacyGrantInventory,} from '@lib/api'const GRANT_COLUMNS: TableHeaderColumn[] = [@@ -54,6 +55,7 @@ export function GrantsView({error,deletingId,userMap,+ legacyInventory,onEdit,onDelete,}: {@@ -62,6 +64,7 @@ export function GrantsView({error: stringdeletingId: string | nulluserMap: Map<string, string>+ legacyInventory: PluginWorkloadSdkLegacyGrantInventory | nullonEdit: (grant: PluginWorkloadSdkGrant) => voidonDelete: (grant: PluginWorkloadSdkGrant) => void}) {@@ -72,7 +75,7 @@ export function GrantsView({</div>)}- if (grants.length === 0 && !loading) {+ if (grants.length === 0 && !loading && !legacyInventory?.legacyPromptBridgeGrants) {return (<div className="cu-card__body"><div className="cu-empty">@@ -82,69 +85,91 @@ export function GrantsView({)}return (- <div className="cu-table-wrap">- <table className="cu-table">- <thead>- <TableHeaderRow columns={GRANT_COLUMNS} />- </thead>- <tbody>- {grants.map(grant => {- const allowlist =- grant.capabilityFamily === 'promptBridge'- ? (grant.promptTargets ?? []).map(- (target, index) =>- `${index === 0 ? 'default' : `fallback ${index}`}: ${target.provider}/${target.model} (${target.credentialSlot})`- )- : grant.allowedEventTypes- const quotaParts: string[] = []- if (grant.quotaLimits.maxRequestsPerRun)- quotaParts.push(`${grant.quotaLimits.maxRequestsPerRun}/run`)- if (grant.quotaLimits.maxNotificationsPerRun)- quotaParts.push(`${grant.quotaLimits.maxNotificationsPerRun}/run`)- if (grant.quotaLimits.maxInvocationsPerMinute)- quotaParts.push(`${grant.quotaLimits.maxInvocationsPerMinute}/min`)- if (grant.quotaLimits.maxNotificationsPerMinute)- quotaParts.push(`${grant.quotaLimits.maxNotificationsPerMinute}/min`)- const userRefsDisplay =- grant.allowedUserRefs.length > 0- ? grant.allowedUserRefs.map(ref => userMap.get(ref) ?? ref).join(', ')- : null- return (- <tr key={grant.id} className="cu-table__row">- <td>- <span className="cu-link">{grant.recipeName}</span>- <span className="cu-field__hint"> ({grant.recipeNamespace})</span>- </td>- <td>- <span className="cu-badge">{grant.capabilityFamily}</span>- </td>- <td>- {allowlist.length === 0 ? '- (migration required)' : allowlist.join(', ')}- {userRefsDisplay ? (- <span className="cu-field__hint"> · users: {userRefsDisplay}</span>- ) : null}- </td>- <td>{quotaParts.length === 0 ? '-' : quotaParts.join(', ')}</td>- <td className="cu-cell--right">- <Button type="button" variant="ghost" size="sm" onClick={() => onEdit(grant)}>- Edit- </Button>- <Button- type="button"- className="cu-btn--icon cu-btn--danger-icon"- onClick={() => onDelete(grant)}- disabled={deletingId === grant.id}- aria-label={`Delete grant for ${grant.recipeName}`}- >- <IconX width={16} height={16} />- </Button>- </td>- </tr>- )- })}- </tbody>- </table>- </div>+ <>+ {legacyInventory && legacyInventory.legacyPromptBridgeGrants > 0 ? (+ <div className="cu-card__body">+ <div className="cu-banner cu-banner--error">+ {legacyInventory.legacyPromptBridgeGrants} promptBridge grant(s) require explicit+ operator review before activation. Open each row and save the ordered policy; no legacy+ policy is activated automatically.+ </div>+ </div>+ ) : null}+ <div className="cu-table-wrap">+ <table className="cu-table">+ <thead>+ <TableHeaderRow columns={GRANT_COLUMNS} />+ </thead>+ <tbody>+ {grants.map(grant => {+ const allowlist =+ grant.capabilityFamily === 'promptBridge'+ ? (grant.promptTargets ?? []).map(+ (target, index) =>+ `${index === 0 ? 'default' : `fallback ${index}`}: ${target.provider}/${target.model} (${target.credentialSlot})`+ )+ : grant.allowedEventTypes+ const quotaParts: string[] = []+ if (grant.quotaLimits.maxRequestsPerRun)+ quotaParts.push(`${grant.quotaLimits.maxRequestsPerRun}/run`)+ if (grant.quotaLimits.maxNotificationsPerRun)+ quotaParts.push(`${grant.quotaLimits.maxNotificationsPerRun}/run`)+ if (grant.quotaLimits.maxInvocationsPerMinute)+ quotaParts.push(`${grant.quotaLimits.maxInvocationsPerMinute}/min`)+ if (grant.quotaLimits.maxNotificationsPerMinute)+ quotaParts.push(`${grant.quotaLimits.maxNotificationsPerMinute}/min`)+ const userRefsDisplay =+ grant.allowedUserRefs.length > 0+ ? grant.allowedUserRefs.map(ref => userMap.get(ref) ?? ref).join(', ')+ : null+ return (+ <tr key={grant.id} className="cu-table__row">+ <td>+ <span className="cu-link">{grant.recipeName}</span>+ <span className="cu-field__hint"> ({grant.recipeNamespace})</span>+ </td>+ <td>+ <span className="cu-badge">{grant.capabilityFamily}</span>+ <span+ className={+ grant.policyState === 'active'+ ? 'cu-badge cu-badge--ok'+ : 'cu-badge cu-badge--error'+ }+ >+ {grant.policyState === 'active'+ ? 'Active'+ : grant.policyState.replace('_', ' ')}+ </span>+ </td>+ <td>+ {allowlist.length === 0 ? '- (migration required)' : allowlist.join(', ')}+ {userRefsDisplay ? (+ <span className="cu-field__hint"> · users: {userRefsDisplay}</span>+ ) : null}+ </td>+ <td>{quotaParts.length === 0 ? '-' : quotaParts.join(', ')}</td>+ <td className="cu-cell--right">+ <Button type="button" variant="ghost" size="sm" onClick={() => onEdit(grant)}>+ Edit+ </Button>+ <Button+ type="button"+ className="cu-btn--icon cu-btn--danger-icon"+ onClick={() => onDelete(grant)}+ disabled={deletingId === grant.id}+ aria-label={`Delete grant for ${grant.recipeName}`}+ >+ <IconX width={16} height={16} />+ </Button>+ </td>+ </tr>+ )+ })}+ </tbody>+ </table>+ </div>+ </>)}diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsxindex c9a6c8f84..4e9a00736 100644--- a/control-ui/app/plugin-workload-sdk/page.tsx+++ b/control-ui/app/plugin-workload-sdk/page.tsx@@ -21,6 +21,7 @@ import {type WorkflowRecipeResource,deletePluginWorkloadSdkGrant,getAdminUsers,+ getPluginWorkloadSdkLegacyInventory,getRecipes,isSilentApiError,listLlmHostSecrets,@@ -125,6 +126,9 @@ export default function PluginWorkloadSdkPage() {const [grants, setGrants] = useState<PluginWorkloadSdkGrant[]>([])const [grantsLoading, setGrantsLoading] = useState(true)const [grantsError, setGrantsError] = useState('')+ const [legacyInventory, setLegacyInventory] = useState<Awaited<+ ReturnType<typeof getPluginWorkloadSdkLegacyInventory>+ > | null>(null)const [grantSearch, setGrantSearch] = useState('')const [deletingId, setDeletingId] = useState<string | null>(null)const [editing, setEditing] = useState<PluginWorkloadSdkGrant | 'new' | null>(null)@@ -181,6 +185,9 @@ export default function PluginWorkloadSdkPage() {const r = await listPluginWorkloadSdkGrants()const items = (r.items || []) as PluginWorkloadSdkGrant[]setGrants(items)+ void getPluginWorkloadSdkLegacyInventory()+ .then(setLegacyInventory)+ .catch(() => setLegacyInventory(null))const userRefs = items.flatMap(grant => grant.allowedUserRefs)void fetchUsersByRefs(userRefs).then(mergeLoadedUsers)@@ -336,6 +343,7 @@ export default function PluginWorkloadSdkPage() {error={grantsError}deletingId={deletingId}userMap={userMap}+ legacyInventory={legacyInventory}onEdit={setEditing}onDelete={handleDelete}/>diff --git a/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts b/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.tsindex ac3e57530..3979208bd 100644--- a/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts+++ b/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import {deletePluginWorkloadSdkGrant,+ getPluginWorkloadSdkLegacyInventory,getPluginWorkloadSdkQuota,listLlmHostSecrets,listPluginWorkloadSdkGrants,@@ -51,6 +52,16 @@ describe('Plugin Workload SDK admin api — URL shape', () => {expect(url).toContain('recipeName=r1')})+ it('loads the read-only legacy grant inventory for explicit operator review', async () => {+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(jsonResponse(200, { legacyPromptBridgeGrants: 1, items: [] }))+ await getPluginWorkloadSdkLegacyInventory()+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/api/v1/admin/plugin-workload-sdk/legacy-inventory')+ expect(init.credentials).toBe('include')+ })+it('upsertPluginWorkloadSdkGrant POSTs the grant payload as JSON', async () => {const fetchMock = vi.spyOn(globalThis, 'fetch')diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 79497abcd..d0fdb7712 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -3232,11 +3232,32 @@ export type PluginWorkloadSdkGrant = {modelPolicies: Record<string, PluginWorkloadSdkModelPolicy>promptTargets: PluginWorkloadSdkPromptTarget[]defaultTargetRef: string | null+ policyState: 'active' | 'legacy_unreviewed' | 'revoking' | 'disabled'+ revocationId: string | nullpolicyRevision: numbercreatedAt: stringupdatedAt: string}+export type PluginWorkloadSdkLegacyGrantInventoryItem = {+ id: string+ recipeNamespace: string+ recipeName: string+ policyState: string+ policyRevision: number+ providerPresent: boolean+ promptTargetsCount: number+ defaultTargetRefPresent: boolean+ reasons: string[]+}++export type PluginWorkloadSdkLegacyGrantInventory = {+ totalPromptBridgeGrants: number+ legacyPromptBridgeGrants: number+ activationReady: boolean+ items: PluginWorkloadSdkLegacyGrantInventoryItem[]+}+export type PluginWorkloadSdkGrantInput = {recipeNamespace: stringrecipeName: string@@ -3297,6 +3318,16 @@ export async function listPluginWorkloadSdkGrants(filter?: {}) as Promise<{ items?: PluginWorkloadSdkGrant[] }>}+export async function getPluginWorkloadSdkLegacyInventory(filter?: {+ recipeNamespace?: string+ recipeName?: string+}): Promise<PluginWorkloadSdkLegacyGrantInventory> {+ return apiGet('/api/v1/admin/plugin-workload-sdk/legacy-inventory', {+ recipeNamespace: filter?.recipeNamespace,+ recipeName: filter?.recipeName,+ }) as Promise<PluginWorkloadSdkLegacyGrantInventory>+}+export async function upsertPluginWorkloadSdkGrant(grant: PluginWorkloadSdkGrantInput): Promise<{ grant: PluginWorkloadSdkGrant }> {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex ef871d768..ddc127427 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.384",+ "version": "0.1.385","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.384",+ "version": "0.1.385","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex ccdef272f..b8c20a4bb 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.384",+ "version": "0.1.385","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/docs/deploy/minikube.md b/docs/deploy/minikube.mdindex a65f6e01f..487be20c1 100644--- a/docs/deploy/minikube.md+++ b/docs/deploy/minikube.md@@ -73,6 +73,11 @@ generated config, secrets, and rollouts match the current worktree:make minikube-pre-gate-sync GATE=<gate-name>```+For target-aware promptBridge or provider-free `clientNotifications` upgrades,+follow the fail-closed migration and rollout order in+[Plugin Workload SDK upgrade and policy migration](plugin-workload-sdk-upgrade.md)+before enabling the feature flag.+When deployable code changed and the E2E runner will manage port-forwardsitself, force the sync and skip the short-lived background port-forward refresh:diff --git a/docs/deploy/plugin-workload-sdk-upgrade.md b/docs/deploy/plugin-workload-sdk-upgrade.mdnew file mode 100644index 000000000..f360a3e0a--- /dev/null+++ b/docs/deploy/plugin-workload-sdk-upgrade.md@@ -0,0 +1,56 @@+# Plugin Workload SDK upgrade and policy migration++This runbook applies to releases that include the target-aware promptBridge+attempt ledger or the provider-free `clientNotifications` readiness contract.+The SDK is fail-closed during an upgrade: an old writer or an old mcp-host must+not run beside the new policy/ledger contract.++## Required order++1. Keep `PLUGIN_WORKLOAD_SDK_ENABLED=false` while the schema and binaries are+ upgraded.+2. Back up the database and record `schema_migrations`, the SDK grant inventory,+ and the target policy hashes. Do not copy secret values into the backup+ report.+3. Apply the compatible CRDs and deploy the new Control API migration image.+4. Stop old SDK writers before allowing the new Control API to accept writes.+5. Run the migrations, including the forward-only legacy policy repair. The+ repair preserves a complete ordered policy and leaves malformed or legacy+ rows in `legacy_unreviewed`.+6. Start the new Control API and verify the read-only+ `/api/v1/admin/plugin-workload-sdk/legacy-inventory` endpoint. A recipe can+ be enabled only when its inventory is `activationReady=true`.+7. Deploy the matching gateway, Control UI, WRC, and mcp-host images. The+ capabilities probe must report readiness independently for promptBridge and+ clientNotifications.+8. Have an operator review every `legacy_unreviewed` row in Control UI and+ explicitly save its ordered targets. The UI never activates a legacy row on+ page load.+9. Enable the feature for a canary recipe, reconcile it, and verify:+ - the eager host is Ready with a stable pod UID;+ - every declared family has an active grant;+ - a pre-provider credential/configuration failure closes both logical and+ physical attempts as `failed` and can revive the same idempotency key;+ - an ambiguous provider outcome remains `provider_unavailable` and is not+ revivable;+ - a real client notification reaches its authorized target.++## Rollback++Disable the SDK feature and stop new reconciles. Do not roll back the database+or deploy old binaries that cannot understand the attempt ledger. Keep the new+Control API and repair policy rows forward; after the inventory is clean,+re-enable a canary and repeat the readiness and ledger checks.++## Minikube gate++Use the branch-owned profile and generated random ports, then run:++```bash+make minikube-pre-gate-sync GATE=plugin-workload-sdk-review+```++The pre-gate fails when a `legacy_unreviewed` promptBridge policy remains. It+does not fail merely because an operator intentionally disabled or revoked a+grant; those states are fenced at authorization time and are reported by the+inventory for operational review.diff --git a/docs/deploy/production.md b/docs/deploy/production.mdindex a631b3c5c..59bbdd7cd 100644--- a/docs/deploy/production.md+++ b/docs/deploy/production.md@@ -24,6 +24,7 @@ assets.| Overlays | [deploy/overlays](../../deploy/overlays) || Bootstrap scripts | [scripts/](../../scripts/), [deploy/scripts](../../deploy/scripts) || Local full-stack reference | [minikube.md](minikube.md) |+| Plugin Workload SDK upgrade | [plugin-workload-sdk-upgrade.md](plugin-workload-sdk-upgrade.md) || Observability starter | [monitoring/](../../monitoring/README.md) |Install CRDs:@@ -82,6 +83,7 @@ modified MPL-licensed files. See [LICENSE](../../LICENSE).## Related- [WorkflowRecipes operations](workflow-recipes-guide.md)+- [Plugin Workload SDK upgrade and policy migration](plugin-workload-sdk-upgrade.md)- [Member invitations on self-hosted](../how-to/member-invitations-self-hosted.md)- [Architecture / topology](../architecture/platform-topology.md)- [FAQ](../faq.md)diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex a9134ff21..6752d711f 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.228",+ "version": "0.1.229","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.228",+ "version": "0.1.229","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 1d4c88599..17e8ccd74 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.228",+ "version": "0.1.229","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex e14597dd8..56ee86546 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2796,6 +2796,14 @@ async function startPluginWorkloadSdkOnlyMode(): Promise<void> {return null}},+ verifyClientNotifications: async () => {+ if (!pluginWorkloadSdkServer) return null+ try {+ return await pluginWorkloadSdkServer.verifyClientNotificationsBootstrap()+ } catch {+ return null+ }+ },}),})try {@@ -2994,6 +3002,14 @@ async function main(): Promise<void> {return null}},+ verifyPluginWorkloadSdkClientNotifications: async () => {+ if (!pluginWorkloadSdkServer) return null+ try {+ return await pluginWorkloadSdkServer.verifyClientNotificationsBootstrap()+ } catch {+ return null+ }+ },})rpcServer.setWorkflowService(workflowService)wireWorkflowApprovalRuntimeRoutes(rpcServer, {diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.tsindex 8eb816f55..42b15709f 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts@@ -2,11 +2,15 @@ import { isRunnableLlmModelId } from '@clerum/llm-providers'import { isLlmProvider } from '../llm/registryCore'import type { LlmProvider } from '../llm/registryCore'import type { ConfigureResponse, PluginWorkloadSdkBootstrapRequest } from '../workflow/types'-import type { PluginWorkloadSdkBootstrapProof } from './promptBridge/controlApiClient'+import type {+ PluginWorkloadSdkBootstrapProof,+ PluginWorkloadSdkClientNotificationsBootstrapProof,+} from './promptBridge/controlApiClient'export interface PluginWorkloadSdkBootstrapIdentityDeps {onConfigured?: (context: { provider: LlmProvider; defaultModel: string }) => voidverify?: (provider: string, model: string) => Promise<PluginWorkloadSdkBootstrapProof | null>+ verifyClientNotifications?: () => Promise<PluginWorkloadSdkClientNotificationsBootstrapProof | null>}/**@@ -18,6 +22,27 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(req: PluginWorkloadSdkBootstrapRequest | undefined,deps: PluginWorkloadSdkBootstrapIdentityDeps): Promise<ConfigureResponse> {+ if (req?.capabilityFamily === 'clientNotifications') {+ const proof = deps.verifyClientNotifications ? await deps.verifyClientNotifications() : null+ if (!proof) {+ return {+ configured: false,+ ready: false,+ contractVersion: 2,+ capabilityFamily: 'clientNotifications',+ message: 'Plugin Workload SDK clientNotifications readiness is not available',+ }+ }+ return {+ configured: true,+ ready: proof.ready,+ contractVersion: 2,+ capabilityFamily: 'clientNotifications',+ policyReady: proof.policyReady,+ policyState: proof.policyState,+ ...(proof.policyReason ? { policyReason: proof.policyReason } : {}),+ }+ }if (!req?.provider) {return { configured: false, message: 'provider is required' }}@@ -41,6 +66,7 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(return {configured: true,ready: true,+ capabilityFamily: 'promptBridge',provider: req.provider,model,contractVersion: 2,@@ -51,5 +77,14 @@ export async function configurePluginWorkloadSdkBootstrapIdentity(...(proof?.defaultTargetRef !== undefined ? { defaultTargetRef: proof.defaultTargetRef } : {}),...(proof?.defaultProvider !== undefined ? { defaultProvider: proof.defaultProvider } : {}),...(proof?.defaultModel !== undefined ? { defaultModel: proof.defaultModel } : {}),+ ...(proof?.clientNotificationsPolicyReady !== undefined+ ? { clientNotificationsPolicyReady: proof.clientNotificationsPolicyReady }+ : {}),+ ...(proof?.clientNotificationsPolicyState !== undefined+ ? { clientNotificationsPolicyState: proof.clientNotificationsPolicyState }+ : {}),+ ...(proof?.clientNotificationsPolicyReason !== undefined+ ? { clientNotificationsPolicyReason: proof.clientNotificationsPolicyReason }+ : {}),}}diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.tsindex 731f9004e..6b82815be 100644--- a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts@@ -63,6 +63,7 @@ export class PluginWorkloadSdkBootstrapServer {// Identity-only projection: credential-shaped extras never cross the// handler boundary even if a caller includes them in the JSON object.const request: PluginWorkloadSdkBootstrapRequest = {+ capabilityFamily: raw?.capabilityFamily,provider: raw?.provider,model: raw?.model,}diff --git a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts b/mcp-host/src/pluginWorkloadSdk/domain/errors.tsindex 7107dede2..130f3c928 100644--- a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts+++ b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts@@ -50,7 +50,8 @@ export type PluginWorkloadProviderAttemptContext = {}attemptCount: numberfallbackUsed: boolean- llmSecretName: string+ /** Known only after credential resolution; pre-provider failures may not have one. */+ llmSecretName?: string}const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.tsindex 4747f4561..95e1e228d 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts@@ -94,6 +94,8 @@ describe('PluginWorkloadSdkControlApiClient', () => {defaultProvider: null,defaultModel: null,v2Ready: false,+ clientNotificationsPolicyState: 'missing',+ clientNotificationsReady: false,}))const client = makeClient(fetchImpl as unknown as typeof fetch)@@ -106,6 +108,9 @@ describe('PluginWorkloadSdkControlApiClient', () => {policyReady: false,policyState: 'missing',policyReason: 'grant_missing',+ clientNotificationsPolicyReady: false,+ clientNotificationsPolicyState: 'missing',+ clientNotificationsPolicyReason: 'grant_missing',})expect(fetchImpl).toHaveBeenCalledWith('http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/capabilities',@@ -128,6 +133,8 @@ describe('PluginWorkloadSdkControlApiClient', () => {defaultProvider: null,defaultModel: null,v2Ready: false,+ clientNotificationsPolicyState: 'missing',+ clientNotificationsReady: false,}))const client = makeClient(fetchImpl as unknown as typeof fetch)@@ -138,6 +145,35 @@ describe('PluginWorkloadSdkControlApiClient', () => {})})+ it('proves provider-free clientNotifications readiness from the capabilities contract', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ jsonResponse(200, {+ contractVersion: 2,+ supportedContractVersions: [2],+ targetAwarePromptBridge: true,+ attemptLedger: true,+ credentialTickets: true,+ policyState: 'missing',+ policyRevision: 0,+ policyHash: null,+ defaultTargetRef: null,+ defaultProvider: null,+ defaultModel: null,+ v2Ready: false,+ clientNotificationsPolicyState: 'active',+ clientNotificationsReady: true,+ })+ )+ const client = makeClient(fetchImpl as unknown as typeof fetch)++ await expect(client.verifyClientNotificationsBootstrap()).resolves.toEqual({+ ready: true,+ contractVersion: 2,+ policyReady: true,+ policyState: 'active',+ })+ })+it('accepts a policy-only authorization envelope and leaves ticket issuance to the attempt path', async () => {const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, authorizedBody('inv-1')))const client = makeClient(fetchImpl as unknown as typeof fetch)diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.tsindex 6ae6da4ab..cd21c0e91 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts@@ -66,6 +66,8 @@ export interface PluginWorkloadSdkCapabilities {defaultProvider: string | nulldefaultModel: string | nullv2Ready: boolean+ clientNotificationsPolicyState: string+ clientNotificationsReady: boolean}export interface PluginWorkloadSdkBootstrapProof {@@ -94,6 +96,22 @@ export interface PluginWorkloadSdkBootstrapProof {defaultTargetRef?: stringdefaultProvider?: stringdefaultModel?: string+ clientNotificationsPolicyReady?: boolean+ clientNotificationsPolicyState?: string+ clientNotificationsPolicyReason?: string+}++export interface PluginWorkloadSdkClientNotificationsBootstrapProof {+ ready: true+ contractVersion: 2+ policyReady: boolean+ policyState: string+ policyReason?:+ | 'grant_missing'+ | 'policy_unreviewed'+ | 'policy_revoking'+ | 'policy_disabled'+ | 'policy_not_ready'}export interface ReissuedPromptBridgeCredentialTicket {@@ -111,8 +129,8 @@ export interface ReissuedPromptBridgeCredentialTicket {export interface FinalizePromptBridgeResponse {invocationId: stringproviderAttemptId: string- status: 'complete' | 'provider_unavailable'- outcome: 'exact' | 'unknown'+ status: 'complete' | 'failed' | 'provider_unavailable'+ outcome: 'exact' | 'unknown' | 'not_executed'idempotent: booleanusageAccepted: boolean}@@ -182,7 +200,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') &&- typeof value.v2Ready === 'boolean'+ typeof value.v2Ready === 'boolean' &&+ typeof value.clientNotificationsPolicyState === 'string' &&+ typeof value.clientNotificationsReady === 'boolean')}@@ -217,8 +237,12 @@ function isFinalizePromptBridgeResponse(value: unknown): value is FinalizePromptreturn (typeof result.invocationId === 'string' &&typeof result.providerAttemptId === 'string' &&- (result.status === 'complete' || result.status === 'provider_unavailable') &&- (result.outcome === 'exact' || result.outcome === 'unknown') &&+ (result.status === 'complete' ||+ result.status === 'failed' ||+ result.status === 'provider_unavailable') &&+ (result.outcome === 'exact' ||+ result.outcome === 'unknown' ||+ result.outcome === 'not_executed') &&typeof result.idempotent === 'boolean' &&typeof result.usageAccepted === 'boolean')@@ -594,6 +618,50 @@ export class PluginWorkloadSdkControlApiClient {defaultModel: capabilities.defaultModel,}: {}),+ clientNotificationsPolicyReady: capabilities.clientNotificationsReady,+ clientNotificationsPolicyState: capabilities.clientNotificationsPolicyState,+ ...(capabilities.clientNotificationsReady+ ? {}+ : {+ clientNotificationsPolicyReason:+ capabilities.clientNotificationsPolicyState === 'missing'+ ? 'grant_missing'+ : capabilities.clientNotificationsPolicyState === 'legacy_unreviewed'+ ? 'policy_unreviewed'+ : capabilities.clientNotificationsPolicyState === 'revoking'+ ? 'policy_revoking'+ : capabilities.clientNotificationsPolicyState === 'disabled'+ ? 'policy_disabled'+ : 'policy_not_ready',+ }),+ }+ }++ /**+ * Fresh readiness proof for the provider-free clientNotifications family.+ * It shares the v2 capabilities contract but never invents a provider/model+ * binding for a notifications-only recipe.+ */+ async verifyClientNotificationsBootstrap(): Promise<PluginWorkloadSdkClientNotificationsBootstrapProof> {+ const capabilities = await this.getPromptBridgeCapabilities()+ const policyReady = capabilities.clientNotificationsReady+ const policyReason = policyReady+ ? undefined+ : capabilities.clientNotificationsPolicyState === 'missing'+ ? 'grant_missing'+ : capabilities.clientNotificationsPolicyState === 'legacy_unreviewed'+ ? 'policy_unreviewed'+ : capabilities.clientNotificationsPolicyState === 'revoking'+ ? 'policy_revoking'+ : capabilities.clientNotificationsPolicyState === 'disabled'+ ? 'policy_disabled'+ : 'policy_not_ready'+ return {+ ready: true,+ contractVersion: 2,+ policyReady,+ policyState: capabilities.clientNotificationsPolicyState,+ ...(policyReason ? { policyReason } : {}),}}@@ -721,7 +789,7 @@ export class PluginWorkloadSdkControlApiClient {attemptGeneration: numberproviderAttemptId: stringproviderAttemptIndex: number- status: 'complete' | 'provider_unavailable'+ status: 'complete' | 'failed' | 'provider_unavailable'reason: stringtarget: PromptBridgeTargetusage?: {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.tsindex 36e420555..e9ebb3fe0 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts@@ -265,17 +265,86 @@ describe('PromptBridgeHandler', () => {expect(complete).not.toHaveBeenCalled()})- it('reports terminal provider configuration failures without widening fallback', async () => {+ it('reports pre-provider credential/configuration failures as revivable failed invocations', async () => {const complete = vi.fn().mockRejectedValue(- new PluginWorkloadError('provider_unavailable', 'credentials unavailable', false)+ new PluginWorkloadError(+ 'provider_unavailable',+ 'credentials unavailable',+ false,+ 'credential_unavailable',+ false+ ))const { handler, report } = makeDeps({ complete })await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({code: 'provider_unavailable',retryable: false,})+ expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'failed', 1)+ })++ it('atomically finalizes the physical attempt as not_executed in SDK-only mode', async () => {+ const finalize = vi.fn<FinalizePromptBridge>().mockResolvedValue({+ invocationId: 'inv-1',+ providerAttemptId: 'attempt-1',+ status: 'failed',+ outcome: 'not_executed',+ idempotent: false,+ usageAccepted: false,+ })+ const complete = vi.fn().mockRejectedValue(+ new PluginWorkloadError(+ 'provider_unavailable',+ 'credentials unavailable',+ false,+ 'credential_unavailable',+ false,+ {+ providerAttemptId: 'attempt-1',+ providerAttemptIndex: 1,+ target: primary,+ attemptCount: 1,+ fallbackUsed: false,+ }+ )+ )+ const { handler, report } = makeDeps({ complete, finalize })++ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'provider_unavailable',+ reason: 'credential_unavailable',+ })+ expect(finalize).toHaveBeenCalledWith(+ expect.objectContaining({+ invocationId: 'inv-1',+ providerAttemptId: 'attempt-1',+ status: 'failed',+ reason: 'credential_unavailable',+ target: primary,+ })+ )+ expect(report).not.toHaveBeenCalled()+ })++ it('keeps an ambiguous/post-provider failure terminal even when the public code is the same', async () => {+ const complete = vi+ .fn()+ .mockRejectedValue(+ new PluginWorkloadError(+ 'provider_unavailable',+ 'provider outcome unknown',+ false,+ 'outcome_unknown',+ true+ )+ )+ const { handler, report } = makeDeps({ complete })+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'provider_unavailable',+ reason: 'outcome_unknown',+ })expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'provider_unavailable', 1)})diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.tsindex 99f9c03fe..cd8366893 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts@@ -85,7 +85,7 @@ export interface PromptBridgeHandlerDeps {attemptGeneration: numberproviderAttemptId: stringproviderAttemptIndex: number- status: 'complete' | 'provider_unavailable'+ status: 'complete' | 'failed' | 'provider_unavailable'reason: stringtarget: PromptBridgeTargetusage?: {@@ -474,28 +474,39 @@ export class PromptBridgeHandler {}} catch (err) {unknownProviderAttempt = err instanceof PluginWorkloadError ? err.providerAttempt : undefined+ let providerAttemptFinalized = falseif (this.deps.finalizePromptBridge && unknownProviderAttempt) {try {+ const finalizationStatus =+ err instanceof PluginWorkloadError && err.providerMayHaveExecuted+ ? 'provider_unavailable'+ : 'failed'await this.deps.finalizePromptBridge({invocationId: authorized.invocationId,attemptGeneration: authorized.attemptGeneration,providerAttemptId: unknownProviderAttempt.providerAttemptId,providerAttemptIndex: unknownProviderAttempt.providerAttemptIndex,- status: 'provider_unavailable',+ status: finalizationStatus,reason:err instanceof PluginWorkloadError && err.reason ? err.reason : 'outcome_unknown',target: unknownProviderAttempt.target,})+ providerAttemptFinalized = true} catch {console.warn('[PluginWorkloadSdk] provider spend finalization failed')}}+ // The public error code is deliberately not the idempotency decision.+ // A broker/configuration failure uses `provider_unavailable` as the+ // safe workload-facing code, but `providerMayHaveExecuted=false` proves+ // that this invocation did not reach a provider and can be revived with+ // the same key after the operator repairs the credential/policy. Only a+ // positive/ambiguous execution signal permanently fences the key.const status =- err instanceof PluginWorkloadError &&- (err.code === 'provider_unavailable' || err.providerMayHaveExecuted)+ err instanceof PluginWorkloadError && err.providerMayHaveExecuted? 'provider_unavailable': 'failed'- if (!this.deps.finalizePromptBridge || !unknownProviderAttempt) {+ if (!this.deps.finalizePromptBridge || !unknownProviderAttempt || !providerAttemptFinalized) {await reportInvocationStatusBestEffort(this.deps.controlApiClient,authorized.invocationId,diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex 62f9b3894..d3efdfe27 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -158,22 +158,64 @@ describe('LlmBridge authorized multi-provider fallback', () => {expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])})- it('treats credential resolution failure as terminal and never redeems a fallback', async () => {+ it('closes a reserved SDK-only attempt when credential resolution fails before the provider', async () => {const resolve = vi.fn(async () => {throw new PluginWorkloadError('provider_unavailable','authorized provider credentials are unavailable',+ false,+ 'credential_unavailable',false)})const { bridge, providerCalls } = makeBridge({}, resolve)+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }+ const credentialTicketIssuer = {+ issue: vi.fn(async () => ({+ credentialTicket: 'fresh-primary',+ providerAttemptId: 'attempt-primary',+ providerAttemptIndex: 1,+ })),+ }- await expect(bridge.complete(request)).rejects.toMatchObject({+ await expect(+ bridge.complete({+ ...request,+ credentialTicketIssuer,+ providerAttemptReporter,+ })+ ).rejects.toMatchObject({code: 'provider_unavailable',retryable: false,+ providerAttempt: {+ providerAttemptId: 'attempt-primary',+ providerAttemptIndex: 1,+ target: primary,+ attemptCount: 1,+ fallbackUsed: false,+ },})expect(resolve).toHaveBeenCalledTimes(1)expect(providerCalls).toEqual([])+ expect(providerAttemptReporter.report).toHaveBeenCalledWith({+ providerAttemptId: 'attempt-primary',+ providerAttemptIndex: 1,+ status: 'failed',+ })++ await expect(+ bridge.complete({+ ...request,+ deferSuccessfulAttemptAcknowledgement: true,+ credentialTicketIssuer,+ providerAttemptReporter,+ })+ ).rejects.toMatchObject({+ code: 'provider_unavailable',+ reason: 'credential_unavailable',+ providerAttempt: { providerAttemptId: 'attempt-primary' },+ })+ expect(providerAttemptReporter.report).toHaveBeenCalledTimes(2)})it('reissues a fresh target-bound ticket immediately before each credential resolution', async () => {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.tsindex 6f0a9fab3..7a82a6ebd 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts@@ -141,6 +141,39 @@ function providerOutcomeUnknownError()}+/**+ * A ticket reserves the physical attempt before the broker resolves a+ * credential. Preserve that receipt when surfacing a pre-provider failure so+ * the SDK-only handler can close all three lifecycle records atomically. The+ * secret name is intentionally absent here: the broker failed before it could+ * prove which Secret was used.+ */+function withProviderAttemptContext(+ error: unknown,+ providerAttempt: PluginWorkloadProviderAttemptContext+): PluginWorkloadError {+ const publicError =+ error instanceof ClassifiedProviderError+ ? error.toPluginWorkloadError()+ : error instanceof PluginWorkloadError+ ? error+ : new PluginWorkloadError(+ 'provider_unavailable',+ 'provider credentials could not be resolved',+ false,+ 'credential_unavailable',+ false+ )+ return new PluginWorkloadError(+ publicError.code,+ publicError.message,+ publicError.retryable,+ publicError.reason,+ publicError.providerMayHaveExecuted,+ providerAttempt+ )+}+async function withinDeadline<T>(operation: () => Promise<T>,timeoutMs: number,@@ -332,17 +365,28 @@ export class LlmBridge {// not leave that row in_progress until the lease sweep when the broker// rejects the Secret read; close it before surfacing the terminal// credential/configuration failure to the caller.- if (- ticket.providerAttemptId &&- ticket.providerAttemptIndex !== undefined &&- !request.deferSuccessfulAttemptAcknowledgement- ) {+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {+ // `deferSuccessfulAttemptAcknowledgement` applies only to the+ // successful SDK-only terminal ACK. A ticket has already reserved a+ // physical attempt, so every pre-provider credential/configuration+ // failure must close that attempt as `failed`, regardless of the+ // logical finalizer mode. Otherwise the logical invocation closes+ // while the physical ledger remains reserved/in_progress forever.await reportProviderAttemptBestEffort(request.providerAttemptReporter, {providerAttemptId: ticket.providerAttemptId,providerAttemptIndex: ticket.providerAttemptIndex,status: 'failed',})}+ if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {+ throw withProviderAttemptContext(error, {+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ target: authorized.target,+ attemptCount: index + 1,+ fallbackUsed: index > 0,+ })+ }throw error}@@ -393,32 +437,46 @@ export class LlmBridge {})}- if (providerMayHaveExecuted || !providerAttemptAcknowledged) {+ const providerAttemptContext =+ ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined+ ? {+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ target: authorized.target,+ attemptCount: index + 1,+ fallbackUsed: index > 0,+ llmSecretName: credential.llmSecretName,+ }+ : undefined+ if (!providerAttemptAcknowledged) {// Once execution may have started, a failed receipt is not a safe// failover signal. Closing the logical invocation as terminal// provider_unavailable prevents the same idempotency key from// reviving into a second billable provider call.- throw providerOutcomeUnknownError(- ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined- ? {- providerAttemptId: ticket.providerAttemptId,- providerAttemptIndex: ticket.providerAttemptIndex,- target: authorized.target,- attemptCount: index + 1,- fallbackUsed: index > 0,- llmSecretName: credential.llmSecretName,- }- : undefined- )+ throw providerOutcomeUnknownError(providerAttemptContext)+ }+ if (!(error instanceof ClassifiedProviderError)) {+ if (providerMayHaveExecuted) {+ throw providerOutcomeUnknownError(providerAttemptContext)+ }+ // Provider construction/configuration failed before execution. Carry+ // the receipt so SDK-only finalization can atomically mark it+ // not_executed and leave the idempotency key revivable.+ throw providerAttemptContext+ ? withProviderAttemptContext(error, providerAttemptContext)+ : error}- if (!(error instanceof ClassifiedProviderError)) throw errorlastProviderError = errorconst 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 (!eligible || index === request.targets.length - 1) {+ throw providerAttemptContext+ ? withProviderAttemptContext(error.toPluginWorkloadError(), providerAttemptContext)+ : error.toPluginWorkloadError()+ }}}@@ -536,7 +594,11 @@ export class LlmBridge {`LLM provider error: ${classified.code}`,classified.retryable,reason,- classified.code === LlmErrorCode.ApiCallFailed+ // This branch runs only after the provider call was entered. Even a+ // provider-declared auth/rate-limit response is not proof that no+ // billable work occurred, so it must remain fenced as an ambiguous+ // physical outcome rather than reviving the idempotency key.+ true))} finally {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.tsindex 1ffc19bf8..425d04497 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts@@ -312,7 +312,10 @@ describe('Plugin Workload SDK promptBridge deterministic HTTP runtime', () => {expect(active.issuedTickets).toEqual([PRIMARY.targetRef])expect(active.credentialCalls).toEqual([PRIMARY.targetRef])expect(active.providerCalls).toEqual([])- expect(active.reportedStatuses).toEqual(['provider_unavailable'])+ // The HTTP contract remains provider_unavailable, but the logical+ // invocation is revivable because credential resolution proved that no+ // provider call was executed.+ expect(active.reportedStatuses).toEqual(['failed'])})it('rejects an unauthorized target before ticket, credential, or provider lookup', async () => {diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.tsindex 3f34db27d..b473f29f9 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts@@ -393,6 +393,7 @@ export function maybeCreatePluginWorkloadSdkServer(maxConnections: config.pluginWorkloadSdkMaxConnections,maxRequestsPerMinutePerWorkload: config.pluginWorkloadSdkMaxRpmPerWorkload,maxConcurrentPerWorkload: config.pluginWorkloadSdkMaxConnectionsPerWorkload,+ verifyClientNotificationsBootstrap: () => controlApiClient.verifyClientNotificationsBootstrap(),// Re-validate the rotating runtime token on every request: the boot-time// gate is one-shot, but refreshed tokens could in theory carry a drifted// binding. Fail closed instead of trusting the boot decision forever.diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.tsindex 0b0e90b32..b5228f6c2 100644--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts@@ -2,7 +2,10 @@ import express, { type Express } from 'express'import type http from 'http'import { type RuntimeJwtBinding, getJwtRuntimeBinding } from '../../workflow/mcpHostRuntimeJwt'import type { ClientNotificationsHandler } from '../clientNotifications/handler'-import type { PluginWorkloadSdkBootstrapProof } from '../promptBridge/controlApiClient'+import type {+ PluginWorkloadSdkBootstrapProof,+ PluginWorkloadSdkClientNotificationsBootstrapProof,+} from '../promptBridge/controlApiClient'import type { PromptBridgeHandler } from '../promptBridge/handler'import { registerSdkRoutes } from './routes'@@ -93,6 +96,7 @@ export interface SdkServerOptions {* required namespace. Fails closed with 503 on any drift.*/getRuntimeBinding?: () => RuntimeJwtBinding | null+ verifyClientNotificationsBootstrap?: () => Promise<PluginWorkloadSdkClientNotificationsBootstrapProof>}/**@@ -150,6 +154,13 @@ export class PluginWorkloadSdkServer {return this.opts.promptBridgeHandler.verifyBootstrapV2(expectedProvider, expectedModel)}+ verifyClientNotificationsBootstrap(): Promise<PluginWorkloadSdkClientNotificationsBootstrapProof> {+ if (!this.opts.verifyClientNotificationsBootstrap) {+ return Promise.reject(new Error('clientNotifications bootstrap verifier is not configured'))+ }+ return this.opts.verifyClientNotificationsBootstrap()+ }+async start(): Promise<void> {await new Promise<void>((resolve, reject) => {// Bind to 0.0.0.0 inside the pod; the SDK port is reachable only fromdiff --git a/mcp-host/src/workflow/__tests__/configureHandler.test.ts b/mcp-host/src/workflow/__tests__/configureHandler.test.tsindex 8277b7ecd..bf7fa08f0 100644--- a/mcp-host/src/workflow/__tests__/configureHandler.test.ts+++ b/mcp-host/src/workflow/__tests__/configureHandler.test.ts@@ -69,6 +69,7 @@ describe('POST /configure — JWT scope', () => {apiKey: 'must-not-be-consumed',})expect(result).toEqual({+ capabilityFamily: 'promptBridge',configured: true,ready: true,provider: 'openai',diff --git a/mcp-host/src/workflow/types.ts b/mcp-host/src/workflow/types.tsindex 9bbbb7bc6..a1761baf6 100644--- a/mcp-host/src/workflow/types.ts+++ b/mcp-host/src/workflow/types.ts@@ -103,6 +103,7 @@ export interface ConfigureRequest {export interface ConfigureResponse {configured: boolean+ capabilityFamily?: 'promptBridge' | 'clientNotifications'provider?: stringmodel?: string/**@@ -121,11 +122,15 @@ export interface ConfigureResponse {defaultTargetRef?: stringdefaultProvider?: stringdefaultModel?: string+ clientNotificationsPolicyReady?: boolean+ clientNotificationsPolicyState?: string+ clientNotificationsPolicyReason?: stringmessage?: string}/** Public identity handshake for a stepless Plugin Workload SDK host. */export interface PluginWorkloadSdkBootstrapRequest {+ capabilityFamily?: 'promptBridge' | 'clientNotifications'provider?: LlmProvidermodel?: string}diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex 4fa455079..8d942d269 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -168,6 +168,7 @@ export function createWorkflowRouter(service: WorkflowService): Router {// apiKey/secret-shaped field supplied by a caller is ignored before the// service boundary and can never reach the SDK context holder.const body: PluginWorkloadSdkBootstrapRequest = {+ capabilityFamily: raw?.capabilityFamily,provider: raw?.provider,model: raw?.model,}diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex 647be87c1..4c259b48f 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -17,7 +17,10 @@ import { createGfscClient, hasGfsRuntimeAccess } from '../internalTools/gfsClienimport { SingleTurnProvider, createLLMProvider } from '../llm'import { type LlmProvider, descriptorFor, isLlmProvider, primarySlot } from '../llm/registryCore'import { configurePluginWorkloadSdkBootstrapIdentity } from '../pluginWorkloadSdk/bootstrapIdentity'-import type { PluginWorkloadSdkBootstrapProof } from '../pluginWorkloadSdk/promptBridge/controlApiClient'+import type {+ PluginWorkloadSdkBootstrapProof,+ PluginWorkloadSdkClientNotificationsBootstrapProof,+} from '../pluginWorkloadSdk/promptBridge/controlApiClient'import type { ApiKeys } from '../types'import { type LlmUsageEvent, type UsageReporter, newRequestId } from '../usage/usageReporter'import {@@ -306,6 +309,7 @@ export class WorkflowService {provider: string,model: string) => Promise<PluginWorkloadSdkBootstrapProof | null>+ verifyPluginWorkloadSdkClientNotifications?: () => Promise<PluginWorkloadSdkClientNotificationsBootstrapProof | null>}) {this.recipeName = recipeName@@ -325,6 +329,8 @@ export class WorkflowService {this.onPluginWorkloadSdkBootstrapConfigured =opts?.onPluginWorkloadSdkBootstrapConfigured ?? nullthis.verifyPluginWorkloadSdkBootstrapV2 = opts?.verifyPluginWorkloadSdkBootstrapV2 ?? null+ this.verifyPluginWorkloadSdkClientNotifications =+ opts?.verifyPluginWorkloadSdkClientNotifications ?? null}private readonly onLlmConfigured:@@ -346,6 +352,10 @@ export class WorkflowService {| ((provider: string, model: string) => Promise<PluginWorkloadSdkBootstrapProof | null>)| null = null+ private readonly verifyPluginWorkloadSdkClientNotifications:+ | (() => Promise<PluginWorkloadSdkClientNotificationsBootstrapProof | null>)+ | null = null+private notifyLlmConfigured(provider: string, model: string, apiKey: string): void {if (!this.onLlmConfigured) return// The provider id IS the ApiKeys record key; validate before indexing.@@ -373,6 +383,9 @@ export class WorkflowService {...(this.verifyPluginWorkloadSdkBootstrapV2? { verify: this.verifyPluginWorkloadSdkBootstrapV2 }: {}),+ ...(this.verifyPluginWorkloadSdkClientNotifications+ ? { verifyClientNotifications: this.verifyPluginWorkloadSdkClientNotifications }+ : {}),})}diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex 31790983e..ba752ed3d 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -202,8 +202,8 @@ provision_gfs_serving() {assert_no_legacy_prompt_bridge_grants() {# Target-aware promptBridge authorization is fail-closed for legacy rows.- # Inventory them after migrations and before any target-aware mcp-host rollout- # so an operator gets an actionable gate failure instead of a silent outage.+ # Inventory only policies that require migration review; intentionally+ # disabled/revoking grants are already fenced and must not block an upgrade.# This check deliberately does not infer a provider, model, slot, or order;# migration remains an explicit operator-reviewed action.local legacy_count query@@ -211,7 +211,7 @@ assert_no_legacy_prompt_bridge_grants() {SELECT count(*)::intFROM plugin_workload_sdk_grantsWHERE capability_family = 'promptBridge'- AND policy_state <> 'active';+ AND policy_state = 'legacy_unreviewed';"# Keep the command after `kubectl exec --` on the same continued shell# command. A bare newline after `--` makes kubectl receive no command anddiff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 0ec736c30..cec272f40 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.277",+ "version": "0.1.278","lockfileVersion": 3,"requires": true,"packages": {@@ -34,7 +34,7 @@"engines": {"node": ">=24"},- "version": "0.1.277"+ "version": "0.1.278"},"../packages/image-policy": {"name": "@clerum/image-policy",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex e36b28aeb..d1bf60f5f 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.277",+ "version": "0.1.278","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.tsindex 073afcb9d..cdcda8736 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts@@ -319,6 +319,8 @@ describe('buildPluginWorkloadSdkStatus', () => {defaultTargetRef: 'primary-zai',defaultProvider: 'zai',defaultModel: 'glm-4.7',+ clientNotificationsPolicyReady: true,+ clientNotificationsPolicyState: 'active',verifiedAt: NOW,},now: NOW,@@ -349,6 +351,45 @@ describe('buildPluginWorkloadSdkStatus', () => {})})+ it('keeps a mixed recipe pending until every declared family has an active proof', () => {+ const projection = buildPluginWorkloadSdkStatus({+ spec: baseSpec({+ promptBridge: {},+ clientNotifications: { allowedEventTypes: ['a.b'] },+ }),+ existingConditions: undefined,+ phase: 'active',+ featureFlagEnabled: true,+ bootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'pod-uid-1',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ policyReady: true,+ policyState: 'active',+ clientNotificationsPolicyReady: false,+ clientNotificationsPolicyState: 'missing',+ clientNotificationsPolicyReason: 'grant_missing',+ verifiedAt: NOW,+ },+ now: NOW,+ })++ expect(projection.conditions[0]).toMatchObject({+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'PolicyNotConfigured',+ message: 'Plugin Workload SDK clientNotifications is awaiting an operator grant',+ })+ expect(projection.capability).toMatchObject({+ state: 'awaiting_policy',+ promptBridge: true,+ clientNotifications: true,+ validatedAt: null,+ })+ })+it('projects provider_unavailable separately from a validated capability declaration', () => {const projection = buildPluginWorkloadSdkStatus({spec: baseSpec({ promptBridge: {} }),@@ -438,6 +479,80 @@ describe('buildPluginWorkloadSdkStatus', () => {})})+ it('does not validate a clientNotifications-only recipe before its grant is proven', () => {+ const projection = buildPluginWorkloadSdkStatus({+ spec: baseSpec(+ { clientNotifications: { allowedEventTypes: ['e2e.test'] } },+ { agent: undefined }+ ),+ existingConditions: undefined,+ phase: 'active',+ featureFlagEnabled: true,+ bootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'pod-uid-1',+ clientNotificationsPolicyReady: false,+ clientNotificationsPolicyState: 'missing',+ clientNotificationsPolicyReason: 'grant_missing',+ verifiedAt: NOW,+ },+ now: NOW,+ })++ expect(projection.conditions).toEqual([+ {+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'PolicyNotConfigured',+ message: 'Plugin Workload SDK clientNotifications is awaiting an operator grant',+ lastTransitionTime: NOW,+ },+ {+ type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,+ status: 'True',+ reason: 'grant_missing',+ message: 'Plugin Workload SDK clientNotifications is awaiting an operator grant',+ lastTransitionTime: NOW,+ },+ ])+ expect(projection.capability).toMatchObject({+ state: 'awaiting_policy',+ promptBridge: false,+ clientNotifications: true,+ validatedAt: null,+ })+ })++ it('keeps clientNotifications-only recipes degraded while the SDK host is not ready', () => {+ const projection = buildPluginWorkloadSdkStatus({+ spec: baseSpec(+ { clientNotifications: { allowedEventTypes: ['e2e.test'] } },+ { agent: undefined }+ ),+ existingConditions: undefined,+ phase: 'deploying',+ featureFlagEnabled: true,+ now: NOW,+ })++ expect(projection.conditions).toEqual([+ {+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'BootstrapNotReady',+ message: 'Plugin Workload SDK host readiness proof is not ready',+ lastTransitionTime: NOW,+ },+ ])+ expect(projection.capability).toMatchObject({+ state: 'degraded',+ promptBridge: false,+ clientNotifications: true,+ validatedAt: null,+ })+ })+it('clears validated metadata when the capability degrades after a prior validation', () => {const validated = buildPluginWorkloadSdkStatus({spec: baseSpec({ promptBridge: {} }),diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.tsindex 7367e23a9..e433d08c1 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts@@ -186,8 +186,8 @@ export interface PluginWorkloadSdkBootstrapProofInput {ready: truecontractVersion: 2podUid: string- provider: string- model: string+ provider?: string+ model?: stringpolicyReady?: booleanpolicyState?: stringpolicyReason?: string@@ -196,6 +196,9 @@ export interface PluginWorkloadSdkBootstrapProofInput {defaultTargetRef?: stringdefaultProvider?: stringdefaultModel?: string+ clientNotificationsPolicyReady?: boolean+ clientNotificationsPolicyState?: string+ clientNotificationsPolicyReason?: stringverifiedAt: string}@@ -324,11 +327,22 @@ export function buildPluginWorkloadSdkStatus(args: {}}- if (promptBridge && policyPending) {+ const clientNotificationsPolicyPending =+ clientNotifications &&+ bootstrapProof?.ready === true &&+ bootstrapProof.clientNotificationsPolicyReady !== true+ if (policyPending || clientNotificationsPolicyPending) {+ const family = promptBridge && policyPending ? 'promptBridge' : 'clientNotifications'+ const policyReason =+ family === 'clientNotifications'+ ? (bootstrapProof?.clientNotificationsPolicyReason ??+ bootstrapProof?.clientNotificationsPolicyState ??+ 'unknown')+ : (bootstrapProof?.policyReason ?? bootstrapProof?.policyState ?? 'unknown')const message =- bootstrapProof?.policyReason === 'grant_missing'- ? 'Plugin Workload SDK promptBridge is awaiting an operator grant'- : `Plugin Workload SDK promptBridge policy is not ready (${bootstrapProof?.policyReason ?? bootstrapProof?.policyState ?? 'unknown'})`+ policyReason === 'grant_missing'+ ? `Plugin Workload SDK ${family} is awaiting an operator grant`+ : `Plugin Workload SDK ${family} policy is not ready (${policyReason})`return {conditions: [{@@ -341,7 +355,7 @@ export function buildPluginWorkloadSdkStatus(args: {{type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,status: 'True',- reason: bootstrapProof?.policyReason ?? 'PolicyNotReady',+ reason: policyReason,message,lastTransitionTime: now,},@@ -356,8 +370,8 @@ export function buildPluginWorkloadSdkStatus(args: {? {bootstrapContractVersion: bootstrapProof.contractVersion,bootstrapPodUid: bootstrapProof.podUid,- bootstrapProvider: bootstrapProof.provider,- bootstrapModel: bootstrapProof.model,+ ...(bootstrapProof.provider ? { bootstrapProvider: bootstrapProof.provider } : {}),+ ...(bootstrapProof.model ? { bootstrapModel: bootstrapProof.model } : {}),verifiedAt: bootstrapProof.verifiedAt,}: {}),@@ -365,8 +379,8 @@ export function buildPluginWorkloadSdkStatus(args: {}}- if (promptBridge && !bootstrapProof?.ready) {- const message = 'promptBridge bootstrap policy proof is not ready'+ if ((promptBridge || clientNotifications) && !bootstrapProof?.ready) {+ const message = 'Plugin Workload SDK host readiness proof is not ready'return {conditions: [{@@ -415,8 +429,8 @@ export function buildPluginWorkloadSdkStatus(args: {? {bootstrapContractVersion: bootstrapProof.contractVersion,bootstrapPodUid: bootstrapProof.podUid,- bootstrapProvider: bootstrapProof.provider,- bootstrapModel: bootstrapProof.model,+ ...(bootstrapProof.provider ? { bootstrapProvider: bootstrapProof.provider } : {}),+ ...(bootstrapProof.model ? { bootstrapModel: bootstrapProof.model } : {}),verifiedAt: bootstrapProof.verifiedAt,...(bootstrapProof.policyRevision !== undefined? { policyRevision: bootstrapProof.policyRevision }diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex 952dd8862..1691629b6 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -2386,7 +2386,7 @@ export class WorkflowRecipeReconciler {// active+BootstrapNotReady as a settled state.const sdkOnlyBootstrapPending =sdkOnlyRuntime?.phase === 'active' &&- recipe.spec.pluginWorkloadSdk?.promptBridge !== undefined &&+ recipe.spec.pluginWorkloadSdk !== undefined &&sdkOnlyRuntime.pluginWorkloadSdkBootstrapProof?.ready !== trueif (sdkOnlyRuntime?.phase === 'failed') {return {diff --git a/workflow-recipes/src/workflow/httpMcpHostClient.ts b/workflow-recipes/src/workflow/httpMcpHostClient.tsindex 51f9675b7..51753ae64 100644--- a/workflow-recipes/src/workflow/httpMcpHostClient.ts+++ b/workflow-recipes/src/workflow/httpMcpHostClient.ts@@ -57,7 +57,11 @@ export class HttpMcpHostClient implements McpHostClient {async configurePluginWorkloadSdkBootstrap(endpoint: string,token: string,- body: { provider: string; model: string }+ body: {+ capabilityFamily?: 'promptBridge' | 'clientNotifications'+ provider?: string+ model?: string+ }): Promise<{ status: number; body: Record<string, unknown> }> {const url = `${endpoint}${PLUGIN_SDK_BOOTSTRAP_PATH}`const controller = new AbortController()diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.tsindex 4a53c4666..9f5f3385b 100644--- a/workflow-recipes/src/workflow/modelConfigHandler.ts+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts@@ -94,7 +94,11 @@ export interface McpHostClient {configurePluginWorkloadSdkBootstrap?(endpoint: string,token: string,- body: { provider: string; model: string }+ body: {+ capabilityFamily?: 'promptBridge' | 'clientNotifications'+ provider?: string+ model?: string+ }): Promise<{ status: number; body: Record<string, unknown> }>}@@ -191,12 +195,16 @@ export class ModelConfigHandler {* key into the eager mcp-host.*/async configurePluginWorkloadSdkBootstrap(- provider: string,- model: string,+ provider: string | undefined,+ model: string | undefined,mcpHostEndpoint: string,- wrcConfigureToken: string+ wrcConfigureToken: string,+ capabilityFamily: 'promptBridge' | 'clientNotifications' = 'promptBridge'): Promise<ConfigureModelResult> {- if (!isLlmProviderId(provider) || !isRunnableLlmModelId(model)) {+ if (+ capabilityFamily === 'promptBridge' &&+ (!provider || !model || !isLlmProviderId(provider) || !isRunnableLlmModelId(model))+ ) {return { status: 400, body: { error: 'Invalid Plugin Workload SDK bootstrap target' } }}if (!this.mcpHost.configurePluginWorkloadSdkBootstrap) {@@ -206,25 +214,39 @@ export class ModelConfigHandler {const result = await this.mcpHost.configurePluginWorkloadSdkBootstrap(mcpHostEndpoint,wrcConfigureToken,- { provider, model }+ {+ ...(capabilityFamily === 'clientNotifications' ? { capabilityFamily } : {}),+ ...(provider ? { provider } : {}),+ ...(model ? { model } : {}),+ })if (result.status >= 400) {return { status: 502, body: { error: 'mcp_host bootstrap failed' } }}+ const familyProofValid =+ capabilityFamily === 'clientNotifications'+ ? result.body.capabilityFamily === 'clientNotifications' &&+ typeof result.body.policyReady === 'boolean' &&+ typeof result.body.policyState === 'string'+ : isBootstrapIdentityProof(result.body)if (result.body.configured !== true ||result.body.ready !== true ||result.body.contractVersion !== 2 ||- result.body.provider !== provider ||- result.body.model !== model ||- !isBootstrapIdentityProof(result.body)+ (capabilityFamily === 'clientNotifications'+ ? result.body.capabilityFamily !== capabilityFamily+ : result.body.capabilityFamily !== undefined &&+ result.body.capabilityFamily !== capabilityFamily) ||+ (capabilityFamily === 'promptBridge' &&+ (result.body.provider !== provider || result.body.model !== model)) ||+ !familyProofValid) {return {status: 502,body: { error: 'mcp_host bootstrap identity is not Plugin Workload SDK v2' },}}- const policyProof = isBootstrapPolicyProof(result.body)+ const policyProof = capabilityFamily === 'promptBridge' && isBootstrapPolicyProof(result.body)return {status: 202,body: {@@ -233,6 +255,7 @@ export class ModelConfigHandler {provider,model,contractVersion: 2,+ capabilityFamily,...(typeof result.body.policyReady === 'boolean'? { policyReady: result.body.policyReady }: {}),@@ -242,6 +265,15 @@ export class ModelConfigHandler {...(typeof result.body.policyReason === 'string'? { policyReason: result.body.policyReason }: {}),+ ...(typeof result.body.clientNotificationsPolicyReady === 'boolean'+ ? { clientNotificationsPolicyReady: result.body.clientNotificationsPolicyReady }+ : {}),+ ...(typeof result.body.clientNotificationsPolicyState === 'string'+ ? { clientNotificationsPolicyState: result.body.clientNotificationsPolicyState }+ : {}),+ ...(typeof result.body.clientNotificationsPolicyReason === 'string'+ ? { clientNotificationsPolicyReason: result.body.clientNotificationsPolicyReason }+ : {}),...(policyProof? {policyRevision: result.body.policyRevision,diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex 215abf122..cf4e14eb5 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -41,8 +41,8 @@ export interface EagerSdkBootstrapProof {ready: truecontractVersion: 2podUid: string- provider: string- model: string+ provider?: string+ model?: stringpolicyReady?: booleanpolicyState?: stringpolicyReason?: string@@ -53,6 +53,9 @@ export interface EagerSdkBootstrapProof {defaultTargetRef?: stringdefaultProvider?: stringdefaultModel?: string+ clientNotificationsPolicyReady?: boolean+ clientNotificationsPolicyState?: string+ clientNotificationsPolicyReason?: stringverifiedAt: string}@@ -279,13 +282,15 @@ export class PluginWorkloadSdkProvisioner {}const readiness = await this.readinessForEagerSdkMcpHost(recipeName)- if (!spec.pluginWorkloadSdk?.promptBridge) {+ const promptBridge = spec.pluginWorkloadSdk?.promptBridge !== undefined+ const clientNotifications = spec.pluginWorkloadSdk?.clientNotifications !== undefined+ if (!promptBridge && !clientNotifications) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return readiness.status}if (!this.deps.modelConfigHandler) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)- return readiness.status+ return 'failed'}if (readiness.status !== 'ready') {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)@@ -299,20 +304,30 @@ export class PluginWorkloadSdkProvisioner {return 'deploying'}- if (!mcpHostAgent) return 'failed'- const configureKey = `${readiness.uid}:${mcpHostAgent.provider}:${mcpHostAgent.model}`+ if (promptBridge && !mcpHostAgent) return 'failed'+ const capabilityFamily = promptBridge ? 'promptBridge' : 'clientNotifications'+ const configureKey = `${readiness.uid}:${capabilityFamily}:${mcpHostAgent?.provider ?? 'none'}:${mcpHostAgent?.model ?? 'none'}`try {const wrcConfigureToken = await this.deps.tokenFactory.signWrcConfigureToken(recipeName,namespace)const mcpHostEndpoint = buildMcpHostUrl(recipeName, this.deps.config.sandboxNamespace)- const result = await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(- mcpHostAgent.provider,- mcpHostAgent.model,- mcpHostEndpoint,- wrcConfigureToken- )+ const result =+ capabilityFamily === 'promptBridge'+ ? await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(+ mcpHostAgent!.provider,+ mcpHostAgent!.model,+ mcpHostEndpoint,+ wrcConfigureToken+ )+ : await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(+ undefined,+ undefined,+ mcpHostEndpoint,+ wrcConfigureToken,+ 'clientNotifications'+ )if (result.status >= 400) {this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {@@ -330,7 +345,10 @@ export class PluginWorkloadSdkProvisioner {}this.eagerSdkBootstrapProofByRecipe.set(recipeName, proof)this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)- if (spec.pluginWorkloadSdk.promptBridge && proof.policyReady === false) {+ if (promptBridge && proof.policyReady === false) {+ return 'awaiting_policy'+ }+ if (clientNotifications && proof.clientNotificationsPolicyReady === false) {return 'awaiting_policy'}} catch (err) {@@ -496,6 +514,29 @@ function parseEagerSdkBootstrapProof(body: Record<string, unknown>,podUid: string): EagerSdkBootstrapProof | null {+ if (body.capabilityFamily === 'clientNotifications') {+ if (+ body.configured !== true ||+ body.ready !== true ||+ body.contractVersion !== 2 ||+ body.capabilityFamily !== 'clientNotifications' ||+ typeof body.policyReady !== 'boolean' ||+ typeof body.policyState !== 'string'+ ) {+ return null+ }+ return {+ ready: true,+ contractVersion: 2,+ podUid,+ clientNotificationsPolicyReady: body.policyReady,+ clientNotificationsPolicyState: body.policyState,+ ...(typeof body.policyReason === 'string'+ ? { clientNotificationsPolicyReason: body.policyReason }+ : {}),+ verifiedAt: new Date().toISOString(),+ }+ }if (body.configured !== true ||body.ready !== true ||@@ -537,5 +578,14 @@ function parseEagerSdkBootstrapProof(defaultModel: body.defaultModel as string,}: {}),+ ...(typeof body.clientNotificationsPolicyReady === 'boolean'+ ? { clientNotificationsPolicyReady: body.clientNotificationsPolicyReady }+ : {}),+ ...(typeof body.clientNotificationsPolicyState === 'string'+ ? { clientNotificationsPolicyState: body.clientNotificationsPolicyState }+ : {}),+ ...(typeof body.clientNotificationsPolicyReason === 'string'+ ? { clientNotificationsPolicyReason: body.clientNotificationsPolicyReason }+ : {}),}}diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.tsindex d0231a17e..cf65b01ef 100644--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts@@ -1340,6 +1340,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {defaultTargetRef: 'primary-zai',defaultProvider: 'zai',defaultModel: 'glm-4.7',+ clientNotificationsPolicyReady: true,+ clientNotificationsPolicyState: 'active',},}),}@@ -1385,6 +1387,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {defaultTargetRef: 'primary-zai',defaultProvider: 'zai',defaultModel: 'glm-4.7',+ clientNotificationsPolicyReady: true,+ clientNotificationsPolicyState: 'active',})beforeEach(() => {@@ -1580,6 +1584,17 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {it('creates a provider-free eager mcp-host for clientNotifications-only without an agent', async () => {const reconciler = new WorkflowReconciler(makeDeps())+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ contractVersion: 2,+ capabilityFamily: 'clientNotifications',+ policyReady: true,+ policyState: 'active',+ },+ })const result = await reconciler.reconcilePluginWorkloadSdkOnly('notifications-only',@@ -1600,7 +1615,13 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {const envNames = (pod.spec.containers[0].env ?? []).map((entry: { name: string }) => entry.name)expect(envNames).not.toContain('CLERUM_MODEL_PROVIDER')expect(envNames).not.toContain('CLERUM_MODEL')- expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).not.toHaveBeenCalled()+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(+ undefined,+ undefined,+ expect.any(String),+ 'wrc-configure-token',+ 'clientNotifications'+ )})it('cleans SDK-only host resources idempotently without creating workflow resources', async () => {@@ -1833,8 +1854,19 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {)})- it('does NOT broker a provider for clientNotifications-only recipes', async () => {+ it('does not broker a provider for clientNotifications-only recipes but proves its grant', async () => {const reconciler = new WorkflowReconciler(makeDeps())+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ contractVersion: 2,+ capabilityFamily: 'clientNotifications',+ policyReady: true,+ policyState: 'active',+ },+ })await reconciler.reconcile('notif-recipe',@@ -1856,7 +1888,47 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {call => call[0].body.metadata.name)expect(podNames).toContain('notif-recipe-mcp-host')- expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).not.toHaveBeenCalled()+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(+ undefined,+ undefined,+ expect.any(String),+ 'wrc-configure-token',+ 'clientNotifications'+ )+ })++ it('keeps clientNotifications-only recipes awaiting policy when the host proves no grant', async () => {+ const reconciler = new WorkflowReconciler(makeDeps())+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ contractVersion: 2,+ capabilityFamily: 'clientNotifications',+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ },+ })++ const result = await reconciler.reconcilePluginWorkloadSdkOnly(+ 'notifications-policy-pending',+ 'uid-notifications-policy-pending',+ sandboxNamespace,+ sdkSpec({+ agent: undefined,+ steps: undefined,+ pluginWorkloadSdk: {+ clientNotifications: { allowedEventTypes: ['e2e.test'] },+ allowedCallers: ['sdk-caller'],+ },+ })+ )++ expect(result.phase).toBe('awaiting_policy')+ expect(result.message).toContain('operator policy pending')+ expect(result.message).toContain('grant_missing')})it('skips the provider broker while the eager mcp-host is not ready', async () => {diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.tsindex 3eef01263..de1012d46 100644--- a/workflow-recipes/src/workflow/workflowReconciler.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.ts@@ -209,6 +209,30 @@ function delay(ms: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, ms))}+function pluginWorkloadSdkPolicyReason(+ spec: WorkflowRecipeSpec,+ proof: EagerSdkBootstrapProof | undefined+): string {+ if (spec.pluginWorkloadSdk?.promptBridge && proof?.policyReady === false) {+ return proof.policyReason ?? proof.policyState ?? 'unknown'+ }+ if (+ spec.pluginWorkloadSdk?.clientNotifications &&+ proof?.clientNotificationsPolicyReady === false+ ) {+ return (+ proof.clientNotificationsPolicyReason ?? proof.clientNotificationsPolicyState ?? 'unknown'+ )+ }+ return (+ proof?.policyReason ??+ proof?.clientNotificationsPolicyReason ??+ proof?.policyState ??+ proof?.clientNotificationsPolicyState ??+ 'unknown'+ )+}+function normalizeCidrs(cidrs: string[]): string[] {return [...new Set(cidrs.map(cidr => cidr.trim()).filter(Boolean))].sort()}@@ -941,7 +965,7 @@ export class WorkflowReconciler {case 'awaiting_policy':return {phase: 'awaiting_policy',- message: `Plugin Workload SDK operator policy pending (${bootstrapProof?.policyReason ?? bootstrapProof?.policyState ?? 'unknown'})`,+ message: `Plugin Workload SDK operator policy pending (${pluginWorkloadSdkPolicyReason(spec, bootstrapProof)})`,pluginWorkloadSdkBootstrapProof: bootstrapProof,}case 'deploying':@@ -1403,14 +1427,13 @@ export class WorkflowReconciler {}}const eagerPolicyPending = eagerStatus === 'awaiting_policy'+ const pluginWorkloadSdkDeclared =+ spec.pluginWorkloadSdk?.promptBridge !== undefined ||+ spec.pluginWorkloadSdk?.clientNotifications !== undefinedconst eagerReady =(eagerStatus === 'ready' || eagerPolicyPending) &&- (!spec.pluginWorkloadSdk?.promptBridge || eagerBootstrapProof !== undefined)- if (- eagerStatus === 'ready' &&- spec.pluginWorkloadSdk?.promptBridge &&- !eagerBootstrapProof- ) {+ (!pluginWorkloadSdkDeclared || eagerBootstrapProof !== undefined)+ if (eagerStatus === 'ready' && pluginWorkloadSdkDeclared && !eagerBootstrapProof) {return withWorkflowConditions({phase: 'deploying',message: `Plugin Workload SDK bootstrap policy proof pending (${classification})`,@@ -1418,7 +1441,7 @@ export class WorkflowReconciler {})}const eagerMessage = eagerPolicyPending- ? `Plugin Workload SDK operator policy pending (${eagerBootstrapProof?.policyReason ?? eagerBootstrapProof?.policyState ?? 'unknown'}) (${classification})`+ ? `Plugin Workload SDK operator policy pending (${pluginWorkloadSdkPolicyReason(spec, eagerBootstrapProof)}) (${classification})`: eagerReady? `Plugin Workload SDK mcp-host registered (${classification})`: `Plugin Workload SDK mcp-host starting (${classification})`diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.tsindex 2b8d740ef..0d5516797 100644--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts@@ -134,6 +134,7 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {expect(result).toEqual({status: 202,body: {+ capabilityFamily: 'promptBridge',configured: true,ready: true,provider: 'openai',@@ -185,6 +186,7 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {expect(result).toEqual({status: 202,body: {+ capabilityFamily: 'promptBridge',configured: true,ready: true,provider: 'openai',