Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: complete stepless prompt bridge lifecycle
Alfredo Lopezc9eb8a8d9f56
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yamlindex 255f4450e..66841ad7a 100644--- a/charts/clerum-crds/crds/workflowrecipe.yaml+++ b/charts/clerum-crds/crds/workflowrecipe.yaml@@ -47,7 +47,7 @@ spec:# R1: agent{} binds either an executable workflow or the eager# Plugin Workload SDK promptBridge host. Empty steps[] is not a workflow.- rule: "!has(self.agent) || (has(self.steps) && size(self.steps) > 0) || (has(self.pluginWorkloadSdk) && has(self.pluginWorkloadSdk.promptBridge))"- message: "agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge"+ message: "agent requires non-empty workflow steps or spec.pluginWorkloadSdk.promptBridge"# SDK-only recipes are a capability runtime, not a dormant workflow.# Keep resolved workflow-only fields fail-closed in this mode.- rule: "!has(self.pluginWorkloadSdk) || (has(self.steps) && size(self.steps) > 0) || (!has(self.triggers) && !has(self.scheduling) && !has(self.coordinatorImage))"@@ -269,10 +269,14 @@ spec:agent:type: objectdescription: >-- Default agent configuration for workflow execution.+ Default agent configuration for workflow execution, or the+ provider/model bootstrap binding for a stepless+ spec.pluginWorkloadSdk.promptBridge runtime.properties:model:type: string+ maxLength: 128+ pattern: "^[A-Za-z0-9._:/-]{1,128}$"description: LLM model name (e.g., glm-4.7, gpt-4o, claude-3-opus).provider:type: string@@ -547,6 +551,8 @@ spec:properties:model:type: string+ maxLength: 128+ pattern: "^[A-Za-z0-9._:/-]{1,128}$"provider:type: string# bedrock AND azure intentionally absent (mono-credential@@ -1683,9 +1689,10 @@ spec:promptBridge:type: objectdescription: >-- One-shot LLM bridge capability. Requests can select a- model within allowedModels but never the provider —- the provider bound to the recipe's mcp-host wins.+ One-shot LLM bridge capability. The recipe's spec.agent+ supplies the eager host bootstrap identity; Control UI+ grants authorize the ordered provider/model/credential-slot+ targets that a backend may select at runtime.properties:allowedModels:type: array@@ -2132,7 +2139,7 @@ spec:properties:state:type: string- enum: [validated, disabled, degraded]+ enum: [validated, disabled, degraded, awaiting_policy]promptBridge:type: booleanclientNotifications:@@ -2142,6 +2149,26 @@ spec:validatedAt:type: stringformat: date-time+ bootstrapContractVersion:+ type: integer+ enum: [2]+ bootstrapPodUid:+ type: string+ bootstrapProvider:+ type: string+ bootstrapModel:+ type: string+ policyRevision:+ type: integer+ minimum: 1+ policyHash:+ type: string+ pattern: '^[a-f0-9]{64}$'+ defaultTargetRef:+ type: string+ verifiedAt:+ type: string+ format: date-timeconditions:type: arraydescription: Standard Kubernetes conditions.diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex e274676d8..64b831807 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","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 342e9df2e..377f347ea 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.399",+ "version": "0.1.400","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/app.ts b/control-api/src/app.tsindex 5346a471c..c45a2c156 100644--- a/control-api/src/app.ts+++ b/control-api/src/app.ts@@ -23,6 +23,7 @@ import { createInternalAgentRunEventsRouter } from './routes/internal/agentRunEvimport { createInternalBudgetsCheckRouter } from './routes/internal/budgetsCheck.js'import { createInternalInfrastructureTelemetryEventsRouter } from './routes/internal/infrastructureTelemetryEvents.js'import { createInternalOAuthRouter } from './routes/internal/oauth.js'+import { createInternalPluginWorkloadSdkRouter } from './routes/internal/pluginWorkloadSdk.js'import { createInternalSandboxUiRouter } from './routes/internal/sandboxUi.js'import { createInternalApprovalPromptHistoryRouter } from './routes/internal/tracing/approvalPromptHistory.routes.js'import { createInternalUsageEventsRouter } from './routes/internal/usageEvents.js'@@ -183,6 +184,7 @@ export function createApp(gateway: K8sGateway) {}))api.use(createInternalUsageEventsRouter())+ api.use(createInternalPluginWorkloadSdkRouter())api.use(createInternalBudgetsCheckRouter())api.use(createInternalWebhooksRouter(gateway))api.use(createInternalWorkflowApprovalReaderRouter(gateway))diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex 7c4fc7168..af743711e 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -7,9 +7,15 @@ import {import { config } from './config.js'import { applyMemberRegistrationCredentialsSchema } from './services/memberRegistrationCredentialsSchema.js'import {+ addPluginWorkloadSdkAttemptLedgerColumns,addPluginWorkloadSdkJitCredentialTicketColumns,addPluginWorkloadSdkPromptTargetPolicyColumns,+ addPluginWorkloadSdkProtocolAndRevocation,+ addPluginWorkloadSdkProviderAttemptLedger,addPluginWorkloadSdkProviderColumn,+ addPluginWorkloadSdkRevocationEpoch,+ addPluginWorkloadSdkRuntimeAccess,+ addPluginWorkloadSdkUsageSourceKind,applyPluginWorkloadSdkSchema,dropPluginWorkloadSdkSuperAdminApprovedColumn,} from './services/pluginWorkloadSdkSchema.js'@@ -1336,7 +1342,7 @@ async function applyWorkflowRecipeAllowedTeamsAuditSchema(db: DbClient): Promiseasync function applyUsageTrackingBaseline(db: DbClient): Promise<void> {await db.query(`DO $$ BEGIN- CREATE TYPE usage_source_kind AS ENUM ('channel','desktop','workflow','cron','unknown');+ CREATE TYPE usage_source_kind AS ENUM ('channel','desktop','workflow','cron','unknown','plugin_workload_sdk');EXCEPTION WHEN duplicate_object THEN NULL;END $$;@@ -3030,14 +3036,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [WHERE key_name NOT IN ('request_ref', 'provider', 'model', 'source_kind','input_tokens', 'output_tokens', 'cache_read_tokens',- 'cache_write_tokens', 'iteration'+ 'cache_write_tokens', 'iteration', 'prompt_bridge'))AND jsonb_typeof(value->'request_ref') = 'string'AND (value->>'request_ref') ~ '^[0-9a-f]{64}$'AND jsonb_typeof(value->'provider') = 'string'AND jsonb_typeof(value->'model') = 'string'- AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown')+ AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown', 'plugin_workload_sdk')AND jsonb_typeof(value->'source_kind') = 'string'AND jsonb_typeof(value->'input_tokens') = 'number'AND (value->>'input_tokens') ~ '^(0|[1-9][0-9]*)$'@@ -3054,6 +3060,24 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [AND (value->>'iteration') ~ '^(0|[1-9][0-9]*)$'))+ AND (+ NOT (value ? 'prompt_bridge')+ OR (+ jsonb_typeof(value->'prompt_bridge') = 'object'+ AND value->'prompt_bridge' ?& ARRAY[+ 'invocation_id', 'attempt_generation', 'target_ref',+ 'fallback_used', 'attempt_count', 'provider_attempt_id',+ 'provider_attempt_index'+ ]+ AND (value->'prompt_bridge'->>'invocation_id') ~ '^[0-9a-f-]{36}$'+ AND (value->'prompt_bridge'->>'provider_attempt_id') ~ '^[0-9a-f-]{36}$'+ AND (value->'prompt_bridge'->>'attempt_generation') ~ '^[1-9][0-9]*$'+ AND (value->'prompt_bridge'->>'provider_attempt_index') ~ '^[1-9][0-9]*$'+ AND jsonb_typeof(value->'prompt_bridge'->'target_ref') = 'string'+ AND jsonb_typeof(value->'prompt_bridge'->'fallback_used') = 'boolean'+ AND jsonb_typeof(value->'prompt_bridge'->'attempt_count') = 'number'+ )+ )END;$$;@@ -4325,7 +4349,7 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [WHERE key_name NOT IN ('request_ref', 'provider', 'model', 'source_kind','input_tokens', 'output_tokens', 'cache_read_tokens',- 'cache_write_tokens', 'cache_tokens_reported', 'iteration'+ 'cache_write_tokens', 'cache_tokens_reported', 'iteration', 'prompt_bridge'))AND jsonb_typeof(value->'request_ref') = 'string'@@ -4333,7 +4357,7 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [AND jsonb_typeof(value->'provider') = 'string'AND jsonb_typeof(value->'model') = 'string'AND jsonb_typeof(value->'source_kind') = 'string'- AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown')+ AND value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown', 'plugin_workload_sdk')AND jsonb_typeof(value->'input_tokens') = 'number'AND (value->>'input_tokens') ~ '^(0|[1-9][0-9]*)$'AND jsonb_typeof(value->'output_tokens') = 'number'@@ -4350,6 +4374,24 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [AND (value->>'iteration') ~ '^(0|[1-9][0-9]*)$'))+ AND (+ NOT (value ? 'prompt_bridge')+ OR (+ jsonb_typeof(value->'prompt_bridge') = 'object'+ AND value->'prompt_bridge' ?& ARRAY[+ 'invocation_id', 'attempt_generation', 'target_ref',+ 'fallback_used', 'attempt_count', 'provider_attempt_id',+ 'provider_attempt_index'+ ]+ AND (value->'prompt_bridge'->>'invocation_id') ~ '^[0-9a-f-]{36}$'+ AND (value->'prompt_bridge'->>'provider_attempt_id') ~ '^[0-9a-f-]{36}$'+ AND (value->'prompt_bridge'->>'attempt_generation') ~ '^[1-9][0-9]*$'+ AND (value->'prompt_bridge'->>'provider_attempt_index') ~ '^[1-9][0-9]*$'+ AND jsonb_typeof(value->'prompt_bridge'->'target_ref') = 'string'+ AND jsonb_typeof(value->'prompt_bridge'->'fallback_used') = 'boolean'+ AND jsonb_typeof(value->'prompt_bridge'->'attempt_count') = 'number'+ )+ )END;$$;@@ -5048,6 +5090,30 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [version: '0077_plugin_workload_sdk_usage_attribution',apply: addPromptBridgeUsageMetadataColumn,},+ {+ version: '0078_plugin_workload_sdk_attempt_ledger',+ apply: addPluginWorkloadSdkAttemptLedgerColumns,+ },+ {+ version: '0079_plugin_workload_sdk_usage_source_kind',+ apply: addPluginWorkloadSdkUsageSourceKind,+ },+ {+ version: '0080_plugin_workload_sdk_protocol_revocation',+ apply: addPluginWorkloadSdkProtocolAndRevocation,+ },+ {+ version: '0081_plugin_workload_sdk_provider_attempt_ledger',+ apply: addPluginWorkloadSdkProviderAttemptLedger,+ },+ {+ version: '0082_plugin_workload_sdk_revocation_epoch',+ apply: addPluginWorkloadSdkRevocationEpoch,+ },+ {+ version: '0083_plugin_workload_sdk_runtime_access',+ apply: addPluginWorkloadSdkRuntimeAccess,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex 6e4800412..f3898236c 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -10,6 +10,7 @@ import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModelimport {MAX_ALLOWLIST_ENTRY_LENGTH,MAX_ALLOWLIST_ITEMS,+ MAX_PROMPT_BRIDGE_TARGETS_PER_GRANT,PLUGIN_WORKLOAD_SDK_FAMILIES,PLUGIN_WORKLOAD_SDK_INVOCATION_STATUSES,type PluginWorkloadSdkFamily,@@ -18,6 +19,7 @@ import {type PluginWorkloadSdkPromptTarget,type PluginWorkloadSdkQuotaLimits,deleteGrant,+ getPluginWorkloadSdkLegacyGrantInventory,getQuotaCounters,listGrants,listInvocations,@@ -32,6 +34,7 @@ import { isPlainObject } from '../../utils/isPlainObject.js'// GET /admin/plugin-workload-sdk/grants// POST /admin/plugin-workload-sdk/grants (upsert by recipe+family)// DELETE /admin/plugin-workload-sdk/grants/:id+// GET /admin/plugin-workload-sdk/legacy-inventory (read-only migration gate)// GET /admin/plugin-workload-sdk/quota/:recipeNamespace/:recipeName// GET /admin/plugin-workload-sdk/invocations (audit search)@@ -88,6 +91,29 @@ function parseStringArray(value: unknown, field: string, res: Response): string[return value as string[]}+function parseModelArray(value: unknown, field: string, res: Response): string[] | null {+ const values = parseStringArray(value, field, res)+ if (values === null) return null+ // Keep wildcard rejection distinct from the runnable-model grammar error.+ // Wildcards are a policy-boundary violation, not a malformed model id, and+ // callers/tests rely on the stable structured error for that case.+ if (values.some(model => model.includes('*'))) {+ res.status(400).json({ error: 'wildcard_not_allowed' })+ return null+ }+ const invalid = values.find(+ model => !isRunnableLlmModelId(model.trim()) || model.trim() !== model+ )+ if (invalid !== undefined) {+ res.status(400).json({+ error: `${field} entries must be valid runnable model ids`,+ value: invalid,+ })+ return null+ }+ return values+}+const QUOTA_LIMIT_KEYS: ReadonlyArray<keyof PluginWorkloadSdkQuotaLimits> = ['maxRequestsPerRun','maxNotificationsPerRun',@@ -162,10 +188,10 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro.json({ error: 'promptTargets must be a non-empty array for promptBridge grants' })return null}- if (value.length > MAX_ALLOWLIST_ITEMS) {- res- .status(400)- .json({ error: `promptTargets must contain at most ${MAX_ALLOWLIST_ITEMS} entries` })+ if (value.length > MAX_PROMPT_BRIDGE_TARGETS_PER_GRANT) {+ res.status(400).json({+ error: `promptTargets must contain at most ${MAX_PROMPT_BRIDGE_TARGETS_PER_GRANT} entries`,+ })return null}const targets: PluginWorkloadSdkPromptTarget[] = []@@ -258,7 +284,7 @@ export function createAdminPluginWorkloadSdkRouter(): Router {return}- const allowedModels = parseStringArray(body.allowedModels, 'allowedModels', res)+ const allowedModels = parseModelArray(body.allowedModels, 'allowedModels', res)if (allowedModels === null) returnconst allowedEventTypes = parseStringArray(body.allowedEventTypes, 'allowedEventTypes', res)if (allowedEventTypes === null) return@@ -434,6 +460,21 @@ export function createAdminPluginWorkloadSdkRouter(): Router {}))+ router.get(+ '/admin/plugin-workload-sdk/legacy-inventory',+ asyncHandler(async (req, res) => {+ const recipeNamespace =+ typeof req.query.recipeNamespace === 'string' ? req.query.recipeNamespace.trim() : undefined+ const recipeName =+ typeof req.query.recipeName === 'string' ? req.query.recipeName.trim() : undefined+ const inventory = await getPluginWorkloadSdkLegacyGrantInventory({+ ...(recipeNamespace ? { recipeNamespace } : {}),+ ...(recipeName ? { recipeName } : {}),+ })+ res.status(200).json(inventory)+ })+ )+router.get('/admin/plugin-workload-sdk/quota/:recipeNamespace/:recipeName',asyncHandler(async (req, res) => {diff --git a/control-api/src/routes/internal/pluginWorkloadSdk.ts b/control-api/src/routes/internal/pluginWorkloadSdk.tsnew file mode 100644index 000000000..894e3f547--- /dev/null+++ b/control-api/src/routes/internal/pluginWorkloadSdk.ts@@ -0,0 +1,86 @@+import { Router } from 'express'+import { asyncHandler } from '../../http/asyncHandler.js'+import { requireInternalControlJwt } from '../../middleware/internalControlJwt.js'+import {+ finalizePluginWorkloadSdkRevocation,+ revokePluginWorkloadSdkForRecipe,+} from '../../services/pluginWorkloadSdkDb.js'+import { isPlainObject } from '../../utils/isPlainObject.js'++function recipeBinding(body: unknown): { recipeNamespace: string; recipeName: string } | null {+ if (!isPlainObject(body)) return null+ const recipeNamespace =+ typeof body.recipeNamespace === 'string' ? body.recipeNamespace.trim() : ''+ const recipeName = typeof body.recipeName === 'string' ? body.recipeName.trim() : ''+ if (!recipeNamespace || !recipeName || recipeNamespace.length > 253 || recipeName.length > 253) {+ return null+ }+ return { recipeNamespace, recipeName }+}++const REVOCATION_ID_RE =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i++function revocationId(body: unknown): string | null {+ if (!isPlainObject(body) || typeof body.revocationId !== 'string') return null+ const value = body.revocationId.trim()+ return REVOCATION_ID_RE.test(value) ? value : null+}++/**+ * WRC-only revocation boundary for SDK-only recipe teardown. The first call+ * fences Control API authorization and active generations; the second call is+ * accepted only after WRC has proved the endpoint/pod/secrets are absent.+ */+export function createInternalPluginWorkloadSdkRouter(): Router {+ const router = Router()+ router.post(+ '/internal/plugin-workload-sdk/revoke',+ requireInternalControlJwt,+ asyncHandler(async (req, res) => {+ const internalControl = req.internalControl+ if (internalControl?.iss !== 'wrc' || internalControl.sub !== 'wrc-provisioner') {+ res.status(403).json({ error: 'internal issuer not allowed' })+ return+ }+ const binding = recipeBinding(req.body)+ if (!binding) {+ res.status(400).json({ error: 'recipeNamespace and recipeName are required' })+ return+ }+ const result = await revokePluginWorkloadSdkForRecipe(+ binding.recipeNamespace,+ binding.recipeName,+ internalControl.sub+ )+ res.status(200).json(result)+ })+ )++ router.post(+ '/internal/plugin-workload-sdk/finalize-revocation',+ requireInternalControlJwt,+ asyncHandler(async (req, res) => {+ const internalControl = req.internalControl+ if (internalControl?.iss !== 'wrc' || internalControl.sub !== 'wrc-provisioner') {+ res.status(403).json({ error: 'internal issuer not allowed' })+ return+ }+ const binding = recipeBinding(req.body)+ const expectedRevocationId = revocationId(req.body)+ if (!binding || !expectedRevocationId) {+ res.status(400).json({ error: 'recipeNamespace, recipeName and revocationId are required' })+ return+ }+ const result = await finalizePluginWorkloadSdkRevocation(+ binding.recipeNamespace,+ binding.recipeName,+ expectedRevocationId,+ internalControl.sub+ )+ res.status(result.state === 'conflict' ? 409 : 200).json(result)+ })+ )++ return router+}diff --git a/control-api/src/routes/internal/usageEvents.ts b/control-api/src/routes/internal/usageEvents.tsindex 39296bd79..b6ae8f004 100644--- a/control-api/src/routes/internal/usageEvents.ts+++ b/control-api/src/routes/internal/usageEvents.ts@@ -2,7 +2,11 @@ import { Router } from 'express'import { config } from '../../config.js'import type { DbClient } from '../../db.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'-import { getInvocationById } from '../../services/pluginWorkloadSdkDb.js'+import {+ getInvocationById,+ getPluginWorkloadSdkAttemptReceipt,+ getPluginWorkloadSdkProviderAttempt,+} from '../../services/pluginWorkloadSdkDb.js'import { withTraceIngestTransaction } from '../../services/tracing/pools.js'import { projectAcceptedUsageEvents } from '../../services/tracing/usageProjection.js'import { ingestUsageEventsInTransaction } from '../../services/usageEvents.js'@@ -135,7 +139,7 @@ function checkClaimBinding(return { index: i, reason: 'recipe_token_missing_llm_secret_name' }}} else if (- sourceKind !== 'unknown' ||+ !['unknown', 'plugin_workload_sdk'].includes(String(sourceKind)) ||(e as { channel_type?: unknown }).channel_type !== 'plugin_workload_sdk' ||taskId ||!llmSecretName ||@@ -174,11 +178,92 @@ async function checkSdkOnlyUsageBinding(const event = events[index]if (!event || typeof event !== 'object') continueconst record = event as Record<string, unknown>- if (record.source_kind !== 'unknown') continue+ const isSdkOnlySource =+ record.source_kind === 'unknown' || record.source_kind === 'plugin_workload_sdk'+ const isWorkflowSdkSource =+ record.source_kind === 'workflow' && record.channel_type === 'plugin_workload_sdk'+ if (!isSdkOnlySource && !isWorkflowSdkSource) continueconst metadata = record.prompt_bridge_metadataif (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) continueconst invocationId = (metadata as { invocation_id?: unknown }).invocation_idif (typeof invocationId !== 'string') continue+ const attemptGeneration = (metadata as { attempt_generation?: unknown }).attempt_generation+ const providerAttemptId = (metadata as { provider_attempt_id?: unknown }).provider_attempt_id+ const providerAttemptIndex = (metadata as { provider_attempt_index?: unknown })+ .provider_attempt_index+ if (isSdkOnlySource || isWorkflowSdkSource) {+ // A pre-v2 host cannot emit a physical-attempt receipt. Keep its+ // compatibility lane explicit and narrow: the persisted invocation must+ // be contract v1 and the event must match that legacy provider/model.+ if (!Number.isInteger(attemptGeneration) || Number(attemptGeneration) < 1) {+ const invocation = await getInvocationById(invocationId, db)+ if (+ !invocation ||+ invocation.contractVersion !== 1 ||+ invocation.recipeNamespace !== claims.recipeNamespace ||+ invocation.recipeName !== claims.recipeName ||+ invocation.method !== 'promptBridge' ||+ !['in_progress', 'complete'].includes(invocation.status) ||+ invocation.authorizationDecision !== 'authorized' ||+ invocation.detail !== String(record.model ?? '')+ ) {+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }+ }+ continue+ }+ const receipt = await getPluginWorkloadSdkAttemptReceipt(+ invocationId,+ Number(attemptGeneration),+ db+ )+ const targetRef = String((metadata as { target_ref?: unknown }).target_ref ?? '')+ if (+ !receipt ||+ receipt.method !== 'promptBridge' ||+ receipt.recipeNamespace !== claims.recipeNamespace ||+ receipt.recipeName !== claims.recipeName+ ) {+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }+ }+ const hasPhysicalAttempt =+ typeof providerAttemptId === 'string' && Number.isInteger(providerAttemptIndex)+ if (!hasPhysicalAttempt) {+ const invocation = await getInvocationById(invocationId, db)+ if (+ !invocation ||+ invocation.contractVersion !== 1 ||+ invocation.recipeNamespace !== claims.recipeNamespace ||+ invocation.recipeName !== claims.recipeName ||+ invocation.method !== 'promptBridge' ||+ !['in_progress', 'complete'].includes(invocation.status) ||+ invocation.authorizationDecision !== 'authorized' ||+ invocation.detail !== String(record.model ?? '')+ ) {+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }+ }+ continue+ }+ const providerAttempt = await getPluginWorkloadSdkProviderAttempt(+ providerAttemptId as string,+ db+ )+ if (+ !receipt.targetRefs.includes(targetRef) ||+ !providerAttempt ||+ providerAttempt.invocationId !== invocationId ||+ providerAttempt.attemptGeneration !== Number(attemptGeneration) ||+ providerAttempt.attemptIndex !== Number(providerAttemptIndex) ||+ providerAttempt.targetRef !== targetRef ||+ providerAttempt.provider !== String(record.provider ?? '') ||+ providerAttempt.model !== String(record.model ?? '') ||+ providerAttempt.credentialSlot !==+ String((metadata as { credential_slot?: unknown }).credential_slot ?? '') ||+ providerAttempt.status !== 'complete'+ ) {+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }+ }+ continue+ }const invocation = await getInvocationById(invocationId, db)if (!invocation ||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 19b0f61f4..269ae2a4a 100644--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts@@ -1,4 +1,4 @@-import { type Response, Router } from 'express'+import { type Request, type Response, Router } from 'express'import { pool } from '../../db.js'import { asyncHandler } from '../../http/asyncHandler.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'@@ -27,8 +27,11 @@ import {import {findGrant,getInvocationById,+ getPluginWorkloadSdkAttemptReceipt,+ getPluginWorkloadSdkProviderAttempt,hashPromptTargetPolicy,listInvocations,+ markPluginWorkloadSdkProviderAttemptStatus,redeemPluginWorkloadSdkCredentialTicketJti,resolveRecipientProfiles,} from '../../services/pluginWorkloadSdkDb.js'@@ -41,7 +44,9 @@ import { isPlainObject } from '../../utils/isPlainObject.js'// host/control gateway path as every other mcp-host runtime call// (conformance: spec §19 "mcp-host control-api access uses the gateway").//-// POST /mcp-host/plugin-workload-sdk/prompt-bridge+// POST /mcp-host/plugin-workload-sdk/prompt-bridge/v2+// POST /mcp-host/plugin-workload-sdk/prompt-bridge (v1 compatibility)+// GET /mcp-host/plugin-workload-sdk/capabilities// POST /mcp-host/plugin-workload-sdk/client-notification// POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket// GET /mcp-host/plugin-workload-sdk/invocations/:recipeRef@@ -51,6 +56,8 @@ const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)/** Opaque refs must not smuggle raw channel addresses (spec §17). */const EMAIL_LIKE_RE = /@/const PHONE_LIKE_RE = /^\+?[0-9][0-9\s().-]{6,}$/+/** Current target-aware/JIT promptBridge wire contract. */+export const PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION = 2// Credential-ticket introspection and reissue both perform signature checks,// database reads, and (for reissue) signing work before the provider call.@@ -79,6 +86,7 @@ const AUTHZ_HTTP_STATUS: Record<PluginWorkloadSdkErrorCode, number> = {payload_too_large: 413,idempotency_conflict: 422,recipe_binding_mismatch: 400,+ protocol_mismatch: 503,}function sendAuthzError(res: Response, error: PluginWorkloadSdkAuthzError): void {@@ -135,6 +143,7 @@ function validateCallerRef(value: unknown, res: Response): string | null {// ─── promptBridge input validation (plan §2.7) ───────────────────────────interface ParsedPromptBridgeBody {+ contractVersion?: numbercallerRef: stringbootstrapProvider: stringbootstrapModel: string@@ -151,17 +160,45 @@ interface ParsedPromptBridgeBody {function parsePromptBridgeBody(body: Record<string, unknown>,- res: Response+ res: Response,+ options: {+ requireContractVersion?: boolean+ requireBootstrapBinding?: boolean+ legacyProtocol?: boolean+ } = {}): ParsedPromptBridgeBody | null {const callerRef = validateCallerRef(body.callerRef, res)if (!callerRef) return null+ const contractVersion =+ body.contractVersion === undefined+ ? undefined+ : Number.isInteger(body.contractVersion)+ ? Number(body.contractVersion)+ : 0+ if (+ (options.requireContractVersion &&+ contractVersion !== PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION) ||+ (!options.requireContractVersion &&+ contractVersion !== undefined &&+ (options.legacyProtocol+ ? contractVersion !== 1+ : contractVersion !== PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION))+ ) {+ res.status(409).json({+ error: 'protocol_mismatch',+ message: `promptBridge contractVersion ${PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION} is required`,+ retryable: true,+ })+ return null+ }+// These fields are supplied only by the recipe-bound mcp-host. They carry// the public provider/model identity from spec.agent, never credentials.const bootstrapProvider =typeof body.bootstrapProvider === 'string' ? body.bootstrapProvider.trim() : ''const bootstrapModel = typeof body.bootstrapModel === 'string' ? body.bootstrapModel.trim() : ''- if (!bootstrapProvider || !bootstrapModel) {+ if (options.requireBootstrapBinding && (!bootstrapProvider || !bootstrapModel)) {res.status(400).json({ error: 'bootstrap_binding_required' })return null}@@ -245,6 +282,7 @@ function parsePromptBridgeBody(: undefinedreturn {+ ...(contractVersion !== undefined ? { contractVersion } : {}),callerRef,bootstrapProvider,bootstrapModel,@@ -407,6 +445,68 @@ function parseClientNotificationBody(// ─── Router ──────────────────────────────────────────────────────────────+async function handlePromptBridgeAuthorization(+ req: Request,+ res: Response,+ options: {+ requireContractVersion: boolean+ requireBootstrapBinding: boolean+ legacyProtocol?: boolean+ }+): Promise<void> {+ const claims = req.mcpHostJwt!+ const body = isPlainObject(req.body) ? req.body : {}+ if (!checkRecipeBinding(body, claims, res)) return+ const parsed = parsePromptBridgeBody(body, res, options)+ if (!parsed) return++ const result = await authorizePromptBridge({+ claims,+ callerRef: parsed.callerRef,+ bootstrapProvider: parsed.bootstrapProvider,+ bootstrapModel: parsed.bootstrapModel,+ model: parsed.model,+ provider: parsed.provider,+ targetRef: parsed.targetRef,+ modelPolicyRef: parsed.modelPolicyRef,+ purpose: parsed.purpose,+ idempotencyKey: parsed.idempotencyKey,+ payload: {+ messages: parsed.messages,+ model: parsed.model ?? null,+ provider: parsed.provider ?? null,+ targetRef: parsed.targetRef ?? null,+ modelPolicyRef: parsed.modelPolicyRef ?? null,+ purpose: parsed.purpose,+ ...(parsed.metadata ? { metadata: parsed.metadata } : {}),+ },+ correlationId: parsed.correlationId,+ legacyProtocol: options.legacyProtocol,+ })+ if (!result.ok) {+ sendAuthzError(res, result)+ return+ }++ res.status(result.value.replay ? 200 : 201).json({+ ...(options.requireContractVersion+ ? { contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION }+ : {}),+ invocationId: result.value.invocationId,+ replay: result.value.replay,+ providerCallRequired: result.value.providerCallRequired,+ status: result.value.status,+ model: result.value.model,+ modelPolicy: result.value.modelPolicy,+ selectedTarget: result.value.selectedTarget,+ authorizedTargets: result.value.authorizedTargets,+ attemptGeneration: result.value.attemptGeneration,+ policyRevision: result.value.policyRevision,+ policyHash: result.value.policyHash,+ maxOutputTokens: result.value.maxOutputTokens,+ })+}+export function createMcpHostPluginWorkloadSdkRoutes(): Router {const router = Router()@@ -426,14 +526,25 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {if (!checkRecipeBinding(body, claims, res)) returnconst invocationId = typeof body.invocationId === 'string' ? body.invocationId.trim() : ''const targetRef = typeof body.targetRef === 'string' ? body.targetRef.trim() : ''- if (!invocationId || !targetRef || targetRef.length > MAX_TARGET_REF_LENGTH) {- res.status(400).json({ error: 'invocationId and targetRef are required' })+ const attemptGeneration = Number.isInteger(body.attemptGeneration)+ ? Number(body.attemptGeneration)+ : 0+ if (+ !invocationId ||+ !targetRef ||+ targetRef.length > MAX_TARGET_REF_LENGTH ||+ attemptGeneration < 1+ ) {+ res+ .status(400)+ .json({ error: 'invocationId, targetRef and attemptGeneration are required' })return}const result = await reissuePromptBridgeCredentialTicket({claims,invocationId,targetRef,+ attemptGeneration,})if (!result.ok) {sendAuthzError(res, result)@@ -443,55 +554,63 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {}))+ // v2 is the target-aware/JIT contract. It is additive: old mcp-hosts keep+ // using the v1 path below, while new clients fail clearly if this endpoint+ // is absent instead of falling back to bootstrap credentials.router.post(- '/mcp-host/plugin-workload-sdk/prompt-bridge',+ '/mcp-host/plugin-workload-sdk/prompt-bridge/v2',requireMcpHostJwt,- asyncHandler(async (req, res) => {- const claims = req.mcpHostJwt!- const body = isPlainObject(req.body) ? req.body : {}- if (!checkRecipeBinding(body, claims, res)) return- const parsed = parsePromptBridgeBody(body, res)- if (!parsed) return+ asyncHandler(async (req, res) =>+ handlePromptBridgeAuthorization(req, res, {+ requireContractVersion: true,+ requireBootstrapBinding: true,+ })+ )+ )- const result = await authorizePromptBridge({- claims,- callerRef: parsed.callerRef,- bootstrapProvider: parsed.bootstrapProvider,- bootstrapModel: parsed.bootstrapModel,- model: parsed.model,- provider: parsed.provider,- targetRef: parsed.targetRef,- modelPolicyRef: parsed.modelPolicyRef,- purpose: parsed.purpose,- idempotencyKey: parsed.idempotencyKey,- payload: {- messages: parsed.messages,- model: parsed.model ?? null,- provider: parsed.provider ?? null,- targetRef: parsed.targetRef ?? null,- modelPolicyRef: parsed.modelPolicyRef ?? null,- purpose: parsed.purpose,- ...(parsed.metadata ? { metadata: parsed.metadata } : {}),- },- correlationId: parsed.correlationId,+ // Compatibility lane for an older mcp-host during a server-first rollout.+ // It intentionally has no cross-provider target response contract; it uses+ // the current persisted policy but does not require the new bootstrap fields.+ router.post(+ '/mcp-host/plugin-workload-sdk/prompt-bridge',+ requireMcpHostJwt,+ asyncHandler(async (req, res) =>+ handlePromptBridgeAuthorization(req, res, {+ requireContractVersion: false,+ requireBootstrapBinding: false,+ legacyProtocol: true,})- if (!result.ok) {- sendAuthzError(res, result)- return- }+ )+ )- res.status(result.value.replay ? 200 : 201).json({- invocationId: result.value.invocationId,- replay: result.value.replay,- providerCallRequired: result.value.providerCallRequired,- status: result.value.status,- model: result.value.model,- modelPolicy: result.value.modelPolicy,- selectedTarget: result.value.selectedTarget,- authorizedTargets: result.value.authorizedTargets,- policyRevision: result.value.policyRevision,- policyHash: result.value.policyHash,- maxOutputTokens: result.value.maxOutputTokens,+ router.get(+ '/mcp-host/plugin-workload-sdk/capabilities',+ requireMcpHostJwt,+ asyncHandler(async (_req, res) => {+ const claims = _req.mcpHostJwt!+ const grant = await findGrant(claims.recipeNamespace, claims.recipeName, 'promptBridge')+ const v2Ready = Boolean(+ grant &&+ grant.policyState === 'active' &&+ grant.policyRevision >= 1 &&+ grant.promptTargets.length > 0 &&+ grant.defaultTargetRef !== null &&+ grant.promptTargets[0]?.targetRef === grant.defaultTargetRef+ )+ const primaryTarget = grant?.promptTargets[0] ?? null+ res.status(200).json({+ contractVersion: PLUGIN_WORKLOAD_SDK_PROMPT_BRIDGE_CONTRACT_VERSION,+ supportedContractVersions: [1, 2],+ targetAwarePromptBridge: true,+ attemptLedger: true,+ credentialTickets: true,+ policyState: grant?.policyState ?? 'missing',+ policyRevision: grant?.policyRevision ?? 0,+ policyHash: v2Ready && grant ? hashPromptTargetPolicy(grant) : null,+ defaultTargetRef: grant?.defaultTargetRef ?? null,+ defaultProvider: primaryTarget?.provider ?? null,+ defaultModel: primaryTarget?.model ?? null,+ v2Ready,})}))@@ -609,9 +728,30 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {const ticket = typeof body.credentialTicket === 'string' ? body.credentialTicket : ''const invocationId = typeof body.invocationId === 'string' ? body.invocationId : ''const targetRef = typeof body.targetRef === 'string' ? body.targetRef : ''+ const providedAttemptGeneration = Number.isInteger(body.attemptGeneration)+ ? Number(body.attemptGeneration)+ : null+ const attemptGeneration = providedAttemptGeneration ?? 0+ const providerAttemptId =+ typeof body.providerAttemptId === 'string' ? body.providerAttemptId.trim() : ''+ const providerAttemptIndex = Number.isInteger(body.providerAttemptIndex)+ ? Number(body.providerAttemptIndex)+ : 0const redeem = body.redeem === true- if (!ticket || !invocationId || !targetRef) {- res.status(400).json({ error: 'credentialTicket, invocationId and targetRef are required' })+ if (+ !ticket ||+ !invocationId ||+ !targetRef ||+ !providerAttemptId ||+ attemptGeneration < 1 ||+ providerAttemptIndex < 1+ ) {+ res+ .status(400)+ .json({+ error:+ 'credentialTicket, invocationId, targetRef, providerAttemptId and attemptGeneration are required',+ })return}const ticketClaims = verifyPluginWorkloadSdkCredentialTicket(ticket)@@ -621,7 +761,10 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {ticketClaims.recipeName !== claims.recipeName ||ticketClaims.sub !== `${claims.recipeNamespace}/${claims.recipeName}` ||ticketClaims.invocationId !== invocationId ||- ticketClaims.targetRef !== targetRef+ ticketClaims.targetRef !== targetRef ||+ ticketClaims.attemptGeneration !== attemptGeneration ||+ ticketClaims.providerAttemptId !== providerAttemptId ||+ ticketClaims.providerAttemptIndex !== providerAttemptIndex) {res.status(403).json({ error: 'provider_policy_denied', retryable: false })return@@ -633,6 +776,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {invocation.recipeName !== claims.recipeName ||invocation.method !== 'promptBridge' ||invocation.status !== 'in_progress' ||+ invocation.attemptGeneration !== attemptGeneration ||invocation.authorizationDecision !== 'authorized' ||!invocation.promptAuthorization ||!invocation.promptAuthorization.authorizedTargetRefs.includes(targetRef) ||@@ -642,10 +786,29 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {res.status(403).json({ error: 'provider_policy_denied', retryable: false })return}+ const receipt = await getPluginWorkloadSdkAttemptReceipt(invocationId, attemptGeneration)+ const providerAttempt = await getPluginWorkloadSdkProviderAttempt(providerAttemptId)+ if (+ !receipt ||+ receipt.recipeNamespace !== claims.recipeNamespace ||+ receipt.recipeName !== claims.recipeName ||+ receipt.method !== 'promptBridge' ||+ receipt.status !== 'in_progress' ||+ receipt.attemptGeneration !== attemptGeneration ||+ !providerAttempt ||+ providerAttempt.invocationId !== invocationId ||+ providerAttempt.attemptGeneration !== attemptGeneration ||+ providerAttempt.targetRef !== targetRef ||+ providerAttempt.status !== 'in_progress'+ ) {+ res.status(403).json({ error: 'provider_policy_denied', retryable: false })+ return+ }const grant = await findGrant(claims.recipeNamespace, claims.recipeName, 'promptBridge')const target = grant?.promptTargets.find(candidate => candidate.targetRef === targetRef)if (!grant ||+ grant.policyState !== 'active' ||!target ||grant.policyRevision !== ticketClaims.policyRevision ||hashPromptTargetPolicy(grant) !== ticketClaims.policyHash ||@@ -663,6 +826,8 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {recipeName: claims.recipeName,invocationId,targetRef,+ attemptGeneration,+ providerAttemptId,})if (!redeemed) {res.status(403).json({ error: 'provider_policy_denied', retryable: false })@@ -685,13 +850,15 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {if (!checkRecipeBinding(body, claims, res)) returnconst status = typeof body.status === 'string' ? body.status : ''+ const providedAttemptGeneration = Number.isInteger(body.attemptGeneration)+ ? Number(body.attemptGeneration)+ : nullif (!['complete', 'failed', 'provider_unavailable'].includes(status)) {res.status(400).json({ error: 'status must be one of: complete, failed, provider_unavailable' })return}-const invocation = await getInvocationById(req.params.id)if (!invocation) {res.status(404).json({ error: 'invocation not found' })@@ -706,19 +873,93 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {return}+ const attemptGeneration = providedAttemptGeneration ?? invocation.attemptGeneration+ if (+ providedAttemptGeneration === null &&+ (invocation.contractVersion !== 1 || invocation.attemptGeneration !== 1)+ ) {+ res.status(400).json({ error: 'attemptGeneration is required for contract v2' })+ return+ }+ if (attemptGeneration < 1) {+ res.status(400).json({ error: 'attemptGeneration is required' })+ return+ }+const updated = await markInvocationStatus(invocation.id,status as 'complete' | 'failed' | 'provider_unavailable',- { recipeNamespace: claims.recipeNamespace, recipeName: claims.recipeName }+ {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ expectedCurrentStatus: 'in_progress',+ expectedAttemptGeneration: attemptGeneration,+ })if (!updated) {- res.status(404).json({ error: 'invocation not found' })+ res.status(409).json({ error: 'stale_attempt', retryable: false })return}res.status(200).json({ id: invocation.id, status })}))+ router.post(+ '/mcp-host/plugin-workload-sdk/provider-attempts/:id/status',+ requireMcpHostJwt,+ asyncHandler(async (req, res) => {+ const claims = req.mcpHostJwt!+ const body = isPlainObject(req.body) ? req.body : {}+ if (!checkRecipeBinding(body, claims, res)) return+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId.trim() : ''+ const attemptGeneration = Number.isInteger(body.attemptGeneration)+ ? Number(body.attemptGeneration)+ : 0+ const providerAttemptIndex = Number.isInteger(body.providerAttemptIndex)+ ? Number(body.providerAttemptIndex)+ : 0+ const status = body.status+ if (+ !invocationId ||+ attemptGeneration < 1 ||+ providerAttemptIndex < 1 ||+ !['complete', 'failed', 'provider_unavailable'].includes(String(status))+ ) {+ res+ .status(400)+ .json({+ error: 'invocationId, attemptGeneration, providerAttemptIndex and status are required',+ })+ return+ }+ const attempt = await getPluginWorkloadSdkProviderAttempt(req.params.id)+ if (+ !attempt ||+ attempt.invocationId !== invocationId ||+ attempt.recipeNamespace !== claims.recipeNamespace ||+ attempt.recipeName !== claims.recipeName ||+ attempt.attemptGeneration !== attemptGeneration ||+ attempt.attemptIndex !== providerAttemptIndex+ ) {+ res.status(403).json({ error: 'provider_policy_denied', retryable: false })+ return+ }+ const updated = await markPluginWorkloadSdkProviderAttemptStatus({+ id: attempt.id,+ invocationId,+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ attemptGeneration,+ status: status as 'complete' | 'failed' | 'provider_unavailable',+ })+ if (!updated) {+ res.status(409).json({ error: 'stale_attempt', retryable: false })+ return+ }+ res.status(200).json({ id: attempt.id, status })+ })+ )+router.get('/mcp-host/plugin-workload-sdk/invocations/:recipeRef',requireMcpHostJwt,diff --git a/control-api/src/services/budgets/check.ts b/control-api/src/services/budgets/check.tsindex d6d2f58f5..e2b1ca4ab 100644--- a/control-api/src/services/budgets/check.ts+++ b/control-api/src/services/budgets/check.ts@@ -57,7 +57,14 @@ export const budgetCheckRequestSchema = zprovider: z.string().min(1, 'provider is required'),model: z.string().min(1, 'model is required'),llm_secret_name: nullableStr,- source_kind: z.enum(['channel', 'desktop', 'workflow', 'cron', 'unknown']),+ source_kind: z.enum([+ 'channel',+ 'desktop',+ 'workflow',+ 'cron',+ 'unknown',+ 'plugin_workload_sdk',+ ]),recipe_name: nullableStr,cron_job_id: nullableStr,// Correlation id for the anti-race danger-zone reservation (§5.4). mcp-hostdiff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.tsindex ddc89ad5f..1d9b4ce9a 100644--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts@@ -5,16 +5,24 @@ import {issuePluginWorkloadSdkCredentialTicketWithClaims,} from './pluginWorkloadSdkCredentialTicket.js'import {+ MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS,type PluginWorkloadSdkErrorCode,type PluginWorkloadSdkGrant,type PluginWorkloadSdkModelPolicy,type PluginWorkloadSdkPromptTarget,findGrant,getInvocationById,+ getPluginWorkloadSdkAttemptReceipt,hashPromptTargetPolicy,+ markPluginWorkloadSdkProviderAttemptStatus,registerPluginWorkloadSdkCredentialTicketJti,+ reservePluginWorkloadSdkProviderAttempt,} from './pluginWorkloadSdkDb.js'-import { markInvocationStatus, recordInvocation } from './pluginWorkloadSdkInvocationAuditor.js'+import {+ markInvocationStatus,+ recordInvocation,+ reviveFailedSdkInvocation,+} from './pluginWorkloadSdkInvocationAuditor.js'import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js'// ─── Plugin Workload SDK — authorizer (plan §2.2) ────────────────────────@@ -31,7 +39,6 @@ import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js// flipped to failed so the trail shows the denied attempt.const PLUGIN_WORKLOAD_SDK_SCOPE = 'plugin-workload-sdk'-const MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS = 4export type PluginWorkloadSdkAuthzError = {ok: false@@ -99,6 +106,8 @@ export interface AuthorizePromptBridgeParams {/** Canonical request payload — hashed for idempotency conflict detection. */payload: unknowncorrelationId?: string+ /** True only for the temporary pre-v2 mcp-host compatibility route. */+ legacyProtocol?: boolean}export interface AuthorizedPromptBridge {@@ -114,6 +123,8 @@ export interface AuthorizedPromptBridge {selectedTarget: PluginWorkloadSdkPromptTarget/** Selected target plus its strictly ordered authorized fallback suffix. */authorizedTargets: PluginWorkloadSdkPromptTarget[]+ /** Fencing token for this physical provider attempt. */+ attemptGeneration: numberpolicyRevision: numberpolicyHash: stringmaxOutputTokens: number | null@@ -265,6 +276,17 @@ async function authorizePromptBridgeInner(return deny('capability_not_declared', 'recipe has no promptBridge grant')}+ if (params.legacyProtocol) {+ return authorizeLegacyPromptBridge(params, grant)+ }++ if (grant.policyState !== 'active' || grant.policyRevision < 1) {+ return deny(+ 'provider_policy_denied',+ 'promptBridge grant requires an explicit operator-reviewed target policy'+ )+ }+const callerError = checkCaller(grant, callerRef)if (callerError) return callerError@@ -319,7 +341,14 @@ async function authorizePromptBridgeInner(policyHash: resolvedPolicyHash,authorizedTargetRefs: authorizedTargets.map(target => target.targetRef),},+ requiredGrantStates: ['active'],})+ if (recorded.kind === 'policy_revoked') {+ return deny(+ 'provider_policy_denied',+ 'promptBridge policy was revoked before invocation reservation'+ )+ }if (recorded.kind === 'conflict') {return deny('idempotency_conflict', 'idempotency key was already used with a different payload')}@@ -346,6 +375,7 @@ async function authorizePromptBridgeInner(modelPolicy: resolution.modelPolicy,selectedTarget,authorizedTargets,+ attemptGeneration: recorded.invocation.attemptGeneration,policyRevision: grant.policyRevision,policyHash: resolvedPolicyHash,maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,@@ -374,45 +404,75 @@ async function authorizePromptBridgeInner('idempotency key belongs to an older promptBridge policy; retry with a new idempotency key')}- const revived = await markInvocationStatus(recorded.invocation.id, 'in_progress', {+ const revivedGeneration = await reviveFailedSdkInvocation({+ invocationId: recorded.invocation.id,recipeNamespace: claims.recipeNamespace,recipeName: claims.recipeName,- expectedCurrentStatus: 'failed',})- // Older unit doubles did not return a boolean. Treat only an explicit- // false as a lost CAS; the real DB helper always returns true/false.- if (revived === false) {+ if (revivedGeneration === null) {return deny('idempotency_conflict','idempotent retry is already being handled; use a new idempotency key if it fails again',true)}+ recorded.invocation.attemptGeneration = revivedGeneration}- const rate = await checkRateLimit(- claims.recipeNamespace,- claims.recipeName,- 'promptBridge',- grant- )- if (!rate.ok) {- await markInvocationStatus(recorded.invocation.id, 'failed', {- recipeNamespace: claims.recipeNamespace,- recipeName: claims.recipeName,- ...(recorded.kind === 'replay' ? { expectedCurrentStatus: 'in_progress' as const } : {}),- })- return deny(rate.error, rate.message)+ const statusBinding = {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ ...(recorded.kind === 'replay'+ ? {+ expectedCurrentStatus: 'in_progress' as const,+ expectedAttemptGeneration: recorded.invocation.attemptGeneration,+ }+ : { expectedAttemptGeneration: recorded.invocation.attemptGeneration }),+ }+ const transitionToFailed = async (): Promise<void> => {+ await markInvocationStatus(recorded.invocation.id, 'failed', statusBinding)}- const quota = await consumeQuota(claims.recipeNamespace, claims.recipeName, 'promptBridge', grant)- if (!quota.ok) {- await markInvocationStatus(recorded.invocation.id, 'failed', {- recipeNamespace: claims.recipeNamespace,- recipeName: claims.recipeName,- ...(recorded.kind === 'replay' ? { expectedCurrentStatus: 'in_progress' as const } : {}),- })- return deny(quota.error, quota.message)+ // The retry CAS happens before rate/quota checks. Any exception after that+ // claim must release it; otherwise the maintenance sweep can fail an active+ // retry (and make its JIT ticket appear invalid) while the caller is still+ // handling the error.+ try {+ const rate = await checkRateLimit(+ claims.recipeNamespace,+ claims.recipeName,+ 'promptBridge',+ grant+ )+ if (!rate.ok) {+ await transitionToFailed()+ return deny(rate.error, rate.message)+ }++ // Period quota is charged once per logical idempotent invocation. A+ // failed provider retry is a new physical attempt (rate-limited above),+ // not a second logical request that should consume the same run budget.+ if (recorded.kind !== 'replay') {+ const quota = await consumeQuota(+ claims.recipeNamespace,+ claims.recipeName,+ 'promptBridge',+ grant+ )+ if (!quota.ok) {+ await transitionToFailed()+ return deny(quota.error, quota.message)+ }+ }+ } catch (error) {+ try {+ await transitionToFailed()+ } catch {+ // Preserve the original rate/quota/database error. The maintenance+ // sweep remains the final recovery path if the compensating update also+ // fails.+ }+ throw error}return {@@ -426,6 +486,7 @@ async function authorizePromptBridgeInner(modelPolicy: resolution.modelPolicy,selectedTarget,authorizedTargets,+ attemptGeneration: recorded.invocation.attemptGeneration,policyRevision: grant.policyRevision,policyHash: resolvedPolicyHash,maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,@@ -433,15 +494,193 @@ async function authorizePromptBridgeInner(}}+/**+ * Narrow compatibility lane for an older mcp-host during a rolling upgrade.+ * It deliberately reads only the legacy provider + flat allowedModels fields,+ * never target policy/JIT data, and records contract_version=1. This keeps an+ * old host on its already configured single provider while v2 owns the new+ * multiprovider target contract.+ */+async function authorizeLegacyPromptBridge(+ params: AuthorizePromptBridgeParams,+ grant: PluginWorkloadSdkGrant+): Promise<PluginWorkloadSdkAuthzResult<AuthorizedPromptBridge>> {+ const { claims, callerRef } = params+ if (grant.policyState !== 'legacy_unreviewed' && grant.policyState !== 'active') {+ return deny('provider_policy_denied', 'promptBridge policy is being revoked or is disabled')+ }+ const callerError = checkCaller(grant, callerRef)+ if (callerError) return callerError+ if (params.targetRef !== undefined || params.modelPolicyRef !== undefined) {+ return deny(+ 'protocol_mismatch',+ 'legacy promptBridge accepts only the configured provider and model; upgrade mcp-host for target selectors',+ true+ )+ }+ const provider = grant.provider?.trim() || params.bootstrapProvider?.trim() || ''+ const model = params.model?.trim() || params.bootstrapModel?.trim() || grant.allowedModels[0]+ if (!provider || !model || grant.allowedModels.length === 0) {+ return deny(+ 'provider_policy_denied',+ 'legacy promptBridge grant has no explicit provider/model binding; review it before use'+ )+ }+ if (params.provider !== undefined && params.provider !== provider) {+ return deny(+ 'provider_policy_denied',+ 'legacy promptBridge provider is fixed by the host binding'+ )+ }+ if (params.bootstrapProvider !== undefined && params.bootstrapProvider.trim() !== provider) {+ return deny(+ 'provider_policy_denied',+ 'legacy promptBridge bootstrap provider is not authorized'+ )+ }+ if (params.bootstrapModel !== undefined && params.bootstrapModel.trim() !== model) {+ return deny('provider_policy_denied', 'legacy promptBridge bootstrap model is not authorized')+ }+ if (!grant.allowedModels.includes(model)) {+ return deny('target_not_allowed', 'requested model is not in the legacy grant allowlist')+ }++ const selectedTarget: PluginWorkloadSdkPromptTarget = {+ targetRef: `legacy:${provider}:${model}`,+ provider,+ model,+ credentialSlot: 'legacy-host-binding',+ }+ const recorded = await recordInvocation({+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ callerRef,+ correlationId: params.correlationId,+ method: 'promptBridge',+ detail: model,+ purpose: params.purpose,+ idempotencyKey: params.idempotencyKey,+ payload: params.payload,+ status: 'in_progress',+ authorizationDecision: 'authorized',+ contractVersion: 1,+ requiredGrantStates: ['active', 'legacy_unreviewed'],+ })+ if (recorded.kind === 'policy_revoked') {+ return deny(+ 'provider_policy_denied',+ 'legacy promptBridge policy was revoked before invocation reservation'+ )+ }+ if (recorded.kind === 'conflict') {+ return deny('idempotency_conflict', 'idempotency key was already used with a different payload')+ }+ if (recorded.kind === 'race_unresolved') {+ return deny('idempotency_conflict', 'idempotency reservation could not be resolved', true)+ }+ if (recorded.kind === 'replay') {+ if (recorded.invocation.contractVersion !== 1 || recorded.invocation.status === 'failed') {+ return deny(+ 'idempotency_conflict',+ 'legacy invocation cannot be replayed after a failed or upgraded attempt; retry with a new key'+ )+ }+ return {+ ok: true,+ value: {+ invocationId: recorded.invocation.id,+ replay: true,+ providerCallRequired: false,+ status: recorded.invocation.status,+ model: selectedTarget.model,+ modelPolicy: null,+ selectedTarget,+ authorizedTargets: [selectedTarget],+ attemptGeneration: recorded.invocation.attemptGeneration,+ policyRevision: 0,+ policyHash: '0'.repeat(64),+ maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,+ },+ }+ }++ try {+ const rate = await checkRateLimit(+ claims.recipeNamespace,+ claims.recipeName,+ 'promptBridge',+ grant+ )+ if (!rate.ok) {+ await markInvocationStatus(recorded.invocation.id, 'failed', {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ expectedCurrentStatus: 'in_progress',+ expectedAttemptGeneration: recorded.invocation.attemptGeneration,+ })+ return deny(rate.error, rate.message)+ }+ const quota = await consumeQuota(+ claims.recipeNamespace,+ claims.recipeName,+ 'promptBridge',+ grant+ )+ if (!quota.ok) {+ await markInvocationStatus(recorded.invocation.id, 'failed', {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ expectedCurrentStatus: 'in_progress',+ expectedAttemptGeneration: recorded.invocation.attemptGeneration,+ })+ return deny(quota.error, quota.message)+ }+ } catch (error) {+ try {+ await markInvocationStatus(recorded.invocation.id, 'failed', {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ expectedCurrentStatus: 'in_progress',+ expectedAttemptGeneration: recorded.invocation.attemptGeneration,+ })+ } catch {+ // Preserve the original database/rate error; maintenance will fence it.+ }+ throw error+ }++ return {+ ok: true,+ value: {+ invocationId: recorded.invocation.id,+ replay: false,+ providerCallRequired: true,+ status: 'in_progress',+ model: selectedTarget.model,+ modelPolicy: null,+ selectedTarget,+ authorizedTargets: [selectedTarget],+ attemptGeneration: recorded.invocation.attemptGeneration,+ policyRevision: 0,+ policyHash: '0'.repeat(64),+ maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,+ },+ }+}+export interface ReissuePromptBridgeCredentialTicketParams {claims: McpHostAccessClaimsinvocationId: stringtargetRef: string+ attemptGeneration: number}export type ReissuedPromptBridgeCredentialTicket = {invocationId: stringtargetRef: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbercredentialTicket: stringpolicyRevision: numberpolicyHash: string@@ -468,6 +707,7 @@ export async function reissuePromptBridgeCredentialTicket(invocation.recipeName !== params.claims.recipeName ||invocation.method !== 'promptBridge' ||invocation.status !== 'in_progress' ||+ invocation.attemptGeneration !== params.attemptGeneration ||invocation.authorizationDecision !== 'authorized' ||!invocation.promptAuthorization) {@@ -478,6 +718,16 @@ export async function reissuePromptBridgeCredentialTicket(}const authorization = invocation.promptAuthorization+ const receipt = await getPluginWorkloadSdkAttemptReceipt(invocation.id, params.attemptGeneration)+ if (+ !receipt ||+ receipt.recipeNamespace !== params.claims.recipeNamespace ||+ receipt.recipeName !== params.claims.recipeName ||+ receipt.method !== 'promptBridge' ||+ receipt.status !== 'in_progress'+ ) {+ return deny('provider_policy_denied', 'promptBridge attempt receipt is stale or missing')+ }if (!authorization.authorizedTargetRefs.includes(params.targetRef)) {return deny('target_not_allowed', 'target was not authorized for this invocation')}@@ -487,7 +737,8 @@ export async function reissuePromptBridgeCredentialTicket(params.claims.recipeName,'promptBridge')- if (!grant || checkCaller(grant, invocation.callerRef)) {+ const callerError = grant ? checkCaller(grant, invocation.callerRef) : null+ if (!grant || grant.policyState !== 'active' || grant.policyRevision < 1 || callerError) {return deny('provider_policy_denied','promptBridge policy no longer authorizes this invocation'@@ -508,11 +759,28 @@ export async function reissuePromptBridgeCredentialTicket(return deny('target_not_allowed', 'target is not in the current promptBridge policy')}+ const providerAttempt = await reservePluginWorkloadSdkProviderAttempt({+ invocationId: invocation.id,+ recipeNamespace: params.claims.recipeNamespace,+ recipeName: params.claims.recipeName,+ attemptGeneration: invocation.attemptGeneration,+ target,+ })+ if (!providerAttempt) {+ return deny(+ 'provider_policy_denied',+ 'promptBridge attempt is stale, fenced, or exceeds the physical-attempt budget'+ )+ }+const issued = issuePluginWorkloadSdkCredentialTicketWithClaims({recipeNamespace: params.claims.recipeNamespace,recipeName: params.claims.recipeName,invocationId: invocation.id,target,+ providerAttemptId: providerAttempt.id,+ providerAttemptIndex: providerAttempt.attemptIndex,+ attemptGeneration: invocation.attemptGeneration,policyRevision: grant.policyRevision,policyHash,})@@ -522,9 +790,19 @@ export async function reissuePromptBridgeCredentialTicket(recipeName: params.claims.recipeName,invocationId: invocation.id,targetRef: target.targetRef,+ attemptGeneration: invocation.attemptGeneration,+ providerAttemptId: providerAttempt.id,expiresAt: new Date(Date.now() + PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS * 1_000),})if (!registered) {+ await markPluginWorkloadSdkProviderAttemptStatus({+ id: providerAttempt.id,+ invocationId: invocation.id,+ recipeNamespace: params.claims.recipeNamespace,+ recipeName: params.claims.recipeName,+ attemptGeneration: invocation.attemptGeneration,+ status: 'failed',+ })return deny('provider_unavailable','credential ticket issuance is temporarily unavailable',@@ -536,6 +814,9 @@ export async function reissuePromptBridgeCredentialTicket(value: {invocationId: invocation.id,targetRef: target.targetRef,+ attemptGeneration: invocation.attemptGeneration,+ providerAttemptId: providerAttempt.id,+ providerAttemptIndex: providerAttempt.attemptIndex,credentialTicket: issued.credentialTicket,policyRevision: grant.policyRevision,policyHash,@@ -624,7 +905,14 @@ async function authorizeClientNotificationInner(payload: params.payload,status: 'accepted',authorizationDecision: 'authorized',+ requiredGrantStates: ['active'],})+ if (recorded.kind === 'policy_revoked') {+ return deny(+ 'provider_policy_denied',+ 'clientNotifications policy was revoked before invocation reservation'+ )+ }if (recorded.kind === 'conflict') {return deny('idempotency_conflict', 'idempotency key was already used with a different payload')}diff --git a/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts b/control-api/src/services/pluginWorkloadSdkCredentialTicket.tsindex 59a841133..66cdc93f0 100644--- a/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts+++ b/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts@@ -17,6 +17,9 @@ export type PluginWorkloadSdkCredentialTicketClaims = {recipeNamespace: stringrecipeName: stringinvocationId: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbertargetRef: stringprovider: stringmodel: string@@ -35,6 +38,9 @@ export function issuePluginWorkloadSdkCredentialTicket(input: {recipeNamespace: stringrecipeName: stringinvocationId: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbertarget: PluginWorkloadSdkPromptTargetpolicyRevision: numberpolicyHash: string@@ -51,6 +57,9 @@ export function issuePluginWorkloadSdkCredentialTicketWithClaims(input: {recipeNamespace: stringrecipeName: stringinvocationId: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbertarget: PluginWorkloadSdkPromptTargetpolicyRevision: numberpolicyHash: string@@ -61,6 +70,9 @@ export function issuePluginWorkloadSdkCredentialTicketWithClaims(input: {recipeNamespace: input.recipeNamespace,recipeName: input.recipeName,invocationId: input.invocationId,+ attemptGeneration: input.attemptGeneration,+ providerAttemptId: input.providerAttemptId,+ providerAttemptIndex: input.providerAttemptIndex,targetRef: input.target.targetRef,provider: input.target.provider,model: input.target.model,@@ -102,6 +114,14 @@ export function verifyPluginWorkloadSdkCredentialTicket(typeof claims.recipeNamespace !== 'string' ||typeof claims.recipeName !== 'string' ||typeof claims.invocationId !== 'string' ||+ typeof claims.attemptGeneration !== 'number' ||+ !Number.isInteger(claims.attemptGeneration) ||+ claims.attemptGeneration < 1 ||+ typeof claims.providerAttemptId !== 'string' ||+ claims.providerAttemptId.length === 0 ||+ typeof claims.providerAttemptIndex !== 'number' ||+ !Number.isInteger(claims.providerAttemptIndex) ||+ claims.providerAttemptIndex < 1 ||typeof claims.targetRef !== 'string' ||typeof claims.provider !== 'string' ||typeof claims.model !== 'string' ||diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex 51967bc28..358bbbb63 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -1,4 +1,4 @@-import { createHash } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import { type DbClient, pool, withTransaction } from '../db.js'import { stableStringify } from '../utils/stableStringify.js'import {@@ -41,6 +41,7 @@ export const PLUGIN_WORKLOAD_SDK_ERROR_CODES = ['payload_too_large','idempotency_conflict','recipe_binding_mismatch',+ 'protocol_mismatch',] as constexport type PluginWorkloadSdkErrorCode = (typeof PLUGIN_WORKLOAD_SDK_ERROR_CODES)[number]@@ -70,6 +71,28 @@ export const MAX_USER_REF_LENGTH = 256/** Max length for a single admin allowlist entry. */export const MAX_ALLOWLIST_ENTRY_LENGTH = 256export const MAX_ALLOWLIST_ITEMS = 64+/**+ * Maximum number of provider targets an operator may persist in one grant.+ * This is deliberately separate from the execution budget below: a policy may+ * contain a catalogue larger than a single invocation's ordered suffix.+ */+export const MAX_PROMPT_BRIDGE_TARGETS_PER_GRANT = MAX_ALLOWLIST_ITEMS+/** Hard cap for physical provider attempts in one logical invocation. */+export const MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS = 4+/** Default lease is the prompt timeout plus a bounded recovery grace period. */+export const DEFAULT_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS = 180+const MIN_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS = 30+const MAX_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS = 3600++/** One operator-controlled lease value is shared by issuance and stale sweep. */+export function getPromptBridgeAttemptLeaseSeconds(): number {+ const raw = Number(process.env.PLUGIN_WORKLOAD_SDK_ATTEMPT_LEASE_SECONDS)+ if (!Number.isInteger(raw)) return DEFAULT_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS+ return Math.min(+ Math.max(raw, MIN_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS),+ MAX_PROMPT_BRIDGE_ATTEMPT_LEASE_SECONDS+ )+}/** Idempotency keys are reusable after this window (OQ-5). */const IDEMPOTENCY_TTL_HOURS = 24@@ -121,8 +144,8 @@ export interface PluginWorkloadSdkGrant {/*** Explicit provider bound to a promptBridge grant (R1). NULL for grants* written before the provider column existed and for clientNotifications- * grants — the control-ui read path falls back to inferring it from the- * model list when NULL.+ * grants. A NULL value is legacy/unreviewed state; neither the API nor the+ * Control UI may infer a routable provider from a flat model list.*/provider: string | nullallowedModels: string[]@@ -135,7 +158,10 @@ export interface PluginWorkloadSdkGrant {/** Empty/null means a legacy grant and is deliberately not routable. */promptTargets: PluginWorkloadSdkPromptTarget[]defaultTargetRef: string | null+ policyState: 'active' | 'legacy_unreviewed' | 'revoking' | 'disabled'policyRevision: number+ /** Kill-switch epoch. Non-null while a recipe is revoking or disabled. */+ revocationId: string | nullcreatedAt: stringupdatedAt: string}@@ -155,8 +181,13 @@ export interface PluginWorkloadSdkInvocationRecord {status: PluginWorkloadSdkInvocationStatusquotaConsumed: booleanauthorizationDecision: string+ contractVersion: 1 | 2promptAuthorization: PluginWorkloadSdkPromptAuthorization | null+ /** Monotonic physical-attempt generation; increments on failed replay. */+ attemptGeneration: number+ leaseExpiresAt: string | nullcreatedAt: string+ updatedAt: stringcompletedAt: string | null}@@ -256,10 +287,17 @@ function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {modelPolicies,promptTargets: promptTargets(row.prompt_targets),defaultTargetRef: row.default_target_ref == null ? null : String(row.default_target_ref),+ policyState:+ row.policy_state === 'legacy_unreviewed' ||+ row.policy_state === 'revoking' ||+ row.policy_state === 'disabled'+ ? (row.policy_state as 'legacy_unreviewed' | 'revoking' | 'disabled')+ : 'active',policyRevision:typeof row.policy_revision === 'number' && Number.isInteger(row.policy_revision)? row.policy_revision: 0,+ revocationId: row.revocation_id == null ? null : String(row.revocation_id),createdAt: new Date(row.created_at as string).toISOString(),updatedAt: new Date(row.updated_at as string).toISOString(),}@@ -280,8 +318,16 @@ function mapInvocationRow(row: Record<string, unknown>): PluginWorkloadSdkInvocastatus: row.status as PluginWorkloadSdkInvocationStatus,quotaConsumed: row.quota_consumed === true,authorizationDecision: String(row.authorization_decision),+ contractVersion: row.contract_version === 1 ? 1 : 2,promptAuthorization: promptAuthorization(row.prompt_authorization),+ attemptGeneration:+ typeof row.attempt_generation === 'number' && Number.isInteger(row.attempt_generation)+ ? Math.max(row.attempt_generation, 1)+ : 1,+ leaseExpiresAt:+ row.lease_expires_at == null ? null : new Date(row.lease_expires_at as string).toISOString(),createdAt: new Date(row.created_at as string).toISOString(),+ updatedAt: new Date((row.updated_at ?? row.created_at) as string).toISOString(),completedAt:row.completed_at === null ? null : new Date(row.completed_at as string).toISOString(),}@@ -352,16 +398,34 @@ export async function upsertGrant(operatorSub: string): Promise<PluginWorkloadSdkGrant> {return withTransaction(async db => {- const resourceRef = `plugin_workload_sdk:${params.recipeNamespace}/${params.recipeName}:${params.capabilityFamily}`- await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [resourceRef])+ // All capability families for a recipe share one lock. A family-scoped+ // lock permits an SDK-only revoke to race an upsert for the other family.+ const recipeLock = `plugin_workload_sdk:${params.recipeNamespace}/${params.recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])const previous = await db.query(- `SELECT allowed_user_refs+ `SELECT allowed_user_refs, policy_state, revocation_idFROM plugin_workload_sdk_grantsWHERE recipe_namespace = $1 AND recipe_name = $2 AND capability_family = $3FOR UPDATE`,[params.recipeNamespace, params.recipeName, params.capabilityFamily])const previousRow = previous.rows[0] as { allowed_user_refs?: unknown } | undefined+ const recipeState = await db.query(+ `SELECT policy_state, revocation_id+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND policy_state IN ('revoking', 'disabled')+ ORDER BY updated_at DESC+ LIMIT 1+ FOR UPDATE`,+ [params.recipeNamespace, params.recipeName]+ )+ if (recipeState.rows.length > 0) {+ throw new Error(+ `Plugin Workload SDK policy for ${params.recipeNamespace}/${params.recipeName} is ${String((recipeState.rows[0] as { policy_state: unknown }).policy_state)} and cannot be reactivated`+ )+ }const previousUserRefs = Array.isArray(previousRow?.allowed_user_refs)? previousRow.allowed_user_refs.map(String): []@@ -369,7 +433,7 @@ export async function upsertGrant(`INSERT INTO plugin_workload_sdk_grants(recipe_namespace, recipe_name, capability_family, provider, allowed_models,allowed_event_types, allowed_target_refs, allowed_user_refs, allowed_callers,- quota_limits, model_policies, prompt_targets, default_target_ref)+ quota_limits, model_policies, prompt_targets, default_target_ref)VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb, $12::jsonb, $13)ON CONFLICT (recipe_namespace, recipe_name, capability_family)DO UPDATE SET@@ -383,6 +447,19 @@ export async function upsertGrant(model_policies = EXCLUDED.model_policies,prompt_targets = EXCLUDED.prompt_targets,default_target_ref = EXCLUDED.default_target_ref,+ -- A stale upsert must never undo a kill-switch. The recipe-wide+ -- lock plus the guard above makes this branch defensive for rows+ -- created by older binaries that did not know revocation_id.+ policy_state = CASE+ WHEN plugin_workload_sdk_grants.policy_state IN ('revoking', 'disabled')+ THEN plugin_workload_sdk_grants.policy_state+ ELSE 'active'+ END,+ revocation_id = CASE+ WHEN plugin_workload_sdk_grants.policy_state IN ('revoking', 'disabled')+ THEN plugin_workload_sdk_grants.revocation_id+ ELSE NULL+ END,policy_revision = plugin_workload_sdk_grants.policy_revision + 1,updated_at = now()RETURNING *`,@@ -414,6 +491,7 @@ export async function upsertGrant(])for (const row of users.rows) resolvedUsers.add(String((row as { id: string }).id))}+ const resourceRef = `plugin_workload_sdk:${params.recipeNamespace}/${params.recipeName}:${params.capabilityFamily}`const changes: ControlApiPermissionChange[] = [{action: 'grant' as const,@@ -473,6 +551,335 @@ export async function listGrants(filter?: {return (result.rows as Record<string, unknown>[]).map(mapGrantRow)}+/**+ * Read-only migration gate for promptBridge rows written before the ordered+ * target policy existed. Legacy rows are intentionally never inferred or+ * rewritten here; operators get only non-secret identifiers, shape flags, and+ * reasons that must be resolved by an explicit policy upsert.+ */+export interface PluginWorkloadSdkLegacyGrantInventoryItem {+ id: string+ recipeNamespace: string+ recipeName: string+ policyState: string+ policyRevision: number+ providerPresent: boolean+ promptTargetsCount: number+ defaultTargetRefPresent: boolean+ reasons: string[]+}++export interface PluginWorkloadSdkLegacyGrantInventory {+ totalPromptBridgeGrants: number+ legacyPromptBridgeGrants: number+ activationReady: boolean+ items: PluginWorkloadSdkLegacyGrantInventoryItem[]+}++export async function getPluginWorkloadSdkLegacyGrantInventory(filter?: {+ recipeNamespace?: string+ recipeName?: string+}): Promise<PluginWorkloadSdkLegacyGrantInventory> {+ const clauses = ["capability_family = 'promptBridge'"]+ const values: unknown[] = []+ if (filter?.recipeNamespace) {+ values.push(filter.recipeNamespace)+ clauses.push(`recipe_namespace = $${values.length}`)+ }+ if (filter?.recipeName) {+ values.push(filter.recipeName)+ clauses.push(`recipe_name = $${values.length}`)+ }+ const result = await pool.query(+ `SELECT id, recipe_namespace, recipe_name, policy_state, policy_revision,+ provider, prompt_targets, default_target_ref+ FROM plugin_workload_sdk_grants+ WHERE ${clauses.join(' AND ')}+ ORDER BY recipe_namespace, recipe_name`,+ values+ )++ const items = (result.rows as Record<string, unknown>[]).flatMap(row => {+ const rawTargets = Array.isArray(row.prompt_targets) ? row.prompt_targets : []+ const targets = promptTargets(row.prompt_targets)+ const policyState = String(row.policy_state ?? '')+ const policyRevision =+ typeof row.policy_revision === 'number' && Number.isInteger(row.policy_revision)+ ? row.policy_revision+ : Number(row.policy_revision ?? 0)+ const providerPresent = typeof row.provider === 'string' && row.provider.trim().length > 0+ const defaultTargetRefPresent =+ typeof row.default_target_ref === 'string' && row.default_target_ref.trim().length > 0+ const reasons: string[] = []+ if (policyState === 'legacy_unreviewed') reasons.push('legacy_policy_state')+ if (!providerPresent) reasons.push('missing_provider')+ if (rawTargets.length !== targets.length) reasons.push('invalid_prompt_targets')+ if (targets.length === 0) reasons.push('empty_prompt_targets')+ if (!defaultTargetRefPresent) reasons.push('missing_default_target')+ if (policyRevision < 1) reasons.push('invalid_policy_revision')+ if (defaultTargetRefPresent && targets[0]?.targetRef !== String(row.default_target_ref)) {+ reasons.push('default_target_not_first')+ }+ const targetRefs = targets.map(target => target.targetRef)+ if (new Set(targetRefs).size !== targetRefs.length) reasons.push('duplicate_target_refs')+ if (reasons.length === 0) return []+ return [+ {+ id: String(row.id),+ recipeNamespace: String(row.recipe_namespace),+ recipeName: String(row.recipe_name),+ policyState,+ policyRevision: Number.isFinite(policyRevision) ? policyRevision : 0,+ providerPresent,+ promptTargetsCount: targets.length,+ defaultTargetRefPresent,+ reasons,+ },+ ]+ })+ return {+ totalPromptBridgeGrants: result.rows.length,+ legacyPromptBridgeGrants: items.length,+ activationReady: items.length === 0,+ items,+ }+}++export type PluginWorkloadSdkRevocationState = 'missing' | 'revoking' | 'disabled' | 'conflict'++export interface PluginWorkloadSdkRevocationReceipt {+ state: PluginWorkloadSdkRevocationState+ revocationId?: string+ revoked: number+ fencedInvocations: number+ disabled?: number+}++/**+ * Fence every SDK capability for a recipe before its runtime resources are+ * torn down. This is deliberately recipe-scoped and transactional: the+ * recipe-wide advisory lock is the linearization point shared with upserts,+ * authorization, JIT issuance, and ticket redemption. A receipt epoch is+ * returned so only the reconcile that fenced this exact policy can finalize it.+ */+export async function revokePluginWorkloadSdkForRecipe(+ recipeNamespace: string,+ recipeName: string,+ operatorSub: string+): Promise<PluginWorkloadSdkRevocationReceipt> {+ return withTransaction(async db => {+ const recipeLock = `plugin_workload_sdk:${recipeNamespace}/${recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ const grants = await db.query(+ `SELECT id, capability_family, policy_state, revocation_id+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1 AND recipe_name = $2+ FOR UPDATE`,+ [recipeNamespace, recipeName]+ )+ if (grants.rows.length === 0) {+ return { state: 'missing', revoked: 0, fencedInvocations: 0 }+ }++ const revocationIds = [+ ...new Set(+ grants.rows+ .map(row => (row as { revocation_id?: unknown }).revocation_id)+ .filter((value): value is string => typeof value === 'string' && value.length > 0)+ .map(String)+ ),+ ]+ if (revocationIds.length > 1) {+ return {+ state: 'conflict',+ revoked: 0,+ fencedInvocations: 0,+ }+ }+ const currentRevocationId = revocationIds[0] ?? randomUUID()+ const hasActivePolicy = grants.rows.some(row =>+ ['active', 'legacy_unreviewed'].includes(+ String((row as { policy_state: unknown }).policy_state)+ )+ )+ const hasRevokingPolicy = grants.rows.some(+ row => String((row as { policy_state: unknown }).policy_state) === 'revoking'+ )++ const revoked = await db.query(+ `UPDATE plugin_workload_sdk_grants+ SET policy_state = 'revoking',+ policy_revision = policy_revision + 1,+ revocation_id = COALESCE(revocation_id, $3::uuid),+ updated_at = now()+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND policy_state IN ('active', 'legacy_unreviewed')`,+ [recipeNamespace, recipeName, currentRevocationId]+ )++ const fenced = await db.query(+ `UPDATE plugin_workload_sdk_invocations+ SET status = 'failed',+ authorization_decision = 'revoked',+ updated_at = now(),+ lease_expires_at = NULL,+ completed_at = COALESCE(completed_at, now())+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND status = 'in_progress'+ RETURNING id`,+ [recipeNamespace, recipeName]+ )+ await db.query(+ `UPDATE plugin_workload_sdk_invocation_attempts+ SET status = 'failed',+ lease_expires_at = NULL,+ completed_at = COALESCE(completed_at, now())+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND status = 'in_progress'`,+ [recipeNamespace, recipeName]+ )+ await db.query(+ `UPDATE plugin_workload_sdk_provider_attempts+ SET status = 'failed',+ lease_expires_at = NULL,+ completed_at = COALESCE(completed_at, now())+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND status IN ('reserved', 'in_progress')`,+ [recipeNamespace, recipeName]+ )++ const changes: ControlApiPermissionChange[] = grants.rows+ .filter(row =>+ ['active', 'legacy_unreviewed'].includes(+ String((row as { policy_state: unknown }).policy_state)+ )+ )+ .map(row => ({+ action: 'revoke' as const,+ resourceClass: 'plugin_workload_sdk_access',+ resourceRef: `plugin_workload_sdk:${recipeNamespace}/${recipeName}:${String((row as { capability_family: unknown }).capability_family)}`,+ subject: {+ kind: 'service' as const,+ id: String((row as { capability_family: unknown }).capability_family),+ },+ namespace: recipeNamespace,+ sourceAuditRef: `plugin_workload_sdk_grants:${String((row as { id: unknown }).id)}`,+ status: 'revoking',+ }))+ if (changes.length > 0) {+ await appendControlApiPermissionEventsInTransaction(db, { operatorSub, changes })+ }+ return {+ state:+ hasActivePolicy || hasRevokingPolicy || (revoked.rowCount ?? 0) > 0+ ? 'revoking'+ : 'disabled',+ revocationId: currentRevocationId,+ revoked: revoked.rowCount ?? 0,+ fencedInvocations: fenced.rowCount ?? 0,+ }+ })+}++/**+ * Complete a previously fenced revocation only after the caller has proved+ * that the recipe-bound SDK endpoint and credentials are gone. The state+ * transition is intentionally impossible from `active`, preventing callers+ * from declaring a kill-switch success without the teardown boundary.+ */+export async function finalizePluginWorkloadSdkRevocation(+ recipeNamespace: string,+ recipeName: string,+ expectedRevocationId: string,+ operatorSub: string+): Promise<PluginWorkloadSdkRevocationReceipt> {+ return withTransaction(async db => {+ const recipeLock = `plugin_workload_sdk:${recipeNamespace}/${recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ const grants = await db.query(+ `SELECT id, capability_family, policy_state, revocation_id+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1 AND recipe_name = $2+ FOR UPDATE`,+ [recipeNamespace, recipeName]+ )+ if (grants.rows.length === 0) {+ return { state: 'missing', revoked: 0, fencedInvocations: 0, disabled: 0 }+ }+ const hasActive = grants.rows.some(row =>+ ['active', 'legacy_unreviewed'].includes(+ String((row as { policy_state: unknown }).policy_state)+ )+ )+ const hasWrongEpoch = grants.rows.some(row => {+ const state = String((row as { policy_state: unknown }).policy_state)+ return (+ (state === 'revoking' || state === 'disabled') &&+ String((row as { revocation_id?: unknown }).revocation_id ?? '') !== expectedRevocationId+ )+ })+ if (hasActive || hasWrongEpoch) {+ return {+ state: 'conflict',+ revocationId: expectedRevocationId,+ revoked: 0,+ fencedInvocations: 0,+ }+ }+ const result = await db.query(+ `UPDATE plugin_workload_sdk_grants+ SET policy_state = 'disabled',+ updated_at = now()+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND policy_state = 'revoking'+ AND revocation_id = $3::uuid+ RETURNING id, capability_family`,+ [recipeNamespace, recipeName, expectedRevocationId]+ )+ const disabledRows =+ result.rows.length > 0+ ? result.rows+ : grants.rows.filter(+ row => String((row as { policy_state: unknown }).policy_state) === 'disabled'+ )+ if (disabledRows.length === 0) {+ return {+ state: 'conflict',+ revocationId: expectedRevocationId,+ revoked: 0,+ fencedInvocations: 0,+ }+ }+ const changes: ControlApiPermissionChange[] = result.rows.map(row => ({+ action: 'revoke' as const,+ resourceClass: 'plugin_workload_sdk_access',+ resourceRef: `plugin_workload_sdk:${recipeNamespace}/${recipeName}:${String((row as { capability_family: unknown }).capability_family)}`,+ subject: {+ kind: 'service' as const,+ id: String((row as { capability_family: unknown }).capability_family),+ },+ namespace: recipeNamespace,+ sourceAuditRef: `plugin_workload_sdk_grants:${String((row as { id: unknown }).id)}`,+ status: 'disabled',+ }))+ if (changes.length > 0) {+ await appendControlApiPermissionEventsInTransaction(db, { operatorSub, changes })+ }+ return {+ state: 'disabled',+ revocationId: expectedRevocationId,+ revoked: 0,+ fencedInvocations: 0,+ disabled: result.rowCount ?? 0,+ }+ })+}+/*** Delete a grant by UUID, scoped to its recipe binding. The recipe_namespace* + recipe_name predicates prevent a UUID alone from deleting a grant that@@ -575,6 +982,281 @@ export async function resolveRecipientProfiles(// ─── Invocations ─────────────────────────────────────────────────────────+/**+ * Immutable identity for one physical provider attempt. The parent invocation+ * is the idempotent logical request; this row is the receipt/fencing record+ * used by tickets, usage ingestion, and late-result rejection.+ */+export interface PluginWorkloadSdkAttemptReceipt {+ invocationId: string+ recipeNamespace: string+ recipeName: string+ attemptGeneration: number+ method: PluginWorkloadSdkFamily+ targetRefs: string[]+ policyRevision: number | null+ policyHash: string | null+ status: PluginWorkloadSdkInvocationStatus+ startedAt: string+ leaseExpiresAt: string | null+ completedAt: string | null+}++function mapAttemptReceiptRow(row: Record<string, unknown>): PluginWorkloadSdkAttemptReceipt {+ return {+ invocationId: String(row.invocation_id),+ recipeNamespace: String(row.recipe_namespace),+ recipeName: String(row.recipe_name),+ attemptGeneration: Number(row.attempt_generation),+ method: row.method as PluginWorkloadSdkFamily,+ targetRefs: stringArray(row.target_refs),+ policyRevision: row.policy_revision == null ? null : Number(row.policy_revision),+ policyHash: row.policy_hash == null ? null : String(row.policy_hash),+ status: row.status as PluginWorkloadSdkInvocationStatus,+ startedAt: new Date(row.started_at as string).toISOString(),+ leaseExpiresAt:+ row.lease_expires_at == null ? null : new Date(row.lease_expires_at as string).toISOString(),+ completedAt:+ row.completed_at == null ? null : new Date(row.completed_at as string).toISOString(),+ }+}++export async function getPluginWorkloadSdkAttemptReceipt(+ invocationId: string,+ attemptGeneration: number,+ db: DbClient = pool+): Promise<PluginWorkloadSdkAttemptReceipt | null> {+ const result = await db.query(+ `SELECT * FROM plugin_workload_sdk_invocation_attempts+ WHERE invocation_id = $1 AND attempt_generation = $2`,+ [invocationId, attemptGeneration]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ return row ? mapAttemptReceiptRow(row) : null+}++export type PluginWorkloadSdkProviderAttemptStatus =+ | 'reserved'+ | 'in_progress'+ | 'complete'+ | 'failed'+ | 'provider_unavailable'++export interface PluginWorkloadSdkProviderAttempt {+ id: string+ invocationId: string+ recipeNamespace: string+ recipeName: string+ attemptGeneration: number+ attemptIndex: number+ targetRef: string+ provider: string+ model: string+ credentialSlot: string+ status: PluginWorkloadSdkProviderAttemptStatus+ credentialJti: string | null+ startedAt: string+ leaseExpiresAt: string | null+ completedAt: string | null+ usageRequestId: string | null+}++function mapProviderAttemptRow(row: Record<string, unknown>): PluginWorkloadSdkProviderAttempt {+ return {+ id: String(row.id),+ invocationId: String(row.invocation_id),+ recipeNamespace: String(row.recipe_namespace),+ recipeName: String(row.recipe_name),+ attemptGeneration: Number(row.attempt_generation),+ attemptIndex: Number(row.attempt_index),+ targetRef: String(row.target_ref),+ provider: String(row.provider),+ model: String(row.model),+ credentialSlot: String(row.credential_slot),+ status: row.status as PluginWorkloadSdkProviderAttemptStatus,+ credentialJti: row.credential_jti == null ? null : String(row.credential_jti),+ startedAt: new Date(row.started_at as string).toISOString(),+ leaseExpiresAt:+ row.lease_expires_at == null ? null : new Date(row.lease_expires_at as string).toISOString(),+ completedAt:+ row.completed_at == null ? null : new Date(row.completed_at as string).toISOString(),+ usageRequestId: row.usage_request_id == null ? null : String(row.usage_request_id),+ }+}++/** Reserve one physical target before issuing a JIT credential ticket. */+export async function reservePluginWorkloadSdkProviderAttempt(input: {+ invocationId: string+ recipeNamespace: string+ recipeName: string+ attemptGeneration: number+ target: PluginWorkloadSdkPromptTarget+}): Promise<PluginWorkloadSdkProviderAttempt | null> {+ return withTransaction(async db => {+ // Revoke and every capability-creation path use this same recipe lock.+ // Acquire it before the invocation row lock to keep one global order and+ // avoid a revoke↔attempt deadlock.+ const recipeLock = `plugin_workload_sdk:${input.recipeNamespace}/${input.recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ const invocationResult = await db.query(+ `SELECT id, method, status, attempt_generation, lease_expires_at, prompt_authorization+ FROM plugin_workload_sdk_invocations+ WHERE id = $1 AND recipe_namespace = $2 AND recipe_name = $3+ FOR UPDATE`,+ [input.invocationId, input.recipeNamespace, input.recipeName]+ )+ const invocation = invocationResult.rows[0] as Record<string, unknown> | undefined+ const authorization = promptAuthorization(invocation?.prompt_authorization)+ if (+ !invocation ||+ invocation.method !== 'promptBridge' ||+ invocation.status !== 'in_progress' ||+ Number(invocation.attempt_generation) !== input.attemptGeneration ||+ !invocation.lease_expires_at ||+ new Date(invocation.lease_expires_at as string).getTime() <= Date.now() ||+ !authorization?.authorizedTargetRefs.includes(input.target.targetRef)+ ) {+ return null+ }+ const grantResult = await db.query(+ `SELECT policy_state, policy_revision, prompt_targets, default_target_ref+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND capability_family = 'promptBridge'+ FOR UPDATE`,+ [input.recipeNamespace, input.recipeName]+ )+ const grant = grantResult.rows[0] as Record<string, unknown> | undefined+ const currentTargets = promptTargets(grant?.prompt_targets)+ const currentRevision = Number(grant?.policy_revision)+ const currentHash = hashPromptTargetPolicy({+ policyRevision: currentRevision,+ defaultTargetRef: grant?.default_target_ref == null ? null : String(grant.default_target_ref),+ promptTargets: currentTargets,+ })+ const currentTarget = currentTargets.find(target => target.targetRef === input.target.targetRef)+ if (+ !grant ||+ grant.policy_state !== 'active' ||+ currentRevision !== authorization?.policyRevision ||+ currentHash !== authorization?.policyHash ||+ !currentTarget ||+ currentTarget.provider !== input.target.provider ||+ currentTarget.model !== input.target.model ||+ currentTarget.credentialSlot !== input.target.credentialSlot+ ) {+ return null+ }+ const count = await db.query(+ `SELECT COUNT(*)::integer AS count+ FROM plugin_workload_sdk_provider_attempts+ WHERE invocation_id = $1 AND attempt_generation = $2`,+ [input.invocationId, input.attemptGeneration]+ )+ const attemptIndex = Number((count.rows[0] as { count?: unknown } | undefined)?.count ?? 0) + 1+ if (attemptIndex > MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS) return null+ const result = await db.query(+ `INSERT INTO plugin_workload_sdk_provider_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation, attempt_index,+ target_ref, provider, model, credential_slot, status, lease_expires_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'reserved', $10)+ RETURNING *`,+ [+ input.invocationId,+ input.recipeNamespace,+ input.recipeName,+ input.attemptGeneration,+ attemptIndex,+ input.target.targetRef,+ input.target.provider,+ input.target.model,+ input.target.credentialSlot,+ invocation.lease_expires_at,+ ]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ return row ? mapProviderAttemptRow(row) : null+ })+}++export async function getPluginWorkloadSdkProviderAttempt(+ id: string,+ db: DbClient = pool+): Promise<PluginWorkloadSdkProviderAttempt | null> {+ const result = await db.query(+ `SELECT * FROM plugin_workload_sdk_provider_attempts WHERE id = $1`,+ [id]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ return row ? mapProviderAttemptRow(row) : null+}++export async function markPluginWorkloadSdkProviderAttemptStatus(input: {+ id: string+ invocationId: string+ recipeNamespace: string+ recipeName: string+ attemptGeneration: number+ status: Exclude<PluginWorkloadSdkProviderAttemptStatus, 'reserved' | 'in_progress'>+}): Promise<boolean> {+ const result = await pool.query(+ `UPDATE plugin_workload_sdk_provider_attempts+ SET status = $6,+ completed_at = now(),+ lease_expires_at = NULL+ WHERE id = $1+ AND invocation_id = $2+ AND recipe_namespace = $3+ AND recipe_name = $4+ AND attempt_generation = $5+ AND status IN ('reserved', 'in_progress')+ AND EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_invocations inv+ WHERE inv.id = $2+ AND inv.status = 'in_progress'+ AND inv.attempt_generation = $5+ AND inv.lease_expires_at > now()+ )`,+ [+ input.id,+ input.invocationId,+ input.recipeNamespace,+ input.recipeName,+ input.attemptGeneration,+ input.status,+ ]+ )+ return (result.rowCount ?? 0) === 1+}++async function insertAttemptReceipt(+ db: DbClient,+ invocation: PluginWorkloadSdkInvocationRecord+): Promise<void> {+ const authorization = invocation.promptAuthorization+ await db.query(+ `INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation, method, target_refs, policy_revision,+ policy_hash, status, lease_expires_at)+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10)+ ON CONFLICT (invocation_id, attempt_generation) DO NOTHING`,+ [+ invocation.id,+ invocation.recipeNamespace,+ invocation.recipeName,+ invocation.attemptGeneration,+ invocation.method,+ JSON.stringify(authorization?.authorizedTargetRefs ?? []),+ authorization?.policyRevision ?? null,+ authorization?.policyHash ?? null,+ invocation.status,+ invocation.leaseExpiresAt,+ ]+ )+}+export interface InsertInvocationParams {recipeNamespace: stringrecipeName: string@@ -588,6 +1270,14 @@ export interface InsertInvocationParams {status: PluginWorkloadSdkInvocationStatusauthorizationDecision: stringpromptAuthorization?: PluginWorkloadSdkPromptAuthorization+ contractVersion?: 1 | 2+ /** Lease for the first physical attempt; terminal transitions clear it. */+ attemptLeaseSeconds?: number+ /**+ * States that may create/replay an invocation. The check runs under the+ * recipe-wide advisory lock so revoke and authorization have one ordering.+ */+ requiredGrantStates?: readonly ('active' | 'legacy_unreviewed')[]}export type InsertInvocationResult =@@ -599,6 +1289,7 @@ export type InsertInvocationResult =// — so the caller maps it to a deterministic idempotency_conflict (409-style)// deny instead of a 500. The caller can safely retry with a fresh key.| { kind: 'race_unresolved' }+ | { kind: 'policy_revoked' }/*** Insert an invocation with idempotency semantics: same key + same payload@@ -608,49 +1299,76 @@ export type InsertInvocationResult =export async function insertInvocation(params: InsertInvocationParams): Promise<InsertInvocationResult> {- const inserted = await pool.query(- `INSERT INTO plugin_workload_sdk_invocations+ return withTransaction(async db => {+ const recipeLock = `plugin_workload_sdk:${params.recipeNamespace}/${params.recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ if (params.requiredGrantStates) {+ const grant = await db.query(+ `SELECT policy_state+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND capability_family = $3+ FOR UPDATE`,+ [params.recipeNamespace, params.recipeName, params.method]+ )+ const state = String(+ (grant.rows[0] as { policy_state?: unknown } | undefined)?.policy_state ?? ''+ )+ if (!params.requiredGrantStates.includes(state as 'active' | 'legacy_unreviewed')) {+ return { kind: 'policy_revoked' }+ }+ }+ const inserted = await db.query(+ `INSERT INTO plugin_workload_sdk_invocations(recipe_namespace, recipe_name, caller_ref, correlation_id, method, detail, purpose,- idempotency_key_hash, payload_hash, status, authorization_decision, prompt_authorization)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)+ idempotency_key_hash, payload_hash, status, authorization_decision, prompt_authorization,+ contract_version, attempt_generation, lease_expires_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, 1,+ now() + interval '1 second' * $14)ON CONFLICT (recipe_namespace, recipe_name, method, idempotency_key_hash) DO NOTHINGRETURNING *`,- [- params.recipeNamespace,- params.recipeName,- params.callerRef,- params.correlationId ?? null,- params.method,- params.detail,- params.purpose ?? null,- params.idempotencyKeyHash,- params.payloadHash,- params.status,- params.authorizationDecision,- params.promptAuthorization ? JSON.stringify(params.promptAuthorization) : null,- ]- )- const insertedRow = inserted.rows[0] as Record<string, unknown> | undefined- if (insertedRow) {- return { kind: 'inserted', invocation: mapInvocationRow(insertedRow) }- }+ [+ params.recipeNamespace,+ params.recipeName,+ params.callerRef,+ params.correlationId ?? null,+ params.method,+ params.detail,+ params.purpose ?? null,+ params.idempotencyKeyHash,+ params.payloadHash,+ params.status,+ params.authorizationDecision,+ params.promptAuthorization ? JSON.stringify(params.promptAuthorization) : null,+ params.contractVersion ?? 2,+ params.attemptLeaseSeconds ?? getPromptBridgeAttemptLeaseSeconds(),+ ]+ )+ const insertedRow = inserted.rows[0] as Record<string, unknown> | undefined+ if (insertedRow) {+ const invocation = mapInvocationRow(insertedRow)+ await insertAttemptReceipt(db, invocation)+ return { kind: 'inserted', invocation }+ }- const existing = await pool.query(- `SELECT * FROM plugin_workload_sdk_invocations+ const existing = await db.query(+ `SELECT * FROM plugin_workload_sdk_invocationsWHERE recipe_namespace = $1 AND recipe_name = $2 AND method = $3 AND idempotency_key_hash = $4`,- [params.recipeNamespace, params.recipeName, params.method, params.idempotencyKeyHash]- )- const existingRow = existing.rows[0] as Record<string, unknown> | undefined- if (!existingRow) {- // Lost the race AND the winner vanished (pruned between statements) —- // surface a structured signal so the caller returns a deterministic- // idempotency_conflict (NOT a 500) and the workload retries with a fresh key.- return { kind: 'race_unresolved' }- }- const invocation = mapInvocationRow(existingRow)- return invocation.payloadHash === params.payloadHash- ? { kind: 'replay', invocation }- : { kind: 'conflict', invocation }+ [params.recipeNamespace, params.recipeName, params.method, params.idempotencyKeyHash]+ )+ const existingRow = existing.rows[0] as Record<string, unknown> | undefined+ if (!existingRow) {+ // Lost the race AND the winner vanished (pruned between statements) —+ // surface a structured signal so the caller returns a deterministic+ // idempotency_conflict (NOT a 500) and the workload retries with a fresh key.+ return { kind: 'race_unresolved' }+ }+ const invocation = mapInvocationRow(existingRow)+ return invocation.payloadHash === params.payloadHash+ ? { kind: 'replay', invocation }+ : { kind: 'conflict', invocation }+ })}export async function getInvocationById(@@ -668,28 +1386,116 @@ export async function registerPluginWorkloadSdkCredentialTicketJti(input: {recipeName: stringinvocationId: stringtargetRef: string+ attemptGeneration: number+ providerAttemptId: stringexpiresAt: Date}): Promise<boolean> {- // Opportunistic cleanup bounds the one-shot registry without retaining any- // credentials or ticket bodies.- await pool.query(- `DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE expires_at <= now()`- )- const result = await pool.query(- `INSERT INTO plugin_workload_sdk_credential_ticket_jtis- (jti, recipe_namespace, recipe_name, invocation_id, target_ref, expires_at)- VALUES ($1, $2, $3, $4, $5, $6)- ON CONFLICT (jti) DO NOTHING`,- [+ return withTransaction(async db => {+ const recipeLock = `plugin_workload_sdk:${input.recipeNamespace}/${input.recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ const grant = await db.query(+ `SELECT policy_state+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND capability_family = 'promptBridge'+ FOR UPDATE`,+ [input.recipeNamespace, input.recipeName]+ )+ if (+ String((grant.rows[0] as { policy_state?: unknown } | undefined)?.policy_state ?? '') !==+ 'active'+ ) {+ return false+ }+ const invocation = await db.query(+ `SELECT id, status, attempt_generation, lease_expires_at+ FROM plugin_workload_sdk_invocations+ WHERE id = $1+ AND recipe_namespace = $2+ AND recipe_name = $3+ FOR UPDATE`,+ [input.invocationId, input.recipeNamespace, input.recipeName]+ )+ const invocationRow = invocation.rows[0] as Record<string, unknown> | undefined+ if (+ !invocationRow ||+ invocationRow.status !== 'in_progress' ||+ Number(invocationRow.attempt_generation) !== input.attemptGeneration ||+ !invocationRow.lease_expires_at ||+ new Date(invocationRow.lease_expires_at as string).getTime() <= Date.now()+ ) {+ return false+ }+ const providerAttempt = await db.query(+ `SELECT id+ FROM plugin_workload_sdk_provider_attempts+ WHERE id = $1+ AND invocation_id = $2+ AND recipe_namespace = $3+ AND recipe_name = $4+ AND attempt_generation = $5+ AND target_ref = $6+ AND status = 'reserved'+ FOR UPDATE`,+ [+ input.providerAttemptId,+ input.invocationId,+ input.recipeNamespace,+ input.recipeName,+ input.attemptGeneration,+ input.targetRef,+ ]+ )+ if (providerAttempt.rows.length !== 1) return false+ // Opportunistic cleanup bounds the one-shot registry without retaining any+ // credentials or ticket bodies.+ await db.query(+ `DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE expires_at <= now()`+ )+ const result = await db.query(+ `INSERT INTO plugin_workload_sdk_credential_ticket_jtis+ (jti, recipe_namespace, recipe_name, invocation_id, target_ref, attempt_generation,+ provider_attempt_id, expires_at)+ SELECT $1, $2, $3, $4, $5, $6, $7, $8+ WHERE EXISTS (+ SELECT 1 FROM plugin_workload_sdk_provider_attempts+ WHERE id = $7+ AND invocation_id = $4+ AND recipe_namespace = $2+ AND recipe_name = $3+ AND attempt_generation = $6+ AND target_ref = $5+ AND status = 'reserved'+ )+ ON CONFLICT (jti) DO NOTHING`,+ [+ input.jti,+ input.recipeNamespace,+ input.recipeName,+ input.invocationId,+ input.targetRef,+ input.attemptGeneration,+ input.providerAttemptId,+ input.expiresAt,+ ]+ )+ if ((result.rowCount ?? 0) !== 1) return false+ const promoted = await db.query(+ `UPDATE plugin_workload_sdk_provider_attempts+ SET credential_jti = $2, status = 'in_progress'+ WHERE id = $1 AND status = 'reserved'`,+ [input.providerAttemptId, input.jti]+ )+ if ((promoted.rowCount ?? 0) === 1) return true+ // The JTI insert and the reservation promotion are one state transition.+ // Remove the orphaned registry row before committing a false result so a+ // race cannot leave a redeemable ticket with no physical attempt owner.+ await db.query(`DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE jti = $1`, [input.jti,- input.recipeNamespace,- input.recipeName,- input.invocationId,- input.targetRef,- input.expiresAt,- ]- )- return (result.rowCount ?? 0) === 1+ ])+ return false+ })}/** Atomically consumes a ticket identity after all binding/policy checks pass. */@@ -699,20 +1505,84 @@ export async function redeemPluginWorkloadSdkCredentialTicketJti(input: {recipeName: stringinvocationId: stringtargetRef: string+ attemptGeneration: number+ providerAttemptId: string}): Promise<boolean> {- const result = await pool.query(- `UPDATE plugin_workload_sdk_credential_ticket_jtis- SET redeemed_at = now()- WHERE jti = $1- AND recipe_namespace = $2- AND recipe_name = $3- AND invocation_id = $4- AND target_ref = $5- AND redeemed_at IS NULL- AND expires_at > now()`,- [input.jti, input.recipeNamespace, input.recipeName, input.invocationId, input.targetRef]- )- return (result.rowCount ?? 0) === 1+ return withTransaction(async db => {+ const recipeLock = `plugin_workload_sdk:${input.recipeNamespace}/${input.recipeName}`+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [recipeLock])+ const grant = await db.query(+ `SELECT policy_state+ FROM plugin_workload_sdk_grants+ WHERE recipe_namespace = $1+ AND recipe_name = $2+ AND capability_family = 'promptBridge'+ FOR UPDATE`,+ [input.recipeNamespace, input.recipeName]+ )+ if (+ String((grant.rows[0] as { policy_state?: unknown } | undefined)?.policy_state ?? '') !==+ 'active'+ ) {+ return false+ }+ const result = await db.query(+ `UPDATE plugin_workload_sdk_credential_ticket_jtis AS ticket+ SET redeemed_at = now()+ WHERE ticket.jti = $1+ AND ticket.recipe_namespace = $2+ AND ticket.recipe_name = $3+ AND ticket.invocation_id = $4+ AND ticket.target_ref = $5+ AND ticket.attempt_generation = $6+ AND ticket.provider_attempt_id = $7+ AND ticket.redeemed_at IS NULL+ AND ticket.expires_at > now()+ AND EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_invocations invocation+ WHERE invocation.id = ticket.invocation_id+ AND invocation.recipe_namespace = ticket.recipe_namespace+ AND invocation.recipe_name = ticket.recipe_name+ AND invocation.method = 'promptBridge'+ AND invocation.status = 'in_progress'+ AND invocation.attempt_generation = ticket.attempt_generation+ AND invocation.lease_expires_at > now()+ )+ AND EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_invocation_attempts receipt+ WHERE receipt.invocation_id = ticket.invocation_id+ AND receipt.recipe_namespace = ticket.recipe_namespace+ AND receipt.recipe_name = ticket.recipe_name+ AND receipt.attempt_generation = ticket.attempt_generation+ AND receipt.method = 'promptBridge'+ AND receipt.status = 'in_progress'+ AND receipt.lease_expires_at > now()+ )+ AND EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_provider_attempts attempt+ WHERE attempt.id = ticket.provider_attempt_id+ AND attempt.invocation_id = ticket.invocation_id+ AND attempt.recipe_namespace = ticket.recipe_namespace+ AND attempt.recipe_name = ticket.recipe_name+ AND attempt.attempt_generation = ticket.attempt_generation+ AND attempt.target_ref = ticket.target_ref+ AND attempt.status = 'in_progress'+ )`,+ [+ input.jti,+ input.recipeNamespace,+ input.recipeName,+ input.invocationId,+ input.targetRef,+ input.attemptGeneration,+ input.providerAttemptId,+ ]+ )+ return (result.rowCount ?? 0) === 1+ })}export async function updateInvocationStatus(@@ -722,6 +1592,8 @@ export async function updateInvocationStatus(completed?: booleanrecipeNamespace?: stringrecipeName?: string+ expectedAttemptGeneration?: number+ leaseSeconds?: number/*** Optimistic-concurrency guard: when set, the UPDATE only applies if the* row is currently in this status. Used to transition accepted → delivered@@ -730,7 +1602,7 @@ export async function updateInvocationStatus(expectedCurrentStatus?: PluginWorkloadSdkInvocationStatus} = {}): Promise<boolean> {- const values: unknown[] = [id, status, opts.completed ?? false]+ const values: unknown[] = [id, status, opts.completed ?? false, opts.leaseSeconds ?? 0]let bindingClause = ''if (opts.recipeNamespace !== undefined && opts.recipeName !== undefined) {values.push(opts.recipeNamespace, opts.recipeName)@@ -741,28 +1613,121 @@ export async function updateInvocationStatus(values.push(opts.expectedCurrentStatus)statusGuardClause = ` AND status = $${values.length}`}- const result = await pool.query(- `UPDATE plugin_workload_sdk_invocations- SET status = $2,- completed_at = CASE WHEN $3 THEN now() ELSE NULL END- WHERE id = $1${bindingClause}${statusGuardClause}`,- values- )- return (result.rowCount ?? 0) > 0+ let generationGuardClause = ''+ if (opts.expectedAttemptGeneration !== undefined) {+ values.push(opts.expectedAttemptGeneration)+ generationGuardClause = ` AND attempt_generation = $${values.length}`+ }+ return withTransaction(async db => {+ const result = await db.query(+ `UPDATE plugin_workload_sdk_invocations+ SET status = $2,+ updated_at = now(),+ lease_expires_at = CASE+ WHEN $2 = 'in_progress' AND $4 > 0+ THEN now() + interval '1 second' * $4+ ELSE NULL+ END,+ completed_at = CASE WHEN $3 THEN now() ELSE NULL END+ WHERE id = $1${bindingClause}${statusGuardClause}${generationGuardClause}`,+ values+ )+ if ((result.rowCount ?? 0) === 0) return false+ const generation =+ opts.expectedAttemptGeneration ??+ Number(+ (+ (+ await db.query(+ `SELECT attempt_generation FROM plugin_workload_sdk_invocations WHERE id = $1`,+ [id]+ )+ ).rows[0] as { attempt_generation?: unknown } | undefined+ )?.attempt_generation ?? 1+ )+ await db.query(+ `UPDATE plugin_workload_sdk_invocation_attempts+ SET status = $3,+ lease_expires_at = CASE+ WHEN $3 = 'in_progress' AND $4 > 0+ THEN now() + interval '1 second' * $4+ ELSE NULL+ END,+ completed_at = CASE WHEN $2 THEN now() ELSE NULL END+ WHERE invocation_id = $1 AND attempt_generation = $5`,+ [id, opts.completed ?? false, status, opts.leaseSeconds ?? 0, generation]+ )+ return true+ })+}++/**+ * Atomically claims the next physical attempt for a failed invocation. The+ * generation is the fencing token: every ticket, usage receipt, and terminal+ * status update must carry it, so a late result from an earlier attempt cannot+ * close a newer retry (ABA protection).+ */+export async function reviveFailedInvocation(input: {+ id: string+ recipeNamespace: string+ recipeName: string+ leaseSeconds: number+}): Promise<number | null> {+ return withTransaction(async db => {+ const result = await db.query(+ `UPDATE plugin_workload_sdk_invocations+ SET status = 'in_progress',+ attempt_generation = attempt_generation + 1,+ updated_at = now(),+ lease_expires_at = now() + interval '1 second' * $4,+ completed_at = NULL+ WHERE id = $1+ AND recipe_namespace = $2+ AND recipe_name = $3+ AND status = 'failed'+ RETURNING *`,+ [input.id, input.recipeNamespace, input.recipeName, input.leaseSeconds]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ if (!row) return null+ const invocation = mapInvocationRow(row)+ await insertAttemptReceipt(db, invocation)+ return invocation.attemptGeneration+ })}/*** Mark stale in_progress invocations as failed (mcp-host restart recovery —* plan §2.4). Returns the number of rows transitioned.*/-export async function failStaleInvocations(olderThanSeconds: number): Promise<number> {- const result = await pool.query(- `UPDATE plugin_workload_sdk_invocations- SET status = 'failed', completed_at = now()- WHERE status = 'in_progress' AND created_at < now() - interval '1 second' * $1`,- [olderThanSeconds]- )- return result.rowCount ?? 0+export async function failStaleInvocations(_olderThanSeconds: number): Promise<number> {+ return withTransaction(async db => {+ const result = await db.query(+ `UPDATE plugin_workload_sdk_invocations+ SET status = 'failed', updated_at = now(), completed_at = now()+ WHERE status = 'in_progress'+ AND lease_expires_at IS NOT NULL+ AND lease_expires_at < now()+ RETURNING id, attempt_generation`+ )+ for (const row of result.rows as Array<{ id: string; attempt_generation: number }>) {+ await db.query(+ `UPDATE plugin_workload_sdk_invocation_attempts+ SET status = 'failed', lease_expires_at = NULL, completed_at = now()+ WHERE invocation_id = $1 AND attempt_generation = $2`,+ [row.id, row.attempt_generation]+ )+ await db.query(+ `UPDATE plugin_workload_sdk_provider_attempts+ SET status = 'provider_unavailable', lease_expires_at = NULL, completed_at = now()+ WHERE invocation_id = $1+ AND attempt_generation = $2+ AND status IN ('reserved', 'in_progress')`,+ [row.id, row.attempt_generation]+ )+ }+ return result.rowCount ?? 0+ })}export interface ListInvocationsFilter {@@ -808,13 +1773,42 @@ export async function listInvocations(* failStaleInvocations.*/export async function prunePluginWorkloadSdkExpiredIdempotency(): Promise<number> {- const result = await pool.query(- `DELETE FROM plugin_workload_sdk_invocations- WHERE created_at < now() - interval '1 hour' * $1- AND status <> 'in_progress'`,- [IDEMPOTENCY_TTL_HOURS]- )- return result.rowCount ?? 0+ return withTransaction(async db => {+ // Child receipts and one-shot JTIs have no useful life once the parent+ // idempotency reservation expires. Delete them in one transaction so+ // usage and ticket lookups cannot observe orphaned authority.+ await db.query(+ `DELETE FROM plugin_workload_sdk_credential_ticket_jtis jt+ USING plugin_workload_sdk_invocations inv+ WHERE jt.invocation_id = inv.id+ AND inv.created_at < now() - interval '1 hour' * $1+ AND inv.status <> 'in_progress'`,+ [IDEMPOTENCY_TTL_HOURS]+ )+ await db.query(+ `DELETE FROM plugin_workload_sdk_invocation_attempts attempts+ USING plugin_workload_sdk_invocations inv+ WHERE attempts.invocation_id = inv.id+ AND inv.created_at < now() - interval '1 hour' * $1+ AND inv.status <> 'in_progress'`,+ [IDEMPOTENCY_TTL_HOURS]+ )+ await db.query(+ `DELETE FROM plugin_workload_sdk_provider_attempts attempts+ USING plugin_workload_sdk_invocations inv+ WHERE attempts.invocation_id = inv.id+ AND inv.created_at < now() - interval '1 hour' * $1+ AND inv.status <> 'in_progress'`,+ [IDEMPOTENCY_TTL_HOURS]+ )+ const result = await db.query(+ `DELETE FROM plugin_workload_sdk_invocations+ WHERE created_at < now() - interval '1 hour' * $1+ AND status <> 'in_progress'`,+ [IDEMPOTENCY_TTL_HOURS]+ )+ return result.rowCount ?? 0+ })}// ─── Quota counters ──────────────────────────────────────────────────────diff --git a/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts b/control-api/src/services/pluginWorkloadSdkInvocationAuditor.tsindex ef967c94b..2f5fae32d 100644--- a/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts+++ b/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts@@ -3,9 +3,11 @@ import {type PluginWorkloadSdkFamily,type PluginWorkloadSdkInvocationStatus,type PluginWorkloadSdkPromptAuthorization,+ getPromptBridgeAttemptLeaseSeconds,hashIdempotencyKey,hashPayload,insertInvocation,+ reviveFailedInvocation,updateInvocationStatus,} from './pluginWorkloadSdkDb.js'@@ -37,6 +39,8 @@ export interface RecordInvocationParams {status: PluginWorkloadSdkInvocationStatusauthorizationDecision: stringpromptAuthorization?: PluginWorkloadSdkPromptAuthorization+ contractVersion?: 1 | 2+ requiredGrantStates?: readonly ('active' | 'legacy_unreviewed')[]}export async function recordInvocation(@@ -55,6 +59,9 @@ export async function recordInvocation(status: params.status,authorizationDecision: params.authorizationDecision,promptAuthorization: params.promptAuthorization,+ contractVersion: params.contractVersion,+ attemptLeaseSeconds: getPromptBridgeAttemptLeaseSeconds(),+ requiredGrantStates: params.requiredGrantStates,})}@@ -66,6 +73,8 @@ export async function markInvocationStatus(recipeName?: string/** Optimistic guard: only transition when the row is in this status. */expectedCurrentStatus?: PluginWorkloadSdkInvocationStatus+ expectedAttemptGeneration?: number+ leaseSeconds?: number}): Promise<boolean> {const terminal = status !== 'in_progress' && status !== 'accepted'@@ -74,6 +83,21 @@ export async function markInvocationStatus(recipeNamespace: binding?.recipeNamespace,recipeName: binding?.recipeName,expectedCurrentStatus: binding?.expectedCurrentStatus,+ expectedAttemptGeneration: binding?.expectedAttemptGeneration,+ leaseSeconds: binding?.leaseSeconds,+ })+}++export async function reviveFailedSdkInvocation(input: {+ invocationId: string+ recipeNamespace: string+ recipeName: string+}): Promise<number | null> {+ return reviveFailedInvocation({+ id: input.invocationId,+ recipeNamespace: input.recipeNamespace,+ recipeName: input.recipeName,+ leaseSeconds: getPromptBridgeAttemptLeaseSeconds(),})}diff --git a/control-api/src/services/pluginWorkloadSdkMaintenanceCron.ts b/control-api/src/services/pluginWorkloadSdkMaintenanceCron.tsindex 152fb014e..3e951a688 100644--- a/control-api/src/services/pluginWorkloadSdkMaintenanceCron.ts+++ b/control-api/src/services/pluginWorkloadSdkMaintenanceCron.ts@@ -2,6 +2,7 @@ import { rootLogger } from '../observability/logger.js'import { pluginWorkloadSdkMaintenanceRunsTotal } from '../observability/metrics.js'import {failStaleInvocations,+ getPromptBridgeAttemptLeaseSeconds,prunePluginWorkloadSdkExpiredIdempotency,} from './pluginWorkloadSdkDb.js'@@ -12,9 +13,6 @@ import {// 2. Idempotency pruning: terminal invocation rows older than the 24h// TTL are deleted so their keys become reusable in a new period.-/** Default mcp-host PLUGIN_WORKLOAD_SDK_PROMPT_TIMEOUT_SECONDS is 120. */-const STALE_INVOCATION_TIMEOUT_SECONDS = 150-let intervalHandle: ReturnType<typeof setInterval> | null = nullexport function startPluginWorkloadSdkMaintenanceCron(intervalMs = 60_000): void {@@ -22,7 +20,7 @@ export function startPluginWorkloadSdkMaintenanceCron(intervalMs = 60_000): voidintervalHandle = setInterval(async () => {try {- const failed = await failStaleInvocations(STALE_INVOCATION_TIMEOUT_SECONDS)+ const failed = await failStaleInvocations(getPromptBridgeAttemptLeaseSeconds())const pruned = await prunePluginWorkloadSdkExpiredIdempotency()if (failed > 0 || pruned > 0) {rootLogger.info(diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.tsindex c7fccf76d..e56184ad6 100644--- a/control-api/src/services/pluginWorkloadSdkSchema.ts+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts@@ -13,8 +13,9 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>capability_family TEXT NOT NULL CHECK (capability_family IN ('promptBridge','clientNotifications')),-- Explicit provider bound to a promptBridge grant (R1: credentials resolve-- per-provider, not per-model). NULLABLE: rows written before migration- -- 0050 carry NULL and are read back with a provider inferred from the- -- model list (control-ui fallback). clientNotifications grants leave it NULL.+ -- 0050 carry NULL and remain legacy/unreviewed until an operator+ -- explicitly resaves an ordered target policy. clientNotifications+ -- grants leave it NULL.provider TEXT,allowed_models JSONB NOT NULL DEFAULT '[]'::jsonb,allowed_event_types JSONB NOT NULL DEFAULT '[]'::jsonb,@@ -29,6 +30,8 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>prompt_targets JSONB NOT NULL DEFAULT '[]'::jsonb,default_target_ref TEXT NULL,policy_revision INTEGER NOT NULL DEFAULT 1,+ policy_state TEXT NOT NULL DEFAULT 'active'+ CHECK (policy_state IN ('active', 'legacy_unreviewed', 'revoking', 'disabled')),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE (recipe_namespace, recipe_name, capability_family)@@ -48,10 +51,17 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>status TEXT NOT NULL CHECK (status IN ('in_progress','complete','failed','provider_unavailable','accepted','delivered')),quota_consumed BOOLEAN NOT NULL DEFAULT true,authorization_decision TEXT NOT NULL,+ contract_version INTEGER NOT NULL DEFAULT 2 CHECK (contract_version IN (1, 2)),-- Persisted, non-secret prompt authorization snapshot used to mint a-- fresh fallback ticket without trusting caller-supplied target lists.prompt_authorization JSONB NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Tracks the most recent lifecycle transition, including a failed+ -- idempotent retry revived by CAS. Stale recovery must not use the+ -- original reservation time for an active retry.+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ attempt_generation INTEGER NOT NULL DEFAULT 1 CHECK (attempt_generation >= 1),+ lease_expires_at TIMESTAMPTZ NULL,completed_at TIMESTAMPTZ NULL);@@ -61,12 +71,44 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>recipe_name TEXT NOT NULL,invocation_id UUID NOT NULL,target_ref TEXT NOT NULL,+ attempt_generation INTEGER NOT NULL DEFAULT 1 CHECK (attempt_generation >= 1),expires_at TIMESTAMPTZ NOT NULL,redeemed_at TIMESTAMPTZ NULL);CREATE INDEX IF NOT EXISTS plugin_workload_sdk_credential_ticket_jtis_expiryON plugin_workload_sdk_credential_ticket_jtis (expires_at);+ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_invocation_attempts (+ invocation_id UUID NOT NULL,+ recipe_namespace TEXT NOT NULL,+ recipe_name TEXT NOT NULL,+ attempt_generation INTEGER NOT NULL CHECK (attempt_generation >= 1),+ method TEXT NOT NULL CHECK (method IN ('promptBridge','clientNotifications')),+ target_refs JSONB NOT NULL DEFAULT '[]'::jsonb,+ policy_revision INTEGER NULL,+ policy_hash TEXT NULL,+ status TEXT NOT NULL DEFAULT 'in_progress'+ CHECK (status IN ('in_progress','complete','failed','provider_unavailable','accepted','delivered')),+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ lease_expires_at TIMESTAMPTZ NULL,+ completed_at TIMESTAMPTZ NULL,+ PRIMARY KEY (invocation_id, attempt_generation)+ );+ ALTER TABLE plugin_workload_sdk_invocation_attempts+ ADD COLUMN IF NOT EXISTS recipe_namespace TEXT,+ ADD COLUMN IF NOT EXISTS recipe_name TEXT;+ UPDATE plugin_workload_sdk_invocation_attempts attempts+ SET recipe_namespace = invocations.recipe_namespace,+ recipe_name = invocations.recipe_name+ FROM plugin_workload_sdk_invocations invocations+ WHERE attempts.invocation_id = invocations.id+ AND (attempts.recipe_namespace IS NULL OR attempts.recipe_name IS NULL);+ ALTER TABLE plugin_workload_sdk_invocation_attempts+ ALTER COLUMN recipe_namespace SET NOT NULL,+ ALTER COLUMN recipe_name SET NOT NULL;+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocation_attempts_status_idx+ ON plugin_workload_sdk_invocation_attempts (status, lease_expires_at);+-- Idempotency uniqueness scoped per recipe + method (OQ-5). Rows older-- than the 24h TTL are pruned by prunePluginWorkloadSdkExpiredIdempotency-- so keys become reusable in a new invocation period.@@ -99,8 +141,8 @@ export async function dropPluginWorkloadSdkSuperAdminApprovedColumn(db: DbClient/*** Adds the explicit `provider` column to promptBridge grants (R1). Idempotent* (IF NOT EXISTS) so it is a no-op on fresh clusters that already created the- * column via applyPluginWorkloadSdkSchema. Existing rows keep NULL — the read- * path (control-ui) falls back to inferring the provider from the model list.+ * column via applyPluginWorkloadSdkSchema. Existing rows keep NULL and remain+ * legacy/unreviewed; no provider is inferred from their model list.*/export async function addPluginWorkloadSdkProviderColumn(db: DbClient): Promise<void> {await db.query(`@@ -145,3 +187,256 @@ export async function addPluginWorkloadSdkJitCredentialTicketColumns(db: DbClienON plugin_workload_sdk_credential_ticket_jtis (expires_at);`)}++/**+ * 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.+ */+export async function addPluginWorkloadSdkAttemptLedgerColumns(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE plugin_workload_sdk_grants+ ADD COLUMN IF NOT EXISTS policy_state TEXT NOT NULL DEFAULT 'active';+ DO $$ BEGIN+ ALTER TABLE plugin_workload_sdk_grants+ ADD CONSTRAINT plugin_workload_sdk_grants_policy_state_check+ CHECK (policy_state IN ('active', 'legacy_unreviewed'));+ EXCEPTION WHEN duplicate_object THEN NULL;+ END $$;++ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_invocation_attempts (+ invocation_id UUID NOT NULL,+ recipe_namespace TEXT NOT NULL,+ recipe_name TEXT NOT NULL,+ attempt_generation INTEGER NOT NULL CHECK (attempt_generation >= 1),+ method TEXT NOT NULL CHECK (method IN ('promptBridge','clientNotifications')),+ target_refs JSONB NOT NULL DEFAULT '[]'::jsonb,+ policy_revision INTEGER NULL,+ policy_hash TEXT NULL,+ status TEXT NOT NULL DEFAULT 'in_progress'+ CHECK (status IN ('in_progress','complete','failed','provider_unavailable','accepted','delivered')),+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ lease_expires_at TIMESTAMPTZ NULL,+ completed_at TIMESTAMPTZ NULL,+ PRIMARY KEY (invocation_id, attempt_generation)+ );+ ALTER TABLE plugin_workload_sdk_invocation_attempts+ ADD COLUMN IF NOT EXISTS recipe_namespace TEXT,+ ADD COLUMN IF NOT EXISTS recipe_name TEXT;+ UPDATE plugin_workload_sdk_invocation_attempts attempts+ SET recipe_namespace = invocations.recipe_namespace,+ recipe_name = invocations.recipe_name+ FROM plugin_workload_sdk_invocations invocations+ WHERE attempts.invocation_id = invocations.id+ AND (attempts.recipe_namespace IS NULL OR attempts.recipe_name IS NULL);+ ALTER TABLE plugin_workload_sdk_invocation_attempts+ ALTER COLUMN recipe_namespace SET NOT NULL,+ ALTER COLUMN recipe_name SET NOT NULL;+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocation_attempts_status_idx+ ON plugin_workload_sdk_invocation_attempts (status, lease_expires_at);++ ALTER TABLE plugin_workload_sdk_invocations+ ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ ADD COLUMN IF NOT EXISTS attempt_generation INTEGER NOT NULL DEFAULT 1,+ ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ NULL;+ UPDATE plugin_workload_sdk_invocations+ SET updated_at = COALESCE(updated_at, created_at),+ attempt_generation = GREATEST(COALESCE(attempt_generation, 1), 1)+ WHERE updated_at IS NULL OR attempt_generation IS NULL OR attempt_generation < 1;+ DO $$ BEGIN+ ALTER TABLE plugin_workload_sdk_invocations+ ADD CONSTRAINT plugin_workload_sdk_invocations_attempt_generation_check+ CHECK (attempt_generation >= 1);+ EXCEPTION WHEN duplicate_object THEN NULL;+ END $$;++ ALTER TABLE plugin_workload_sdk_credential_ticket_jtis+ ADD COLUMN IF NOT EXISTS attempt_generation INTEGER NOT NULL DEFAULT 1;+ DO $$ BEGIN+ ALTER TABLE plugin_workload_sdk_credential_ticket_jtis+ ADD CONSTRAINT plugin_workload_sdk_credential_ticket_jtis_attempt_generation_check+ CHECK (attempt_generation >= 1);+ EXCEPTION WHEN duplicate_object THEN NULL;+ END $$;++ -- Rows that predate the attempt ledger still need an immutable receipt.+ -- Backfill from the parent snapshot without inferring a new policy: legacy+ -- promptBridge grants are blocked below until an operator explicitly+ -- reviews them. A malformed/absent policyRevision remains NULL rather+ -- than making the migration fail for an otherwise valid audit row.+ INSERT INTO plugin_workload_sdk_invocation_attempts+ (invocation_id, recipe_namespace, recipe_name, attempt_generation, method,+ target_refs, policy_revision, policy_hash, status, started_at,+ lease_expires_at, completed_at)+ SELECT inv.id,+ inv.recipe_namespace,+ inv.recipe_name,+ GREATEST(COALESCE(inv.attempt_generation, 1), 1),+ inv.method,+ COALESCE(inv.prompt_authorization->'authorizedTargetRefs', '[]'::jsonb),+ CASE+ WHEN jsonb_typeof(inv.prompt_authorization->'policyRevision') = 'number'+ THEN (inv.prompt_authorization->>'policyRevision')::integer+ ELSE NULL+ END,+ CASE+ WHEN jsonb_typeof(inv.prompt_authorization->'policyHash') = 'string'+ THEN inv.prompt_authorization->>'policyHash'+ ELSE NULL+ END,+ inv.status,+ inv.created_at,+ CASE WHEN inv.status = 'in_progress' THEN inv.lease_expires_at ELSE NULL END,+ inv.completed_at+ FROM plugin_workload_sdk_invocations inv+ WHERE NOT EXISTS (+ SELECT 1+ FROM plugin_workload_sdk_invocation_attempts existing+ WHERE existing.invocation_id = inv.id+ AND existing.attempt_generation = GREATEST(COALESCE(inv.attempt_generation, 1), 1)+ )+ 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.+ UPDATE plugin_workload_sdk_grants+ SET policy_state = 'legacy_unreviewed',+ policy_revision = 0+ WHERE capability_family = 'promptBridge';++ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocations_lease_idx+ ON plugin_workload_sdk_invocations (status, lease_expires_at)+ WHERE status = 'in_progress';+ `)+}++/** 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';`)+}++/**+ * Establishes the dual wire-contract and revocation state without rewriting+ * any previously applied migration. Existing invocation rows are explicitly+ * classified as legacy v1 and abandoned in-progress rows are terminalized so+ * the new lease/sweep contract cannot inherit an unbounded old reservation.+ */+export async function addPluginWorkloadSdkProtocolAndRevocation(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE plugin_workload_sdk_grants+ DROP CONSTRAINT IF EXISTS plugin_workload_sdk_grants_policy_state_check;+ ALTER TABLE plugin_workload_sdk_grants+ ADD CONSTRAINT plugin_workload_sdk_grants_policy_state_check+ CHECK (policy_state IN ('active', 'legacy_unreviewed', 'revoking', 'disabled'));++ ALTER TABLE plugin_workload_sdk_invocations+ ADD COLUMN IF NOT EXISTS contract_version INTEGER NOT NULL DEFAULT 2;+ DO $$ BEGIN+ ALTER TABLE plugin_workload_sdk_invocations+ ADD CONSTRAINT plugin_workload_sdk_invocations_contract_version_check+ CHECK (contract_version IN (1, 2));+ EXCEPTION WHEN duplicate_object THEN NULL;+ END $$;++ -- Rows written before this migration used the pre-v2 endpoint. Preserve+ -- that fact for status compatibility and operational inventory rather than+ -- pretending they negotiated the target-aware/JIT contract.+ UPDATE plugin_workload_sdk_invocations+ SET contract_version = 1+ WHERE contract_version = 2;++ -- Old rows had no lease. They cannot be safely resumed after a rollout;+ -- close them deterministically and fence any matching attempt receipt.+ UPDATE plugin_workload_sdk_invocations+ SET status = 'failed',+ authorization_decision = CASE+ WHEN authorization_decision = 'authorized' THEN 'migration_interrupted'+ ELSE authorization_decision+ END,+ updated_at = now(),+ completed_at = COALESCE(completed_at, now()),+ lease_expires_at = NULL+ WHERE contract_version = 1+ AND status = 'in_progress'+ AND lease_expires_at IS NULL;+ UPDATE plugin_workload_sdk_invocation_attempts attempts+ SET status = 'failed',+ completed_at = COALESCE(attempts.completed_at, now()),+ lease_expires_at = NULL+ FROM plugin_workload_sdk_invocations invocations+ WHERE attempts.invocation_id = invocations.id+ AND attempts.attempt_generation = invocations.attempt_generation+ AND invocations.contract_version = 1+ AND invocations.status = 'failed';++ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_invocations_contract_idx+ ON plugin_workload_sdk_invocations (recipe_namespace, recipe_name, contract_version, created_at DESC);+ `)+}++/** Adds one immutable ledger row for every physical provider attempt. */+export async function addPluginWorkloadSdkProviderAttemptLedger(db: DbClient): Promise<void> {+ await db.query(`+ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_provider_attempts (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ invocation_id UUID NOT NULL,+ recipe_namespace TEXT NOT NULL,+ recipe_name TEXT NOT NULL,+ attempt_generation INTEGER NOT NULL CHECK (attempt_generation >= 1),+ attempt_index INTEGER NOT NULL CHECK (attempt_index BETWEEN 1 AND 4),+ target_ref TEXT NOT NULL,+ provider TEXT NOT NULL,+ model TEXT NOT NULL,+ credential_slot TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'reserved'+ CHECK (status IN ('reserved','in_progress','complete','failed','provider_unavailable')),+ credential_jti UUID NULL,+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ lease_expires_at TIMESTAMPTZ NULL,+ completed_at TIMESTAMPTZ NULL,+ usage_request_id UUID NULL,+ UNIQUE (invocation_id, attempt_generation, attempt_index)+ );+ ALTER TABLE plugin_workload_sdk_credential_ticket_jtis+ ADD COLUMN IF NOT EXISTS provider_attempt_id UUID NULL;+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_provider_attempts_invocation_idx+ ON plugin_workload_sdk_provider_attempts (invocation_id, attempt_generation, attempt_index);+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_provider_attempts_status_idx+ ON plugin_workload_sdk_provider_attempts (status, lease_expires_at);+ `)+}++/**+ * Adds the recipe-scoped revocation epoch used by the teardown kill-switch.+ * A receipt is deliberately separate from policy_revision: policy revisions+ * describe operator edits, while revocation_id is a one-shot CAS capability+ * that prevents a stale reconciler from disabling a newly-authorized policy.+ */+export async function addPluginWorkloadSdkRevocationEpoch(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE plugin_workload_sdk_grants+ ADD COLUMN IF NOT EXISTS revocation_id UUID NULL;+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_grants_revocation_idx+ ON plugin_workload_sdk_grants (recipe_namespace, recipe_name, revocation_id)+ WHERE revocation_id IS NOT NULL;+ `)+}++/** Applies the runtime ACL for the attempt-ledger tables added after the+ * original runtime-role migration. The control API owns their lifecycle and+ * retention; no workflow or maintenance runtime should be able to mutate or+ * read these provider-attempt receipts. */+export async function addPluginWorkloadSdkRuntimeAccess(db: DbClient): Promise<void> {+ await db.query(`+ REVOKE ALL ON TABLE+ plugin_workload_sdk_invocation_attempts,+ plugin_workload_sdk_provider_attempts+ FROM PUBLIC, trace_maintenance_runtime, workflow_recipes_runtime;+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE+ plugin_workload_sdk_invocation_attempts,+ plugin_workload_sdk_provider_attempts+ TO control_api_runtime;+ `)+}diff --git a/control-api/src/services/tracing/usageProjection.ts b/control-api/src/services/tracing/usageProjection.tsindex 9615f62bd..831bf9a01 100644--- a/control-api/src/services/tracing/usageProjection.ts+++ b/control-api/src/services/tracing/usageProjection.ts@@ -40,6 +40,15 @@ type TokenUsagePayload = {cache_write_tokens: numbercache_tokens_reported: booleaniteration?: number+ prompt_bridge?: {+ invocation_id: string+ attempt_generation: number+ target_ref: string+ fallback_used: boolean+ attempt_count: number+ provider_attempt_id: string+ provider_attempt_index: number+ }}function sha256(value: string): string {@@ -62,6 +71,22 @@ function tokenUsagePayload(usage: LlmUsageEvent): TokenUsagePayload {cache_write_tokens: usage.cache_write_tokens,cache_tokens_reported: usage.cache_tokens_reported,...(usage.iteration === null ? {} : { iteration: usage.iteration }),+ ...(usage.prompt_bridge_metadata?.invocation_id &&+ usage.prompt_bridge_metadata.attempt_generation !== undefined &&+ usage.prompt_bridge_metadata.provider_attempt_id &&+ usage.prompt_bridge_metadata.provider_attempt_index !== undefined+ ? {+ prompt_bridge: {+ invocation_id: usage.prompt_bridge_metadata.invocation_id,+ attempt_generation: usage.prompt_bridge_metadata.attempt_generation,+ target_ref: usage.prompt_bridge_metadata.target_ref,+ fallback_used: usage.prompt_bridge_metadata.fallback_used,+ attempt_count: usage.prompt_bridge_metadata.attempt_count,+ provider_attempt_id: usage.prompt_bridge_metadata.provider_attempt_id!,+ provider_attempt_index: usage.prompt_bridge_metadata.provider_attempt_index!,+ },+ }+ : {}),}}@@ -224,6 +249,55 @@ function pendingWorkflowUsageEvent(})}+/**+ * SDK-only calls have no workflow run, but they still need a governed,+ * invocation-anchored usage event. The server-issued invocation UUID is used+ * as the run identity for this direct API lane; it is never supplied by the+ * workload and is already bound to the recipe JWT and attempt receipt.+ */+function pendingSdkOnlyUsageEvent(+ usage: LlmUsageEvent,+ context: UsageProjectionContext,+ now: () => Date,+ newEventId: () => string+): PendingGovernedEvent<'agent_run'> {+ const metadata = usage.prompt_bridge_metadata+ const invocationId = metadata?.invocation_id+ if (!invocationId) {+ throw new Error(`accepted SDK-only usage ${usage.request_id} has no invocation binding`)+ }+ return pendingTokenUsageEvent({+ usage,+ environment: context.environment ?? canonicalTracingEnvironment(),+ now,+ newEventId,+ binding: {+ runId: invocationId,+ sessionId: null,+ spanId: sha256(`plugin-sdk:${invocationId}:token-usage:${usage.request_id.toLowerCase()}`),+ parentSpanId: sha256(`plugin-sdk:${invocationId}:root`),+ origin: 'api',+ identityIssuer: 'control-api',+ actorHumanSub: null,+ agentSub: `plugin-workload-sdk:${context.recipeNamespace}/${context.recipeName}`,+ actorMedium: 'api',+ approvalRequestId: null,+ teamId: null,+ userId: null,+ recipeNamespace: context.recipeNamespace,+ recipeName: context.recipeName,+ hostRef: context.hostRef,+ },+ canonicalBinding: {+ invocationId,+ attemptGeneration: metadata.attempt_generation,+ recipeNamespace: context.recipeNamespace,+ recipeName: context.recipeName,+ hostRef: context.hostRef,+ },+ })+}+function pendingSubmitterUsageEvent(usage: LlmUsageEvent,binding: NonWorkflowRunBinding,@@ -469,6 +543,10 @@ export async function projectAcceptedUsageEvents(}for (const usage of acceptedEvents) {+ if (usage.source_kind === 'plugin_workload_sdk') {+ pending.push(pendingSdkOnlyUsageEvent(usage, context, now, newEventId))+ continue+ }if (usage.source_kind === 'workflow') {const runId = usage.run_id?.toLowerCase()const binding = runId ? workflowBindings.get(runId) : undefineddiff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.tsindex 572e03a6f..d14729ab4 100644--- a/control-api/src/services/usageEvents.ts+++ b/control-api/src/services/usageEvents.ts@@ -1,7 +1,13 @@import type { DbClient } from '../db.js'import { pool } from '../db.js'-export type UsageSourceKind = 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown'+export type UsageSourceKind =+ | 'channel'+ | 'desktop'+ | 'workflow'+ | 'cron'+ | 'unknown'+ | 'plugin_workload_sdk'export type LlmUsageEvent = {request_id: string@@ -32,6 +38,9 @@ export type LlmUsageEvent = {credential_slot: stringfallback_used: booleanattempt_count: number+ attempt_generation?: number+ provider_attempt_id?: string+ provider_attempt_index?: number} | null}@@ -46,8 +55,36 @@ export type UsageIngestTransactionResult = {acceptedEvents: LlmUsageEvent[]}+type PromptBridgeAttemptBinding = {+ invocation_id: string+ recipe_name: string+ contract_version: number+ attempt_generation: number+ method: string+ target_refs: unknown+}++type ProviderAttemptBinding = {+ id: string+ invocation_id: string+ attempt_generation: number+ attempt_index: number+ target_ref: string+ provider: string+ model: string+ credential_slot: string+ status: string+}+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i-const SOURCE_KINDS: Set<string> = new Set(['channel', 'desktop', 'workflow', 'cron', 'unknown'])+const SOURCE_KINDS: Set<string> = new Set([+ 'channel',+ 'desktop',+ 'workflow',+ 'cron',+ 'unknown',+ 'plugin_workload_sdk',+])const CONTROL_PLANE_ADMIN_USAGE_TEAM_ID = 'control-plane-admin-ui'const CONTROL_PLANE_ADMIN_USAGE_USER_PREFIX = 'admin-ui/'@@ -88,6 +125,19 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metatypeof record.credential_slot === 'string' ? record.credential_slot.trim() : ''const fallbackUsed = record.fallback_usedconst attemptCount = intOrNull(record.attempt_count)+ const attemptGeneration =+ record.attempt_generation === undefined ? null : intOrNull(record.attempt_generation)+ const providerAttemptId =+ record.provider_attempt_id === undefined+ ? null+ : typeof record.provider_attempt_id === 'string' &&+ UUID_REGEX.test(record.provider_attempt_id)+ ? record.provider_attempt_id+ : null+ const providerAttemptIndex =+ record.provider_attempt_index === undefined ? null : intOrNull(record.provider_attempt_index)+ const hasProviderAttemptId = record.provider_attempt_id !== undefined+ const hasProviderAttemptIndex = record.provider_attempt_index !== undefinedif (!targetRef ||targetRef.length > 256 ||@@ -96,7 +146,11 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metatypeof fallbackUsed !== 'boolean' ||attemptCount === null ||attemptCount < 1 ||- attemptCount > 4+ attemptCount > 4 ||+ (attemptGeneration !== null && attemptGeneration < 1) ||+ hasProviderAttemptId !== hasProviderAttemptIndex ||+ (hasProviderAttemptId && providerAttemptId === null) ||+ (hasProviderAttemptIndex && (providerAttemptIndex === null || providerAttemptIndex < 1))) {return null}@@ -106,6 +160,9 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metacredential_slot: credentialSlot,fallback_used: fallbackUsed,attempt_count: attemptCount,+ ...(attemptGeneration !== null ? { attempt_generation: attemptGeneration } : {}),+ ...(providerAttemptId !== null ? { provider_attempt_id: providerAttemptId } : {}),+ ...(providerAttemptIndex !== null ? { provider_attempt_index: providerAttemptIndex } : {}),}}@@ -168,6 +225,14 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {const run_id = trimOrNull(r.run_id)if (run_id && !UUID_REGEX.test(run_id)) return nullconst isSdkOnly =+ source_kind_raw === 'plugin_workload_sdk' &&+ r.channel_type === 'plugin_workload_sdk' &&+ recipe_name !== null &&+ run_id === null &&+ task_id === null &&+ llm_secret_name !== null &&+ prompt_bridge_metadata?.invocation_id !== undefined+ const isLegacySdkOnly =source_kind_raw === 'unknown' &&r.channel_type === 'plugin_workload_sdk' &&recipe_name !== null &&@@ -175,13 +240,34 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {task_id === null &&llm_secret_name !== null &&prompt_bridge_metadata?.invocation_id !== undefined+ const isWorkflowSdk = source_kind_raw === 'workflow' && r.channel_type === 'plugin_workload_sdk'if (source_kind_raw === 'workflow') {const taskRunId = workflowRunIdFromTaskId(task_id)if (!recipe_name || !llm_secret_name || !run_id || !taskRunId) return nullif (taskRunId.toLowerCase() !== run_id.toLowerCase()) return null}- if (r.channel_type === 'plugin_workload_sdk' && !isSdkOnly) return null- if (isSdkOnly && !UUID_REGEX.test(prompt_bridge_metadata?.invocation_id ?? '')) return null+ // Workflow promptBridge calls use the same channel marker as SDK-only calls,+ // but retain their canonical workflow run/task/secret binding above. Reject+ // only an unrecognised shape; otherwise the usage emitted by a step-bearing+ // host would be dropped before it can be metered.+ if (+ r.channel_type === 'plugin_workload_sdk' &&+ !isSdkOnly &&+ !isLegacySdkOnly &&+ !isWorkflowSdk+ ) {+ return null+ }+ if (+ (isSdkOnly || isWorkflowSdk) &&+ !UUID_REGEX.test(prompt_bridge_metadata?.invocation_id ?? '')+ ) {+ return null+ }+ // Contract v2 physical-attempt fields are checked against the persisted+ // receipt during ingestion. A v1 host may omit generation/attempt fields;+ // retaining the event here lets the binding layer classify it explicitly as+ // the narrow legacy lane instead of confusing it with malformed JSON.return {request_id,@@ -265,6 +351,142 @@ function buildInsertParams(events: LlmUsageEvent[]): unknown[] {return params}+/**+ * Bind SDK-only usage to an immutable attempt receipt rather than the mutable+ * parent invocation status. A delayed reporter remains valid for the attempt+ * that actually executed, while a stale generation or forged target is+ * rejected before it can enter the usage ledger.+ */+async function filterEventsByAttemptReceipt(+ events: LlmUsageEvent[],+ db: DbClient+): Promise<{ accepted: LlmUsageEvent[]; rejected: number }> {+ // Both runtime lanes use the same immutable attempt receipt. SDK-only+ // hosts emit source_kind=plugin_workload_sdk; step-bearing hosts retain+ // source_kind=workflow for run attribution but mark the channel as the+ // Plugin Workload SDK. Treating the latter as ordinary workflow usage+ // would leave the target/generation binding unaudited.+ const isPromptBridgeSdkEvent = (event: LlmUsageEvent): boolean =>+ event.channel_type === 'plugin_workload_sdk' &&+ (event.source_kind === 'unknown' ||+ event.source_kind === 'plugin_workload_sdk' ||+ event.source_kind === 'workflow')+ const sdkEvents = events.filter(isPromptBridgeSdkEvent)+ if (sdkEvents.length === 0) return { accepted: events, rejected: 0 }+ const invocationIds = [+ ...new Set(+ sdkEvents+ .map(event => event.prompt_bridge_metadata?.invocation_id)+ .filter((value): value is string => typeof value === 'string')+ ),+ ]+ if (invocationIds.length === 0) {+ return {+ accepted: events.filter(event => !isPromptBridgeSdkEvent(event)),+ rejected: sdkEvents.length,+ }+ }+ const result = await db.query(+ `SELECT attempts.invocation_id::text, attempts.attempt_generation, attempts.method,+ attempts.target_refs, attempts.recipe_name, invocations.contract_version+ FROM plugin_workload_sdk_invocation_attempts attempts+ JOIN plugin_workload_sdk_invocations invocations+ ON invocations.id = attempts.invocation_id+ WHERE attempts.invocation_id = ANY($1::uuid[])`,+ [invocationIds]+ )+ const receipts = new Map<string, PromptBridgeAttemptBinding>()+ for (const row of result.rows as PromptBridgeAttemptBinding[]) {+ receipts.set(`${row.invocation_id}:${row.attempt_generation}`, row)+ }+ const providerAttemptIds = sdkEvents+ .map(event => event.prompt_bridge_metadata?.provider_attempt_id)+ .filter((value): value is string => typeof value === 'string')+ const providerAttempts = providerAttemptIds.length+ ? await db.query(+ `SELECT id::text, invocation_id::text, attempt_generation, attempt_index,+ target_ref, provider, model, credential_slot, status+ FROM plugin_workload_sdk_provider_attempts+ WHERE id = ANY($1::uuid[])`,+ [[...new Set(providerAttemptIds)]]+ )+ : { rows: [] }+ const providerAttemptById = new Map<string, ProviderAttemptBinding>()+ for (const row of providerAttempts.rows as ProviderAttemptBinding[]) {+ providerAttemptById.set(row.id, row)+ }+ const accepted: LlmUsageEvent[] = []+ let rejected = 0+ for (const event of events) {+ if (!isPromptBridgeSdkEvent(event)) {+ accepted.push(event)+ continue+ }+ const metadata = event.prompt_bridge_metadata+ const invocationId = metadata?.invocation_id+ const generation = metadata?.attempt_generation+ const providerAttemptId = metadata?.provider_attempt_id+ const providerAttemptIndex = metadata?.provider_attempt_index+ const receipt =+ typeof invocationId === 'string' && Number.isInteger(generation)+ ? receipts.get(`${invocationId}:${generation}`)+ : undefined+ const targetRefs = receipt && Array.isArray(receipt.target_refs) ? receipt.target_refs : []+ const targetRef = metadata?.target_ref+ const legacyInvocation =+ typeof invocationId === 'string'+ ? await db.query(+ `SELECT contract_version, method, status, authorization_decision, detail,+ recipe_namespace, recipe_name+ FROM plugin_workload_sdk_invocations+ WHERE id = $1`,+ [invocationId]+ )+ : { rows: [] }+ const legacy = legacyInvocation.rows[0] as+ | {+ contract_version?: unknown+ method?: unknown+ status?: unknown+ authorization_decision?: unknown+ detail?: unknown+ recipe_namespace?: unknown+ recipe_name?: unknown+ }+ | undefined+ const hasPhysicalAttempt =+ typeof providerAttemptId === 'string' && Number.isInteger(providerAttemptIndex)+ const legacyCompatible =+ !hasPhysicalAttempt &&+ legacy?.contract_version === 1 &&+ legacy.method === 'promptBridge' &&+ ['in_progress', 'complete'].includes(String(legacy.status)) &&+ legacy.authorization_decision === 'authorized' &&+ legacy.recipe_name === event.recipe_name &&+ legacy.detail === event.model+ const physicalCompatible =+ hasPhysicalAttempt &&+ receipt?.method === 'promptBridge' &&+ receipt.recipe_name === event.recipe_name &&+ typeof targetRef === 'string' &&+ targetRefs.some(ref => ref === targetRef) &&+ providerAttemptById.get(providerAttemptId!)?.invocation_id === invocationId &&+ providerAttemptById.get(providerAttemptId!)?.attempt_generation === generation &&+ providerAttemptById.get(providerAttemptId!)?.attempt_index === providerAttemptIndex &&+ providerAttemptById.get(providerAttemptId!)?.target_ref === targetRef &&+ providerAttemptById.get(providerAttemptId!)?.provider === event.provider &&+ providerAttemptById.get(providerAttemptId!)?.model === event.model &&+ providerAttemptById.get(providerAttemptId!)?.credential_slot === metadata?.credential_slot &&+ providerAttemptById.get(providerAttemptId!)?.status === 'complete'+ if (physicalCompatible || legacyCompatible) {+ accepted.push(event)+ } else {+ rejected += 1+ }+ }+ return { accepted, rejected }+}+export async function ingestUsageEvents(rawEvents: unknown[],db: DbClient = pool@@ -277,12 +499,22 @@ export async function ingestUsageEventsInTransaction(db: DbClient): Promise<UsageIngestTransactionResult> {const total = rawEvents.length- const validated: LlmUsageEvent[] = []+ let validated: LlmUsageEvent[] = []for (const raw of rawEvents) {const ev = validateUsageEvent(raw)if (ev) validated.push(ev)}- const rejected = total - validated.length+ let rejected = total - validated.length+ if (validated.length === 0) {+ return {+ result: { accepted: 0, duplicates: 0, rejected },+ acceptedEvents: [],+ }+ }++ const receiptFilter = await filterEventsByAttemptReceipt(validated, db)+ validated = receiptFilter.accepted+ rejected += receiptFilter.rejectedif (validated.length === 0) {return {result: { accepted: 0, duplicates: 0, rejected },diff --git a/control-api/test/db.governedRunTraceMigration.test.ts b/control-api/test/db.governedRunTraceMigration.test.tsindex f19caf0c8..631bfcde4 100644--- a/control-api/test/db.governedRunTraceMigration.test.ts+++ b/control-api/test/db.governedRunTraceMigration.test.ts@@ -70,7 +70,7 @@ describe('0061_governed_run_trace_schema_foundation migration', () => {expect(migrationSql).toContain('ADD COLUMN IF NOT EXISTS run_id UUID NULL')expect(migrationSql).toContain('governed_trace_safe_agent_run_metadata')expect(migrationSql).toContain(- "value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown')"+ "value->>'source_kind' IN ('channel', 'desktop', 'workflow', 'cron', 'unknown', 'plugin_workload_sdk')")expect(migrationSql).toContain("(value->>'input_tokens') ~ '^(0|[1-9][0-9]*)$'")expect(migrationSql).toContain(diff --git a/control-api/test/db.initDb.test.ts b/control-api/test/db.initDb.test.tsindex b84db559c..b4e431e7b 100644--- a/control-api/test/db.initDb.test.ts+++ b/control-api/test/db.initDb.test.ts@@ -237,7 +237,7 @@ describe('db.initDb', () => {expect(sqls).toContainEqual(expect.stringContaining(- "CREATE TYPE usage_source_kind AS ENUM ('channel','desktop','workflow','cron','unknown')"+ "CREATE TYPE usage_source_kind AS ENUM ('channel','desktop','workflow','cron','unknown','plugin_workload_sdk')"))expect(sqls).toContainEqual(expect.stringContaining('CREATE TABLE IF NOT EXISTS usage_events'))diff --git a/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.tsnew file mode 100644index 000000000..3a46ddc94--- /dev/null+++ b/control-api/test/db.pluginWorkloadSdkProtocolMigration.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from 'vitest'+import {+ addPluginWorkloadSdkProtocolAndRevocation,+ addPluginWorkloadSdkRuntimeAccess,+} from '../src/services/pluginWorkloadSdkSchema.js'++describe('plugin workload SDK protocol migration', () => {+ it('qualifies attempt completed_at when backfilling from invocations', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await addPluginWorkloadSdkProtocolAndRevocation({ query } as never)++ const migrationSql = String(query.mock.calls[0]?.[0])+ expect(migrationSql).toContain('completed_at = COALESCE(attempts.completed_at, now())')+ })++ it('grants attempt-ledger DML only to control_api_runtime', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })++ await addPluginWorkloadSdkRuntimeAccess({ query } as never)++ const migrationSql = String(query.mock.calls[0]?.[0])+ expect(migrationSql).toContain(+ 'FROM PUBLIC, trace_maintenance_runtime, workflow_recipes_runtime'+ )+ expect(migrationSql).toContain('TO control_api_runtime')+ expect(migrationSql).toContain('plugin_workload_sdk_invocation_attempts')+ expect(migrationSql).toContain('plugin_workload_sdk_provider_attempts')+ })+})diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex 01dfea97f..7d31d9775 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -23,6 +23,7 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {upsertGrant: vi.fn(),deleteGrant: vi.fn(),getQuotaCounters: vi.fn(),+ getPluginWorkloadSdkLegacyGrantInventory: vi.fn(),listInvocations: vi.fn(),}})@@ -63,6 +64,7 @@ beforeEach(() => {vi.mocked(sdkDb.upsertGrant).mockReset()vi.mocked(sdkDb.deleteGrant).mockReset()vi.mocked(sdkDb.getQuotaCounters).mockReset()+ vi.mocked(sdkDb.getPluginWorkloadSdkLegacyGrantInventory).mockReset()vi.mocked(sdkDb.listInvocations).mockReset()// R3 allowlist cross-check (listEnabledModelNamesForProvider) queries pool.// Default to the seed model so the valid-grant success paths pass; individual@@ -85,6 +87,24 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {})})+ it('exposes the read-only legacy migration gate with optional recipe filters', async () => {+ vi.mocked(sdkDb.getPluginWorkloadSdkLegacyGrantInventory).mockResolvedValue({+ totalPromptBridgeGrants: 1,+ legacyPromptBridgeGrants: 0,+ activationReady: true,+ items: [],+ })+ const res = await request(buildApp()).get(+ '/admin/plugin-workload-sdk/legacy-inventory?recipeNamespace=sandbox-recipes&recipeName=r1'+ )+ expect(res.status).toBe(200)+ expect(res.body.activationReady).toBe(true)+ expect(sdkDb.getPluginWorkloadSdkLegacyGrantInventory).toHaveBeenCalledWith({+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'r1',+ })+ })+it('rejects an invalid capabilityFamily', async () => {const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')@@ -112,7 +132,7 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {promptTargets: [{ ...validGrantBody.promptTargets[0], model: oversized }],})expect(res.status).toBe(400)- expect(res.body.error).toContain('promptTargets[0].model')+ expect(res.body.error).toContain('allowedModels entries')expect(sdkDb.upsertGrant).not.toHaveBeenCalled()})@@ -198,6 +218,33 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {expect(JSON.stringify(vi.mocked(sdkDb.upsertGrant).mock.calls)).not.toContain('secret-value')})+ it('accepts a policy catalogue larger than the bounded execution suffix', async () => {+ const targets = Array.from({ length: 5 }, (_, index) => ({+ targetRef: `target-${index}`,+ provider: 'zai',+ model: `glm-4.${index + 7}`,+ credentialSlot: 'zai-api-key',+ }))+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'catalogue' } as never)+ vi.mocked(pool.query).mockResolvedValue({+ rows: targets.map(target => ({ model: target.model })),+ rowCount: targets.length,+ } as never)+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ allowedModels: targets.map(target => target.model),+ promptTargets: targets,+ defaultTargetRef: targets[0]!.targetRef,+ })+ expect(res.status).toBe(200)+ expect(sdkDb.upsertGrant).toHaveBeenCalledWith(+ expect.objectContaining({ promptTargets: targets }),+ '11111111-1111-4111-8111-111111111111'+ )+ })+it('requires an explicit provider for promptBridge grants (R1)', async () => {const { provider: _omit, ...bodyWithoutProvider } = validGrantBodyconst res = await request(buildApp())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 6e4d3c0bd..0d87eb412 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@@ -32,9 +32,12 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {return {...actual,getInvocationById: vi.fn(),+ getPluginWorkloadSdkAttemptReceipt: vi.fn(),+ getPluginWorkloadSdkProviderAttempt: vi.fn(),findGrant: vi.fn(),listInvocations: vi.fn(),redeemPluginWorkloadSdkCredentialTicketJti: vi.fn(),+ markPluginWorkloadSdkProviderAttemptStatus: vi.fn(),resolveRecipientProfiles: vi.fn(),}})@@ -108,17 +111,24 @@ beforeEach(() => {vi.mocked(sdkDb.listInvocations).mockReset()vi.mocked(auditor.markInvocationStatus).mockReset().mockResolvedValue(true)vi.mocked(sdkDb.getInvocationById).mockReset()+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()+ vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockReset()vi.mocked(sdkDb.findGrant).mockReset()vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockReset()+ vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockReset()vi.mocked(notificationEmitter.enqueuePluginWorkloadSdkNotification).mockReset().mockResolvedValue(undefined)vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue(null)+ vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockResolvedValue(null)+ vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockResolvedValue(true)vi.mocked(authorizer.authorizePromptBridge).mockResolvedValue({ok: true,value: {invocationId: 'inv-1',replay: false,+ providerCallRequired: true,status: 'in_progress',model: 'glm-4.7',modelPolicy: null,@@ -136,6 +146,7 @@ beforeEach(() => {credentialSlot: 'zai-api-key',},],+ attemptGeneration: 1,policyRevision: 1,policyHash: 'policy-hash',maxOutputTokens: null,@@ -145,7 +156,10 @@ beforeEach(() => {ok: true,value: {invocationId: 'inv-1',+ attemptGeneration: 1,targetRef: 'openai-fallback',+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,credentialTicket: 'signed-fresh-ticket',policyRevision: 1,policyHash: 'policy-hash',@@ -169,6 +183,77 @@ beforeEach(() => {])})+describe('GET /mcp-host/plugin-workload-sdk/capabilities', () => {+ it('advertises the v2 identity contract while a prompt policy is missing', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(null)++ const res = await request(buildApp())+ .get('/mcp-host/plugin-workload-sdk/capabilities')+ .set('Authorization', `Bearer ${issueSdkToken()}`)++ expect(res.status).toBe(200)+ expect(res.body).toMatchObject({+ contractVersion: 2,+ supportedContractVersions: [1, 2],+ targetAwarePromptBridge: true,+ attemptLedger: true,+ credentialTickets: true,+ policyState: 'missing',+ policyRevision: 0,+ policyHash: null,+ defaultTargetRef: null,+ defaultProvider: null,+ defaultModel: null,+ v2Ready: false,+ })+ })++ it('reports an active target policy as v2-ready', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue({+ id: 'grant-capabilities',+ recipeNamespace: NS,+ recipeName: RECIPE,+ capabilityFamily: 'promptBridge',+ provider: 'openai',+ allowedModels: ['gpt-5.4-mini'],+ allowedEventTypes: [],+ allowedTargetRefs: [],+ allowedUserRefs: [],+ allowedCallers: ['api'],+ quotaLimits: {},+ modelPolicies: {},+ promptTargets: [+ {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+ },+ ],+ defaultTargetRef: 'primary-openai',+ policyState: 'active',+ policyRevision: 2,+ createdAt: '2026-08-03T00:00:00.000Z',+ updatedAt: '2026-08-03T00:00:00.000Z',+ })++ const res = await request(buildApp())+ .get('/mcp-host/plugin-workload-sdk/capabilities')+ .set('Authorization', `Bearer ${issueSdkToken()}`)++ expect(res.status).toBe(200)+ expect(res.body).toMatchObject({+ policyState: 'active',+ policyRevision: 2,+ defaultTargetRef: 'primary-openai',+ defaultProvider: 'openai',+ defaultModel: 'gpt-5.4-mini',+ v2Ready: true,+ })+ expect(res.body.policyHash).toMatch(/^[a-f0-9]{64}$/)+ })+})+describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {it('returns 401 without a token', async () => {const res = await request(buildApp())@@ -341,6 +426,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket', (recipeName: RECIPE,invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,}it('requires the runtime JWT and recipe binding', async () => {@@ -367,6 +453,9 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket', (invocationId: 'inv-1',targetRef: 'openai-fallback',credentialTicket: 'signed-fresh-ticket',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,policyRevision: 1,policyHash: 'policy-hash',expiresInSeconds: 60,@@ -375,6 +464,7 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket', (claims: expect.objectContaining({ recipeNamespace: NS, recipeName: RECIPE }),invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,})})})@@ -599,7 +689,7 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/status', () => {const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/invocations/missing/status').set('Authorization', `Bearer ${issueSdkToken()}`)- .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete' })+ .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete', attemptGeneration: 1 })expect(res.status).toBe(404)})@@ -611,20 +701,21 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/status', () => {const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/invocations/inv-1/status').set('Authorization', `Bearer ${issueSdkToken()}`)- .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete' })+ .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete', attemptGeneration: 1 })expect(res.status).toBe(403)expect(res.body.error).toBe('binding_mismatch')expect(auditor.markInvocationStatus).not.toHaveBeenCalled()})- it('returns 404 when the status update does not match the invocation binding', async () => {+ it('returns 409 when the status update loses the invocation CAS race', async () => {vi.mocked(sdkDb.getInvocationById).mockResolvedValue(invocation)vi.mocked(auditor.markInvocationStatus).mockResolvedValue(false)const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/invocations/inv-1/status').set('Authorization', `Bearer ${issueSdkToken()}`)- .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete' })- expect(res.status).toBe(404)+ .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'complete', attemptGeneration: 1 })+ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'stale_attempt', retryable: false })})it('marks the invocation status on a valid report', async () => {@@ -632,11 +723,18 @@ describe('POST /mcp-host/plugin-workload-sdk/invocations/:id/status', () => {const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/invocations/inv-1/status').set('Authorization', `Bearer ${issueSdkToken()}`)- .send({ recipeNamespace: NS, recipeName: RECIPE, status: 'provider_unavailable' })+ .send({+ recipeNamespace: NS,+ recipeName: RECIPE,+ status: 'provider_unavailable',+ attemptGeneration: 1,+ })expect(res.status).toBe(200)expect(auditor.markInvocationStatus).toHaveBeenCalledWith('inv-1', 'provider_unavailable', {recipeNamespace: NS,recipeName: RECIPE,+ expectedCurrentStatus: 'in_progress',+ expectedAttemptGeneration: 1,})})})@@ -693,7 +791,14 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =const res = await request(buildApp()).post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect').set('Authorization', `Bearer ${issueSdkToken()}`)- .send({ credentialTicket: 'not-a-ticket', invocationId: 'inv-1', targetRef: 'primary-zai' })+ .send({+ credentialTicket: 'not-a-ticket',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,+ })expect(res.status).toBe(403)expect(res.body).toEqual({ error: 'provider_policy_denied', retryable: false })expect(JSON.stringify(res.body)).not.toContain('credentialSlot')@@ -715,6 +820,9 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =recipeNamespace: NS,recipeName: RECIPE,invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,target,policyRevision: 1,policyHash,@@ -733,12 +841,16 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =status: 'in_progress',quotaConsumed: true,authorizationDecision: 'authorized',+ contractVersion: 2,promptAuthorization: {policyRevision: 1,policyHash,authorizedTargetRefs: ['primary-zai'],},+ attemptGeneration: 1,+ leaseExpiresAt: '2026-08-02T00:01:00.000Z',createdAt: '2026-08-02T00:00:00.000Z',+ updatedAt: '2026-08-02T00:00:00.000Z',completedAt: null,})vi.mocked(sdkDb.findGrant).mockResolvedValue({@@ -756,15 +868,52 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =modelPolicies: {},promptTargets: [target],defaultTargetRef: 'primary-zai',+ policyState: 'active',policyRevision: 1,createdAt: '2026-08-02T00:00:00.000Z',updatedAt: '2026-08-02T00:00:00.000Z',})+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue({+ invocationId: 'inv-1',+ recipeNamespace: NS,+ recipeName: RECIPE,+ attemptGeneration: 1,+ method: 'promptBridge',+ targetRefs: ['primary-zai'],+ policyRevision: 1,+ policyHash,+ status: 'in_progress',+ startedAt: '2026-08-02T00:00:00.000Z',+ leaseExpiresAt: '2026-08-02T00:01:00.000Z',+ completedAt: null,+ })+ vi.mocked(sdkDb.getPluginWorkloadSdkProviderAttempt).mockResolvedValue({+ id: '33333333-3333-4333-8333-333333333333',+ invocationId: 'inv-1',+ recipeNamespace: NS,+ recipeName: RECIPE,+ attemptGeneration: 1,+ attemptIndex: 1,+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ status: 'in_progress',+ credentialJti: null,+ startedAt: '2026-08-02T00:00:00.000Z',+ leaseExpiresAt: '2026-08-02T00:01:00.000Z',+ completedAt: null,+ usageRequestId: null,+ })+const body = {credentialTicket: ticket,invocationId: 'inv-1',targetRef: 'primary-zai',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,redeem: true,}await request(buildApp())diff --git a/control-api/test/services.notificationAckService.test.ts b/control-api/test/services.notificationAckService.test.tsindex 9d4c90692..1224e19a7 100644--- a/control-api/test/services.notificationAckService.test.ts+++ b/control-api/test/services.notificationAckService.test.ts@@ -1,10 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-vi.mock('../src/db.js', () => ({- pool: {- query: vi.fn(),- },-}))+vi.mock('../src/db.js', () => {+ const pool = { query: vi.fn() }+ return {+ pool,+ withTransaction: vi.fn(async (fn: (db: typeof pool) => unknown) => fn(pool)),+ }+})const { pool } = await import('../src/db.js')const { acknowledgeDesktopNotificationDelivery } =@@ -24,6 +26,8 @@ describe('notificationAckService', () => {rows: [{ invocationId: '33333333-3333-3333-3333-333333333333' }],} as never).mockResolvedValueOnce({ rowCount: 1, rows: [] } as never)+ .mockResolvedValueOnce({ rowCount: 1, rows: [{ attempt_generation: 1 }] } as never)+ .mockResolvedValueOnce({ rowCount: 1, rows: [] } as never)const result = await acknowledgeDesktopNotificationDelivery('22222222-2222-2222-2222-222222222222',@@ -43,6 +47,7 @@ describe('notificationAckService', () => {'33333333-3333-3333-3333-333333333333','delivered',true,+ 0,'accepted',])})diff --git a/control-api/test/services.notificationDeliveryTerminalService.test.ts b/control-api/test/services.notificationDeliveryTerminalService.test.tsindex ae7b93149..d5577b098 100644--- a/control-api/test/services.notificationDeliveryTerminalService.test.ts+++ b/control-api/test/services.notificationDeliveryTerminalService.test.ts@@ -6,12 +6,13 @@ import {resolvePendingWorkflowApprovalDelivery,} from '../src/services/notificationDeliveryQueueService.js'-vi.mock('../src/db.js', () => ({- pool: {- query: vi.fn(),- },- withTransaction: vi.fn(),-}))+vi.mock('../src/db.js', () => {+ const pool = { query: vi.fn() }+ return {+ pool,+ withTransaction: vi.fn(async (fn: (db: typeof pool) => unknown) => fn(pool)),+ }+})const mockedPoolQuery = vi.mocked(pool.query) as ReturnType<typeof vi.fn>@@ -162,6 +163,8 @@ describe('notificationDeliveryTerminalService', () => {rowCount: 1,} as any).mockResolvedValueOnce({ rows: [], rowCount: 1 } as any)+ .mockResolvedValueOnce({ rows: [{ attempt_generation: 1 }], rowCount: 1 } as any)+ .mockResolvedValueOnce({ rows: [], rowCount: 1 } as any)await expect(acknowledgeNotificationDelivery({@@ -173,7 +176,7 @@ describe('notificationDeliveryTerminalService', () => {})).resolves.toBe(true)- expect(mockedPoolQuery).toHaveBeenCalledTimes(2)+ expect(mockedPoolQuery).toHaveBeenCalledTimes(4)const invocationSql = String(mockedPoolQuery.mock.calls[1]![0])expect(invocationSql).toContain('UPDATE plugin_workload_sdk_invocations')// Guarded transition: only from 'accepted', sets completed_at.@@ -181,6 +184,7 @@ describe('notificationDeliveryTerminalService', () => {'invocation-1','delivered',true,+ 0,'accepted',])})diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.tsindex 2491e2de0..48812c76d 100644--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts@@ -25,10 +25,14 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {...actual,findGrant: vi.fn(),insertInvocation: vi.fn(),+ reviveFailedInvocation: vi.fn(),updateInvocationStatus: vi.fn(),consumePeriodQuota: vi.fn(),countRecentInvocations: vi.fn(),getInvocationById: vi.fn(),+ getPluginWorkloadSdkAttemptReceipt: vi.fn(),+ reservePluginWorkloadSdkProviderAttempt: vi.fn(),+ markPluginWorkloadSdkProviderAttemptStatus: vi.fn(),registerPluginWorkloadSdkCredentialTicketJti: vi.fn(),}})@@ -76,6 +80,7 @@ function grant(},],defaultTargetRef: 'primary-zai',+ policyState: 'active',policyRevision: 1,createdAt: '2026-06-09T00:00:00.000Z',updatedAt: '2026-06-09T00:00:00.000Z',@@ -100,6 +105,10 @@ function invocation(status: 'in_progress',quotaConsumed: true,authorizationDecision: 'authorized',+ contractVersion: 2,+ attemptGeneration: 1,+ leaseExpiresAt: null,+ updatedAt: '2026-06-09T00:00:00.000Z',createdAt: '2026-06-09T00:00:00.000Z',completedAt: null,promptAuthorization: null,@@ -126,18 +135,56 @@ const baseNotificationParams = {beforeEach(() => {vi.mocked(sdkDb.findGrant).mockReset()vi.mocked(sdkDb.insertInvocation).mockReset()+ vi.mocked(sdkDb.reviveFailedInvocation).mockReset()vi.mocked(sdkDb.updateInvocationStatus).mockReset()vi.mocked(sdkDb.consumePeriodQuota).mockReset()vi.mocked(sdkDb.countRecentInvocations).mockReset()vi.mocked(sdkDb.getInvocationById).mockReset()+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockReset()+ vi.mocked(sdkDb.reservePluginWorkloadSdkProviderAttempt).mockReset()+ vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockReset()vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockReset()vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(0)vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)+ vi.mocked(sdkDb.getPluginWorkloadSdkAttemptReceipt).mockResolvedValue({+ invocationId: 'inv-1',+ recipeNamespace: NS,+ recipeName: RECIPE,+ attemptGeneration: 1,+ method: 'promptBridge',+ targetRefs: ['primary-zai', 'openai-fallback'],+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ status: 'in_progress',+ startedAt: '2026-06-09T00:00:00.000Z',+ leaseExpiresAt: '2026-06-09T00:01:00.000Z',+ completedAt: null,+ })+ vi.mocked(sdkDb.reservePluginWorkloadSdkProviderAttempt).mockResolvedValue({+ id: '33333333-3333-4333-8333-333333333333',+ invocationId: 'inv-1',+ recipeNamespace: NS,+ recipeName: RECIPE,+ attemptGeneration: 1,+ attemptIndex: 1,+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key',+ status: 'reserved',+ credentialJti: null,+ startedAt: '2026-06-09T00:00:00.000Z',+ leaseExpiresAt: '2026-06-09T00:01:00.000Z',+ completedAt: null,+ usageRequestId: null,+ })+ vi.mocked(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).mockResolvedValue(true)vi.mocked(sdkDb.insertInvocation).mockResolvedValue({kind: 'inserted',invocation: invocation(),})+ vi.mocked(sdkDb.reviveFailedInvocation).mockResolvedValue(2)})describe('authorizePromptBridge', () => {@@ -455,11 +502,16 @@ describe('authorizePromptBridge', () => {const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })expect(result).toMatchObject({ ok: false, error: 'quota_exceeded', retryable: false })expect(sdkDb.insertInvocation).toHaveBeenCalledOnce()- expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith('inv-1', 'failed', {- completed: true,- recipeNamespace: NS,- recipeName: RECIPE,- })+ expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith(+ 'inv-1',+ 'failed',+ expect.objectContaining({+ completed: true,+ recipeNamespace: NS,+ recipeName: RECIPE,+ expectedAttemptGeneration: 1,+ })+ )})it('allows exactly maxInvocationsPerMinute calls (the limit-th call is not self-rejected)', async () => {@@ -496,11 +548,16 @@ describe('authorizePromptBridge', () => {vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(false)const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })expect(result).toMatchObject({ ok: false, error: 'quota_exceeded' })- expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith('inv-1', 'failed', {- completed: true,- recipeNamespace: NS,- recipeName: RECIPE,- })+ expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith(+ 'inv-1',+ 'failed',+ expect.objectContaining({+ completed: true,+ recipeNamespace: NS,+ recipeName: RECIPE,+ expectedAttemptGeneration: 1,+ })+ )})it('authorizes a valid request and records the invocation', async () => {@@ -564,7 +621,7 @@ describe('authorizePromptBridge', () => {it('re-consumes quota and revives status for a failed-replay retry', async () => {const currentGrant = grant({ quotaLimits: { maxRequestsPerRun: 10 } })vi.mocked(sdkDb.findGrant).mockResolvedValue(currentGrant)- vi.mocked(sdkDb.updateInvocationStatus).mockResolvedValue(true)+ vi.mocked(sdkDb.reviveFailedInvocation).mockResolvedValue(2)vi.mocked(sdkDb.insertInvocation).mockResolvedValue({kind: 'replay',invocation: invocation({@@ -577,14 +634,16 @@ describe('authorizePromptBridge', () => {}),})const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })- // quota must be re-consumed for a failed retry- expect(sdkDb.consumePeriodQuota).toHaveBeenCalledOnce()- // status revived to in_progress- expect(sdkDb.updateInvocationStatus).toHaveBeenCalledWith('inv-1', 'in_progress', {- completed: false,+ // A failed replay is a new physical attempt, but it remains the same+ // logical idempotent invocation and therefore does not consume period+ // quota a second time.+ expect(sdkDb.consumePeriodQuota).not.toHaveBeenCalled()+ // The retry transition is performed atomically by the DB revive operation.+ expect(sdkDb.reviveFailedInvocation).toHaveBeenCalledWith({+ id: 'inv-1',recipeNamespace: NS,recipeName: RECIPE,- expectedCurrentStatus: 'failed',+ leaseSeconds: expect.any(Number),})expect(result).toMatchObject({ok: true,@@ -646,6 +705,7 @@ describe('reissuePromptBridgeCredentialTicket', () => {claims: claims(),invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,})expect(result).toMatchObject({@@ -683,6 +743,7 @@ describe('reissuePromptBridgeCredentialTicket', () => {claims: claims(),invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,})expect(result).toMatchObject({ ok: false, error: 'target_not_allowed' })expect(sdkDb.findGrant).not.toHaveBeenCalled()@@ -706,6 +767,7 @@ describe('reissuePromptBridgeCredentialTicket', () => {claims: claims(),invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,})).resolves.toMatchObject({ ok: false, error: 'provider_policy_denied' })@@ -717,6 +779,7 @@ describe('reissuePromptBridgeCredentialTicket', () => {claims: claims(),invocationId: 'inv-1',targetRef: 'openai-fallback',+ attemptGeneration: 1,})).resolves.toMatchObject({ ok: false, error: 'provider_policy_denied' })})diff --git a/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.tsindex 8f582f753..8949650a0 100644--- a/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts+++ b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts@@ -9,6 +9,12 @@ import {} from '../src/services/pluginWorkloadSdkCredentialTicket.js'describe('plugin workload SDK credential ticket', () => {+ const ticketBinding = {+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',+ providerAttemptIndex: 1,+ }+afterEach(() => {vi.useRealTimers()})@@ -18,6 +24,7 @@ describe('plugin workload SDK credential ticket', () => {recipeNamespace: 'sandbox-recipes',recipeName: 'prompt-notify',invocationId: 'invocation-1',+ ...ticketBinding,target: {targetRef: 'openai-fallback',provider: 'openai',@@ -59,6 +66,7 @@ describe('plugin workload SDK credential ticket', () => {recipeNamespace: 'sandbox-recipes',recipeName: 'prompt-notify',invocationId: 'invocation-slow-primary',+ ...ticketBinding,target: {targetRef: 'openai-fallback',provider: 'openai',@@ -80,6 +88,7 @@ describe('plugin workload SDK credential ticket', () => {recipeNamespace: 'sandbox-recipes',recipeName: 'prompt-notify',invocationId: 'invocation-1',+ ...ticketBinding,target: {targetRef: 'openai-fallback',provider: 'openai',diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.tsindex ffc7d413c..36ce2bbfd 100644--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts@@ -3,9 +3,12 @@ import { pool } from '../src/db.js'import {consumePeriodQuota,deleteGrant,+ failStaleInvocations,+ getPluginWorkloadSdkLegacyGrantInventory,redeemPluginWorkloadSdkCredentialTicketJti,registerPluginWorkloadSdkCredentialTicketJti,resolveRecipientProfiles,+ updateInvocationStatus,upsertGrant,} from '../src/services/pluginWorkloadSdkDb.js'@@ -35,6 +38,15 @@ function maxPlaceholder(sql: string): number {return matches.reduce((max, p) => Math.max(max, Number(p.slice(1))), 0)}+function mockUpsertGrantQueries(row: Record<string, unknown>): void {+ // recipe advisory lock → family row → recipe kill-switch guard → upsert.+ vi.mocked(pool.query)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [row], rowCount: 1 } as never)+}+describe('consumePeriodQuota — SQL bind parameter contract', () => {beforeEach(() => {vi.mocked(pool.query).mockClear()@@ -81,6 +93,23 @@ describe('JIT credential ticket jti registry', () => {it('registers a non-secret, invocation-bound jti and reports insertion conflicts', async () => {vi.mocked(pool.query).mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [{ policy_state: 'active' }], rowCount: 1 } as never)+ .mockResolvedValueOnce({+ rows: [+ {+ status: 'in_progress',+ attempt_generation: 1,+ lease_expires_at: new Date(Date.now() + 60_000),+ },+ ],+ rowCount: 1,+ } as never)+ .mockResolvedValueOnce({+ rows: [{ id: '33333333-3333-4333-8333-333333333333' }],+ rowCount: 1,+ } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 1 } as never).mockResolvedValueOnce({ rows: [], rowCount: 1 } as never)await expect(registerPluginWorkloadSdkCredentialTicketJti({@@ -89,18 +118,27 @@ describe('JIT credential ticket jti registry', () => {recipeName: 'sdk-recipe',invocationId: '22222222-2222-4222-8222-222222222222',targetRef: 'openai-fallback',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',expiresAt: new Date('2026-08-02T12:01:00.000Z'),})).resolves.toBe(true)- const [sql, params] = vi.mocked(pool.query).mock.calls[1] as unknown as [string, unknown[]]+ const [sql, params] = vi+ .mocked(pool.query)+ .mock.calls.find(([statement]) =>+ String(statement).includes('INSERT INTO plugin_workload_sdk_credential_ticket_jtis')+ ) as unknown as [string, unknown[]]expect(sql).toContain('plugin_workload_sdk_credential_ticket_jtis')expect(sql).toContain('ON CONFLICT (jti) DO NOTHING')- expect(params).toHaveLength(6)+ expect(params).toHaveLength(8)expect(JSON.stringify(params)).not.toContain('secret-value')})it('redeems a jti atomically once and binds every identifying field in SQL', async () => {- vi.mocked(pool.query).mockResolvedValue({ rows: [], rowCount: 1 } as never)+ vi.mocked(pool.query)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [{ policy_state: 'active' }], rowCount: 1 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 1 } as never)await expect(redeemPluginWorkloadSdkCredentialTicketJti({jti: '11111111-1111-4111-8111-111111111111',@@ -108,9 +146,11 @@ describe('JIT credential ticket jti registry', () => {recipeName: 'sdk-recipe',invocationId: '22222222-2222-4222-8222-222222222222',targetRef: 'openai-fallback',+ attemptGeneration: 1,+ providerAttemptId: '33333333-3333-4333-8333-333333333333',})).resolves.toBe(true)- const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]+ const [sql, params] = vi.mocked(pool.query).mock.calls[2] as unknown as [string, unknown[]]expect(sql).toContain('redeemed_at IS NULL')expect(sql).toContain('expires_at > now()')expect(params).toEqual([@@ -119,10 +159,113 @@ describe('JIT credential ticket jti registry', () => {'sdk-recipe','22222222-2222-4222-8222-222222222222','openai-fallback',+ 1,+ '33333333-3333-4333-8333-333333333333',])})})+describe('legacy promptBridge inventory', () => {+ beforeEach(() => {+ vi.mocked(pool.query).mockReset()+ })++ it('reports legacy shape without rewriting policy or exposing secrets', async () => {+ vi.mocked(pool.query).mockResolvedValueOnce({+ rows: [+ {+ id: 'grant-legacy',+ recipe_namespace: 'sandbox-recipes',+ recipe_name: 'legacy-recipe',+ policy_state: 'legacy_unreviewed',+ policy_revision: 0,+ provider: null,+ prompt_targets: [],+ default_target_ref: null,+ },+ {+ id: 'grant-active',+ recipe_namespace: 'sandbox-recipes',+ recipe_name: 'active-recipe',+ policy_state: 'active',+ policy_revision: 2,+ provider: 'openai',+ prompt_targets: [+ {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+ },+ ],+ default_target_ref: 'primary-openai',+ },+ ],+ rowCount: 2,+ } as never)+ await expect(+ getPluginWorkloadSdkLegacyGrantInventory({ recipeNamespace: 'sandbox-recipes' })+ ).resolves.toEqual({+ totalPromptBridgeGrants: 2,+ legacyPromptBridgeGrants: 1,+ activationReady: false,+ items: [+ expect.objectContaining({+ id: 'grant-legacy',+ recipeName: 'legacy-recipe',+ reasons: expect.arrayContaining([+ 'legacy_policy_state',+ 'missing_provider',+ 'empty_prompt_targets',+ 'missing_default_target',+ 'invalid_policy_revision',+ ]),+ }),+ ],+ })+ const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]+ expect(sql).toContain("capability_family = 'promptBridge'")+ expect(params).toEqual(['sandbox-recipes'])+ expect(sql).not.toContain('credential')+ })+})++describe('invocation retry lifecycle timestamps', () => {+ beforeEach(() => {+ vi.mocked(pool.query).mockReset()+ vi.mocked(pool.query).mockResolvedValue({ rows: [], rowCount: 1 } as never)+ })++ it('touches updated_at on every status transition and preserves the CAS guard', async () => {+ await expect(+ updateInvocationStatus('inv-1', 'in_progress', {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'sdk-recipe',+ expectedCurrentStatus: 'failed',+ })+ ).resolves.toBe(true)+ const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]+ expect(sql).toContain('updated_at = now()')+ expect(sql).toContain('status = $7')+ expect(params).toEqual([+ 'inv-1',+ 'in_progress',+ false,+ 0,+ 'sandbox-recipes',+ 'sdk-recipe',+ 'failed',+ ])+ })++ it('sweeps by the latest retry timestamp rather than the original reservation', async () => {+ await expect(failStaleInvocations(150)).resolves.toBe(1)+ const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]+ expect(sql).toContain('lease_expires_at < now()')+ expect(sql).not.toContain('created_at < now()')+ })+})+describe('upsertGrant — provider column (R1)', () => {const grantRow = {id: 'g1',@@ -137,6 +280,11 @@ describe('upsertGrant — provider column (R1)', () => {allowed_callers: ['api'],quota_limits: {},model_policies: {},+ prompt_targets: [],+ default_target_ref: null,+ policy_state: 'active',+ policy_revision: 1,+ revocation_id: null,created_at: '2026-07-09T00:00:00.000Z',updated_at: '2026-07-09T00:00:00.000Z',}@@ -146,7 +294,7 @@ describe('upsertGrant — provider column (R1)', () => {})it('persists the explicit provider and maps it back on the returned grant', async () => {- vi.mocked(pool.query).mockResolvedValue({ rows: [grantRow], rowCount: 1 } as never)+ mockUpsertGrantQueries(grantRow)const grant = await upsertGrant({recipeNamespace: 'sandbox-recipes',@@ -171,10 +319,11 @@ describe('upsertGrant — provider column (R1)', () => {})it('binds NULL when no provider is supplied (clientNotifications)', async () => {- vi.mocked(pool.query).mockResolvedValue({- rows: [{ ...grantRow, capability_family: 'clientNotifications', provider: null }],- rowCount: 1,- } as never)+ mockUpsertGrantQueries({+ ...grantRow,+ capability_family: 'clientNotifications',+ provider: null,+ })const grant = await upsertGrant({recipeNamespace: 'sandbox-recipes',@@ -195,7 +344,7 @@ describe('upsertGrant — provider column (R1)', () => {it('reads a legacy grant with no provider column as null (undefined → null)', async () => {const { provider: _drop, ...legacyRow } = grantRow- vi.mocked(pool.query).mockResolvedValue({ rows: [legacyRow], rowCount: 1 } as never)+ mockUpsertGrantQueries(legacyRow)const grant = await upsertGrant({recipeNamespace: 'sandbox-recipes',@@ -211,24 +360,19 @@ describe('upsertGrant — provider column (R1)', () => {})it('writes ordered targets and default atomically while incrementing the policy revision', async () => {- vi.mocked(pool.query).mockResolvedValue({- rows: [+ mockUpsertGrantQueries({+ ...grantRow,+ prompt_targets: [{- ...grantRow,- prompt_targets: [- {- targetRef: 'primary-zai',- provider: 'zai',- model: 'glm-4.7',- credentialSlot: 'zai-api-key',- },- ],- default_target_ref: 'primary-zai',- policy_revision: 2,+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',},],- rowCount: 1,- } as never)+ default_target_ref: 'primary-zai',+ policy_revision: 2,+ })const grant = await upsertGrant({recipeNamespace: 'sandbox-recipes',@@ -352,6 +496,7 @@ describe('Plugin Workload SDK governed permission events', () => {vi.mocked(pool.query).mockResolvedValueOnce({ rows: [], rowCount: 1 } as never).mockResolvedValueOnce({ rows: [{ allowed_user_refs: [U1] }], rowCount: 1 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never).mockResolvedValueOnce({ rows: [grantRow([U1, U2])], rowCount: 1 } as never).mockResolvedValueOnce({ rows: [{ id: U2 }], rowCount: 1 } as never)diff --git a/control-api/test/services.pluginWorkloadSdkMaintenanceCron.test.ts b/control-api/test/services.pluginWorkloadSdkMaintenanceCron.test.tsindex 0008d1101..5e4ba13b4 100644--- a/control-api/test/services.pluginWorkloadSdkMaintenanceCron.test.ts+++ b/control-api/test/services.pluginWorkloadSdkMaintenanceCron.test.ts@@ -39,7 +39,7 @@ describe('pluginWorkloadSdkMaintenanceCron (plan §5.1, OQ-5)', () => {it('sweeps stale invocations and prunes expired idempotency rows on each tick', async () => {startPluginWorkloadSdkMaintenanceCron(60_000)await vi.advanceTimersByTimeAsync(60_000)- expect(sdkDb.failStaleInvocations).toHaveBeenCalledWith(150)+ expect(sdkDb.failStaleInvocations).toHaveBeenCalledWith(180)expect(sdkDb.prunePluginWorkloadSdkExpiredIdempotency).toHaveBeenCalledTimes(1)await vi.advanceTimersByTimeAsync(60_000)expect(sdkDb.prunePluginWorkloadSdkExpiredIdempotency).toHaveBeenCalledTimes(2)diff --git a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.tsindex 9fed48010..48a10a660 100644--- a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts+++ b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts@@ -40,6 +40,7 @@ const grant = (modelPolicies: {},promptTargets: [],defaultTargetRef: null,+ policyState: 'active',policyRevision: 0,createdAt: '',updatedAt: '',diff --git a/control-api/test/services.usageEvents.test.ts b/control-api/test/services.usageEvents.test.tsindex b62640cc9..67273ce2b 100644--- a/control-api/test/services.usageEvents.test.ts+++ b/control-api/test/services.usageEvents.test.ts@@ -176,6 +176,28 @@ describe('validateUsageEvent', () => {})).toBeNull()})++ it('accepts workflow promptBridge usage with the SDK channel marker', () => {+ const workflowEvent = {+ ...VALID_EVENT,+ source_kind: 'workflow',+ channel_type: 'plugin_workload_sdk',+ run_id: '00000000-0000-4000-8000-000000000001',+ host_ref: 'sandbox-recipes/e2e-recipe',+ context_ref: null,+ recipe_name: 'e2e-recipe',+ task_id: '00000000-0000-4000-8000-000000000001:e2e-recipe:2026-05-09T00:00:00.000Z',+ llm_secret_name: 'openai-key',+ prompt_bridge_metadata: {+ invocation_id: '00000000-0000-4000-8000-000000000099',+ target_ref: 'openai-primary',+ credential_slot: 'openai-api-key',+ fallback_used: false,+ attempt_count: 1,+ },+ }+ expect(validateUsageEvent(workflowEvent)).not.toBeNull()+ })})describe('ingestUsageEvents', () => {diff --git a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.tsindex 9aabd8e58..e89e87929 100644--- a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts+++ b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts@@ -5,10 +5,9 @@* 1. Publish the SDK recipe to the Marketplace (registry-api).* 2. Instantiate it from the Marketplace UI → POST /admin/registry/install-recipe* → a versioned WorkflowRecipe CRD in sandbox-recipes.- * 3. Wait for the stepless eager mcp-host to validate the SDK capability- * (status.pluginWorkloadSdk.state === 'validated'). This is the path that- * regressed (configure readiness race) — the operator journey must observe- * it self-validate without a keepalive step or manual intervention.+ * 3. Wait for the stepless eager mcp-host identity bootstrap. A fresh recipe+ * normally reports `awaiting_policy` until the operator creates a grant;+ * this is an expected policy state, not provider failure.* 4. Configure the two SDK grants (promptBridge + clientNotifications) from* the grant page UI so an allowed user can receive notifications.* 5. Verify both grants are listed and bound to the installed recipe.@@ -23,6 +22,8 @@*/import { type Page, expect, test } from '@playwright/test'import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import path from 'node:path'import { setTimeout as delay } from 'node:timers/promises'const BASE_API =@@ -30,7 +31,11 @@ const BASE_API =process.env.CONTROL_API_URL ||process.env.E2E_CONTROL_API_URL ||''-const REGISTRY_BASE = process.env.REGISTRY_API_BASE_URL || process.env.REGISTRY_URL || ''+const REGISTRY_BASE =+ process.env.REGISTRY_API_BASE_URL ||+ process.env.REGISTRY_API_URL ||+ process.env.REGISTRY_URL ||+ ''const CONTROL_UI_BASE = process.env.CONTROL_UI_BASE_URL || process.env.CONTROL_UI_URL || ''const ADMIN_USER =process.env.E2E_ADMIN_USERNAME ||@@ -46,13 +51,33 @@ const ADMIN_PASS =process.env.E2E_TEST_PASSWORD ||'changeme123!'// Plugin SDK T3 must not inherit the shared Host's historical Z.AI default.-// Use an explicit OpenAI/Claude pair unless the caller supplies another-// provider deliberately; the guard below rejects Z.AI so a 429 cannot be-// mistaken for an SDK regression.-const PROVIDER = process.env.E2E_WORKFLOW_MODEL_PROVIDER || 'openai'-const MODEL = process.env.E2E_WORKFLOW_MODEL_NAME || 'gpt-5.4-mini'-const FALLBACK_PROVIDER = process.env.E2E_PROMPT_FALLBACK_PROVIDER || 'claude'-const FALLBACK_MODEL = process.env.E2E_PROMPT_FALLBACK_MODEL || 'claude-sonnet-4-6'+// An explicit E2E provider wins; otherwise only an OpenAI/Claude root setting+// is inherited. An unsupported root provider fails before any UI mutation+// instead of silently redirecting a paid call.+const configuredProvider = process.env.E2E_WORKFLOW_MODEL_PROVIDER?.trim() || ''+const inheritedProvider = process.env.CLERUM_MODEL_PROVIDER?.trim() || ''+const PROVIDER =+ configuredProvider ||+ (inheritedProvider === 'openai' || inheritedProvider === 'claude' ? inheritedProvider : 'openai')+if (inheritedProvider && !configuredProvider && !['openai', 'claude'].includes(inheritedProvider)) {+ throw new Error(+ `Plugin Workload SDK E2E refuses inherited provider ${inheritedProvider}; set E2E_WORKFLOW_MODEL_PROVIDER and E2E_WORKFLOW_MODEL_NAME explicitly to OpenAI or Claude.`+ )+}+const MODEL =+ process.env.E2E_WORKFLOW_MODEL_NAME ||+ (PROVIDER === 'claude' ? 'claude-sonnet-4-6' : 'gpt-5.4-mini')+const FALLBACK_PROVIDER =+ process.env.E2E_PROMPT_FALLBACK_PROVIDER || (PROVIDER === 'claude' ? 'openai' : 'claude')+const FALLBACK_MODEL =+ process.env.E2E_PROMPT_FALLBACK_MODEL ||+ (FALLBACK_PROVIDER === 'claude' ? 'claude-sonnet-4-6' : 'gpt-5.4-mini')+if (!['openai', 'claude'].includes(PROVIDER) || !['openai', 'claude'].includes(FALLBACK_PROVIDER)) {+ throw new Error('Plugin Workload SDK E2E only permits OpenAI and Claude targets.')+}+if (PROVIDER === FALLBACK_PROVIDER) {+ throw new Error('Plugin Workload SDK E2E requires distinct primary and fallback providers.')+}const RECIPE_NS = 'sandbox-recipes'const EVENT_TYPE = 'e2e.test.notification'const USER_EMAIL =@@ -68,6 +93,21 @@ let adminSessionHeader = ''/** When set, the journey writes labelled success screenshots here (evidence/demo only). */const EVIDENCE_DIR = process.env.E2E_EVIDENCE_DIR+function isProductionContext(context: string): boolean {+ return (+ /(^|[-_])(prod|production)([-_]|$)/i.test(context) ||+ (/(^|[-_])clerum([-_]|$)$/i.test(context) && !/example-dev/i.test(context))+ )+}++function isAllowedMutableContext(context: string): boolean {+ return (+ context === 'clerum-test' ||+ /^clerum-(codex|detached)-.+-[0-9a-f]{8}$/.test(context) ||+ /^clerum-.+-[0-9a-f]{7,8}$/.test(context)+ )+}+function assertMutableBranchProfile(): void {if (process.env.E2E_PLUGIN_SDK_WRITE_CONFIRM !== '1') {throw new Error('Mutable Plugin Workload SDK E2E requires E2E_PLUGIN_SDK_WRITE_CONFIRM=1.')@@ -75,15 +115,59 @@ function assertMutableBranchProfile(): void {const context =process.env.E2E_K8S_CONTEXT || process.env.KUBECONTEXT || process.env.K8S_CONTEXT || ''if (!context) throw new Error('E2E_K8S_CONTEXT is required for the mutable operator journey.')- const currentContext = execFileSync(- 'kubectl',- ['--context', context, 'config', 'current-context'],- { encoding: 'utf8', timeout: 15_000 }- ).trim()+ if (isProductionContext(context) || !isAllowedMutableContext(context)) {+ throw new Error(+ `Mutable Plugin Workload SDK E2E only permits clerum-test or a branch-owned Minikube profile; refusing context ${context}.`+ )+ }+ const currentContext = execFileSync('kubectl', ['config', 'current-context'], {+ encoding: 'utf8',+ timeout: 15_000,+ }).trim()if (currentContext !== context) {throw new Error(`kubectl context mismatch: expected ${context}, got ${currentContext}`)}+ const repoRoot = path.resolve(__dirname, '../..')+ const expectedHead = execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim()+ const expectedWorktreeId = createHash('sha1').update(repoRoot).digest('hex')+ const marker = JSON.parse(+ execFileSync(+ 'kubectl',+ [+ '--context',+ context,+ '-n',+ 'control-plane',+ 'get',+ 'configmap',+ 'clerum-pre-gate-sync-state',+ '-o',+ 'json',+ ],+ { encoding: 'utf8', timeout: 15_000 }+ )+ ) as { data?: Record<string, string> }+ const markerData = marker.data ?? {}+ if (!markerData.gitHead || !markerData.worktreeId || !markerData.clusterFingerprint) {+ throw new Error(+ `Profile ${context} has no complete pre-gate sync marker (gitHead/worktreeId/clusterFingerprint required).`+ )+ }+ if (markerData.gitHead !== expectedHead || markerData.worktreeId !== expectedWorktreeId) {+ throw new Error(+ `Profile ${context} marker does not belong to this worktree/head: marker head=${markerData.gitHead} worktree=${markerData.worktreeId}; expected head=${expectedHead} worktree=${expectedWorktreeId}.`+ )+ }+ const expectedClusterFingerprint = process.env.E2E_EXPECTED_CLUSTER_FINGERPRINT?.trim()+ if (expectedClusterFingerprint && markerData.clusterFingerprint !== expectedClusterFingerprint) {+ throw new Error(+ `Profile ${context} marker cluster fingerprint ${markerData.clusterFingerprint} does not match E2E_EXPECTED_CLUSTER_FINGERPRINT ${expectedClusterFingerprint}.`+ )+ }+const urls = [['CONTROL_UI_BASE_URL', CONTROL_UI_BASE],['CONTROL_API_BASE_URL', BASE_API],@@ -240,17 +324,24 @@ function recipeManifest(name: string, userRef: string): Record<string, unknown>}}-async function waitForSdkValidated(token: string, recipeName: string): Promise<void> {+async function waitForSdkState(+ token: string,+ recipeName: string,+ acceptedStates: readonly string[],+ label: string+): Promise<string> {for (let attempt = 1; attempt <= 60; attempt += 1) {const { status, data } = await api(token, 'GET', `/api/v1/admin/recipes/${recipeName}`)if (status === 200) {const sdk = (data as { status?: { pluginWorkloadSdk?: { state?: string } } }).status?.pluginWorkloadSdk- if (sdk?.state === 'validated') return+ if (sdk?.state && acceptedStates.includes(sdk.state)) return sdk.state}await delay(2_000)}- throw new Error(`recipe ${recipeName} SDK capability did not reach validated`)+ throw new Error(+ `recipe ${recipeName} SDK capability did not reach ${label} (${acceptedStates.join(' or ')})`+ )}test.describe('Plugin Workload SDK — operator journey (Marketplace → install → grants)', () => {@@ -327,8 +418,16 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installexpect(installedRecipeName).not.toBe('')await expect(row.getByRole('button', { name: 'Installed' })).toBeDisabled()- // 3. The eager mcp-host self-validates the SDK capability (regression path).- await waitForSdkValidated(token, installedRecipeName)+ // 3. The eager mcp-host proves the SDK identity before a grant exists.+ // The expected fresh-install state is awaiting_policy; no provider call+ // is authorized until the operator completes the grant journey below.+ const identityState = await waitForSdkState(+ token,+ installedRecipeName,+ ['awaiting_policy', 'validated'],+ 'identity bootstrap readiness'+ )+ expect(['awaiting_policy', 'validated']).toContain(identityState)// 4. promptBridge grant — configured through the grant page UI. Add the// fallback first, then the bootstrap target, and reorder it visibly so@@ -416,6 +515,11 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installawait expect(notifyRow).toBeVisible({ timeout: 15_000 })await expect(notifyRow).toContainText('users:')await expect(notifyRow).not.toContainText(userRef) // resolved to a handle, not the UUID++ // Both grants now exist. The WRC must observe the active target policy+ // and transition from awaiting_policy to validated before data-plane use.+ await waitForSdkState(token, installedRecipeName, ['validated'], 'validated policy')+if (EVIDENCE_DIR)await page.screenshot({ path: `${EVIDENCE_DIR}/operator-2-grant-created.png` })@@ -495,6 +599,24 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installcleanupErrors.push(`delete grant ${grant.id}: ${String(error)}`)}}+ try {+ const afterDelete = await api(+ token,+ 'GET',+ `/api/v1/admin/plugin-workload-sdk/grants?recipeNamespace=${RECIPE_NS}&recipeName=${installedRecipeName}`+ )+ const remaining = (afterDelete.data.data ??+ afterDelete.data.items ??+ afterDelete.data.grants ??+ []) as unknown[]+ if (afterDelete.status !== 200 || remaining.length > 0) {+ cleanupErrors.push(+ `grant cleanup postcondition failed: status=${afterDelete.status}, remaining=${remaining.length}`+ )+ }+ } catch (error) {+ cleanupErrors.push(`verify grants deleted: ${String(error)}`)+ }}} catch (error) {cleanupErrors.push(`list/delete grants: ${String(error)}`)@@ -508,6 +630,24 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installif (uninstalled.status >= 300 && uninstalled.status !== 404) {cleanupErrors.push(`uninstall ${installedRecipeName}: ${uninstalled.status}`)}+ if (uninstalled.status < 300 || uninstalled.status === 404) {+ let recipeStatus = uninstalled.status+ for (let attempt = 0; attempt < 15 && recipeStatus !== 404; attempt++) {+ await delay(1_000)+ recipeStatus = (+ await api(+ token,+ 'GET',+ `/api/v1/admin/recipes/${encodeURIComponent(installedRecipeName)}`+ )+ ).status+ }+ if (recipeStatus !== 404) {+ cleanupErrors.push(+ `recipe cleanup postcondition failed: ${installedRecipeName} still returned HTTP ${recipeStatus}`+ )+ }+ }} catch (error) {cleanupErrors.push(`uninstall ${installedRecipeName}: ${String(error)}`)}@@ -520,6 +660,16 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installif (!deletedEntry.ok && deletedEntry.status !== 404) {cleanupErrors.push(`delete registry entry ${entryName}: ${deletedEntry.status}`)}+ if (deletedEntry.ok || deletedEntry.status === 404) {+ const afterDelete = await fetch(+ `${REGISTRY_BASE}/api/v1/entries/${encodeURIComponent(entryName)}/versions/1.0.0`+ )+ if (afterDelete.status !== 404) {+ cleanupErrors.push(+ `registry cleanup postcondition failed: ${entryName} returned HTTP ${afterDelete.status}`+ )+ }+ }} catch (error) {cleanupErrors.push(`delete registry entry ${entryName}: ${String(error)}`)}diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex bed88c146..79497abcd 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -3219,8 +3219,9 @@ export type PluginWorkloadSdkGrant = {recipeName: stringcapabilityFamily: PluginWorkloadSdkFamily// Explicit provider bound to a promptBridge grant (R1). `null` for older- // grants written before the column existed (and for clientNotifications) —- // the form falls back to inferProviderFromModels when reading a null provider.+ // grants written before the column existed (and for clientNotifications).+ // Null promptBridge grants are legacy/unreviewed; the editor must require an+ // explicit operator resave and never infer a routable provider from models.provider: string | nullallowedModels: string[]allowedEventTypes: string[]diff --git a/control-ui/playwright.config.ts b/control-ui/playwright.config.tsindex d4b363dab..029ecbd7d 100644--- a/control-ui/playwright.config.ts+++ b/control-ui/playwright.config.ts@@ -4,8 +4,14 @@ import fs from 'node:fs'import path from 'node:path'function loadEnvFile(envPath: string) {- if (!fs.existsSync(envPath)) return false- const lines = fs.readFileSync(envPath, 'utf8').split('\n')+ let contents: string+ try {+ contents = fs.readFileSync(envPath, 'utf8')+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false+ throw error+ }+ const lines = contents.split('\n')for (const line of lines) {const trimmed = line.trim()if (!trimmed || trimmed.startsWith('#')) continue@@ -19,7 +25,7 @@ function loadEnvFile(envPath: string) {) {value = value.slice(1, -1)}- if (!process.env[key]) process.env[key] = value+ if (!(key in process.env)) process.env[key] = value}return true}@@ -28,14 +34,21 @@ function loadRootEnv() {const repoRoot = path.resolve(__dirname, '..')if (loadEnvFile(path.join(repoRoot, '.env'))) returnconst gitCommonDir = path.resolve(repoRoot, '.git')- if (!fs.existsSync(gitCommonDir)) return- if (!fs.statSync(gitCommonDir).isFile()) return- const gitFile = fs.readFileSync(gitCommonDir, 'utf8').trim()+ let gitFile: string+ try {+ gitFile = fs.readFileSync(gitCommonDir, 'utf8').trim()+ } catch (error) {+ if (+ (error as NodeJS.ErrnoException).code === 'ENOENT' ||+ (error as NodeJS.ErrnoException).code === 'EISDIR'+ )+ return+ throw error+ }const match = gitFile.match(/^gitdir:\s*(.+)$/)if (!match) returnconst worktreeGitDir = path.resolve(repoRoot, match[1])const commonDirPath = path.join(worktreeGitDir, 'commondir')- if (!fs.existsSync(commonDirPath)) returnconst commonDir = fs.readFileSync(commonDirPath, 'utf8').trim()const mainGitDir = path.resolve(worktreeGitDir, commonDir)loadEnvFile(path.join(mainGitDir, '..', '.env'))diff --git a/deploy/base/sandbox-recipes/rbac.yaml b/deploy/base/sandbox-recipes/rbac.yamlindex 2cc4ea7c0..a14073e6e 100644--- a/deploy/base/sandbox-recipes/rbac.yaml+++ b/deploy/base/sandbox-recipes/rbac.yaml@@ -112,6 +112,13 @@ rules:- apiGroups: [""]resources: ["services", "persistentvolumeclaims", "configmaps"]verbs: ["get", "list", "create", "update", "delete"]+ # Endpoint objects are created by the Service controller. WRC only reads+ # the recipe-scoped endpoint during SDK-host teardown to prove that the+ # headless Service has actually disappeared; it never creates or mutates+ # endpoint data.+ - apiGroups: [""]+ resources: ["endpoints"]+ verbs: ["get"]# Secrets — full lifecycle, plus list+watch for the envSecret optional-key# watcher (§4.1.1 in the recipe guide). The watcher diffs key-sets on# ADDED/MODIFIED/DELETED and fans reconciles out to recipes that referencediff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsvindex 3bc0610dd..63cfbda45 100644--- a/deploy/scripts/control-api-runtime-access-profiles.tsv+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv@@ -33,8 +33,10 @@ member_registration_credentials upsertnotification_deliveries legacy_dmloauth_grants legacy_dmlplugin_workload_sdk_credential_ticket_jtis legacy_dml+plugin_workload_sdk_invocation_attempts legacy_dmlplugin_workload_sdk_grants legacy_dmlplugin_workload_sdk_invocations legacy_dml+plugin_workload_sdk_provider_attempts legacy_dmlplugin_workload_sdk_quota_counters legacy_dmlprofiles legacy_dmlrate_limit_buckets legacy_dmldiff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex d78d2a0a9..ad1629d86 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.329",+ "version": "0.1.330","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.329",+ "version": "0.1.330","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex e25374665..e7643c29a 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.329",+ "version": "0.1.330","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/test/e2e-playwright/global-setup.ts b/desktop-app/test/e2e-playwright/global-setup.tsindex a31a0ae31..21cb98347 100644--- a/desktop-app/test/e2e-playwright/global-setup.ts+++ b/desktop-app/test/e2e-playwright/global-setup.ts@@ -1,14 +1,22 @@import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import path from 'node:path'import { E2E_TEST_EMAIL } from '../../../tests/e2e/testUser'+const configuredAllowedContexts = process.env.E2E_ALLOWED_CONTEXTS?.split(',')+ .map(context => context.trim())+ .filter(Boolean)const ALLOWED_CONTEXTS = new Set(- (process.env.E2E_ALLOWED_CONTEXTS || 'clerum-test,gke_${GCP_PROJECT}_us-central1-a_example-dev')- .split(',')- .map(context => context.trim())- .filter(Boolean)+ configuredAllowedContexts?.length ? configuredAllowedContexts : ['clerum-test'])-const DEV_CONTEXT = 'gke_${GCP_PROJECT}_us-central1-a_example-dev'-const PROD_CONTEXT = 'gke_${GCP_PROJECT}_us-central1-a_clerum'+const PROD_CONTEXT = process.env.E2E_PROD_CONTEXT?.trim() || ''++function isProductionContext(context: string): boolean {+ return (+ (PROD_CONTEXT !== '' && context === PROD_CONTEXT) ||+ /(^|[-_])(prod|production)([-_]|$)/i.test(context)+ )+}function isLocalhost(url: string): boolean {return /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(url)@@ -141,12 +149,6 @@ function kubectlCurrentContext(): string {}).trim()}-function kubectlUseContext(ctx: string): void {- execFileSync('kubectl', ['config', 'use-context', ctx], {- stdio: ['ignore', 'pipe', 'pipe'],- })-}-async function assertHealth(baseUrl: string, label: string, path = '/health'): Promise<void> {let response: Responsetry {@@ -163,11 +165,15 @@ async function assertHealth(baseUrl: string, label: string, path = '/health'): P}async function globalSetup(): Promise<void> {- const expected = process.env.E2E_K8S_CONTEXT || 'clerum-test'+ const expected =+ process.env.E2E_K8S_CONTEXT ||+ process.env.KUBECONTEXT ||+ process.env.K8S_CONTEXT ||+ 'clerum-test'- if (expected === PROD_CONTEXT) {+ if (isProductionContext(expected)) {throw new Error(- `[E2E-GUARD] Production context "${PROD_CONTEXT}" is hard-blocked. E2E against prod is never allowed.`+ `[E2E-GUARD] Production context "${expected}" is hard-blocked. E2E against prod is never allowed.`)}if (!isLocalPortForwardContext(expected) && !ALLOWED_CONTEXTS.has(expected)) {@@ -184,33 +190,83 @@ async function globalSetup(): Promise<void> {throw new Error(`[E2E-GUARD] Failed to read kubectl current-context: ${(err as Error).message}`)}- if (current === PROD_CONTEXT) {+ if (isProductionContext(current)) {throw new Error(- `[E2E-GUARD] kubectl current-context is production "${PROD_CONTEXT}". Refusing to run E2E.`+ `[E2E-GUARD] kubectl current-context is production "${current}". Refusing to run E2E.`)}if (current !== expected) {- // eslint-disable-next-line no-console- console.log(`[E2E-GUARD] Switching kubectl context "${current}" → "${expected}"`)- try {- kubectlUseContext(expected)- } catch (err) {- throw new Error(- `[E2E-GUARD] Failed to switch context to "${expected}": ${(err as Error).message}. ` +- `Is the context configured in ~/.kube/config?`- )- }+ throw new Error(+ `[E2E-GUARD] kubectl context mismatch: expected "${expected}", got "${current}". ` ++ 'Select the branch-owned context before starting the Desktop E2E; the test never changes global kubeconfig state.'+ )+ }++ const repoRoot = path.resolve(__dirname, '../../..')+ const expectedHead = execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim()+ const expectedWorktreeId = createHash('sha1').update(repoRoot).digest('hex')+ const marker = JSON.parse(+ execFileSync(+ 'kubectl',+ [+ '--context',+ expected,+ '-n',+ 'control-plane',+ 'get',+ 'configmap',+ 'clerum-pre-gate-sync-state',+ '-o',+ 'json',+ ],+ { encoding: 'utf8', timeout: 15_000 }+ )+ ) as { data?: Record<string, string> }+ const markerData = marker.data ?? {}+ if (!markerData.gitHead || !markerData.worktreeId || !markerData.clusterFingerprint) {+ throw new Error(+ `[E2E-GUARD] profile ${expected} has no complete pre-gate marker (gitHead/worktreeId/clusterFingerprint required).`+ )+ }+ if (markerData.gitHead !== expectedHead || markerData.worktreeId !== expectedWorktreeId) {+ throw new Error(+ `[E2E-GUARD] profile marker does not belong to this worktree/head: ` ++ `marker head=${markerData.gitHead} worktree=${markerData.worktreeId}, ` ++ `expected head=${expectedHead} worktree=${expectedWorktreeId}.`+ )+ }+ const expectedClusterFingerprint = process.env.E2E_EXPECTED_CLUSTER_FINGERPRINT?.trim()+ if (expectedClusterFingerprint && markerData.clusterFingerprint !== expectedClusterFingerprint) {+ throw new Error(+ `[E2E-GUARD] profile marker cluster fingerprint ${markerData.clusterFingerprint} does not match E2E_EXPECTED_CLUSTER_FINGERPRINT ${expectedClusterFingerprint}.`+ )}- const controlApi = process.env.CONTROL_API_BASE_URL || 'http://127.0.0.1:8090'+ const controlApi =+ process.env.CONTROL_API_BASE_URL ||+ process.env.CONTROL_API_URL ||+ process.env.E2E_CONTROL_API_URL ||+ 'http://127.0.0.1:8090'const controlUi =process.env.CONTROL_UI_BASE_URL || process.env.CONTROL_UI_URL || 'http://127.0.0.1:3000'- const externalRest = process.env.EXTERNAL_REST_API_BASE_URL || 'http://127.0.0.1:8091'- const rpcProxy = process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094'+ const externalRest =+ process.env.EXTERNAL_REST_API_BASE_URL ||+ process.env.EXTERNAL_REST_API_URL ||+ process.env.E2E_EXTERNAL_REST_API_URL ||+ 'http://127.0.0.1:8091'+ const rpcProxy =+ process.env.RPC_PROXY_BASE_URL ||+ process.env.RPC_PROXY_URL ||+ process.env.E2E_RPC_PROXY_URL ||+ 'http://127.0.0.1:8094'const workflowApprovalReader =process.env.E2E_WORKFLOW_APPROVAL_QUADRANTS === '1'- ? process.env.WORKFLOW_APPROVAL_READER_BASE_URL || 'http://127.0.0.1:8098'+ ? process.env.WORKFLOW_APPROVAL_READER_BASE_URL ||+ process.env.WORKFLOW_APPROVAL_READER_URL ||+ 'http://127.0.0.1:8098': undefinedconst allowDevPortForward = parseBooleanEnv(process.env.E2E_ALLOW_DEV_PORT_FORWARD)diff --git a/desktop-app/test/e2e-playwright/playwright.config.ts b/desktop-app/test/e2e-playwright/playwright.config.tsindex 8be64574b..d5652c4d1 100644--- a/desktop-app/test/e2e-playwright/playwright.config.ts+++ b/desktop-app/test/e2e-playwright/playwright.config.ts@@ -29,7 +29,9 @@ function loadEnvContents(contents: string): void {) {value = value.slice(1, -1)}- if (!process.env[key]) process.env[key] = value+ // Presence, not truthiness: an explicit empty process value is still an+ // operator decision and must not be replaced by a lane default.+ if (!(key in process.env)) process.env[key] = value}}@@ -50,40 +52,49 @@ function loadCanonicalRootEnv(): void {// This matters when Playwright is launched directly from a secondary// worktree: the canonical .env lives in the primary Evenfire checkout.const repoRoot = path.resolve(__dirname, '../../..')- const localEnv = path.join(repoRoot, '.env')- const localEnvContents = readOptionalFile(localEnv)- if (localEnvContents !== null) {- loadEnvContents(localEnvContents)- return- }-const gitFile = path.join(repoRoot, '.git')let gitFileContents: stringtry {gitFileContents = fs.readFileSync(gitFile, 'utf8')} catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ loadEnvFile(path.join(repoRoot, '.env'))+ return+ }// A normal checkout has a file-form worktree pointer here. If `.git` is a// directory (for example in a non-worktree checkout), there is no safe// common-dir traversal to perform from this config file.- if ((error as NodeJS.ErrnoException).code === 'EISDIR') return+ if ((error as NodeJS.ErrnoException).code === 'EISDIR') {+ loadEnvFile(path.join(repoRoot, '.env'))+ return+ }throw error}const gitdirMatch = gitFileContents.trim().match(/^gitdir:\s*(.+)$/)- if (!gitdirMatch) return+ if (!gitdirMatch) {+ loadEnvFile(path.join(repoRoot, '.env'))+ return+ }const worktreeGitDir = path.resolve(repoRoot, gitdirMatch[1])const commonDirFile = path.join(worktreeGitDir, 'commondir')const commonDirValue = readOptionalFile(commonDirFile)- if (commonDirValue === null) return+ if (commonDirValue === null) {+ loadEnvFile(path.join(repoRoot, '.env'))+ return+ }const commonDir = path.resolve(worktreeGitDir, commonDirValue.trim())+ // For a linked worktree, the canonical root is the parent of Git's common+ // directory (the primary checkout), not the secondary worktree containing+ // this config. This keeps seeded credentials and endpoint policy aligned+ // with the operator lane.loadEnvFile(path.join(commonDir, '..', '.env'))}loadCanonicalRootEnv()-// A lane-specific file may supply values missing from the canonical root env,-// but never overrides an explicit shell value or a value already loaded from-// the root. It is optional; the root .env remains the primary contract.-loadEnvFile(path.resolve(__dirname, '../../../.env.e2e'))+// The Desktop lane-specific file is optional and only fills values missing+// from the canonical root env. Do not read a second root-level `.env.e2e`: that+// file belongs to another lane and previously masked desktop-app/.env.e2e.+loadEnvFile(path.resolve(__dirname, '../../.env.e2e'))export default defineConfig({testDir: '.',diff --git a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.tsindex fcb8ea963..e7ed8b1cc 100644--- a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts@@ -379,24 +379,38 @@ async function activateEmbedded(async function selectEmbeddedRecipient(app: ElectronApplication,webContentsId: number,- selector: string+ selector: string,+ expectedEmail: string): Promise<EmbeddedOption> {const options = await embeddedOptions(app, webContentsId, selector)- const recipient = options.find(option => option.value && /@/.test(option.label))+ const normalizedExpectedEmail = expectedEmail.trim().toLowerCase()+ const recipient = options.find(+ option => option.value && option.label.trim().toLowerCase() === normalizedExpectedEmail+ )if (!recipient) {- throw new Error(`Embedded recipient picker ${selector} has no visible email option.`)+ throw new Error(+ `Embedded recipient picker ${selector} has no option for authenticated user ${expectedEmail}.`+ )+ }+ const recipientIndex = options.findIndex(option => option.value === recipient.value)+ if (recipientIndex < 0) {+ throw new Error(`Embedded recipient picker ${selector} lost the authenticated-user option.`)}// This is the native select path a user takes: focus the control, move from- // the placeholder to the first granted recipient, and commit with Enter.+ // the first option to the authenticated user's granted recipient, and commit+ // with Enter. The option order is not part of the contract, so the number of+ // ArrowDown events is derived from the live option list rather than assumed.// We inspect the option label only to verify the UI displays a human handle;// the value is never injected into the DOM or sent directly to the backend.await focusEmbeddedControl(app, webContentsId, selector)await sendEmbeddedKey(app, webContentsId, 'Home')- await sendEmbeddedKey(app, webContentsId, 'ArrowDown')+ for (let index = 0; index < recipientIndex; index += 1) {+ await sendEmbeddedKey(app, webContentsId, 'ArrowDown')+ }await sendEmbeddedKey(app, webContentsId, 'Enter')await expect.poll(() => embeddedValue(app, webContentsId, selector)).toBe(recipient.value)- expect(recipient.label).toContain('@')+ expect(recipient.label.trim().toLowerCase()).toBe(normalizedExpectedEmail)expect(recipient.label).not.toMatch(/^[0-9a-f-]{36}$/i)return recipient}@@ -448,10 +462,11 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the reallet app: ElectronApplication | undefinedlet page: Page | undefinedtry {+ const credentials = desktopCredentials()const launched = await launchDesktopApp(testInfo)app = launched.apppage = launched.page- await login(page, desktopCredentials())+ await login(page, credentials)await page.getByTestId('nav-sandbox-ui').click()await expect(page.getByRole('heading', { name: 'Apps', exact: true })).toBeVisible()@@ -544,7 +559,7 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real// visible grant-backed choice before continuing; the missing-field guard// below still proves the form rejects an incomplete notification without// creating an SDK invocation.- await selectEmbeddedRecipient(app, webContentsId, '#userRef')+ await selectEmbeddedRecipient(app, webContentsId, '#userRef', credentials.email)await typeEmbedded(app, webContentsId, '#title', `Evenfire E2E ${marker}`)await test.step('reject a notification missing its body before the SDK call', async () => {const before = sdkInvocationCount('clientNotifications')diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.tsindex f24d0cd9c..02dd2c575 100644--- a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts@@ -25,8 +25,15 @@ import path from 'node:path'export const DESKTOP_APP_ROOT = path.resolve(__dirname, '../..')export const MAIN_ENTRY = path.join(DESKTOP_APP_ROOT, 'dist/main.js')export const EXTERNAL_REST_API_BASE_URL =- process.env.EXTERNAL_REST_API_BASE_URL || 'http://127.0.0.1:8091'-export const RPC_PROXY_BASE_URL = process.env.RPC_PROXY_BASE_URL || 'http://127.0.0.1:8094'+ process.env.EXTERNAL_REST_API_BASE_URL ||+ process.env.EXTERNAL_REST_API_URL ||+ process.env.E2E_EXTERNAL_REST_API_URL ||+ 'http://127.0.0.1:8091'+export const RPC_PROXY_BASE_URL =+ process.env.RPC_PROXY_BASE_URL ||+ process.env.RPC_PROXY_URL ||+ process.env.E2E_RPC_PROXY_URL ||+ 'http://127.0.0.1:8094'const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])const DEFAULT_DESKTOP_EMAIL = '[email protected]'const DEFAULT_DESKTOP_PASSWORD = 'changeme123!'diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.mdindex 80e6443d8..69ff13db5 100644--- a/docs/crds/workflowrecipe.md+++ b/docs/crds/workflowrecipe.md@@ -1023,7 +1023,7 @@ spec:**What gets rejected**-- **CEL R1** — `agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge`. An agent remains invalid for an ordinary workloads-only recipe, but a stepless `promptBridge` recipe uses `spec.agent` as the eager mcp-host bootstrap binding rather than as a workflow agent.+- **CEL R1** — `agent requires non-empty workflow steps or spec.pluginWorkloadSdk.promptBridge`. An agent remains invalid for an ordinary workloads-only recipe, but a stepless `promptBridge` recipe uses `spec.agent` as the eager mcp-host bootstrap binding rather than as a workflow agent.- A `provider` outside the four-value enum.- An `instruction` step with no resolvable agent: _"step requires an agent configuration"_.@@ -1332,7 +1332,7 @@ spec:Opts plugin workloads into two **controlled side-effect channels**:-- **`promptBridge`** — a one-shot LLM call routed through the recipe's `mcp-host`. A request may select a model within `allowedModels` but never the provider: the provider bound to the recipe's `mcp-host` wins.+- **`promptBridge`** — a one-shot LLM call routed through the recipe's `mcp-host`. `spec.agent` supplies the host bootstrap identity; the operator's Control UI grant is the only authority for ordered `{provider, model, credentialSlot}` targets, default selection, and authorized fallback.- **`clientNotifications`** — notification _intent_ authorized by control-api and delivered by the Notification Service. Targets are opaque refs, never raw channel addresses.Declaring this block forces an always-on `mcp-host`. Runtime enforcement is additionally gated by the `PLUGIN_WORKLOAD_SDK_ENABLED` flag.@@ -1360,7 +1360,7 @@ Declaring this block forces an always-on `mcp-host`. Runtime enforcement is addi- **CEL PS1** — at least one of `promptBridge` / `clientNotifications`.- **CEL PS2 / PS3** — no wildcards in `allowedEventTypes` or `allowedModels`. Only explicit admin grants (control-api) may use wildcards.- **PS4** (reconciler) — `allowedCallers` entries must reference existing `workloads[].id`.-- `promptBridge` needs a resolvable agent. A stepless SDK recipe may provide the complete provider/model binding in `spec.agent`; it is not a workflow and creates no coordinator, run, step graph, or workflow output PVC. A `clientNotifications`-only recipe needs no agent.+- `promptBridge` needs a resolvable provider/model binding. A stepless SDK recipe provides it in `spec.agent`; it is not a workflow and creates no coordinator, run, step graph, or workflow output PVC. Runtime provider selection remains grant-authorized and per-attempt. A `clientNotifications`-only recipe needs no agent.- A stepless SDK recipe must not declare `triggers`, `scheduling`, or `coordinatorImage`; these are workflow-only fields and fail closed at admission and in WRC defence in depth.### 3.20 Global File System (`spec.gfs`)diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex acd624289..d9881a75c 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 576ac3fa7..97668f9f5 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.220",+ "version": "0.1.221","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts b/mcp-host/src/__tests__/workflow/workflowRouter.test.tsindex 71557d332..2e4c0ab7b 100644--- a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts+++ b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts@@ -84,10 +84,17 @@ async function createTestApp(const service = {executeStep: vi.fn().mockResolvedValue({ stepId: 's1', status: 'completed' }),configure: vi.fn().mockReturnValue({ configured: true }),- configurePluginWorkloadSdkBootstrap: vi.fn().mockReturnValue({+ configurePluginWorkloadSdkBootstrap: vi.fn().mockResolvedValue({configured: true,+ ready: true,provider: 'openai',model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-openai',+ defaultProvider: 'openai',+ defaultModel: 'gpt-5.4-mini',}),getStatus: vi.fn().mockReturnValue({ ready: true, configured: true }),...serviceOverride,@@ -366,10 +373,17 @@ describe('workflowRouter — JWT auth middleware', () => {it('POST /plugin-workload-sdk/bootstrap accepts only public identity and forwards no credential', async () => {const token = await signWorkflowToken({ sub: 'wrc', scopes: ['configure'] })- const bootstrap = vi.fn().mockReturnValue({+ const bootstrap = vi.fn().mockResolvedValue({configured: true,+ ready: true,provider: 'openai',model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-openai',+ defaultProvider: 'openai',+ defaultModel: 'gpt-5.4-mini',})const { baseUrl, server } = await createTestApp(publicKeyPem, true, {configurePluginWorkloadSdkBootstrap: bootstrap,diff --git a/mcp-host/src/budget/types.ts b/mcp-host/src/budget/types.tsindex 8ef476695..43864ae4e 100644--- a/mcp-host/src/budget/types.ts+++ b/mcp-host/src/budget/types.ts@@ -8,7 +8,13 @@*//** Source dimension reported to control-api. Same union as `UsageContext.source_kind`. */-export type BudgetSourceKind = 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown'+export type BudgetSourceKind =+ | 'channel'+ | 'desktop'+ | 'workflow'+ | 'cron'+ | 'unknown'+ | 'plugin_workload_sdk'/*** Request body for `POST /api/v1/internal/budgets/check`. Identity fields thatdiff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.tsindex d83beee36..1850a31c1 100644--- a/mcp-host/src/core/types.ts+++ b/mcp-host/src/core/types.ts@@ -92,7 +92,7 @@ export interface TokenUsage {* vary per task (source_kind, user_id, etc.) come from the call site.*/export interface UsageContext {- source_kind: 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown'+ source_kind: 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown' | 'plugin_workload_sdk'/** Immutable ingress trace identity. It is carried to usage ingestion, not treated as DB authority. */traceContext?: TraceContextV1 | nullteam_id?: string | nulldiff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 91a116e1c..f38e2a152 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2901,6 +2901,14 @@ async function main(): Promise<void> {onPluginWorkloadSdkBootstrapConfigured: context => {pluginSdkLlmContext = context},+ verifyPluginWorkloadSdkBootstrapV2: async (provider, model) => {+ if (!pluginWorkloadSdkServer) return null+ try {+ return await pluginWorkloadSdkServer.verifyPromptBridgeBootstrapV2(provider, model)+ } catch {+ return null+ }+ },})rpcServer.setWorkflowService(workflowService)wireWorkflowApprovalRuntimeRoutes(rpcServer, {diff --git a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts b/mcp-host/src/pluginWorkloadSdk/domain/errors.tsindex acb2453b8..38b390b9f 100644--- a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts+++ b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts@@ -21,6 +21,7 @@ export const PLUGIN_WORKLOAD_ERROR_CODES = ['idempotency_conflict','invalid_request','unauthorized',+ 'protocol_mismatch',] as constexport type PluginWorkloadErrorCode = (typeof PLUGIN_WORKLOAD_ERROR_CODES)[number]@@ -51,6 +52,7 @@ const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {idempotency_conflict: 422,invalid_request: 400,unauthorized: 401,+ protocol_mismatch: 503,}const ERROR_CODE_SET = new Set<string>(PLUGIN_WORKLOAD_ERROR_CODES)diff --git a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts b/mcp-host/src/pluginWorkloadSdk/metrics.test.tsindex ec2cd08f6..c12e1c0ae 100644--- a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/metrics.test.ts@@ -25,7 +25,9 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {credentialSlot: 'zai-api-key',}const controlApiClient = {+ ensurePromptBridgeCapabilities: vi.fn().mockResolvedValue(undefined),authorizePromptBridge: vi.fn().mockResolvedValue({+ contractVersion: 2,invocationId: 'inv-1',replay: false,providerCallRequired: true,@@ -34,10 +36,12 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {modelPolicy: null,selectedTarget: target,authorizedTargets: [target],+ attemptGeneration: 1,policyRevision: 1,policyHash: 'a'.repeat(64),maxOutputTokens: null,}),+ reportProviderAttemptStatus: vi.fn().mockResolvedValue(undefined),reportInvocationStatus: vi.fn().mockResolvedValue(undefined),} as unknown as PluginWorkloadSdkControlApiClientconst llmBridge = {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.tsindex 6567845a1..82e1c3b07 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts@@ -20,6 +20,7 @@ const target = {function authorizedBody(invocationId: string) {return {+ contractVersion: 2,invocationId,replay: false,providerCallRequired: true,@@ -28,6 +29,7 @@ function authorizedBody(invocationId: string) {modelPolicy: null,selectedTarget: target,authorizedTargets: [target],+ attemptGeneration: 1,policyRevision: 2,policyHash: 'a'.repeat(64),maxOutputTokens: null,@@ -59,7 +61,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {const result = await client.authorizePromptBridge(promptBody)expect(result.invocationId).toBe('inv-1')const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]- expect(url).toBe('http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge')+ expect(url).toBe('http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/v2')expect((init.headers as Record<string, string>).Authorization).toBe('Bearer jwt-access')})@@ -77,6 +79,65 @@ describe('PluginWorkloadSdkControlApiClient', () => {expect(fetchImpl).toHaveBeenCalledTimes(1) // 4xx is not retried})+ it('accepts identity-only bootstrap before an operator grant exists', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ jsonResponse(200, {+ contractVersion: 2,+ supportedContractVersions: [1, 2],+ targetAwarePromptBridge: true,+ attemptLedger: true,+ credentialTickets: true,+ policyState: 'missing',+ policyRevision: 0,+ policyHash: null,+ defaultTargetRef: null,+ defaultProvider: null,+ defaultModel: null,+ v2Ready: false,+ })+ )+ const client = makeClient(fetchImpl as unknown as typeof fetch)++ await expect(client.verifyPromptBridgeBootstrapV2('openai', 'gpt-5.4-mini')).resolves.toEqual({+ ready: true,+ contractVersion: 2,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ })+ expect(fetchImpl).toHaveBeenCalledWith(+ 'http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/capabilities',+ expect.objectContaining({ method: 'GET' })+ )+ })++ it('keeps request-time policy readiness separate from identity bootstrap', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ jsonResponse(200, {+ contractVersion: 2,+ supportedContractVersions: [1, 2],+ targetAwarePromptBridge: true,+ attemptLedger: true,+ credentialTickets: true,+ policyState: 'missing',+ policyRevision: 0,+ policyHash: null,+ defaultTargetRef: null,+ defaultProvider: null,+ defaultModel: null,+ v2Ready: false,+ })+ )+ const client = makeClient(fetchImpl as unknown as typeof fetch)++ await expect(client.ensurePromptBridgeCapabilities()).rejects.toMatchObject({+ code: 'provider_policy_denied',+ retryable: false,+ })+ })+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)@@ -117,6 +178,9 @@ describe('PluginWorkloadSdkControlApiClient', () => {const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, {invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'attempt-1',+ providerAttemptIndex: 1,targetRef: target.targetRef,credentialTicket: 'fresh-signed-ticket',policyRevision: 2,@@ -131,6 +195,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {recipeNamespace: 'sandbox-recipes',recipeName: 'r1',invocationId: 'inv-1',+ attemptGeneration: 1,target,policyRevision: 2,policyHash: 'a'.repeat(64),@@ -146,6 +211,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {recipeName: 'r1',invocationId: 'inv-1',targetRef: target.targetRef,+ attemptGeneration: 1,})})@@ -153,6 +219,9 @@ describe('PluginWorkloadSdkControlApiClient', () => {const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, {invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'attempt-1',+ providerAttemptIndex: 1,targetRef: 'different-target',credentialTicket: 'fresh-signed-ticket',policyRevision: 2,@@ -166,6 +235,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {recipeNamespace: 'sandbox-recipes',recipeName: 'r1',invocationId: 'inv-1',+ attemptGeneration: 1,target,policyRevision: 2,policyHash: 'a'.repeat(64),@@ -294,12 +364,12 @@ describe('PluginWorkloadSdkControlApiClient', () => {})})- it('reportInvocationStatus never throws (best-effort)', async () => {+ it('reportInvocationStatus surfaces a rejected terminal acknowledgement', async () => {const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(500, {}))const client = makeClient(fetchImpl as unknown as typeof fetch)await expect(- client.reportInvocationStatus('inv-1', 'sandbox-recipes', 'r1', 'complete')- ).resolves.toBeUndefined()+ client.reportInvocationStatus('inv-1', 'sandbox-recipes', 'r1', 'complete', 1)+ ).rejects.toMatchObject({ code: 'provider_unavailable', retryable: true })})it('submitClientNotification maps event_type_not_allowed', async () => {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.tsindex 38142a123..1e940f1e5 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts@@ -38,6 +38,7 @@ export interface ControlApiClientOptions {}export interface AuthorizePromptBridgeResponse {+ contractVersion: 2invocationId: stringreplay: booleanproviderCallRequired: boolean@@ -46,13 +47,60 @@ export interface AuthorizePromptBridgeResponse {modelPolicy: { provider: string; model: string; temperature?: number; maxCostUsd?: number } | nullselectedTarget: PromptBridgeTargetauthorizedTargets: PromptBridgeTarget[]+ attemptGeneration: numberpolicyRevision: numberpolicyHash: stringmaxOutputTokens: number | null}+export interface PluginWorkloadSdkCapabilities {+ contractVersion: 2+ supportedContractVersions: number[]+ targetAwarePromptBridge: true+ attemptLedger: true+ credentialTickets: true+ policyState: string+ policyRevision: number+ policyHash: string | null+ defaultTargetRef: string | null+ defaultProvider: string | null+ defaultModel: string | null+ v2Ready: boolean+}++export interface PluginWorkloadSdkBootstrapProof {+ ready: true+ contractVersion: 2+ provider: string+ model: string+ policyReady: boolean+ policyState: string+ policyReason?:+ | 'grant_missing'+ | 'policy_unreviewed'+ | 'policy_revoking'+ | 'policy_disabled'+ | 'bootstrap_target_mismatch'+ | 'policy_not_ready'+ /**+ * Policy metadata is deliberately optional at identity bootstrap. A recipe+ * may be installed and publish an awaiting-policy SDK runtime before an+ * operator creates its promptBridge grant. The grant is still required for+ * every request and is checked by the authorization endpoint against this+ * binding.+ */+ policyRevision?: number+ policyHash?: string+ defaultTargetRef?: string+ defaultProvider?: string+ defaultModel?: string+}+export interface ReissuedPromptBridgeCredentialTicket {invocationId: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbertargetRef: stringcredentialTicket: stringpolicyRevision: number@@ -83,6 +131,7 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridgeif (typeof v !== 'object' || v === null) return falseconst r = v as Record<string, unknown>return (+ r.contractVersion === 2 &&typeof r.invocationId === 'string' &&typeof r.replay === 'boolean' &&(r.providerCallRequired === undefined || typeof r.providerCallRequired === 'boolean') &&@@ -97,6 +146,8 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridgeArray.isArray(r.authorizedTargets) &&r.authorizedTargets.length > 0 &&r.authorizedTargets.every(isPromptBridgeTarget) &&+ Number.isInteger(r.attemptGeneration) &&+ (r.attemptGeneration as number) >= 1 &&Number.isInteger(r.policyRevision) &&(r.policyRevision as number) >= 1 &&typeof r.policyHash === 'string' &&@@ -105,6 +156,27 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridge)}+function isPluginWorkloadSdkCapabilities(v: unknown): v is PluginWorkloadSdkCapabilities {+ if (typeof v !== 'object' || v === null) return false+ const value = v as Record<string, unknown>+ return (+ value.contractVersion === 2 &&+ Array.isArray(value.supportedContractVersions) &&+ value.supportedContractVersions.includes(2) &&+ value.targetAwarePromptBridge === true &&+ value.attemptLedger === true &&+ value.credentialTickets === true &&+ typeof value.policyState === 'string' &&+ Number.isInteger(value.policyRevision) &&+ Number(value.policyRevision) >= 0 &&+ (value.policyHash === null || typeof value.policyHash === 'string') &&+ (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'+ )+}+function isReissuedPromptBridgeCredentialTicket(value: unknown): value is ReissuedPromptBridgeCredentialTicket {@@ -112,6 +184,12 @@ function isReissuedPromptBridgeCredentialTicket(const ticket = value as Record<string, unknown>return (typeof ticket.invocationId === 'string' &&+ Number.isInteger(ticket.attemptGeneration) &&+ (ticket.attemptGeneration as number) >= 1 &&+ typeof ticket.providerAttemptId === 'string' &&+ ticket.providerAttemptId.length > 0 &&+ Number.isInteger(ticket.providerAttemptIndex) &&+ (ticket.providerAttemptIndex as number) >= 1 &&typeof ticket.targetRef === 'string' &&typeof ticket.credentialTicket === 'string' &&ticket.credentialTicket.length > 0 &&@@ -168,6 +246,7 @@ function isListClientNotificationRecipientsResponse(export class PluginWorkloadSdkControlApiClient {private readonly breaker: CircuitBreakerprivate refreshInFlight: Promise<void> | null = null+ private capabilitiesInFlight: Promise<PluginWorkloadSdkCapabilities> | null = nullconstructor(private readonly opts: ControlApiClientOptions) {this.breaker = opts.breaker ?? new CircuitBreaker()@@ -274,6 +353,14 @@ export class PluginWorkloadSdkControlApiClient {return response.json()}+ if (response.status === 404 && path.endsWith('/prompt-bridge/v2')) {+ throw new PluginWorkloadError(+ 'protocol_mismatch',+ 'control-api does not expose the promptBridge v2 contract; rollout must upgrade control-api before mcp-host',+ true+ )+ }+// Non-retryable 4xx: map the structured code without leaking the body.const errorBody = (await response.json().catch(() => ({}))) as {error?: unknown@@ -307,6 +394,187 @@ export class PluginWorkloadSdkControlApiClient {)}+ private async getOnce(path: string): Promise<unknown> {+ if (!this.breaker.allow()) {+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'control-api gateway circuit breaker is open',+ true+ )+ }+ const fetchImpl = this.opts.fetchImpl ?? fetch+ let response: Response+ try {+ response = await fetchImpl(`${this.opts.baseUrl.replace(/\/+$/, '')}${path}`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${this.opts.getAccessToken()}` },+ })+ } catch {+ this.breaker.record(false)+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'control-api capability probe failed',+ true+ )+ }+ if (response.status === 404 || response.status === 405) {+ this.breaker.record(true)+ throw new PluginWorkloadError(+ 'protocol_mismatch',+ 'control-api does not advertise the promptBridge v2 contract; upgrade control-api before mcp-host',+ true+ )+ }+ if (response.status >= 500) {+ this.breaker.record(false)+ throw new PluginWorkloadError(+ 'provider_unavailable',+ `control-api capability probe responded ${response.status}`,+ true+ )+ }+ this.breaker.record(true)+ if (response.ok) return response.json()+ if (response.status === 401) {+ throw new PluginWorkloadError('unauthorized', 'gateway rejected mcp-host credentials')+ }+ throw new PluginWorkloadError(+ 'protocol_mismatch',+ 'control-api capability contract was rejected',+ true+ )+ }++ private async get(path: string): Promise<unknown> {+ try {+ return await this.getOnce(path)+ } catch (err) {+ if (+ err instanceof PluginWorkloadError &&+ err.code === 'unauthorized' &&+ this.opts.refreshOnUnauthorized+ ) {+ await this.triggerRefresh()+ return this.getOnce(path)+ }+ throw err+ }+ }++ /** Fetch the capabilities contract, coalescing only concurrent probes. */+ async getPromptBridgeCapabilities(): Promise<PluginWorkloadSdkCapabilities> {+ if (this.capabilitiesInFlight) return this.capabilitiesInFlight+ const request = this.get('/api/v1/mcp-host/plugin-workload-sdk/capabilities')+ .then(result => {+ if (!isPluginWorkloadSdkCapabilities(result)) {+ throw new PluginWorkloadError(+ 'protocol_mismatch',+ 'control-api capability response is not the promptBridge v2 contract',+ true+ )+ }+ return result+ })+ .finally(() => {+ if (this.capabilitiesInFlight === request) this.capabilitiesInFlight = null+ })+ this.capabilitiesInFlight = request+ return request+ }++ /**+ * Negotiates the target-aware/JIT wire contract before a prompt. There is no+ * v1 fallback: an SDK host must not send multiprovider traffic to an API that+ * cannot fence attempts or tickets.+ */+ async ensurePromptBridgeCapabilities(): Promise<void> {+ const capabilities = await this.getPromptBridgeCapabilities()+ if (!capabilities.v2Ready) {+ throw new PluginWorkloadError(+ 'provider_policy_denied',+ 'control-api promptBridge policy is not ready; an active operator grant is required',+ false+ )+ }+ }++ /**+ * Fresh two-phase bootstrap proof. The completed response is never cached;+ * only an in-flight request may be shared. This always proves that+ * control-api and mcp-host speak the v2 SDK contract. `policyReady` is a+ * separate live signal: a missing or unreviewed grant is a legitimate+ * awaiting-policy state, not a provider outage. Policy/default/target+ * coherence is enforced again when the workload authorizes its first prompt.+ */+ async verifyPromptBridgeBootstrapV2(+ expectedProvider: string,+ expectedModel: string+ ): Promise<PluginWorkloadSdkBootstrapProof> {+ const capabilities = await this.getPromptBridgeCapabilities()+ if (+ capabilities.contractVersion !== 2 ||+ !capabilities.supportedContractVersions.includes(2) ||+ capabilities.targetAwarePromptBridge !== true ||+ capabilities.attemptLedger !== true ||+ capabilities.credentialTickets !== true ||+ typeof expectedProvider !== 'string' ||+ expectedProvider.length === 0 ||+ typeof expectedModel !== 'string' ||+ expectedModel.length === 0+ ) {+ throw new PluginWorkloadError(+ 'protocol_mismatch',+ 'control-api promptBridge identity bootstrap contract is not ready',+ true+ )+ }+ const policyReady =+ capabilities.v2Ready &&+ capabilities.policyRevision >= 1 &&+ !!capabilities.policyHash &&+ /^[a-f0-9]{64}$/.test(capabilities.policyHash) &&+ !!capabilities.defaultTargetRef &&+ capabilities.defaultProvider === expectedProvider &&+ capabilities.defaultModel === expectedModel+ const policyReason = policyReady+ ? undefined+ : capabilities.policyState === 'missing'+ ? 'grant_missing'+ : capabilities.policyState === 'legacy_unreviewed'+ ? 'policy_unreviewed'+ : capabilities.policyState === 'revoking'+ ? 'policy_revoking'+ : capabilities.policyState === 'disabled'+ ? 'policy_disabled'+ : capabilities.v2Ready+ ? 'bootstrap_target_mismatch'+ : 'policy_not_ready'+ return {+ ready: true,+ contractVersion: 2,+ provider: expectedProvider,+ model: expectedModel,+ policyReady,+ policyState: capabilities.policyState,+ ...(policyReason ? { policyReason } : {}),+ ...(capabilities.v2Ready &&+ capabilities.policyRevision >= 1 &&+ capabilities.policyHash &&+ /^[a-f0-9]{64}$/.test(capabilities.policyHash) &&+ capabilities.defaultTargetRef &&+ capabilities.defaultProvider &&+ capabilities.defaultModel+ ? {+ policyRevision: capabilities.policyRevision,+ policyHash: capabilities.policyHash,+ defaultTargetRef: capabilities.defaultTargetRef,+ defaultProvider: capabilities.defaultProvider,+ defaultModel: capabilities.defaultModel,+ }+ : {}),+ }+ }+async authorizePromptBridge(body: {recipeNamespace: stringrecipeName: string@@ -323,7 +591,10 @@ export class PluginWorkloadSdkControlApiClient {metadata?: Record<string, unknown>correlationId?: string}): Promise<AuthorizePromptBridgeResponse> {- const result = await this.post('/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge', body)+ const result = await this.post('/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/v2', {+ contractVersion: 2,+ ...body,+ })if (!isAuthorizePromptBridgeResponse(result)) {throw new PluginWorkloadError('provider_unavailable',@@ -331,11 +602,9 @@ export class PluginWorkloadSdkControlApiClient {true)}- // N/N-1 compatibility: control-api versions predating the explicit- // provider-call disposition omitted this field. Their idempotency contract- // already made non-replay responses executable and replay responses- // non-executable, so derive the same fail-closed decision while rejecting- // any malformed non-boolean value.+ // The v2 response is strict. Only the provider-call disposition remains+ // additive for a short server-first rollout window; absence is derived from+ // the already persisted idempotency contract and never enables credentials.return {...result,providerCallRequired:@@ -355,6 +624,7 @@ export class PluginWorkloadSdkControlApiClient {recipeNamespace: stringrecipeName: stringinvocationId: string+ attemptGeneration: numbertarget: PromptBridgeTargetpolicyRevision: numberpolicyHash: string@@ -366,6 +636,7 @@ export class PluginWorkloadSdkControlApiClient {recipeName: body.recipeName,invocationId: body.invocationId,targetRef: body.target.targetRef,+ attemptGeneration: body.attemptGeneration,})if (!isReissuedPromptBridgeCredentialTicket(result)) {@@ -377,6 +648,9 @@ export class PluginWorkloadSdkControlApiClient {}if (result.invocationId !== body.invocationId ||+ result.attemptGeneration !== body.attemptGeneration ||+ result.providerAttemptId.length === 0 ||+ result.providerAttemptIndex < 1 ||result.targetRef !== body.target.targetRef ||result.policyRevision !== body.policyRevision ||result.policyHash !== body.policyHash@@ -390,28 +664,37 @@ export class PluginWorkloadSdkControlApiClient {return result}+ async reportProviderAttemptStatus(body: {+ invocationId: string+ recipeNamespace: string+ recipeName: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: number+ status: 'complete' | 'failed' | 'provider_unavailable'+ }): Promise<void> {+ await this.post(+ `/api/v1/mcp-host/plugin-workload-sdk/provider-attempts/${encodeURIComponent(+ body.providerAttemptId+ )}/status`,+ body+ )+ }+async reportInvocationStatus(invocationId: string,recipeNamespace: string,recipeName: string,- status: 'complete' | 'failed' | 'provider_unavailable'+ status: 'complete' | 'failed' | 'provider_unavailable',+ attemptGeneration: number): Promise<void> {- // Status reporting is best-effort: a failure to report must never mask- // the actual promptBridge outcome for the workload.- try {- await this.post(- `/api/v1/mcp-host/plugin-workload-sdk/invocations/${encodeURIComponent(invocationId)}/status`,- { recipeNamespace, recipeName, status }- )- } catch (err) {- // Best-effort: log structured via src/logger.ts ([Component] prefix →- // JSON). Fold the error into the message so it is not lost.- console.warn(- `[PluginWorkloadSdk] failed to report invocation ${invocationId} status=${status}: ${- err instanceof Error ? err.message : String(err)- }`- )- }+ // A completion is not safe to return until control-api has accepted the+ // generation-fenced terminal transition. Swallowing this error would let+ // the caller observe a result whose audit/usage lease is still active.+ await this.post(+ `/api/v1/mcp-host/plugin-workload-sdk/invocations/${encodeURIComponent(invocationId)}/status`,+ { recipeNamespace, recipeName, status, attemptGeneration }+ )}async submitClientNotification(body: {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.tsindex 6bd48d030..67ba5819d 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.ts@@ -37,6 +37,7 @@ describe('PluginWorkloadSdkCredentialBrokerClient', () => {const result = await client.resolve({invocationId: 'inv-1',+ attemptGeneration: 1,target,credentialTicket: 'signed-ticket',})@@ -48,6 +49,7 @@ describe('PluginWorkloadSdkCredentialBrokerClient', () => {expect(JSON.parse(String(init.body))).toEqual({recipeNamespace: 'sandbox-recipes',invocationId: 'inv-1',+ attemptGeneration: 1,target,credentialTicket: 'signed-ticket',})@@ -65,7 +67,12 @@ describe('PluginWorkloadSdkCredentialBrokerClient', () => {fetchImpl: fetchImpl as unknown as typeof fetch,})const error = await client- .resolve({ invocationId: 'inv-1', target, credentialTicket: 'signed-ticket' })+ .resolve({+ invocationId: 'inv-1',+ attemptGeneration: 1,+ target,+ credentialTicket: 'signed-ticket',+ }).catch(caught => caught)expect(error).toMatchObject({ code: 'provider_unavailable', retryable: false })expect(String(error.message)).not.toContain('secret-name-that-must-not-leak')@@ -89,7 +96,12 @@ describe('PluginWorkloadSdkCredentialBrokerClient', () => {fetchImpl: fetchImpl as unknown as typeof fetch,})await expect(- client.resolve({ invocationId: 'inv-1', target, credentialTicket: 'signed-ticket' })+ client.resolve({+ invocationId: 'inv-1',+ attemptGeneration: 1,+ target,+ credentialTicket: 'signed-ticket',+ })).rejects.toMatchObject({ code: 'provider_unavailable', retryable: false })})})diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.tsindex 12c271a4a..e78209d14 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts@@ -27,6 +27,9 @@ export class PluginWorkloadSdkCredentialBrokerClient {async resolve(input: {invocationId: string+ attemptGeneration: number+ providerAttemptId?: string+ providerAttemptIndex?: numbertarget: PromptBridgeTargetcredentialTicket: stringtimeoutMs?: number@@ -51,6 +54,11 @@ export class PluginWorkloadSdkCredentialBrokerClient {body: JSON.stringify({recipeNamespace: this.opts.recipeNamespace,invocationId: input.invocationId,+ attemptGeneration: input.attemptGeneration,+ ...(input.providerAttemptId ? { providerAttemptId: input.providerAttemptId } : {}),+ ...(input.providerAttemptIndex !== undefined+ ? { providerAttemptIndex: input.providerAttemptIndex }+ : {}),target: input.target,credentialTicket: input.credentialTicket,}),diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.tsindex 3212fed6e..bdec0b8a6 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts@@ -25,6 +25,7 @@ const fallback: PromptBridgeTarget = {function authorization(overrides: Record<string, unknown> = {}) {return {+ contractVersion: 2,invocationId: 'inv-1',replay: false,providerCallRequired: true,@@ -33,6 +34,7 @@ function authorization(overrides: Record<string, unknown> = {}) {modelPolicy: null,selectedTarget: primary,authorizedTargets: [primary, fallback],+ attemptGeneration: 1,policyRevision: 7,policyHash: 'a'.repeat(64),maxOutputTokens: 2048,@@ -42,6 +44,7 @@ function authorization(overrides: Record<string, unknown> = {}) {function makeDeps(overrides: {+ ensure?: ReturnType<typeof vi.fn>authorize?: ReturnType<typeof vi.fn>complete?: ReturnType<typeof vi.fn>report?: ReturnType<typeof vi.fn>@@ -65,7 +68,10 @@ function makeDeps(})const handler = new PromptBridgeHandler({controlApiClient: {+ ensurePromptBridgeCapabilities: overrides.ensure ?? vi.fn().mockResolvedValue(undefined),authorizePromptBridge: authorize,+ reissuePromptBridgeCredentialTicket: vi.fn(),+ reportProviderAttemptStatus: vi.fn().mockResolvedValue(undefined),reportInvocationStatus: report,} as unknown as PluginWorkloadSdkControlApiClient,llmBridge: { complete } as unknown as LlmBridge,@@ -138,6 +144,27 @@ describe('PromptBridgeHandler', () => {expect(authorize).not.toHaveBeenCalled()})+ it('reports missing operator policy as a policy denial before creating an invocation', async () => {+ const ensure = vi+ .fn()+ .mockRejectedValue(+ new PluginWorkloadError(+ 'provider_policy_denied',+ 'an active operator grant is required',+ false+ )+ )+ const { handler, authorize, complete, report } = makeDeps({ ensure })++ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'provider_policy_denied',+ retryable: false,+ })+ expect(authorize).not.toHaveBeenCalled()+ expect(complete).not.toHaveBeenCalled()+ expect(report).not.toHaveBeenCalled()+ })+it('passes exactly the signed authorized suffix and returns the served target', async () => {const onUsage = vi.fn()const { handler, complete, report } = makeDeps({ onUsage })@@ -158,7 +185,7 @@ describe('PromptBridgeHandler', () => {policyRevision: 7,content: 'summary text',})- expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'complete')+ expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'complete', 1)expect(onUsage).toHaveBeenCalledWith(expect.objectContaining({provider: 'openai',@@ -207,6 +234,6 @@ describe('PromptBridgeHandler', () => {code: 'provider_unavailable',retryable: false,})- expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'provider_unavailable')+ 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 08a2fc630..0ec68b901 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts@@ -14,7 +14,10 @@ import {pluginSdkPromptBridgeRequestsTotal,pluginSdkPromptBridgeTokensTotal,} from '../metrics'-import type { PluginWorkloadSdkControlApiClient } from './controlApiClient'+import type {+ PluginWorkloadSdkBootstrapProof,+ PluginWorkloadSdkControlApiClient,+} from './controlApiClient'import type { LlmBridge } from './llmBridge'/**@@ -44,11 +47,14 @@ export interface PromptBridgeHandlerDeps {getBootstrapTarget?: () => { provider: string; model: string } | nullonUsage?: (usage: {invocationId: string+ attemptGeneration: numberprovider: stringmodel: stringservedTarget: PromptBridgeTargetfallbackUsed: booleanattemptCount: number+ providerAttemptId?: string+ providerAttemptIndex?: numberllmSecretName: stringinputTokens: numberoutputTokens: number@@ -155,6 +161,18 @@ export function validatePromptBridgeRequest(raw: unknown): PromptBridgeRequest {export class PromptBridgeHandler {constructor(private readonly deps: PromptBridgeHandlerDeps) {}+ /**+ * Verify the live Control API policy without issuing a provider request.+ * WRC uses this during eager bootstrap so Pod Ready cannot masquerade as a+ * validated SDK binding when the grant/default target is stale.+ */+ verifyBootstrapV2(+ expectedProvider: string,+ expectedModel: string+ ): Promise<PluginWorkloadSdkBootstrapProof> {+ return this.deps.controlApiClient.verifyPromptBridgeBootstrapV2(expectedProvider, expectedModel)+ }+async handle(rawBody: unknown, callerRef: string): Promise<PromptBridgeResult> {const startedAt = process.hrtime.bigint()try {@@ -207,6 +225,7 @@ export class PromptBridgeHandler {true)}+ await this.deps.controlApiClient.ensurePromptBridgeCapabilities()const authorized = await this.deps.controlApiClient.authorizePromptBridge({recipeNamespace: this.deps.recipeNamespace,recipeName: this.deps.recipeName,@@ -249,6 +268,7 @@ export class PromptBridgeHandler {try {const completion = await this.deps.llmBridge.complete({invocationId: authorized.invocationId,+ attemptGeneration: authorized.attemptGeneration,targets: authorized.authorizedTargets.map(target => ({ target })),messages: request.messages,policyRevision: authorized.policyRevision,@@ -259,23 +279,54 @@ export class PromptBridgeHandler {recipeNamespace: this.deps.recipeNamespace,recipeName: this.deps.recipeName,invocationId: input.invocationId,+ attemptGeneration: authorized.attemptGeneration,target: input.target,policyRevision: input.policyRevision,policyHash: input.policyHash,}),},+ providerAttemptReporter: {+ report: async input =>+ this.deps.controlApiClient.reportProviderAttemptStatus({+ invocationId: authorized.invocationId,+ recipeNamespace: this.deps.recipeNamespace,+ recipeName: this.deps.recipeName,+ attemptGeneration: authorized.attemptGeneration,+ providerAttemptId: input.providerAttemptId,+ providerAttemptIndex: input.providerAttemptIndex,+ status: input.status,+ }),+ },maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),temperature: request.temperature ?? authorized.modelPolicy?.temperature,timeoutMs: this.deps.promptTimeoutMs,})+ await this.deps.controlApiClient.reportInvocationStatus(+ authorized.invocationId,+ this.deps.recipeNamespace,+ this.deps.recipeName,+ 'complete',+ authorized.attemptGeneration+ )++ // Usage is emitted only after the generation-fenced terminal ACK. A+ // result whose audit transition was rejected must not enter metering as+ // if the provider call had completed authoritatively.this.deps.onUsage?.({invocationId: authorized.invocationId,+ attemptGeneration: authorized.attemptGeneration,provider: completion.servedTarget.provider,model: completion.model,servedTarget: completion.servedTarget,fallbackUsed: completion.fallbackUsed,attemptCount: completion.attemptCount,+ ...(completion.providerAttemptId+ ? { providerAttemptId: completion.providerAttemptId }+ : {}),+ ...(completion.providerAttemptIndex !== undefined+ ? { providerAttemptIndex: completion.providerAttemptIndex }+ : {}),llmSecretName: completion.llmSecretName,inputTokens: completion.usage.inputTokens,outputTokens: completion.usage.outputTokens,@@ -283,13 +334,6 @@ export class PromptBridgeHandler {...(request.metadata ? { metadata: request.metadata } : {}),})- await this.deps.controlApiClient.reportInvocationStatus(- authorized.invocationId,- this.deps.recipeNamespace,- this.deps.recipeName,- 'complete'- )-return {invocationId: authorized.invocationId,model: completion.model,@@ -311,7 +355,8 @@ export class PromptBridgeHandler {authorized.invocationId,this.deps.recipeNamespace,this.deps.recipeName,- status+ status,+ authorized.attemptGeneration)throw err}diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex 822d8ec60..e464cf7be 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -77,6 +77,7 @@ function makeBridge(const request = {invocationId: 'inv-1',+ attemptGeneration: 1,targets: [{ target: primary }, { target: fallback }],policyRevision: 1,policyHash: 'a'.repeat(64),@@ -175,12 +176,14 @@ describe('LlmBridge authorized multi-provider fallback', () => {expect(issue).toHaveBeenNthCalledWith(1, {invocationId: 'inv-1',+ attemptGeneration: 1,target: primary,policyRevision: 1,policyHash: 'a'.repeat(64),})expect(issue).toHaveBeenNthCalledWith(2, {invocationId: 'inv-1',+ attemptGeneration: 1,target: fallback,policyRevision: 1,policyHash: 'a'.repeat(64),diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.tsindex 0ef0cc9ca..e7835420a 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts@@ -25,8 +25,11 @@ class ClassifiedProviderError extends Error {export interface PromptBridgeCredentialResolver {resolve(input: {invocationId: string+ attemptGeneration: numbertarget: PromptBridgeTargetcredentialTicket: string+ providerAttemptId?: string+ providerAttemptIndex?: numbertimeoutMs?: number}): Promise<BrokeredCredential>}@@ -34,18 +37,33 @@ export interface PromptBridgeCredentialResolver {export interface PromptBridgeCredentialTicketIssuer {issue(input: {invocationId: string+ attemptGeneration: numbertarget: PromptBridgeTargetpolicyRevision: numberpolicyHash: string- }): Promise<{ credentialTicket: string }>+ }): Promise<{+ credentialTicket: string+ providerAttemptId?: string+ providerAttemptIndex?: number+ }>+}++export interface PromptBridgeProviderAttemptReporter {+ report(input: {+ providerAttemptId: string+ providerAttemptIndex: number+ status: 'complete' | 'failed' | 'provider_unavailable'+ }): Promise<void>}export interface LlmBridgeRequest {invocationId: string+ attemptGeneration: numbertargets: Array<{ target: PromptBridgeTarget }>policyRevision: numberpolicyHash: stringcredentialTicketIssuer: PromptBridgeCredentialTicketIssuer+ providerAttemptReporter?: PromptBridgeProviderAttemptReportermessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>maxTokens?: numbertemperature?: number@@ -59,6 +77,8 @@ export interface LlmBridgeResult {fallbackUsed: booleanattemptCount: numberllmSecretName: string+ providerAttemptId?: string+ providerAttemptIndex?: numbercontent: stringusage: { inputTokens: number; outputTokens: number }finishReason: 'complete' | 'length' | 'content_filter'@@ -214,6 +234,7 @@ export class LlmBridge {() =>request.credentialTicketIssuer.issue({invocationId: request.invocationId,+ attemptGeneration: request.attemptGeneration,target: authorized.target,policyRevision: request.policyRevision,policyHash: request.policyHash,@@ -221,17 +242,42 @@ export class LlmBridge {remainingTimeoutMs(deadlineAt),'timeout')- const credential = await withinDeadline(- () =>- this.credentials.resolve({- invocationId: request.invocationId,- target: authorized.target,- credentialTicket: ticket.credentialTicket,- timeoutMs: remainingTimeoutMs(deadlineAt),- }),- remainingTimeoutMs(deadlineAt),- 'timeout'- )+ let credential: BrokeredCredential+ try {+ credential = await withinDeadline(+ () =>+ this.credentials.resolve({+ invocationId: request.invocationId,+ attemptGeneration: request.attemptGeneration,+ target: authorized.target,+ credentialTicket: ticket.credentialTicket,+ ...(ticket.providerAttemptId ? { providerAttemptId: ticket.providerAttemptId } : {}),+ ...(ticket.providerAttemptIndex !== undefined+ ? { providerAttemptIndex: ticket.providerAttemptIndex }+ : {}),+ timeoutMs: remainingTimeoutMs(deadlineAt),+ }),+ remainingTimeoutMs(deadlineAt),+ 'timeout'+ )+ } catch (error) {+ // A ticket has already reserved a physical attempt by this point. Do+ // 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 (+ request.providerAttemptReporter &&+ ticket.providerAttemptId &&+ ticket.providerAttemptIndex !== undefined+ ) {+ await request.providerAttemptReporter.report({+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ status: 'failed',+ })+ }+ throw error+ }try {const completion = await this.attempt(@@ -239,14 +285,40 @@ export class LlmBridge {{ ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },breaker)+ if (+ request.providerAttemptReporter &&+ ticket.providerAttemptId &&+ ticket.providerAttemptIndex !== undefined+ ) {+ await request.providerAttemptReporter.report({+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ status: 'complete',+ })+ }return {...completion,servedTarget: authorized.target,fallbackUsed: index > 0,attemptCount: index + 1,llmSecretName: credential.llmSecretName,+ ...(ticket.providerAttemptId ? { providerAttemptId: ticket.providerAttemptId } : {}),+ ...(ticket.providerAttemptIndex !== undefined+ ? { providerAttemptIndex: ticket.providerAttemptIndex }+ : {}),}} catch (error) {+ if (+ request.providerAttemptReporter &&+ ticket.providerAttemptId &&+ ticket.providerAttemptIndex !== undefined+ ) {+ await request.providerAttemptReporter.report({+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,+ status: error instanceof ClassifiedProviderError ? 'provider_unavailable' : 'failed',+ })+ }if (!(error instanceof ClassifiedProviderError)) throw errorlastProviderError = errorconst failureClass = classifyFailoverClass(diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.tsindex 6da1ce40e..1ffc19bf8 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts@@ -137,6 +137,7 @@ function makeHarness(scenario: Scenario): RuntimeHarness {)}return {+ contractVersion: 2,invocationId: 'inv-runtime-http',replay: false,providerCallRequired: true,@@ -145,18 +146,23 @@ function makeHarness(scenario: Scenario): RuntimeHarness {modelPolicy: null,selectedTarget: PRIMARY,authorizedTargets: [PRIMARY, FALLBACK],+ attemptGeneration: 1,policyRevision: 9,policyHash: POLICY_HASH,maxOutputTokens: 256,}})const controlApiClient = {+ ensurePromptBridgeCapabilities: vi.fn().mockResolvedValue(undefined),authorizePromptBridge,reissuePromptBridgeCredentialTicket: vi.fn(async ({ target }: { target: PromptBridgeTarget }) => {issuedTickets.push(target.targetRef)return {invocationId: 'inv-runtime-http',+ attemptGeneration: 1,+ providerAttemptId: `attempt-${target.targetRef}`,+ providerAttemptIndex: issuedTickets.length,targetRef: target.targetRef,credentialTicket: `ticket-${target.targetRef}`,policyRevision: 9,@@ -165,6 +171,7 @@ function makeHarness(scenario: Scenario): RuntimeHarness {}}),+ reportProviderAttemptStatus: vi.fn().mockResolvedValue(undefined),reportInvocationStatus: vi.fn(async (_id: string, _ns: string, _recipe: string, status: string) => {reportedStatuses.push(status)diff --git a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.tsindex ab18608ed..4a9c7d8eb 100644--- a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts@@ -40,7 +40,9 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()credentialSlot: 'zai-api-key',}const controlApiClient = {+ ensurePromptBridgeCapabilities: vi.fn().mockResolvedValue(undefined),authorizePromptBridge: vi.fn().mockResolvedValue({+ contractVersion: 2,invocationId: 'inv-1',replay: false,providerCallRequired: true,@@ -51,10 +53,12 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()modelPolicy: { provider: 'zai', model: 'glm-4.7', apiKey: 'sk-provider-secret' },selectedTarget: target,authorizedTargets: [target],+ attemptGeneration: 1,policyRevision: 1,policyHash: 'a'.repeat(64),maxOutputTokens: null,}),+ reportProviderAttemptStatus: vi.fn().mockResolvedValue(undefined),reportInvocationStatus: vi.fn().mockResolvedValue(undefined),} as unknown as PluginWorkloadSdkControlApiClientconst llmBridge = {diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts b/mcp-host/src/pluginWorkloadSdk/server/index.test.tsindex 783682269..115826212 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts@@ -83,7 +83,7 @@ describe('PluginWorkloadSdk server usage attribution', () => {})expect(event).toMatchObject({- source_kind: 'unknown',+ source_kind: 'plugin_workload_sdk',channel_type: 'plugin_workload_sdk',recipe_name: 'stepless',run_id: null,@@ -100,6 +100,8 @@ describe('PluginWorkloadSdk server usage attribution', () => {recipeNamespace: 'sandbox-apps',recipeName: 'prompt-notify',},+ runtimeMode: 'sdk-only',+ invocationId: '00000000-0000-4000-8000-000000000100',provider: 'openai',model: 'gpt-5.4-mini',inputTokens: 10,diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.tsindex d2a92d568..dfbfc5f4c 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts@@ -54,6 +54,9 @@ export function buildPromptBridgeUsageEvent(input: {credentialSlot: stringfallbackUsed: booleanattemptCount: number+ attemptGeneration?: number+ providerAttemptId?: string+ providerAttemptIndex?: number}metadata?: Record<string, unknown>}): LlmUsageEvent | null {@@ -88,10 +91,20 @@ export function buildPromptBridgeUsageEvent(input: {...(input.promptBridgeMetadata? {prompt_bridge_metadata: {+ invocation_id: input.invocationId,target_ref: input.promptBridgeMetadata.targetRef,credential_slot: input.promptBridgeMetadata.credentialSlot,fallback_used: input.promptBridgeMetadata.fallbackUsed,attempt_count: input.promptBridgeMetadata.attemptCount,+ ...(input.promptBridgeMetadata.attemptGeneration !== undefined+ ? { attempt_generation: input.promptBridgeMetadata.attemptGeneration }+ : {}),+ ...(input.promptBridgeMetadata.providerAttemptId+ ? { provider_attempt_id: input.promptBridgeMetadata.providerAttemptId }+ : {}),+ ...(input.promptBridgeMetadata.providerAttemptIndex !== undefined+ ? { provider_attempt_index: input.promptBridgeMetadata.providerAttemptIndex }+ : {}),},}: {}),@@ -109,7 +122,7 @@ export function buildPromptBridgeUsageEvent(input: {team_id: null,provider: input.provider,model: input.model,- source_kind: 'unknown',+ source_kind: 'plugin_workload_sdk',user_id: null,sender: input.callerRef,channel_type: 'plugin_workload_sdk',@@ -128,6 +141,9 @@ export function buildPromptBridgeUsageEvent(input: {credential_slot: input.promptBridgeMetadata.credentialSlot,fallback_used: input.promptBridgeMetadata.fallbackUsed,attempt_count: input.promptBridgeMetadata.attemptCount,+ attempt_generation: input.promptBridgeMetadata.attemptGeneration,+ provider_attempt_id: input.promptBridgeMetadata.providerAttemptId,+ provider_attempt_index: input.promptBridgeMetadata.providerAttemptIndex,},}: {}),@@ -147,6 +163,9 @@ export function buildPromptBridgeUsageEvent(input: {if (!runId || !executionId || !executionId.toLowerCase().startsWith(runId) || !llmSecretName) {return null}+ if (input.promptBridgeMetadata && !UUID_RE.test(input.invocationId?.trim() ?? '')) {+ return null+ }return {request_id: randomUUID(),@@ -171,10 +190,20 @@ export function buildPromptBridgeUsageEvent(input: {...(input.promptBridgeMetadata? {prompt_bridge_metadata: {+ invocation_id: input.invocationId!.trim(),target_ref: input.promptBridgeMetadata.targetRef,credential_slot: input.promptBridgeMetadata.credentialSlot,fallback_used: input.promptBridgeMetadata.fallbackUsed,attempt_count: input.promptBridgeMetadata.attemptCount,+ ...(input.promptBridgeMetadata.attemptGeneration !== undefined+ ? { attempt_generation: input.promptBridgeMetadata.attemptGeneration }+ : {}),+ ...(input.promptBridgeMetadata.providerAttemptId+ ? { provider_attempt_id: input.promptBridgeMetadata.providerAttemptId }+ : {}),+ ...(input.promptBridgeMetadata.providerAttemptIndex !== undefined+ ? { provider_attempt_index: input.promptBridgeMetadata.providerAttemptIndex }+ : {}),},}: {}),@@ -327,6 +356,9 @@ export function maybeCreatePluginWorkloadSdkServer(credentialSlot: usage.servedTarget.credentialSlot,fallbackUsed: usage.fallbackUsed,attemptCount: usage.attemptCount,+ attemptGeneration: usage.attemptGeneration,+ providerAttemptId: usage.providerAttemptId,+ providerAttemptIndex: usage.providerAttemptIndex,},runtimeMode: config.pluginWorkloadSdkRuntimeMode === 'sdk-only' ? 'sdk-only' : 'workflow',invocationId: usage.invocationId,diff --git a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.tsindex 277fbcbcc..49b22bce8 100644--- a/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/sdkServer.ts@@ -2,6 +2,7 @@ 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 { PromptBridgeHandler } from '../promptBridge/handler'import { registerSdkRoutes } from './routes'@@ -114,6 +115,13 @@ export class PluginWorkloadSdkServer {})}+ verifyPromptBridgeBootstrapV2(+ expectedProvider: string,+ expectedModel: string+ ): Promise<PluginWorkloadSdkBootstrapProof> {+ return this.opts.promptBridgeHandler.verifyBootstrapV2(expectedProvider, expectedModel)+ }+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/usage/usageReporter.ts b/mcp-host/src/usage/usageReporter.tsindex c67df6ca6..dad962457 100644--- a/mcp-host/src/usage/usageReporter.ts+++ b/mcp-host/src/usage/usageReporter.ts@@ -21,7 +21,7 @@ export type LlmUsageEvent = {provider: stringmodel: stringllm_secret_name: string | null- source_kind: 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown'+ source_kind: 'channel' | 'desktop' | 'workflow' | 'cron' | 'unknown' | 'plugin_workload_sdk'user_id: string | nullsender: string | nullchannel_type: string | null@@ -52,6 +52,9 @@ export type LlmUsageEvent = {credential_slot: stringfallback_used: booleanattempt_count: number+ attempt_generation?: number+ provider_attempt_id?: string+ provider_attempt_index?: number}}diff --git a/mcp-host/src/workflow/__tests__/configureHandler.test.ts b/mcp-host/src/workflow/__tests__/configureHandler.test.tsindex 411627934..8277b7ecd 100644--- a/mcp-host/src/workflow/__tests__/configureHandler.test.ts+++ b/mcp-host/src/workflow/__tests__/configureHandler.test.ts@@ -56,19 +56,25 @@ describe('POST /configure — JWT scope', () => {expect(result.provider).toBe('openai')})- it('publishes SDK bootstrap identity without making the workflow service ready or receiving a key', () => {+ it('publishes SDK bootstrap identity without making the workflow service ready or receiving a key', async () => {const onBootstrap = vi.fn()const svc = new WorkflowService('test', {llmFactory: mockLlmFactory(),onPluginWorkloadSdkBootstrapConfigured: onBootstrap,})- const result = svc.configurePluginWorkloadSdkBootstrap({+ const result = await svc.configurePluginWorkloadSdkBootstrap({provider: 'openai',model: 'gpt-4',// @ts-expect-error the public bootstrap contract intentionally has no apiKeyapiKey: 'must-not-be-consumed',})- expect(result).toEqual({ configured: true, provider: 'openai', model: 'gpt-4' })+ expect(result).toEqual({+ configured: true,+ ready: true,+ provider: 'openai',+ model: 'gpt-4',+ contractVersion: 2,+ })expect(onBootstrap).toHaveBeenCalledWith({ provider: 'openai', defaultModel: 'gpt-4' })expect(svc.isReady()).toBe(false)})diff --git a/mcp-host/src/workflow/types.ts b/mcp-host/src/workflow/types.tsindex d186979b6..9bbbb7bc6 100644--- a/mcp-host/src/workflow/types.ts+++ b/mcp-host/src/workflow/types.ts@@ -105,6 +105,22 @@ export interface ConfigureResponse {configured: booleanprovider?: stringmodel?: string+ /**+ * Version of the identity-only Plugin Workload SDK bootstrap contract. This+ * is intentionally present only on the SDK bootstrap response; workflow+ * `/configure` remains on its legacy response shape.+ */+ contractVersion?: 2+ ready?: boolean+ /** Pod/protocol identity is ready even while operator policy is pending. */+ policyReady?: boolean+ policyState?: string+ policyReason?: string+ policyRevision?: number+ policyHash?: string+ defaultTargetRef?: string+ defaultProvider?: string+ defaultModel?: stringmessage?: string}diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex 57eeeca18..6c1d3c8b2 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -282,7 +282,7 @@ export function createWorkflowRouter(service: WorkflowService): Router {'/plugin-workload-sdk/bootstrap',requireWorkflowAuth('configure'),workflowControlRateLimit,- (req: Request, res: Response) => {+ async (req: Request, res: Response) => {if (!validateWorkflowBinding(req, res, { expectedSub: 'wrc' })) returnconst raw = req.body as PluginWorkloadSdkBootstrapRequest// Deliberately project the request to the identity-only contract. Any@@ -292,8 +292,17 @@ export function createWorkflowRouter(service: WorkflowService): Router {provider: raw?.provider,model: raw?.model,}- const result = service.configurePluginWorkloadSdkBootstrap(body)- res.status(result.configured ? 200 : 400).json(result)+ try {+ const result = await service.configurePluginWorkloadSdkBootstrap(body)+ res.status(result.configured ? 200 : result.ready === false ? 503 : 400).json(result)+ } catch {+ res.status(503).json({+ configured: false,+ ready: false,+ contractVersion: 2,+ message: 'Plugin Workload SDK identity bootstrap contract is not ready',+ })+ }})diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex bc63adda3..02dc963fd 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -17,6 +17,7 @@ import { buildGfsReadTools, buildGfsWriteTools } from '../internalTools/gfs'import { createGfscClient, hasGfsRuntimeAccess } from '../internalTools/gfsClient'import { SingleTurnProvider, createLLMProvider } from '../llm'import { type LlmProvider, descriptorFor, isLlmProvider, primarySlot } from '../llm/registryCore'+import type { PluginWorkloadSdkBootstrapProof } from '../pluginWorkloadSdk/promptBridge/controlApiClient'import type { ApiKeys } from '../types'import { type LlmUsageEvent, type UsageReporter, newRequestId } from '../usage/usageReporter'import {@@ -301,6 +302,10 @@ export class WorkflowService {provider: import('../types').ModelConfig['provider']defaultModel: string}) => void+ verifyPluginWorkloadSdkBootstrapV2?: (+ provider: string,+ model: string+ ) => Promise<PluginWorkloadSdkBootstrapProof | null>}) {this.recipeName = recipeName@@ -319,6 +324,7 @@ export class WorkflowService {this.onLlmConfigured = opts?.onLlmConfigured ?? nullthis.onPluginWorkloadSdkBootstrapConfigured =opts?.onPluginWorkloadSdkBootstrapConfigured ?? null+ this.verifyPluginWorkloadSdkBootstrapV2 = opts?.verifyPluginWorkloadSdkBootstrapV2 ?? null}private readonly onLlmConfigured:@@ -336,6 +342,10 @@ export class WorkflowService {}) => void)| null = null+ private readonly verifyPluginWorkloadSdkBootstrapV2:+ | ((provider: string, model: string) => Promise<PluginWorkloadSdkBootstrapProof | 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.@@ -353,7 +363,9 @@ export class WorkflowService {* workflow readiness: stepless SDK traffic resolves credentials per attempt* through the WRC broker rather than loading them into this service.*/- configurePluginWorkloadSdkBootstrap(req?: PluginWorkloadSdkBootstrapRequest): ConfigureResponse {+ async configurePluginWorkloadSdkBootstrap(+ req?: PluginWorkloadSdkBootstrapRequest+ ): Promise<ConfigureResponse> {if (!req?.provider) {return { configured: false, message: 'provider is required' }}@@ -364,11 +376,37 @@ export class WorkflowService {if (!isRunnableLlmModelId(model)) {return { configured: false, message: 'model is required and has an invalid format' }}+ const proof = this.verifyPluginWorkloadSdkBootstrapV2+ ? await this.verifyPluginWorkloadSdkBootstrapV2(req.provider, model)+ : null+ if (this.verifyPluginWorkloadSdkBootstrapV2 && !proof) {+ return {+ configured: false,+ ready: false,+ contractVersion: 2,+ message: 'Plugin Workload SDK identity bootstrap contract is not ready',+ }+ }this.onPluginWorkloadSdkBootstrapConfigured?.({provider: req.provider as import('../types').ModelConfig['provider'],defaultModel: model,})- return { configured: true, provider: req.provider, model }+ return {+ configured: true,+ ready: true,+ provider: req.provider,+ model,+ contractVersion: 2,+ ...(proof ? { policyReady: proof.policyReady, policyState: proof.policyState } : {}),+ ...(proof?.policyReason ? { policyReason: proof.policyReason } : {}),+ ...(proof?.policyRevision !== undefined ? { policyRevision: proof.policyRevision } : {}),+ ...(proof?.policyHash !== undefined ? { policyHash: proof.policyHash } : {}),+ ...(proof?.defaultTargetRef !== undefined+ ? { defaultTargetRef: proof.defaultTargetRef }+ : {}),+ ...(proof?.defaultProvider !== undefined ? { defaultProvider: proof.defaultProvider } : {}),+ ...(proof?.defaultModel !== undefined ? { defaultModel: proof.defaultModel } : {}),+ }}isReady(): boolean {diff --git a/scripts/e2e/e2e-plugin-workload-sdk.sh b/scripts/e2e/e2e-plugin-workload-sdk.shindex 7285f1e2f..6d941c4c4 100755--- a/scripts/e2e/e2e-plugin-workload-sdk.sh+++ b/scripts/e2e/e2e-plugin-workload-sdk.sh@@ -31,78 +31,9 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"## process environment > canonical root .env > safe test defaults#-# The dotenv file is parsed as data without sourcing or evaluating it. Values-# supplied by the caller remain authoritative, and shell expressions in the-# canonical file are preserved literally.-load_canonical_root_env() {- local repo_root env_file common_dir main_repo_dir raw_line line key- repo_root="$(cd "${SCRIPT_DIR}/../.." && pwd)"- env_file=""-- if [ -f "${repo_root}/.env" ]; then- env_file="${repo_root}/.env"- else- common_dir="$(git -C "$repo_root" rev-parse --git-common-dir 2>/dev/null || true)"- if [ -n "$common_dir" ]; then- case "$common_dir" in- /*) main_repo_dir="$(cd "${common_dir}/.." && pwd)" ;;- *) main_repo_dir="$(cd "${repo_root}/${common_dir}/.." && pwd)" ;;- esac- if [ -f "${main_repo_dir}/.env" ]; then- env_file="${main_repo_dir}/.env"- fi- fi- fi-- if [ -z "$env_file" ]; then- return 0- fi-- local line_number=0 value quote- while IFS= read -r raw_line || [ -n "$raw_line" ]; do- line_number=$((line_number + 1))- line="${raw_line#"${raw_line%%[![:space:]]*}"}"- case "$line" in- ''|'#'*) continue ;;- esac- if [[ "$line" == export[[:space:]]* ]]; then- line="${line#export}"- line="${line#"${line%%[![:space:]]*}"}"- fi- if [[ "$line" != *=* ]]; then- printf 'Ignoring invalid canonical .env line %s (expected KEY=value)\n' "$line_number" >&2- return 1- fi- key="${line%%=*}"- key="${key#"${key%%[![:space:]]*}"}"- key="${key%"${key##*[![:space:]]}"}"- if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then- printf 'Ignoring invalid canonical .env key on line %s\n' "$line_number" >&2- return 1- fi- if [ "${!key+x}" = x ]; then- continue- fi- value="${line#*=}"- value="${value#"${value%%[![:space:]]*}"}"- value="${value%"${value##*[![:space:]]}"}"- if [[ "$value" == \"*\" || "$value" == \'*\' ]]; then- quote="${value:0:1}"- if [[ "${value: -1}" != "$quote" ]]; then- printf 'Ignoring unterminated quoted value on canonical .env line %s\n' "$line_number" >&2- return 1- fi- value="${value:1:${#value}-2}"- fi- # Treat dotenv as data. In particular, command substitutions, backticks,- # globbing and variable references remain literal text and are never- # evaluated by a shell.- printf -v "$key" '%s' "$value"- export "$key"- done < "$env_file"-}--load_canonical_root_env+# shellcheck source=scripts/e2e/load-dotenv.sh+source "${SCRIPT_DIR}/load-dotenv.sh"+dotenv_load_canonical_root "$(cd "${SCRIPT_DIR}/../.." && pwd)"export RECIPE_NS="${RECIPE_NS:-sandbox-recipes}"# shellcheck source=e2e-lib.shsource "${SCRIPT_DIR}/e2e-lib.sh"@@ -114,11 +45,10 @@ EVENT_TYPE="e2e.test.notification"E2E_DESKTOP_USER_EMAIL="${E2E_DESKTOP_USER_EMAIL:-${E2E_DEV_LOGIN_EMAIL:[email protected]}}"# The host-wide CLERUM_MODEL_PROVIDER may legitimately remain Z.AI for other-# local workloads, but this gate must not spend its T3 calls against the-# provider currently limited by 429s. Inherit the host provider/model only-# when it is an allowed OpenAI/Claude target; otherwise use the deterministic-# OpenAI default and make the fallback Claude. An explicit E2E_* value still-# wins and is validated below.+# local workloads, but this gate must not silently redirect a paid call. An+# explicit E2E provider/model is required when the root environment selects an+# unavailable provider; only an entirely absent provider uses the documented+# local OpenAI default.E2E_WORKFLOW_MODEL_PROVIDER="${E2E_WORKFLOW_MODEL_PROVIDER:-}"E2E_WORKFLOW_MODEL_NAME="${E2E_WORKFLOW_MODEL_NAME:-}"if [ -z "$E2E_WORKFLOW_MODEL_PROVIDER" ]; then@@ -133,8 +63,7 @@ if [ -z "$E2E_WORKFLOW_MODEL_PROVIDER" ]; thenE2E_WORKFLOW_MODEL_PROVIDER="openai";;*)- warn "CLERUM_MODEL_PROVIDER=${CLERUM_MODEL_PROVIDER} is not used by this Plugin Workload SDK gate; selecting the OpenAI default because the Z.AI lane is unavailable"- E2E_WORKFLOW_MODEL_PROVIDER="openai"+ die "CLERUM_MODEL_PROVIDER=${CLERUM_MODEL_PROVIDER} is not permitted for this gate while that provider is unavailable; set E2E_WORKFLOW_MODEL_PROVIDER and E2E_WORKFLOW_MODEL_NAME explicitly to OpenAI or Claude";;esacfi@@ -177,17 +106,25 @@ E2E_DESKTOP_PASSWORD="${E2E_DESKTOP_PASSWORD:-${ADMIN_PASSWORD:-changeme123!}}"load_branch_profile_ports() {local ctx="${KUBECONTEXT:-${E2E_K8S_CONTEXT:-}}"- local ports_env="${CLERUM_PROFILE_PORTS_ENV:-}"- if [ -z "$ports_env" ] && [ -n "$ctx" ]; then+ local ports_env="${CLERUM_PROFILE_PORTS_ENV:-${E2E_PROFILE_PORTS_ENV:-}}"+ if [[ "$ctx" =~ ^clerum-(codex|detached)- ]] || [[ "$ctx" =~ ^clerum-.+-[0-9a-f]{7,8}$ ]]; then+ if [ -z "$ports_env" ]; then+ die "Branch-owned context ${ctx} requires ports.env generated by clerum/.local-notes/minikube-profiles/branch.mk; set CLERUM_PROFILE_PORTS_ENV or E2E_PROFILE_PORTS_ENV before running this gate"+ fi+ elif [ -z "$ports_env" ] && [ -n "$ctx" ]; thenports_env="${HOME}/.cache/clerum/minikube-profiles/${ctx}/ports.env"fi- if [ -f "$ports_env" ]; then- # shellcheck disable=SC1090- . "$ports_env"+ if [[ -n "$ports_env" ]]; then+ [[ -f "$ports_env" ]] || die "profile ports file not found: ${ports_env}"+ dotenv_load_file "$ports_env"fi}load_branch_profile_ports-E2E_EXTERNAL_REST_API_URL="${E2E_EXTERNAL_REST_API_URL:-${EXTERNAL_REST_API_URL:-http://127.0.0.1:8091}}"+E2E_CONTROL_API_URL="${E2E_CONTROL_API_URL:-${CONTROL_API_URL:-${CONTROL_API_BASE_URL:-http://127.0.0.1:8090}}}"+E2E_EXTERNAL_REST_API_URL="${E2E_EXTERNAL_REST_API_URL:-${EXTERNAL_REST_API_URL:-${EXTERNAL_REST_API_BASE_URL:-http://127.0.0.1:8091}}}"+E2E_RPC_PROXY_URL="${E2E_RPC_PROXY_URL:-${RPC_PROXY_URL:-${RPC_PROXY_BASE_URL:-http://127.0.0.1:8094}}}"+MCP_HOST_BASE_URL="${MCP_HOST_BASE_URL:-${MCP_HOST_RUNTIME_BASE_URL:-${MCP_HOST_RUNTIME_URL:-http://127.0.0.1:8080}}}"+export E2E_CONTROL_API_URL E2E_EXTERNAL_REST_API_URL E2E_RPC_PROXY_URL MCP_HOST_BASE_URLFIXTURE="${SCRIPT_DIR}/../../tests/e2e/fixtures/plugin-workload-sdk-recipe.yaml"E2E_CREATED_RECIPE=0ADMIN_CURL_HTTP_STATUS=""@@ -276,7 +213,10 @@ gate_assert_deadline() {}stop_sdk_caller_fixture() {- kctl delete pod "$caller_pod" -n "$SANDBOX_NS" --ignore-not-found --wait=false >/dev/null 2>&1 || true+ if ! kctl delete pod "$caller_pod" -n "$SANDBOX_NS" --ignore-not-found --wait=false >/dev/null 2>&1; then+ warn "could not delete sdk-caller pod before recycling it"+ return 1+ fiif wait_for_pod "$SANDBOX_NS" "clerum.io/recipe=${RECIPE_NAME},clerum.io/workload=${WORKLOAD_ID}" "$TIMEOUT_POD"; thencaller_pod="$(ready_pod_name "$SANDBOX_NS" "clerum.io/recipe=${RECIPE_NAME},clerum.io/workload=${WORKLOAD_ID}")"return 0@@ -285,9 +225,41 @@ stop_sdk_caller_fixture() {}reset_sdk_runtime_state_for_happy_path() {- psql_query "DELETE FROM plugin_workload_sdk_quota_counters WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';" >/dev/null 2>&1 || true- psql_query "DELETE FROM plugin_workload_sdk_invocations WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';" >/dev/null 2>&1 || true- psql_query "DELETE FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';" >/dev/null 2>&1 || true+ local cleanup_status=0 count table query+ local -a delete_queries=(+ "DELETE FROM plugin_workload_sdk_quota_counters WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_provider_attempts WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_invocation_attempts WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_invocations WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';"+ )+ for query in "${delete_queries[@]}"; do+ if ! psql_query "$query" >/dev/null; then+ cleanup_status=1+ warn "could not reset SDK runtime state before happy path"+ fi+ done+ local -a count_tables=(+ plugin_workload_sdk_quota_counters+ plugin_workload_sdk_provider_attempts+ plugin_workload_sdk_credential_ticket_jtis+ plugin_workload_sdk_invocation_attempts+ plugin_workload_sdk_invocations+ )+ for table in "${count_tables[@]}"; do+ query="SELECT count(*) FROM ${table} WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ if ! count="$(psql_query "$query" | tr -d '[:space:]')" || [ "$count" != "0" ]; then+ cleanup_status=1+ warn "SDK runtime reset postcondition failed for ${table}"+ fi+ done+ query="SELECT count(*) FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';"+ if ! count="$(psql_query "$query" | tr -d '[:space:]')" || [ "$count" != "0" ]; then+ cleanup_status=1+ warn "SDK notification delivery reset postcondition failed"+ fi+ return "$cleanup_status"}wait_for_caller_logs_matching() {@@ -345,10 +317,52 @@ notifications_desktop_first_enabled() {# ─── cleanup ─────────────────────────────────────────────────────────────cleanup_plugin_workload_sdk_db() {- psql_query "DELETE FROM plugin_workload_sdk_quota_counters WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';" >/dev/null 2>&1 || true- psql_query "DELETE FROM plugin_workload_sdk_invocations WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';" >/dev/null 2>&1 || true- psql_query "DELETE FROM plugin_workload_sdk_grants WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';" >/dev/null 2>&1 || true- psql_query "DELETE FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';" >/dev/null 2>&1 || true+ local cleanup_status=0 count query label+ local -a delete_queries=(+ "DELETE FROM plugin_workload_sdk_quota_counters WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_provider_attempts WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_invocation_attempts WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_invocations WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM plugin_workload_sdk_grants WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ "DELETE FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';"+ )+ for query in "${delete_queries[@]}"; do+ if ! psql_query "$query" >/dev/null; then+ cleanup_status=1+ warn "SDK DB cleanup query failed (recipe=${RECIPE_NS}/${RECIPE_NAME}); refusing to claim a clean fixture"+ fi+ done++ local -a count_queries=(+ "plugin_workload_sdk_quota_counters"+ "plugin_workload_sdk_invocations"+ "plugin_workload_sdk_credential_ticket_jtis"+ "plugin_workload_sdk_invocation_attempts"+ "plugin_workload_sdk_provider_attempts"+ "plugin_workload_sdk_grants"+ )+ for label in "${count_queries[@]}"; do+ query="SELECT count(*) FROM ${label} WHERE recipe_namespace='${RECIPE_NS}' AND recipe_name='${RECIPE_NAME}';"+ if ! count="$(psql_query "$query" | tr -d '[:space:]')"; then+ cleanup_status=1+ warn "SDK DB cleanup verification failed for ${label}; refusing to claim zero rows"+ continue+ fi+ if [ "$count" != "0" ]; then+ cleanup_status=1+ warn "SDK DB cleanup postcondition failed for ${label}: ${count} rows remain"+ fi+ done+ query="SELECT count(*) FROM notification_deliveries WHERE payload->>'recipeName'='${RECIPE_NAME}' AND payload->>'origin'='plugin_workload_sdk';"+ if ! count="$(psql_query "$query" | tr -d '[:space:]')"; then+ cleanup_status=1+ warn "notification delivery cleanup verification failed; refusing to claim zero rows"+ elif [ "$count" != "0" ]; then+ cleanup_status=1+ warn "notification delivery cleanup postcondition failed: ${count} rows remain"+ fi+ return "$cleanup_status"}prune_recipe_owned_resources() {@@ -368,7 +382,9 @@ prune_recipe_owned_resources() {cleanup_sdk_recipe() {local cleanup_status=0- cleanup_plugin_workload_sdk_db+ if ! cleanup_plugin_workload_sdk_db; then+ cleanup_status=1+ fikctl delete workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" --ignore-not-found --wait=false >/dev/null 2>&1 || cleanup_status=1wait_for_workflowrecipe_deleted "$RECIPE_NS" "$RECIPE_NAME" "$TIMEOUT_DELETE" || cleanup_status=1if ! prune_recipe_owned_resources; then@@ -620,6 +636,41 @@ resolve_e2e_desktop_user_id() {| tr -d '[:space:]'}+wait_for_sdk_protocol_ready() {+ local deadline=$((SECONDS + E2E_WAIT_STATUS_VALIDATED))+ local state=""+ while [ "$SECONDS" -lt "$deadline" ]; do+ gate_assert_deadline "waiting for Plugin Workload SDK identity bootstrap"+ state=$(kctl get workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" -o jsonpath='{.status.pluginWorkloadSdk.state}' 2>/dev/null || true)+ # A missing/unreviewed operator grant is an expected control-plane state,+ # not a provider outage. The eager host identity is usable enough for the+ # operator to create the grant; only the later validated state authorizes+ # prompt traffic.+ if [ "$state" = "awaiting_policy" ] || [ "$state" = "validated" ]; then+ printf '%s\n' "$state"+ return 0+ fi+ sleep "$POLL_INTERVAL"+ done+ printf '%s\n' "$state"+ return 1+}++wait_for_sdk_policy_validated() {+ local deadline=$((SECONDS + E2E_WAIT_STATUS_VALIDATED))+ local state=""+ while [ "$SECONDS" -lt "$deadline" ]; do+ gate_assert_deadline "waiting for status.pluginWorkloadSdk.state=validated after operator grant"+ state=$(kctl get workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" -o jsonpath='{.status.pluginWorkloadSdk.state}' 2>/dev/null || true)+ if [ "$state" = "validated" ]; then+ return 0+ fi+ sleep "$POLL_INTERVAL"+ done+ printf '%s\n' "$state"+ return 1+}+ensure_external_rest_api_reachable() {local url="${E2E_EXTERNAL_REST_API_URL}/health"if curl -sf -m 5 "$url" >/dev/null 2>&1; then@@ -739,20 +790,13 @@ ok "applied WorkflowRecipe ${RECIPE_NAME}"header "Infrastructure invariants"-# 1. Capability validated + projected to status.-status_ok=0-state=""-status_deadline=$((SECONDS + E2E_WAIT_STATUS_VALIDATED))-while [ "$SECONDS" -lt "$status_deadline" ]; do- gate_assert_deadline "waiting for status.pluginWorkloadSdk.state=validated"- state=$(kctl get workflowrecipe "$RECIPE_NAME" -n "$RECIPE_NS" -o jsonpath='{.status.pluginWorkloadSdk.state}' 2>/dev/null || true)- if [ "$state" = "validated" ]; then status_ok=1; break; fi- sleep "$POLL_INTERVAL"-done-if [ "$status_ok" = "1" ]; then- ok "status.pluginWorkloadSdk.state == validated"+# 1. Identity bootstrap is ready. A new recipe normally reports awaiting_policy+# until the operator grant journey below completes; it must not be forced to+# manufacture a grant before the eager host can be observed.+if state="$(wait_for_sdk_protocol_ready)"; then+ ok "Plugin Workload SDK identity bootstrap ready (state=${state})"else- fail "status.pluginWorkloadSdk.state did not reach 'validated' (got '${state:-<empty>}')"+ fail "Plugin Workload SDK identity bootstrap did not reach awaiting_policy/validated (got '${state:-<empty>}')"exit 1fi@@ -936,6 +980,16 @@ elseexit 1fi+# The grant is now active and the WRC's next live capability probe must move+# the recipe from awaiting_policy to validated. This is the point at which the+# data plane is authorized; protocol readiness alone never authorizes a call.+if wait_for_sdk_policy_validated; then+ ok "status.pluginWorkloadSdk.state == validated after operator grants"+else+ fail "status.pluginWorkloadSdk.state did not reach 'validated' after operator grants (got '${state:-<empty>}')"+ exit 1+fi+# Read back only the persisted policy metadata. This proves the operator's# two-provider order/default contract without ever logging a Secret value,# bearer token, or credential ticket.@@ -1073,7 +1127,10 @@ ok "restored promptBridge grant after caller_not_allowed probe"header "Authorized happy path"-reset_sdk_runtime_state_for_happy_path+if ! reset_sdk_runtime_state_for_happy_path; then+ fail "could not prove a clean SDK runtime state before the happy-path fixture"+ exit 1+fiok "reset SDK invocation/quota/delivery state before happy-path fixture"# Restart the caller so the fixture re-runs against the restored grants.diff --git a/scripts/e2e/load-dotenv.sh b/scripts/e2e/load-dotenv.shnew file mode 100644index 000000000..73bba1c0c--- /dev/null+++ b/scripts/e2e/load-dotenv.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash+# Literal dotenv loader shared by the E2E wrappers.+#+# This file is executable shell code; the dotenv files passed to it are data.+# Values already present in the process keep precedence, including an explicit+# empty value. No dotenv line is ever sourced, eval'd, or command-substituted.++dotenv_load_file() {+ local env_file="${1:?dotenv file path is required}"+ [[ -f "${env_file}" ]] || return 0++ local raw_line line key value quote line_number=0+ while IFS= read -r raw_line || [[ -n "${raw_line}" ]]; do+ line_number=$((line_number + 1))+ line="${raw_line#"${raw_line%%[![:space:]]*}"}"+ case "${line}" in+ ''|'#'*) continue ;;+ esac+ if [[ "${line}" == export[[:space:]]* ]]; then+ line="${line#export}"+ line="${line#"${line%%[![:space:]]*}"}"+ fi+ if [[ "${line}" != *=* ]]; then+ printf 'Invalid dotenv line %s in %s (expected KEY=value)\n' "${line_number}" "${env_file}" >&2+ return 1+ fi+ key="${line%%=*}"+ key="${key#"${key%%[![:space:]]*}"}"+ key="${key%"${key##*[![:space:]]}"}"+ if [[ ! "${key}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then+ printf 'Invalid dotenv key on line %s in %s\n' "${line_number}" "${env_file}" >&2+ return 1+ fi+ # Presence, rather than truthiness, preserves an explicit process value.+ if [[ "${!key+x}" == x ]]; then continue; fi+ value="${line#*=}"+ value="${value#"${value%%[![:space:]]*}"}"+ value="${value%"${value##*[![:space:]]}"}"+ if [[ "${value}" == \"*\" || "${value}" == \'*\' ]]; then+ quote="${value:0:1}"+ if [[ "${value: -1}" != "${quote}" ]]; then+ printf 'Unterminated dotenv quote on line %s in %s\n' "${line_number}" "${env_file}" >&2+ return 1+ fi+ value="${value:1:${#value}-2}"+ fi+ printf -v "${key}" '%s' "${value}"+ export "${key}"+ done < "${env_file}"+}++dotenv_canonical_root() {+ local repo_root="${1:?repository root is required}"+ local common_dir main_repo_dir+ if [[ -f "${repo_root}/.env" ]]; then+ printf '%s\n' "${repo_root}/.env"+ return 0+ fi+ common_dir="$(git -C "${repo_root}" rev-parse --git-common-dir 2>/dev/null || true)"+ if [[ -z "${common_dir}" ]]; then return 0; fi+ case "${common_dir}" in+ /*) main_repo_dir="$(cd "${common_dir}/.." && pwd)" ;;+ *) main_repo_dir="$(cd "${repo_root}/${common_dir}/.." && pwd)" ;;+ esac+ [[ -f "${main_repo_dir}/.env" ]] && printf '%s\n' "${main_repo_dir}/.env"+}++dotenv_load_canonical_root() {+ local repo_root="${1:?repository root is required}" env_file+ env_file="$(dotenv_canonical_root "${repo_root}")"+ [[ -n "${env_file}" ]] && dotenv_load_file "${env_file}"+}diff --git a/scripts/e2e/playwright-dev.sh b/scripts/e2e/playwright-dev.shindex f99a14690..c6f217595 100755--- a/scripts/e2e/playwright-dev.sh+++ b/scripts/e2e/playwright-dev.sh@@ -1,9 +1,9 @@#!/usr/bin/env bash# Launches the Desktop App Playwright E2E suite against the selected cluster.-# Assumes port-forwards are running for the same cluster:-# - control-api :8090-# - external-rest-api :8091-# - rpc-proxy :8094+# Assumes branch-profile port-forwards are running for the same cluster. The+# active URLs are read from the caller environment (normally ports.env emitted+# by Clerum's .local-notes/minikube-profiles/branch.mk); fixed shared defaults+# are retained only for the unscoped clerum-test profile.## Visual modes:# VISUAL=1 bash playwright-dev.sh chat.test.ts -g "MongoDB" # --debug inspector (step)@@ -15,47 +15,43 @@ set -eo pipefailHERE="$(cd "$(dirname "$0")" && pwd)"REPO="$(cd "$HERE/../.." && pwd)"-DEFAULT_CONTEXT="$(- kubectl config current-context 2>/dev/null || true-)"-if [[ -z "$DEFAULT_CONTEXT" ]]; then- DEFAULT_CONTEXT="clerum-test"-fi-KCTX="${KUBECONTEXT:-${E2E_K8S_CONTEXT:-$DEFAULT_CONTEXT}}"+# shellcheck source=scripts/e2e/load-dotenv.sh+source "$HERE/load-dotenv.sh"++CALLER_KUBECONTEXT="${KUBECONTEXT:-}"+CALLER_E2E_K8S_CONTEXT="${E2E_K8S_CONTEXT:-}"CALLER_CONTROL_API_BASE_URL="${CONTROL_API_BASE_URL:-}"+CALLER_CONTROL_API_URL="${CONTROL_API_URL:-}"+CALLER_E2E_CONTROL_API_URL="${E2E_CONTROL_API_URL:-}"CALLER_CONTROL_UI_BASE_URL="${CONTROL_UI_BASE_URL:-}"CALLER_CONTROL_UI_URL="${CONTROL_UI_URL:-}"CALLER_EXTERNAL_REST_API_BASE_URL="${EXTERNAL_REST_API_BASE_URL:-}"+CALLER_EXTERNAL_REST_API_URL="${EXTERNAL_REST_API_URL:-}"+CALLER_E2E_EXTERNAL_REST_API_URL="${E2E_EXTERNAL_REST_API_URL:-}"CALLER_RPC_PROXY_BASE_URL="${RPC_PROXY_BASE_URL:-}"+CALLER_RPC_PROXY_URL="${RPC_PROXY_URL:-}"+CALLER_E2E_RPC_PROXY_URL="${E2E_RPC_PROXY_URL:-}"CALLER_WORKFLOW_APPROVAL_READER_BASE_URL="${WORKFLOW_APPROVAL_READER_BASE_URL:-}"+CALLER_WORKFLOW_APPROVAL_READER_URL="${WORKFLOW_APPROVAL_READER_URL:-}"CALLER_MCP_HOST_RUNTIME_BASE_URL="${MCP_HOST_RUNTIME_BASE_URL:-}"--# Load .env so AIRTABLE_API_KEY + AIRTABLE_BASE_ID propagate to preflight.-# shellcheck disable=SC1090,SC1091-if [[ -f "$REPO/.env" ]]; then- set -a- . "$REPO/.env"- set +a-else- GIT_COMMON_DIR="$(cd "$REPO" && git rev-parse --git-common-dir 2>/dev/null || echo "")"- if [[ -n "$GIT_COMMON_DIR" ]]; then- case "$GIT_COMMON_DIR" in- /*) MAIN_REPO_DIR="$(cd "${GIT_COMMON_DIR}/.." && pwd)" ;;- *) MAIN_REPO_DIR="$(cd "${REPO}/${GIT_COMMON_DIR}/.." && pwd)" ;;- esac- if [[ -f "${MAIN_REPO_DIR}/.env" ]]; then- set -a- # shellcheck disable=SC1090- . "${MAIN_REPO_DIR}/.env"- set +a- fi- fi-fi-+CALLER_MCP_HOST_RUNTIME_URL="${MCP_HOST_RUNTIME_URL:-}"+CALLER_MCP_HOST_BASE_URL="${MCP_HOST_BASE_URL:-}"+# Load the canonical root .env as data so AIRTABLE_API_KEY + AIRTABLE_BASE_ID+# reach preflight without executing arbitrary dotenv content.+dotenv_load_canonical_root "$REPO"++[[ -n "$CALLER_KUBECONTEXT" ]] && export KUBECONTEXT="$CALLER_KUBECONTEXT"+[[ -n "$CALLER_E2E_K8S_CONTEXT" ]] && export E2E_K8S_CONTEXT="$CALLER_E2E_K8S_CONTEXT"if [[ -n "$CALLER_CONTROL_API_BASE_URL" ]]; thenexport CONTROL_API_BASE_URL="$CALLER_CONTROL_API_BASE_URL"fi+if [[ -n "$CALLER_CONTROL_API_URL" ]]; then+ export CONTROL_API_URL="$CALLER_CONTROL_API_URL"+fi+if [[ -n "$CALLER_E2E_CONTROL_API_URL" ]]; then+ export E2E_CONTROL_API_URL="$CALLER_E2E_CONTROL_API_URL"+fiif [[ -n "$CALLER_CONTROL_UI_BASE_URL" ]]; thenexport CONTROL_UI_BASE_URL="$CALLER_CONTROL_UI_BASE_URL"fi@@ -65,26 +61,54 @@ fiif [[ -n "$CALLER_EXTERNAL_REST_API_BASE_URL" ]]; thenexport EXTERNAL_REST_API_BASE_URL="$CALLER_EXTERNAL_REST_API_BASE_URL"fi+if [[ -n "$CALLER_EXTERNAL_REST_API_URL" ]]; then+ export EXTERNAL_REST_API_URL="$CALLER_EXTERNAL_REST_API_URL"+fi+if [[ -n "$CALLER_E2E_EXTERNAL_REST_API_URL" ]]; then+ export E2E_EXTERNAL_REST_API_URL="$CALLER_E2E_EXTERNAL_REST_API_URL"+fiif [[ -n "$CALLER_RPC_PROXY_BASE_URL" ]]; thenexport RPC_PROXY_BASE_URL="$CALLER_RPC_PROXY_BASE_URL"fi+if [[ -n "$CALLER_RPC_PROXY_URL" ]]; then+ export RPC_PROXY_URL="$CALLER_RPC_PROXY_URL"+fi+if [[ -n "$CALLER_E2E_RPC_PROXY_URL" ]]; then+ export E2E_RPC_PROXY_URL="$CALLER_E2E_RPC_PROXY_URL"+fiif [[ -n "$CALLER_WORKFLOW_APPROVAL_READER_BASE_URL" ]]; thenexport WORKFLOW_APPROVAL_READER_BASE_URL="$CALLER_WORKFLOW_APPROVAL_READER_BASE_URL"fi+if [[ -n "$CALLER_WORKFLOW_APPROVAL_READER_URL" ]]; then+ export WORKFLOW_APPROVAL_READER_URL="$CALLER_WORKFLOW_APPROVAL_READER_URL"+fiif [[ -n "$CALLER_MCP_HOST_RUNTIME_BASE_URL" ]]; thenexport MCP_HOST_RUNTIME_BASE_URL="$CALLER_MCP_HOST_RUNTIME_BASE_URL"fi+if [[ -n "$CALLER_MCP_HOST_RUNTIME_URL" ]]; then+ export MCP_HOST_RUNTIME_URL="$CALLER_MCP_HOST_RUNTIME_URL"+fi+if [[ -n "$CALLER_MCP_HOST_BASE_URL" ]]; then+ export MCP_HOST_BASE_URL="$CALLER_MCP_HOST_BASE_URL"+fi++DEFAULT_CONTEXT="$(kubectl config current-context 2>/dev/null || true)"+DEFAULT_CONTEXT="${DEFAULT_CONTEXT:-clerum-test}"+KCTX="${KUBECONTEXT:-${E2E_K8S_CONTEXT:-$DEFAULT_CONTEXT}}"# Preflight: ensure Airtable MCP is deployed + allowlisted in context1KUBECONTEXT="$KCTX" AIRTABLE_API_KEY="${AIRTABLE_API_KEY:-}" \bash "$HERE/playwright-preflight-dev.sh"-export CONTROL_API_BASE_URL="${CONTROL_API_BASE_URL:-http://127.0.0.1:8090}"+export CONTROL_API_BASE_URL="${CONTROL_API_BASE_URL:-${CONTROL_API_URL:-${E2E_CONTROL_API_URL:-http://127.0.0.1:8090}}}"export CONTROL_UI_BASE_URL="${CONTROL_UI_BASE_URL:-${CONTROL_UI_URL:-http://127.0.0.1:3000}}"-export EXTERNAL_REST_API_BASE_URL="${EXTERNAL_REST_API_BASE_URL:-http://127.0.0.1:8091}"-export RPC_PROXY_BASE_URL="${RPC_PROXY_BASE_URL:-http://127.0.0.1:8094}"-export WORKFLOW_APPROVAL_READER_BASE_URL="${WORKFLOW_APPROVAL_READER_BASE_URL:-http://127.0.0.1:8098}"-export MCP_HOST_RUNTIME_BASE_URL="${MCP_HOST_RUNTIME_BASE_URL:-http://127.0.0.1:8080}"+export EXTERNAL_REST_API_BASE_URL="${EXTERNAL_REST_API_BASE_URL:-${EXTERNAL_REST_API_URL:-${E2E_EXTERNAL_REST_API_URL:-http://127.0.0.1:8091}}}"+export E2E_EXTERNAL_REST_API_URL="${E2E_EXTERNAL_REST_API_URL:-$EXTERNAL_REST_API_BASE_URL}"+export RPC_PROXY_BASE_URL="${RPC_PROXY_BASE_URL:-${RPC_PROXY_URL:-${E2E_RPC_PROXY_URL:-http://127.0.0.1:8094}}}"+export E2E_RPC_PROXY_URL="${E2E_RPC_PROXY_URL:-$RPC_PROXY_BASE_URL}"+export WORKFLOW_APPROVAL_READER_BASE_URL="${WORKFLOW_APPROVAL_READER_BASE_URL:-${WORKFLOW_APPROVAL_READER_URL:-http://127.0.0.1:8098}}"+export MCP_HOST_RUNTIME_BASE_URL="${MCP_HOST_RUNTIME_BASE_URL:-${MCP_HOST_RUNTIME_URL:-${MCP_HOST_BASE_URL:-http://127.0.0.1:8080}}}"+export MCP_HOST_BASE_URL="${MCP_HOST_BASE_URL:-$MCP_HOST_RUNTIME_BASE_URL}"export E2E_DEV_LOGIN_EMAIL="${E2E_DEV_LOGIN_EMAIL:[email protected]}"# approval-flow.test.ts and global setup use this to enforce cluster/url alignment.# approval-flow.test.ts uses this to target the right cluster (default is minikube).@@ -138,16 +162,6 @@ if [[ "${E2E_SKIP_DESKTOP_BUILD:-0}" != "1" ]]; thennpm run buildfi-if [[ "$E2E_K8S_CONTEXT" == "gke_your-gcp-project_us-central1-a_example-dev" ]] && \- [[ "$CONTROL_API_BASE_URL" =~ ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?(/|$) ]] && \- [[ "$EXTERNAL_REST_API_BASE_URL" =~ ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?(/|$) ]] && \- [[ "$RPC_PROXY_BASE_URL" =~ ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?(/|$) ]] && \- { [[ "${E2E_WORKFLOW_APPROVAL_QUADRANTS:-0}" != "1" ]] || \- { [[ "$WORKFLOW_APPROVAL_READER_BASE_URL" =~ ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?(/|$) ]] && \- [[ "$MCP_HOST_RUNTIME_BASE_URL" =~ ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?(/|$) ]]; }; }; then- export E2E_ALLOW_DEV_PORT_FORWARD="${E2E_ALLOW_DEV_PORT_FORWARD:-1}"-fi-EXTRA_FLAGS=()if [[ "${VISUAL:-0}" == "1" ]]; thenecho "[playwright-dev] VISUAL=1 → enabling Playwright Inspector (step-by-step)"diff --git a/scripts/e2e/seed-e2e-data.sh b/scripts/e2e/seed-e2e-data.shindex eb22d650f..5090b807b 100755--- a/scripts/e2e/seed-e2e-data.sh+++ b/scripts/e2e/seed-e2e-data.sh@@ -99,8 +99,21 @@ PLUGIN_SDK_DEMO_RECIPE_NS="${E2E_PLUGIN_SDK_DEMO_RECIPE_NS:-sandbox-recipes}"PLUGIN_SDK_DEMO_RECIPE_NAME="${E2E_PLUGIN_SDK_DEMO_RECIPE_NAME:-${E2E_SANDBOX_UI_RECIPE:-evenfire-prompt-notify-app}}"PLUGIN_SDK_DEMO_EVENT_TYPE="${E2E_PLUGIN_SDK_DEMO_EVENT_TYPE:-fullstack.prompt.notify}"PLUGIN_SDK_DEMO_CALLER_REF="${E2E_PLUGIN_SDK_DEMO_CALLER_REF:-backend}"-PLUGIN_SDK_DEMO_MODEL_NAME="${E2E_PLUGIN_SDK_DEMO_MODEL_NAME:-${E2E_WORKFLOW_MODEL_NAME:-${CLERUM_MODEL_NAME:-glm-4.7}}}"-PLUGIN_SDK_DEMO_PROVIDER="${E2E_PLUGIN_SDK_DEMO_PROVIDER:-${CLERUM_MODEL_PROVIDER:-zai}}"+PLUGIN_SDK_DEMO_PROVIDER="${E2E_PLUGIN_SDK_DEMO_PROVIDER:-}"+if [ -z "$PLUGIN_SDK_DEMO_PROVIDER" ]; then+ case "${CLERUM_MODEL_PROVIDER:-}" in+ openai|claude) PLUGIN_SDK_DEMO_PROVIDER="$CLERUM_MODEL_PROVIDER" ;;+ *) PLUGIN_SDK_DEMO_PROVIDER="openai" ;;+ esac+fi+PLUGIN_SDK_DEMO_MODEL_NAME="${E2E_PLUGIN_SDK_DEMO_MODEL_NAME:-${E2E_WORKFLOW_MODEL_NAME:-}}"+if [ -z "$PLUGIN_SDK_DEMO_MODEL_NAME" ]; then+ case "$PLUGIN_SDK_DEMO_PROVIDER" in+ openai) PLUGIN_SDK_DEMO_MODEL_NAME="gpt-5.4-mini" ;;+ claude) PLUGIN_SDK_DEMO_MODEL_NAME="claude-sonnet-4-6" ;;+ *) die "Plugin SDK demo provider '$PLUGIN_SDK_DEMO_PROVIDER' requires explicit E2E_PLUGIN_SDK_DEMO_MODEL_NAME" ;;+ esac+fiPLUGIN_SDK_DEMO_TARGET_REF="${E2E_PLUGIN_SDK_DEMO_TARGET_REF:-primary}"PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="${E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT:-}"PLUGIN_SDK_DEMO_PROMPT_MAX="${E2E_PLUGIN_SDK_DEMO_PROMPT_MAX_REQUESTS:-50}"diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex 7726935e8..0f258a30a 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -200,6 +200,36 @@ provision_gfs_serving() {sync_mcp_host_auth_key}+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.+ # This check deliberately does not infer a provider, model, slot, or order;+ # migration remains an explicit operator-reviewed action.+ local legacy_count query+ query="+ SELECT count(*)::int+ FROM plugin_workload_sdk_grants+ WHERE capability_family = 'promptBridge'+ AND policy_state <> 'active';+ "+ # Keep the command after `kubectl exec --` on the same continued shell+ # command. A bare newline after `--` makes kubectl receive no command and+ # then runs `psql` on the host, producing a misleading local-socket error.+ legacy_count="$(${KC} exec -n control-plane deployment/control-postgres -- \+ psql -U postgres -d profiles -Atqc "${query}")"+ legacy_count="$(printf '%s' "${legacy_count}" | tr -d '[:space:]')"+ if [[ ! "${legacy_count}" =~ ^[0-9]+$ ]]; then+ log "ERROR: unable to inventory legacy promptBridge grants; refusing target-aware rollout"+ return 1+ fi+ if [[ "${legacy_count}" != "0" ]]; then+ log "ERROR: ${legacy_count} legacy promptBridge grant(s) require operator-reviewed target migration before mcp-host rollout"+ return 1+ fi+ log "Legacy promptBridge grant inventory is empty"+}+log "Evaluating sync requirements for ${GATE_NAME}"preflight_host_lifecycle_probe@@ -312,6 +342,9 @@ if [[ "${cluster_changed}" == "true" ]]; thenprovision_gfs_servingfi+ # Release invariant: every path that can restart/serve mcp-host proves that+ # no legacy grant is routable, not only the migration path.+ assert_no_legacy_prompt_bridge_grantsensure_evenfire_registryincremental_restart_targets@@ -343,6 +376,7 @@ if [[ "${cluster_changed}" == "true" ]]; thenlog "Pre-gate cluster sync complete"elselog "No cluster sync required before ${GATE_NAME}"+ assert_no_legacy_prompt_bridge_grantsensure_evenfire_registry${KC} get deploy -A --no-headers 2>/dev/null | grep -v kube-system || truefidiff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.shindex eb60d8080..866a9b2f7 100755--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh@@ -159,4 +159,11 @@ elsefail "pre-gate sync can couple unrelated gates to the sibling registry"fi+if contains "deployment/control-postgres -- \\" &&+ contains 'psql -U postgres -d profiles -Atqc "${query}"'; then+ pass "legacy grant inventory keeps the kubectl exec command intact"+else+ fail "legacy grant inventory can execute psql on the host instead of PostgreSQL"+fi+exit "$FAIL"diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex fed15dfad..9b9f870de 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.261",+ "version": "0.1.262","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.261",+ "version": "0.1.262","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 3a2048c90..96809a20c 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.261",+ "version": "0.1.262","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.tsindex d7294f9ae..0d594b6ce 100644--- a/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts+++ b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts@@ -1,5 +1,10 @@import { describe, expect, it, vi } from 'vitest'-import { ClerumMcpServer, revalidatePluginSdkCredentialTicket } from './server'+import {+ ClerumMcpServer,+ bindPluginSdkCredentialTarget,+ pluginSdkCredentialTargetEchoMatches,+ revalidatePluginSdkCredentialTicket,+} from './server'function response(status: number, body: unknown): Response {return new Response(JSON.stringify(body), {@@ -9,6 +14,20 @@ function response(status: number, body: unknown): Response {}describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {+ it('denies a body target mismatch before the resolver and returns only signed claims', () => {+ const signedTarget = {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+ }+ const mismatched = { ...signedTarget, provider: 'claude' }+ expect(bindPluginSdkCredentialTarget(signedTarget, mismatched)).toBeNull()+ expect(bindPluginSdkCredentialTarget(signedTarget, signedTarget)).toEqual(signedTarget)+ expect(pluginSdkCredentialTargetEchoMatches(signedTarget, mismatched)).toBe(false)+ expect(pluginSdkCredentialTargetEchoMatches(signedTarget, signedTarget)).toBe(true)+ })+it('consumes each verified ticket jti only once within its TTL', () => {const server = new ClerumMcpServer({} as never, 8082, {} as never, 'sandbox-recipes')const consume = (@@ -26,6 +45,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {runtimeToken: 'runtime-jwt',credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',fetchImpl: fetchImpl as unknown as typeof fetch,controlApiBaseUrl: 'http://control-api:8090/',@@ -39,6 +61,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {expect(JSON.parse(String(init.body))).toEqual({credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',})})@@ -50,6 +75,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {runtimeToken: 'runtime-jwt',credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-2',+ providerAttemptIndex: 2,targetRef: 'fallback-openai',redeem: true,fetchImpl: fetchImpl as unknown as typeof fetch,@@ -59,6 +87,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {expect(JSON.parse(String(init.body))).toEqual({credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-2',+ providerAttemptIndex: 2,targetRef: 'fallback-openai',redeem: true,})@@ -75,6 +106,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {runtimeToken: 'runtime-jwt',credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',fetchImpl: fetchImpl as unknown as typeof fetch,controlApiBaseUrl: 'http://control-api:8090',@@ -89,6 +123,9 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {runtimeToken: 'runtime-jwt',credentialTicket: 'signed-ticket',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',fetchImpl: fetchImpl as unknown as typeof fetch,})diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.tsindex 07a0cf55f..01df28cfd 100644--- a/workflow-recipes/src/mcp/server.ts+++ b/workflow-recipes/src/mcp/server.ts@@ -42,11 +42,51 @@ const MAX_BODY_BYTES = 512 * 1024 // 512KBconst CONTROL_API_BASE_URL =process.env.CONTROL_API_BASE_URL || 'http://control-api.control-plane.svc.cluster.local:8090'+/**+ * Bind a credential request to the already verified signed-ticket target.+ * Callers may echo the target for diagnostics, but the resolver must receive+ * only these ticket claims. A mismatch is denied before any Secret lookup.+ */+export function bindPluginSdkCredentialTarget(+ ticketTarget: PluginSdkCredentialTarget,+ bodyTarget: PluginSdkCredentialTarget+): PluginSdkCredentialTarget | null {+ if (+ ticketTarget.targetRef !== bodyTarget.targetRef ||+ ticketTarget.provider !== bodyTarget.provider ||+ ticketTarget.model !== bodyTarget.model ||+ ticketTarget.credentialSlot !== bodyTarget.credentialSlot+ ) {+ return null+ }+ return { ...ticketTarget }+}++/**+ * The request may echo the target for diagnostics, but this predicate is+ * never an authority source. The signed ticket remains the only value used by+ * revalidation and Secret resolution (see the broker route below).+ */+export function pluginSdkCredentialTargetEchoMatches(+ signedTarget: PluginSdkCredentialTarget,+ bodyTarget: PluginSdkCredentialTarget+): boolean {+ return (+ signedTarget.targetRef === bodyTarget.targetRef &&+ signedTarget.provider === bodyTarget.provider &&+ signedTarget.model === bodyTarget.model &&+ signedTarget.credentialSlot === bodyTarget.credentialSlot+ )+}+export async function revalidatePluginSdkCredentialTicket(input: {runtimeToken: stringcredentialTicket: stringinvocationId: stringtargetRef: string+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: number/** Consume the control-plane jti after the Secret read, not during preflight. */redeem?: booleanfetchImpl?: typeof fetch@@ -66,6 +106,9 @@ export async function revalidatePluginSdkCredentialTicket(input: {credentialTicket: input.credentialTicket,invocationId: input.invocationId,targetRef: input.targetRef,+ attemptGeneration: input.attemptGeneration,+ providerAttemptId: input.providerAttemptId,+ providerAttemptIndex: input.providerAttemptIndex,...(input.redeem ? { redeem: true } : {}),}),}@@ -423,6 +466,12 @@ export class ClerumMcpServer {if (body.recipeNamespace !== this.sandboxNamespace ||typeof body.invocationId !== 'string' ||+ !Number.isInteger(body.attemptGeneration) ||+ Number(body.attemptGeneration) < 1 ||+ typeof body.providerAttemptId !== 'string' ||+ !body.providerAttemptId ||+ !Number.isInteger(body.providerAttemptIndex) ||+ Number(body.providerAttemptIndex) < 1 ||!target ||typeof target.targetRef !== 'string' ||typeof target.provider !== 'string' ||@@ -443,15 +492,24 @@ export class ClerumMcpServer {res.end(JSON.stringify({ error: 'Credential ticket denied' }))return}- const ticketMatches =- ticket.recipeName === recipeName &&- ticket.recipeNamespace === this.sandboxNamespace &&- ticket.invocationId === body.invocationId &&- ticket.targetRef === target.targetRef &&- ticket.provider === target.provider &&- ticket.model === target.model &&- ticket.credentialSlot === target.credentialSlot- if (!ticketMatches) {+ // Derive the resolver target directly from the verified JWT claims.+ // `target` is an untrusted diagnostic echo and must not flow into any+ // policy, revalidation, or Secret-resolution operation.+ const signedTarget: PluginSdkCredentialTarget = {+ targetRef: ticket.targetRef,+ provider: ticket.provider,+ model: ticket.model,+ credentialSlot: ticket.credentialSlot,+ }+ if (+ ticket.recipeName !== recipeName ||+ ticket.recipeNamespace !== this.sandboxNamespace ||+ ticket.invocationId !== body.invocationId ||+ ticket.attemptGeneration !== Number(body.attemptGeneration) ||+ ticket.providerAttemptId !== body.providerAttemptId ||+ ticket.providerAttemptIndex !== Number(body.providerAttemptIndex) ||+ !pluginSdkCredentialTargetEchoMatches(signedTarget, target)+ ) {res.writeHead(403, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ error: 'Credential ticket denied' }))return@@ -460,12 +518,6 @@ export class ClerumMcpServer {// is verified, use its claims as the sole identity passed to the// Secret resolver and to all subsequent policy revalidation calls.const boundInvocationId = ticket.invocationId- const boundTarget: PluginSdkCredentialTarget = {- targetRef: ticket.targetRef,- provider: ticket.provider,- model: ticket.model,- credentialSlot: ticket.credentialSlot,- }// TOCTOU gate: ticket signature proves what was authorized, while this// control-api read proves that the invocation and policy revision/hash// are still current immediately before the Secret lookup.@@ -473,7 +525,10 @@ export class ClerumMcpServer {runtimeToken,credentialTicket: body.credentialTicket,invocationId: boundInvocationId,- targetRef: boundTarget.targetRef,+ targetRef: signedTarget.targetRef,+ attemptGeneration: ticket.attemptGeneration,+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,})if (!ticketStillActive) {res.writeHead(403, { 'Content-Type': 'application/json' })@@ -485,7 +540,7 @@ export class ClerumMcpServer {res.end(JSON.stringify({ error: 'Credential broker unavailable' }))return}- const result = await this.modelConfigHandler.resolvePluginSdkCredential(boundTarget)+ const result = await this.modelConfigHandler.resolvePluginSdkCredential(signedTarget)// Re-check after the Secret read as well as before it. Control API// and the WRC Secret store are separate systems, so a single remote// check cannot be atomic with the read; the post-read gate ensures a@@ -495,7 +550,10 @@ export class ClerumMcpServer {runtimeToken,credentialTicket: body.credentialTicket,invocationId: boundInvocationId,- targetRef: boundTarget.targetRef,+ targetRef: signedTarget.targetRef,+ attemptGeneration: ticket.attemptGeneration,+ providerAttemptId: ticket.providerAttemptId,+ providerAttemptIndex: ticket.providerAttemptIndex,redeem: true,})if (!ticketStillActiveAfterResolve) {diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.tsindex 31ecb111d..a37eefdcc 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import type { PluginWorkloadSdkSpec, WorkflowRecipeSpec } from '../types'import {PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE,buildPluginWorkloadSdkStatus,validatePluginWorkloadSdkSpec,@@ -163,7 +164,22 @@ describe('validatePluginWorkloadSdkSpec', () => {baseSpec({ promptBridge: {} }, { agent: undefined }))expect(errors).toHaveLength(1)- expect(errors[0]).toContain('promptBridge requires a resolvable agent')+ expect(errors[0]).toContain(+ 'promptBridge requires spec.agent or a step agent with provider + model'+ )+ })++ it('rejects promptBridge when the resolved agent model is outside the runnable grammar', () => {+ const errors = validatePluginWorkloadSdkSpec(+ baseSpec({ promptBridge: {} }, { agent: { provider: 'openai', model: 'model with spaces' } })+ )+ expect(errors).toHaveLength(2)+ expect(errors).toContain(+ 'spec.agent.model must be a valid runnable model id when spec.agent is declared'+ )+ expect(errors).toContain(+ 'pluginWorkloadSdk.promptBridge requires spec.agent or a step agent with provider + model'+ )})it('accepts promptBridge when only a step agent provides provider + model', () => {@@ -271,6 +287,19 @@ describe('buildPluginWorkloadSdkStatus', () => {existingConditions: undefined,phase: 'active',featureFlagEnabled: true,+ bootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'pod-uid-1',+ provider: 'zai',+ model: 'glm-4.7',+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-zai',+ defaultProvider: 'zai',+ defaultModel: 'glm-4.7',+ verifiedAt: NOW,+ },now: NOW,})expect(projection.conditions).toEqual([@@ -283,10 +312,18 @@ describe('buildPluginWorkloadSdkStatus', () => {},])expect(projection.capability).toEqual({+ bootstrapContractVersion: 2,+ bootstrapModel: 'glm-4.7',+ bootstrapPodUid: 'pod-uid-1',+ bootstrapProvider: 'zai',+ clientNotifications: true,+ defaultTargetRef: 'primary-zai',+ policyHash: 'a'.repeat(64),+ policyRevision: 1,state: 'validated',promptBridge: true,- clientNotifications: true,validatedAt: NOW,+ verifiedAt: NOW,})})@@ -323,6 +360,49 @@ describe('buildPluginWorkloadSdkStatus', () => {})})+ it('projects a missing operator grant as awaiting_policy, not provider_unavailable', () => {+ const projection = buildPluginWorkloadSdkStatus({+ spec: baseSpec({ promptBridge: {} }),+ existingConditions: undefined,+ phase: 'active',+ featureFlagEnabled: true,+ policyPending: true,+ bootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'pod-uid-1',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ verifiedAt: NOW,+ },+ now: NOW,+ })+ expect(projection.conditions).toEqual([+ {+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'PolicyNotConfigured',+ message: 'Plugin Workload SDK promptBridge is awaiting an operator grant',+ lastTransitionTime: NOW,+ },+ {+ type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,+ status: 'True',+ reason: 'grant_missing',+ message: 'Plugin Workload SDK promptBridge is awaiting an operator grant',+ lastTransitionTime: NOW,+ },+ ])+ expect(projection.capability).toMatchObject({+ state: 'awaiting_policy',+ promptBridge: true,+ clientNotifications: false,+ })+ })+it('carries forward existing owned conditions when reconcile failed', () => {const existing = {type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,@@ -341,4 +421,16 @@ describe('buildPluginWorkloadSdkStatus', () => {expect(projection.conditions).toEqual([existing])expect(projection.capability).toBeUndefined()})++ it('does not project disabled when flag-off teardown failed', () => {+ const projection = buildPluginWorkloadSdkStatus({+ spec: baseSpec({ promptBridge: {} }),+ existingConditions: undefined,+ phase: 'failed',+ featureFlagEnabled: false,+ now: NOW,+ })+ expect(projection.capability).toBeUndefined()+ expect(projection.conditions).toEqual([])+ })})diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.tsindex b1ab38408..c761f6094 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts@@ -23,6 +23,7 @@ export const DEFAULT_IDEMPOTENCY_KEY_PATTERN = '^[a-zA-Z0-9_-]{1,128}$'export const PLUGIN_WORKLOAD_SDK_CONDITION_TYPE = 'PluginWorkloadSdkCapability'export const PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE ='PluginWorkloadSdkProviderUnavailable'+export const PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE = 'PluginWorkloadSdkPolicyPending'/*** WorkflowRecipe remains the CRD that carries Plugin Workload SDK, but an SDK@@ -120,13 +121,23 @@ export function validatePluginWorkloadSdkSpec(spec: WorkflowRecipeSpec): string[errors)+ if (spec.agent !== undefined) {+ if (!spec.agent.provider) {+ errors.push('spec.agent.provider is required when spec.agent is declared')+ }+ if (!isRunnableLlmModelId(spec.agent.model)) {+ errors.push('spec.agent.model must be a valid runnable model id when spec.agent is declared')+ }+ }+// promptBridge issues real LLM calls, so the recipe must declare a resolvable- // agent (provider + model) — either spec.agent or a step agent. The WRC uses- // it to broker the provider API key into the eager mcp-host. clientNotifications- // needs no provider, so this rule is scoped to promptBridge only.+ // agent (provider + model). A stepless SDK recipe uses spec.agent as the+ // eager mcp-host bootstrap binding; a workflow may instead resolve a step+ // agent. clientNotifications needs no provider, so this rule is scoped to+ // promptBridge only.if (sdk.promptBridge && !hasResolvableAgent(spec)) {errors.push(- 'pluginWorkloadSdk.promptBridge requires a resolvable agent (spec.agent or a step agent with provider + model)'+ 'pluginWorkloadSdk.promptBridge requires spec.agent or a step agent with provider + model')}@@ -168,6 +179,23 @@ export interface PluginWorkloadSdkStatusProjection {capability: PluginWorkloadSdkCapabilityStatus | null | undefined}+export interface PluginWorkloadSdkBootstrapProofInput {+ ready: true+ contractVersion: 2+ podUid: string+ provider: string+ model: string+ policyReady?: boolean+ policyState?: string+ policyReason?: string+ policyRevision?: number+ policyHash?: string+ defaultTargetRef?: string+ defaultProvider?: string+ defaultModel?: string+ verifiedAt: string+}+/*** Project `spec.pluginWorkloadSdk` + feature flag + reconcile outcome into* the status condition and capability record.@@ -178,7 +206,10 @@ export interface PluginWorkloadSdkStatusProjection {* - reconcile failed → carry forward existing owned conditions untouched and* leave the persisted capability as-is (a transient infra failure must not* flip an already-validated capability)- * - reconcile succeeded → condition True/Validated, state 'validated'+ * - eager host identity is ready but the operator prompt policy is absent or+ * unusable → condition False/PolicyNotConfigured, state 'awaiting_policy'+ * - reconcile succeeded with an active prompt policy → condition True/Validated,+ * state 'validated'*/export function buildPluginWorkloadSdkStatus(args: {spec: WorkflowRecipeSpec@@ -186,9 +217,22 @@ export function buildPluginWorkloadSdkStatus(args: {phase: RecipePhasefeatureFlagEnabled: booleanproviderUnavailable?: boolean+ policyPending?: boolean+ teardownConfirmed?: boolean+ bootstrapProof?: PluginWorkloadSdkBootstrapProofInputnow: string}): PluginWorkloadSdkStatusProjection {- const { spec, existingConditions, phase, featureFlagEnabled, providerUnavailable, now } = args+ const {+ spec,+ existingConditions,+ phase,+ featureFlagEnabled,+ providerUnavailable,+ policyPending,+ teardownConfirmed,+ bootstrapProof,+ now,+ } = argsconst sdk = spec.pluginWorkloadSdkif (!sdk) {@@ -198,6 +242,17 @@ export function buildPluginWorkloadSdkStatus(args: {const promptBridge = sdk.promptBridge !== undefinedconst clientNotifications = sdk.clientNotifications !== undefined+ // A failed reconcile must never be projected as a successful disable. In+ // particular, the SDK kill-switch performs cleanup before this projection;+ // if cleanup failed, reporting `disabled` could leave an old host reachable+ // while claiming revocation completed.+ if (phase === 'failed' && !(teardownConfirmed === true && !featureFlagEnabled)) {+ const carried = (existingConditions ?? []).filter(+ c => c.type === PLUGIN_WORKLOAD_SDK_CONDITION_TYPE+ )+ return { conditions: carried, capability: undefined }+ }+if (!featureFlagEnabled) {const message = 'Disabled (feature flag off)'return {@@ -219,13 +274,6 @@ export function buildPluginWorkloadSdkStatus(args: {}}- if (phase === 'failed') {- const carried = (existingConditions ?? []).filter(- c => c.type === PLUGIN_WORKLOAD_SDK_CONDITION_TYPE- )- return { conditions: carried, capability: undefined }- }-if (providerUnavailable) {const message = 'Capability validated, but the configured provider is unavailable'return {@@ -254,6 +302,67 @@ export function buildPluginWorkloadSdkStatus(args: {}}+ if (promptBridge && policyPending) {+ 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'})`+ return {+ conditions: [+ {+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'PolicyNotConfigured',+ message,+ lastTransitionTime: now,+ },+ {+ type: PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,+ status: 'True',+ reason: bootstrapProof?.policyReason ?? 'PolicyNotReady',+ message,+ lastTransitionTime: now,+ },+ ],+ capability: {+ state: 'awaiting_policy',+ promptBridge,+ clientNotifications,+ message,+ ...(bootstrapProof+ ? {+ bootstrapContractVersion: bootstrapProof.contractVersion,+ bootstrapPodUid: bootstrapProof.podUid,+ bootstrapProvider: bootstrapProof.provider,+ bootstrapModel: bootstrapProof.model,+ verifiedAt: bootstrapProof.verifiedAt,+ }+ : {}),+ },+ }+ }++ if (promptBridge && !bootstrapProof?.ready) {+ const message = 'promptBridge bootstrap policy proof is not ready'+ return {+ conditions: [+ {+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ status: 'False',+ reason: 'BootstrapNotReady',+ message,+ lastTransitionTime: now,+ },+ ],+ capability: {+ state: 'degraded',+ promptBridge,+ clientNotifications,+ message,+ },+ }+ }+const families = [promptBridge ? 'promptBridge' : undefined,clientNotifications ? 'clientNotifications' : undefined,@@ -276,6 +385,24 @@ export function buildPluginWorkloadSdkStatus(args: {promptBridge,clientNotifications,validatedAt: now,+ ...(bootstrapProof+ ? {+ bootstrapContractVersion: bootstrapProof.contractVersion,+ bootstrapPodUid: bootstrapProof.podUid,+ bootstrapProvider: bootstrapProof.provider,+ bootstrapModel: bootstrapProof.model,+ verifiedAt: bootstrapProof.verifiedAt,+ ...(bootstrapProof.policyRevision !== undefined+ ? { policyRevision: bootstrapProof.policyRevision }+ : {}),+ ...(bootstrapProof.policyHash !== undefined+ ? { policyHash: bootstrapProof.policyHash }+ : {}),+ ...(bootstrapProof.defaultTargetRef !== undefined+ ? { defaultTargetRef: bootstrapProof.defaultTargetRef }+ : {}),+ }+ : {}),},}}diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.tsindex a0d2fdaf5..0145b1417 100644--- a/workflow-recipes/src/reconciler/reconciler.test.ts+++ b/workflow-recipes/src/reconciler/reconciler.test.ts@@ -363,6 +363,49 @@ describe('WorkflowRecipeReconciler', () => {expect(workflowReconcile).not.toHaveBeenCalled()})+ it('tears down an existing SDK-only host when the global feature flag is disabled', async () => {+ const cleanupPluginWorkloadSdkOnly = vi.fn().mockResolvedValue(undefined)+ const workflowReconcile = vi.fn()+ ;(+ reconciler as unknown as {+ config: { pluginWorkloadSdkEnabled: boolean }+ workflowReconciler: {+ reconcile: typeof workflowReconcile+ cleanupPluginWorkloadSdkOnly: typeof cleanupPluginWorkloadSdkOnly+ }+ }+ ).config.pluginWorkloadSdkEnabled = false+ ;(+ reconciler as unknown as {+ workflowReconciler: {+ reconcile: typeof workflowReconcile+ cleanupPluginWorkloadSdkOnly: typeof cleanupPluginWorkloadSdkOnly+ }+ }+ ).workflowReconciler = { reconcile: workflowReconcile, cleanupPluginWorkloadSdkOnly }++ const result = await reconciler.reconcile(+ makeRecipe({+ status: {+ phase: 'active',+ pluginWorkloadSdk: { state: 'validated', promptBridge: true, clientNotifications: false },+ },+ spec: {+ workloads: [{ id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 }],+ pluginWorkloadSdk: { promptBridge: {}, allowedCallers: ['app'] },+ },+ })+ )++ expect(result).toMatchObject({+ phase: 'active',+ pluginWorkloadSdkTeardownConfirmed: true,+ message: 'Plugin Workload SDK disabled after confirmed teardown',+ })+ expect(cleanupPluginWorkloadSdkOnly).toHaveBeenCalledWith('test-recipe')+ expect(workflowReconcile).not.toHaveBeenCalled()+ })+it('degrades an active recipe when observed child Deployment readiness drifts', async () => {mockAppsApi.readNamespacedDeployment.mockResolvedValue({metadata: { resourceVersion: '1', generation: 1 },@@ -1280,6 +1323,18 @@ describe('WorkflowRecipeReconciler', () => {expect(deploymentRule?.verbs).not.toContain('patch')})+ it('allows only read access to Service endpoints for SDK teardown absence checks', () => {+ const role = workflowRecipesRole(+ 'deploy/base/sandbox-recipes/rbac.yaml',+ 'sandbox-recipes',+ 'workflow-recipes-sandbox'+ )+ const endpointsRule = role.rules?.find(+ rule => rule.apiGroups?.includes('') && rule.resources?.includes('endpoints')+ )+ expect(endpointsRule?.verbs).toEqual(['get'])+ })+it('grants patch only on apps/statefulsets in mcp-server', () => {const role = workflowRecipesRole('deploy/base/mcp-server/rbac.yaml', 'mcp-server')const statefulSetRule = role.rules?.find(@@ -1430,6 +1485,19 @@ describe('WorkflowRecipeReconciler', () => {message: 'All workloads deployed',workloadStatuses: [],pluginWorkloadSdkProviderUnavailable: false,+ pluginWorkloadSdkBootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'mcp-host-pod-uid',+ provider: 'zai',+ model: 'glm-4.7',+ policyRevision: 3,+ policyHash: 'sha256:policy',+ defaultTargetRef: 'zai/glm-4.7',+ defaultProvider: 'zai',+ defaultModel: 'glm-4.7',+ verifiedAt: new Date().toISOString(),+ },})const recoveredPatch =mockCustomApi.patchNamespacedCustomObjectStatus.mock.calls.at(-1)![0].bodydiff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex 6dc644df7..d7c6801de 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -42,6 +42,8 @@ import { JwtTokenFactory } from '../workflow/jwtTokenFactory'import { K8sSecretReaderImpl } from '../workflow/k8sSecretReaderImpl'import { ModelConfigHandler } from '../workflow/modelConfigHandler'import { buildCoordinatorGfsNetworkPolicy } from '../workflow/networkPolicyFactory'+import type { EagerSdkBootstrapProof } from '../workflow/pluginWorkloadSdkProvisioner'+import { HttpPluginWorkloadSdkRevocationClient } from '../workflow/pluginWorkloadSdkRevocationClient'import { deriveWorkflowRuntimePlan } from '../workflow/runtimePlan'import { validateWorkflowRecipeLimits } from '../workflow/workflowLimits'import {@@ -80,6 +82,7 @@ import {import { issueOAuthBrokerToken } from './oauthBrokerTokenIssuerClient'import {PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE,buildPluginWorkloadSdkStatus,validatePluginWorkloadSdkSpec,@@ -239,6 +242,7 @@ function mergeSecretOwnershipConditions(const PLUGIN_WORKLOAD_SDK_CONDITION_TYPES = new Set([PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,+ PLUGIN_WORKLOAD_SDK_POLICY_PENDING_CONDITION_TYPE,PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE,])@@ -492,6 +496,11 @@ export interface ReconcileResult {workloadConditions?: StatusCondition[]/** SDK-only eager-host provider health, kept separate from workflow phase. */pluginWorkloadSdkProviderUnavailable?: boolean+ /** SDK host identity is ready, but an operator prompt policy is not active yet. */+ pluginWorkloadSdkPolicyPending?: boolean+ /** Cleanup completed successfully while the SDK feature flag was off. */+ pluginWorkloadSdkTeardownConfirmed?: boolean+ pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProofworkflowPhase?: import('../workflow/types').WorkflowPhaseclearWorkflowExecution?: boolean/** When true, the caller should NOT patch the CRD status — the phase hasn't changed. */@@ -747,6 +756,7 @@ export class WorkflowRecipeReconciler {new K8sSecretReaderImpl(this.coreApi),new HttpMcpHostClient()),+ pluginWorkloadSdkRevocationClient: new HttpPluginWorkloadSdkRevocationClient(),}this.workflowReconciler = new WorkflowReconciler(deps)console.log('[WR-Reconciler] Workflow subsystem initialized')@@ -756,6 +766,19 @@ export class WorkflowRecipeReconciler {return { customApi: this.customApi, coreApi: this.coreApi }}+ /**+ * SDK revocation is fail-closed: an uninitialised workflow subsystem is not+ * equivalent to a successful cleanup. Refusing to report the capability as+ * disabled keeps a stale host/token reachable only behind an explicit+ * requeue, until the cleanup dependency is available and converges.+ */+ private async cleanupPluginWorkloadSdkOnlyOrThrow(recipeName: string): Promise<void> {+ if (!this.workflowReconciler) {+ throw new Error('workflow subsystem is not initialized; SDK cleanup cannot be confirmed')+ }+ await this.workflowReconciler.cleanupPluginWorkloadSdkOnly(recipeName)+ }+private async waitForTransportNetworkReadiness(recipe: WorkflowRecipeCRD,preDeployedServers: string[],@@ -1240,14 +1263,22 @@ export class WorkflowRecipeReconciler {// intentionally restricted to the stepless adapter.if (!isWorkflow && recipe.spec.pluginWorkloadSdk && !this.config.pluginWorkloadSdkEnabled) {try {- await this.workflowReconciler?.cleanupPluginWorkloadSdkOnly(name)+ await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)} catch (error) {return {phase: 'failed' as RecipePhase,message: `Plugin Workload SDK teardown failed while the feature flag is disabled: ${String(error)}`,workloadStatuses: [],+ skipStatusPatch: true,+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,}}+ return {+ phase: currentPhase,+ message: 'Plugin Workload SDK disabled after confirmed teardown',+ workloadStatuses: [],+ pluginWorkloadSdkTeardownConfirmed: true,+ }}if (isWorkflow) {// Revocation must precede spec/policy validation: an invalid edit that also@@ -1729,6 +1760,8 @@ export class WorkflowRecipeReconciler {clearWorkflowExecution: result.clearWorkflowExecution,workflowConditions: result.workflowConditions,workloadConditions: workflowWorkloadConditions,+ pluginWorkloadSdkBootstrapProof: result.pluginWorkloadSdkBootstrapProof,+ pluginWorkloadSdkPolicyPending: result.pluginWorkloadSdkPolicyPending,// Thread the inner reconciler's transient-skip up so the watcher leaves// status untouched and requeues instead of patching a false failure.skipStatusPatch: result.skipStatusPatch,@@ -1752,10 +1785,12 @@ export class WorkflowRecipeReconciler {// requeueFixedInterval doc).requeueAfterMs: result.skipStatusPatch? TRANSIENT_REQUEUE_BASE_MS- : result.phase === 'deploying'+ : result.phase === 'deploying' || result.pluginWorkloadSdkPolicyPending? WORKFLOW_PROGRESS_REQUEUE_BASE_MS: undefined,- requeueFixedInterval: !result.skipStatusPatch && result.phase === 'deploying',+ requeueFixedInterval:+ !result.skipStatusPatch &&+ (result.phase === 'deploying' || result.pluginWorkloadSdkPolicyPending === true),internalDependencyConditions: workflowInternalDependencyConditions,secretOwnershipConditions: workflowSecretOwnershipConditions,}@@ -1867,7 +1902,7 @@ export class WorkflowRecipeReconciler {// The status marker is durable across the spec edit; no workflow path is// involved in this cleanup.if (!isWorkflow && !recipe.spec.pluginWorkloadSdk && recipe.status?.pluginWorkloadSdk) {- await this.workflowReconciler?.cleanupPluginWorkloadSdkOnly(name)+ await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)}// Step 2.5: Policy enforcement already ran at the top of reconcile()@@ -2326,6 +2361,7 @@ export class WorkflowRecipeReconciler {? await this.reconcilePluginWorkloadSdkOnly(recipe): undefinedsdkOnlyProviderUnavailable = sdkOnlyRuntime?.phase === 'provider_unavailable'+ const sdkOnlyPolicyPending = sdkOnlyRuntime?.phase === 'awaiting_policy'if (sdkOnlyRuntime?.phase === 'failed') {return {phase: 'failed',@@ -2365,15 +2401,17 @@ export class WorkflowRecipeReconciler {const message =sdkOnlyRuntime?.phase === 'provider_unavailable'? sdkOnlyRuntime.message- : sdkOnlyRuntime?.phase === 'deploying'+ : sdkOnlyPolicyPending? sdkOnlyRuntime.message- : !allReady && !webhookHealthy- ? (webhookOutcome.message ?? 'Webhook gateway not ready')- : allReady- ? 'All workloads deployed'- : workloadStatuses.some(ws => ws.phase === 'failed')- ? 'Some workloads failed'- : 'Some workloads not ready'+ : sdkOnlyRuntime?.phase === 'deploying'+ ? sdkOnlyRuntime.message+ : !allReady && !webhookHealthy+ ? (webhookOutcome.message ?? 'Webhook gateway not ready')+ : allReady+ ? 'All workloads deployed'+ : workloadStatuses.some(ws => ws.phase === 'failed')+ ? 'Some workloads failed'+ : 'Some workloads not ready'return {phase: finalPhase,message,@@ -2383,15 +2421,19 @@ export class WorkflowRecipeReconciler {secretOwnershipConditions: secretOwnership.conditions,workloadConditions,pluginWorkloadSdkProviderUnavailable: sdkOnlyProviderUnavailable,+ pluginWorkloadSdkPolicyPending: sdkOnlyPolicyPending,+ pluginWorkloadSdkBootstrapProof: sdkOnlyRuntime?.pluginWorkloadSdkBootstrapProof,// Issue #637 — requeue if a denied workload's teardown failed (deniedTeardownFailed),// so the revocation is retried rather than left to the next event.requeueAfterMs:legacyRawCleanupPending ||deniedTeardownFailed ||sdkOnlyRuntime?.phase === 'deploying' ||- sdkOnlyRuntime?.phase === 'provider_unavailable'+ sdkOnlyRuntime?.phase === 'provider_unavailable' ||+ sdkOnlyPolicyPending? TRANSIENT_REQUEUE_BASE_MS: undefined,+ requeueFixedInterval: sdkOnlyPolicyPending,}} catch (error) {// Transient failures must not brick a healthy recipe at the terminal,@@ -2458,8 +2500,9 @@ export class WorkflowRecipeReconciler {}private async reconcilePluginWorkloadSdkOnly(recipe: WorkflowRecipeCRD): Promise<{- phase: 'active' | 'deploying' | 'failed' | 'provider_unavailable'+ phase: 'active' | 'awaiting_policy' | 'deploying' | 'failed' | 'provider_unavailable'message: string+ pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProof}> {if (!this.workflowReconciler) {return {@@ -3134,11 +3177,8 @@ export class WorkflowRecipeReconciler {// Use the durable validated status marker as well as the current spec:// a capability may have been removed in an update before Kubernetes emits// the final delete event, and cleanup must still revoke its host tokens.- if (- (recipe.spec.pluginWorkloadSdk || recipe.status?.pluginWorkloadSdk) &&- this.workflowReconciler- ) {- await this.workflowReconciler.cleanupPluginWorkloadSdkOnly(name)+ if (recipe.spec.pluginWorkloadSdk || recipe.status?.pluginWorkloadSdk) {+ await this.cleanupPluginWorkloadSdkOnlyOrThrow(name)}await this.cleanupDelegationIfNeeded(recipe)@@ -5772,6 +5812,9 @@ export class WorkflowRecipeReconciler {condition.type === PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE &&condition.status === 'True'),+ teardownConfirmed: result.pluginWorkloadSdkTeardownConfirmed === true,+ policyPending: result.pluginWorkloadSdkPolicyPending === true,+ bootstrapProof: result.pluginWorkloadSdkBootstrapProof,now,})const pluginSdkMergedConditions = mergePluginWorkloadSdkConditions(diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.tsindex 873265e9c..b14b06bb7 100644--- a/workflow-recipes/src/types.ts+++ b/workflow-recipes/src/types.ts@@ -536,11 +536,19 @@ export interface PluginWorkloadSdkSnippetConfig {* actually has active (vs merely declared in spec).*/export interface PluginWorkloadSdkCapabilityStatus {- state: 'validated' | 'disabled' | 'degraded'+ state: 'validated' | 'disabled' | 'degraded' | 'awaiting_policy'promptBridge: booleanclientNotifications: booleanmessage?: stringvalidatedAt?: string+ bootstrapContractVersion?: 2+ bootstrapPodUid?: string+ bootstrapProvider?: string+ bootstrapModel?: string+ policyRevision?: number+ policyHash?: string+ defaultTargetRef?: string+ verifiedAt?: string}// ─── WorkflowRecipe CRD ─────────────────────────────────────────────────diff --git a/workflow-recipes/src/workflow/agentResolution.ts b/workflow-recipes/src/workflow/agentResolution.tsindex cf9231ea9..ed14a2fa1 100644--- a/workflow-recipes/src/workflow/agentResolution.ts+++ b/workflow-recipes/src/workflow/agentResolution.ts@@ -1,13 +1,14 @@/*** Canonical agent resolution for workflow recipes.*- * A recipe's mcp-host provider/model comes from spec.agent, or — when absent —- * from the first step that declares a complete agent. This is the single source- * of truth shared by the reconciler (which needs the AgentSpec to build the- * mcp-host pod) and the Plugin Workload SDK validator (which only needs to know- * whether one is resolvable). Keeping both on this helper prevents the two from- * drifting apart.+ * A recipe's mcp-host provider/model comes from spec.agent, or — for a genuine+ * workflow — from the first step that declares a complete agent. This is the+ * single source of truth shared by the reconciler (which needs the AgentSpec+ * to build the mcp-host pod) and the Plugin Workload SDK validator (which only+ * needs to know whether one is resolvable). Keeping both on this helper+ * prevents the two from drifting apart.*/+import { isRunnableLlmModelId } from '@clerum/llm-providers'import type { WorkflowRecipeSpec } from '../types'import type { AgentSpec } from './types'@@ -18,8 +19,18 @@ import type { AgentSpec } from './types'* provider + model to match the prior reconciler behavior.*/export function resolveMcpHostAgent(spec: WorkflowRecipeSpec): AgentSpec | undefined {- if (spec.agent) return spec.agent as AgentSpec- const stepAgent = (spec.steps ?? []).find(step => step.agent?.provider && step.agent.model)?.agent+ // An explicitly declared top-level binding is authoritative. Do not silently+ // replace an invalid operator declaration with a step agent: that can boot a+ // different provider/model than the recipe author requested.+ if (spec.agent !== undefined) {+ if (spec.agent.provider && isRunnableLlmModelId(spec.agent.model)) {+ return spec.agent as AgentSpec+ }+ return undefined+ }+ const stepAgent = (spec.steps ?? []).find(+ step => step.agent?.provider && isRunnableLlmModelId(step.agent.model)+ )?.agentif (!stepAgent?.provider || !stepAgent.model) return undefinedreturn { provider: stepAgent.provider, model: stepAgent.model }}@@ -29,40 +40,13 @@ export function hasResolvableAgent(spec: WorkflowRecipeSpec): boolean {return resolveMcpHostAgent(spec) !== undefined}-/**- * Sentinel agent for clientNotifications-only eager mcp-host pods.- *- * INVARIANT: this value MUST NEVER reach a provider LLM call. It exists only so- * the always-on SDK server (:8099) can start for clientNotifications recipes- * that have no resolvable agent and no promptBridge — i.e. no brokered provider- * keys. `model: 'plugin-workload-sdk-notifications'` is not a real model id; it- * is a non-routable marker, deliberately distinct from any provider's catalog so- * an accidental LLM call would fail loudly rather than bill a real model.- *- * Safety is enforced by the caller, not by this value:- * - `resolveEagerSdkMcpHostAgent` only returns this stub when `clientNotifications`- * is set AND `promptBridge` is NOT (promptBridge requires a real resolvable- * agent and returns undefined here instead).- * - The provisioner gates the mcp-host `/configure` call, so the stub never- * drives a chat/completion request.- * Do not widen the conditions that return this stub without re-checking those gates.- */-const PLUGIN_WORKLOAD_SDK_NOTIFICATIONS_STUB_AGENT: AgentSpec = {- provider: 'openai',- model: 'plugin-workload-sdk-notifications',-}-/*** Agent used to build the eager SDK mcp-host pod. promptBridge requires a- * real resolvable agent; clientNotifications-only recipes use a stub agent so- * the always-on SDK server can start without brokered provider keys.+ * real resolvable agent; clientNotifications-only recipes deliberately return+ * no agent so the notification runtime does not invent a provider/model.*/export function resolveEagerSdkMcpHostAgent(spec: WorkflowRecipeSpec): AgentSpec | undefined {const resolved = resolveMcpHostAgent(spec)if (resolved) return resolved- if (spec.pluginWorkloadSdk?.promptBridge) return undefined- if (spec.pluginWorkloadSdk?.clientNotifications) {- return PLUGIN_WORKLOAD_SDK_NOTIFICATIONS_STUB_AGENT- }return undefined}diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.tsindex 9cbc3c500..4a53c4666 100644--- a/workflow-recipes/src/workflow/modelConfigHandler.ts+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts@@ -211,7 +211,48 @@ export class ModelConfigHandler {if (result.status >= 400) {return { status: 502, body: { error: 'mcp_host bootstrap failed' } }}- return { status: 202, body: { configured: true, provider, model } }+ if (+ result.body.configured !== true ||+ result.body.ready !== true ||+ result.body.contractVersion !== 2 ||+ result.body.provider !== provider ||+ result.body.model !== model ||+ !isBootstrapIdentityProof(result.body)+ ) {+ return {+ status: 502,+ body: { error: 'mcp_host bootstrap identity is not Plugin Workload SDK v2' },+ }+ }+ const policyProof = isBootstrapPolicyProof(result.body)+ return {+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider,+ model,+ contractVersion: 2,+ ...(typeof result.body.policyReady === 'boolean'+ ? { policyReady: result.body.policyReady }+ : {}),+ ...(typeof result.body.policyState === 'string'+ ? { policyState: result.body.policyState }+ : {}),+ ...(typeof result.body.policyReason === 'string'+ ? { policyReason: result.body.policyReason }+ : {}),+ ...(policyProof+ ? {+ policyRevision: result.body.policyRevision,+ policyHash: result.body.policyHash,+ defaultTargetRef: result.body.defaultTargetRef,+ defaultProvider: result.body.defaultProvider,+ defaultModel: result.body.defaultModel,+ }+ : {}),+ },+ }} catch {return { status: 502, body: { error: 'mcp_host bootstrap unreachable' } }}@@ -559,3 +600,33 @@ export class ModelConfigHandler {return resolved}}++function isBootstrapIdentityProof(body: Record<string, unknown>): boolean {+ return (+ body.configured === true &&+ body.ready === true &&+ body.contractVersion === 2 &&+ typeof body.provider === 'string' &&+ body.provider.length > 0 &&+ typeof body.model === 'string' &&+ body.model.length > 0+ )+}++function isBootstrapPolicyProof(body: Record<string, unknown>): boolean {+ return (+ isBootstrapIdentityProof(body) &&+ Number.isSafeInteger(body.policyRevision) &&+ Number(body.policyRevision) >= 1 &&+ typeof body.policyHash === 'string' &&+ /^[a-f0-9]{64}$/.test(body.policyHash) &&+ typeof body.defaultTargetRef === 'string' &&+ body.defaultTargetRef.length > 0 &&+ typeof body.defaultProvider === 'string' &&+ body.defaultProvider.length > 0 &&+ typeof body.defaultModel === 'string' &&+ body.defaultModel.length > 0 &&+ body.defaultProvider === body.provider &&+ body.defaultModel === body.model+ )+}diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex 5ce6f6f28..6ee966d98 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -30,7 +30,31 @@ import type { WorkflowRuntimePlan } from './runtimePlan'import { buildPluginWorkloadSdkTokenSecret } from './secretFactory'import type { WorkflowConfig } from './types'-export type EagerSdkMcpHostStatus = 'ready' | 'deploying' | 'failed' | 'provider_unavailable'+export type EagerSdkMcpHostStatus =+ | 'ready'+ | 'awaiting_policy'+ | 'deploying'+ | 'failed'+ | 'provider_unavailable'++export interface EagerSdkBootstrapProof {+ ready: true+ contractVersion: 2+ podUid: string+ provider: string+ model: string+ policyReady?: boolean+ policyState?: string+ policyReason?: string+ /** Optional snapshot when a grant already exists; request authorization+ * always re-reads and validates the current policy. */+ policyRevision?: number+ policyHash?: string+ defaultTargetRef?: string+ defaultProvider?: string+ defaultModel?: string+ verifiedAt: string+}/*** Consecutive eager SDK bootstrap failures tolerated before the provider is@@ -76,15 +100,8 @@ export type PluginWorkloadSdkProvisionerDeps = {* keep the reconciler file bounded while preserving the existing behavior.*/export class PluginWorkloadSdkProvisioner {- /**- * In-memory record of the last successful eager-SDK provider bootstrap, keyed- * by recipe name. The value is `<podUid>:<provider>:<model>` — when it matches- * the current mcp-host pod and agent, the identity-only bootstrap is skipped- * to avoid an RS256 sign + HTTP POST on every level-triggered reconcile. Lost- * on WRC restart, which just bootstraps once (still idempotent); a pod restart- * changes the UID and forces a refresh.- */- private readonly eagerSdkConfiguredByRecipe = new Map<string, string>()+ /** Last fresh Control API proof, tied to the current pod UID. */+ private readonly eagerSdkBootstrapProofByRecipe = new Map<string, EagerSdkBootstrapProof>()/*** Consecutive eager SDK bootstrap failures per recipe and stable bootstrap@@ -104,10 +121,14 @@ export class PluginWorkloadSdkProvisioner {constructor(private readonly deps: PluginWorkloadSdkProvisionerDeps) {}clearRecipeState(recipeName: string): void {- this.eagerSdkConfiguredByRecipe.delete(recipeName)+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)}+ getBootstrapProof(recipeName: string): EagerSdkBootstrapProof | undefined {+ return this.eagerSdkBootstrapProofByRecipe.get(recipeName)+ }+/*** Deletes the eager mcp-host pod (wedge recovery or image-drift roll) and* clears the per-recipe bootstrap failure budget. The failure map is also@@ -120,6 +141,7 @@ export class PluginWorkloadSdkProvisioner {`${recipeName}-mcp-host`,this.deps.config.sandboxNamespace)+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)}@@ -150,13 +172,11 @@ export class PluginWorkloadSdkProvisioner {const log = createLogger('wrc', recipeName)const mcpHostAgent = resolveEagerSdkMcpHostAgent(spec)- if (!mcpHostAgent) {- if (spec.pluginWorkloadSdk?.promptBridge) {- log.warn(- 'Plugin Workload SDK promptBridge declared but no agent is resolvable; ' +- 'add spec.agent or a step agent with provider+model to recover the eager mcp-host'- )- }+ if (!mcpHostAgent && spec.pluginWorkloadSdk?.promptBridge) {+ log.warn(+ 'Plugin Workload SDK promptBridge declared but no agent is resolvable; ' ++ 'declare spec.agent with provider+model to bind the eager mcp-host'+ )return 'failed'}@@ -251,12 +271,17 @@ export class PluginWorkloadSdkProvisioner {const readiness = await this.readinessForEagerSdkMcpHost(recipeName)if (!spec.pluginWorkloadSdk?.promptBridge) {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return readiness.status}if (!this.deps.modelConfigHandler) {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)+ return readiness.status+ }+ if (readiness.status !== 'ready') {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return readiness.status}- if (readiness.status !== 'ready') return readiness.statusif (!readiness.uid) {log.warn(@@ -265,12 +290,8 @@ export class PluginWorkloadSdkProvisioner {return 'deploying'}+ if (!mcpHostAgent) return 'failed'const configureKey = `${readiness.uid}:${mcpHostAgent.provider}:${mcpHostAgent.model}`- if (this.eagerSdkConfiguredByRecipe.get(recipeName) === configureKey) {- this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)- return 'ready'- }-try {const wrcConfigureToken = await this.deps.tokenFactory.signWrcConfigureToken(recipeName,@@ -284,25 +305,33 @@ export class PluginWorkloadSdkProvisioner {wrcConfigureToken)if (result.status >= 400) {- this.eagerSdkConfiguredByRecipe.delete(recipeName)+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {reason: 'Plugin Workload SDK eager mcp-host bootstrap returned an error',detail: { status: result.status },})}- this.eagerSdkConfiguredByRecipe.set(recipeName, configureKey)+ const proof = parseEagerSdkBootstrapProof(result.body, readiness.uid)+ if (!proof) {+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)+ return this.recordEagerConfigureFailure(recipeName, configureKey, log, {+ reason: 'Plugin Workload SDK bootstrap response omitted identity proof',+ detail: { status: result.status },+ })+ }+ this.eagerSdkBootstrapProofByRecipe.set(recipeName, proof)this.eagerSdkConfigureFailuresByRecipe.delete(recipeName)+ if (spec.pluginWorkloadSdk.promptBridge && proof.policyReady === false) {+ return 'awaiting_policy'+ }} catch (err) {- this.eagerSdkConfiguredByRecipe.delete(recipeName)+ this.eagerSdkBootstrapProofByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {reason: 'Plugin Workload SDK eager mcp-host bootstrap failed',detail: { error: err instanceof Error ? err.message : String(err) },})}- // Reuse the readiness captured above: bootstrap does not recreate the pod,- // and we already gated on readiness.status === 'ready', so a second K8s- // readiness GET would return the same status. Avoid the extra round-trip.- return readiness.status+ return 'ready'}async readinessForEagerSdkMcpHost(@@ -453,3 +482,51 @@ export class PluginWorkloadSdkProvisioner {)}}++function parseEagerSdkBootstrapProof(+ body: Record<string, unknown>,+ podUid: string+): EagerSdkBootstrapProof | null {+ if (+ body.configured !== true ||+ body.ready !== true ||+ body.contractVersion !== 2 ||+ typeof body.provider !== 'string' ||+ typeof body.model !== 'string' ||+ body.provider.length === 0 ||+ body.model.length === 0+ ) {+ return null+ }+ const hasPolicyProof =+ Number.isSafeInteger(body.policyRevision) &&+ Number(body.policyRevision) >= 1 &&+ typeof body.policyHash === 'string' &&+ /^[a-f0-9]{64}$/.test(body.policyHash) &&+ typeof body.defaultTargetRef === 'string' &&+ body.defaultTargetRef.length > 0 &&+ typeof body.defaultProvider === 'string' &&+ body.defaultProvider === body.provider &&+ typeof body.defaultModel === 'string' &&+ body.defaultModel === body.model+ return {+ ready: true,+ contractVersion: 2,+ podUid,+ provider: body.provider,+ model: body.model,+ policyReady: body.policyReady !== false && hasPolicyProof,+ policyState: typeof body.policyState === 'string' ? body.policyState : 'unknown',+ ...(typeof body.policyReason === 'string' ? { policyReason: body.policyReason } : {}),+ verifiedAt: new Date().toISOString(),+ ...(hasPolicyProof+ ? {+ policyRevision: Number(body.policyRevision),+ policyHash: body.policyHash as string,+ defaultTargetRef: body.defaultTargetRef as string,+ defaultProvider: body.defaultProvider as string,+ defaultModel: body.defaultModel as string,+ }+ : {}),+ }+}diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkRevocationClient.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkRevocationClient.tsnew file mode 100644index 000000000..662e77bca--- /dev/null+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkRevocationClient.ts@@ -0,0 +1,136 @@+import { signInternalControlJwt } from '../utils/internalControlSigner'++const DEFAULT_CONTROL_API_BASE_URL = 'http://control-api.control-plane.svc.cluster.local:8090'+const REQUEST_TIMEOUT_MS = 10_000++export interface PluginWorkloadSdkRevocationReceipt {+ state: 'missing' | 'revoking' | 'disabled' | 'conflict'+ revocationId?: string+ revoked: number+ fencedInvocations: number+ disabled?: number+}++export interface PluginWorkloadSdkRevocationClient {+ revoke(recipeNamespace: string, recipeName: string): Promise<PluginWorkloadSdkRevocationReceipt>+ finalize(+ recipeNamespace: string,+ recipeName: string,+ revocationId: string+ ): Promise<PluginWorkloadSdkRevocationReceipt>+}++/**+ * WRC-to-control-api revocation client. It carries only the recipe binding;+ * the signed internal JWT identifies WRC and is never exposed to the recipe+ * workload. A failed call is surfaced to the reconciler so teardown cannot+ * publish a false disabled state.+ */+export class HttpPluginWorkloadSdkRevocationClient implements PluginWorkloadSdkRevocationClient {+ constructor(+ private readonly baseUrl = process.env.CONTROL_API_BASE_URL?.trim() ||+ DEFAULT_CONTROL_API_BASE_URL,+ private readonly fetchImpl: typeof fetch = fetch+ ) {}++ revoke(recipeNamespace: string, recipeName: string): Promise<PluginWorkloadSdkRevocationReceipt> {+ return this.post('/api/v1/internal/plugin-workload-sdk/revoke', recipeNamespace, recipeName)+ }++ finalize(+ recipeNamespace: string,+ recipeName: string,+ revocationId: string+ ): Promise<PluginWorkloadSdkRevocationReceipt> {+ return this.post(+ '/api/v1/internal/plugin-workload-sdk/finalize-revocation',+ recipeNamespace,+ recipeName,+ revocationId+ )+ }++ private async post(+ path: string,+ recipeNamespace: string,+ recipeName: string,+ revocationId?: string+ ): Promise<PluginWorkloadSdkRevocationReceipt> {+ const controller = new AbortController()+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)+ try {+ const response = await this.fetchImpl(`${this.baseUrl.replace(/\/+$/, '')}${path}`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${signInternalControlJwt()}`,+ },+ body: JSON.stringify({+ recipeNamespace,+ recipeName,+ ...(revocationId ? { revocationId } : {}),+ }),+ signal: controller.signal,+ })+ if (!response.ok) {+ throw new Error(+ `Plugin Workload SDK revocation failed: HTTP ${response.status} for recipe "${recipeName}"`+ )+ }+ let body: unknown+ try {+ body = await response.json()+ } catch {+ throw new Error(+ `Plugin Workload SDK revocation returned invalid JSON for recipe "${recipeName}"`+ )+ }+ if (!isRevocationReceipt(body)) {+ throw new Error(+ `Plugin Workload SDK revocation returned an invalid receipt for recipe "${recipeName}"`+ )+ }+ if (+ path.endsWith('/finalize-revocation') &&+ body.state !== 'disabled' &&+ body.state !== 'missing'+ ) {+ throw new Error(+ `Plugin Workload SDK revocation did not confirm disabled state for recipe "${recipeName}"`+ )+ }+ return body+ } catch (error) {+ if (error instanceof DOMException && error.name === 'AbortError') {+ throw new Error(+ `Plugin Workload SDK revocation timed out after ${REQUEST_TIMEOUT_MS}ms for recipe "${recipeName}"`+ )+ }+ throw error+ } finally {+ clearTimeout(timeoutId)+ }+ }+}++function isRevocationReceipt(value: unknown): value is PluginWorkloadSdkRevocationReceipt {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false+ const record = value as Record<string, unknown>+ return (+ (record.state === 'missing' ||+ record.state === 'revoking' ||+ record.state === 'disabled' ||+ record.state === 'conflict') &&+ typeof record.revoked === 'number' &&+ Number.isInteger(record.revoked) &&+ record.revoked >= 0 &&+ typeof record.fencedInvocations === 'number' &&+ Number.isInteger(record.fencedInvocations) &&+ record.fencedInvocations >= 0 &&+ (record.revocationId === undefined ||+ (typeof record.revocationId === 'string' &&+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(+ record.revocationId+ )))+ )+}diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.tsindex 271c6904a..8bc9b09d2 100644--- a/workflow-recipes/src/workflow/podFactory.ts+++ b/workflow-recipes/src/workflow/podFactory.ts@@ -558,7 +558,7 @@ export interface McpHostPodOptions {export function buildMcpHostPod(recipeName: string,- agent: AgentSpec,+ agent: AgentSpec | undefined,config: WorkflowConfig,approvalRecipeName: string | undefined,approvalRecipeNamespace: string | undefined,@@ -658,8 +658,12 @@ export function buildMcpHostPod(},},},- { name: 'CLERUM_MODEL_PROVIDER', value: agent.provider },- { name: 'CLERUM_MODEL', value: agent.model },+ ...(agent+ ? [+ { name: 'CLERUM_MODEL_PROVIDER', value: agent.provider },+ { name: 'CLERUM_MODEL', value: agent.model },+ ]+ : []),// mcpHost runtime tokens — mcp-host uses these to call the approval gateway.// Coordinator does NOT get these env vars (least privilege).{diff --git a/workflow-recipes/src/workflow/workflowAuth.ts b/workflow-recipes/src/workflow/workflowAuth.tsindex 5e1222f4b..d956ccfc5 100644--- a/workflow-recipes/src/workflow/workflowAuth.ts+++ b/workflow-recipes/src/workflow/workflowAuth.ts@@ -27,6 +27,10 @@ export interface PluginSdkCredentialTicketClaims {recipeName: stringrecipeNamespace: stringinvocationId: string+ /** Physical-attempt identity issued by control-api; never caller supplied. */+ attemptGeneration: number+ providerAttemptId: string+ providerAttemptIndex: numbertargetRef: stringprovider: stringmodel: string@@ -163,6 +167,14 @@ export async function verifyPluginSdkCredentialTicket(typeof claims.recipeName !== 'string' ||typeof claims.recipeNamespace !== 'string' ||typeof claims.invocationId !== 'string' ||+ typeof claims.attemptGeneration !== 'number' ||+ !Number.isInteger(claims.attemptGeneration) ||+ claims.attemptGeneration < 1 ||+ typeof claims.providerAttemptId !== 'string' ||+ claims.providerAttemptId.length === 0 ||+ typeof claims.providerAttemptIndex !== 'number' ||+ !Number.isInteger(claims.providerAttemptIndex) ||+ claims.providerAttemptIndex < 1 ||typeof claims.targetRef !== 'string' ||typeof claims.provider !== 'string' ||typeof claims.model !== 'string' ||@@ -182,6 +194,9 @@ export async function verifyPluginSdkCredentialTicket(recipeName: claims.recipeName,recipeNamespace: claims.recipeNamespace,invocationId: claims.invocationId,+ attemptGeneration: claims.attemptGeneration as number,+ providerAttemptId: claims.providerAttemptId,+ providerAttemptIndex: claims.providerAttemptIndex as number,targetRef: claims.targetRef,provider: claims.provider,model: claims.model,diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.tsindex 354c2b806..b9d6ad0c2 100644--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts@@ -3,6 +3,7 @@ import { WorkflowReconciler, type WorkflowReconcilerDeps } from './workflowReconconst crashRecoveryMocks = vi.hoisted(() => ({deletePodIfExists: vi.fn().mockResolvedValue(undefined),+ waitForPodDeletion: vi.fn().mockResolvedValue(true),evaluateCompletedRuntimePodRecovery: vi.fn().mockReturnValue({action: 'replace',message:@@ -112,6 +113,7 @@ describe('WorkflowReconciler.reconcileDelete — orphaned Service cleanup', () =readNamespacedPod: vi.fn().mockResolvedValue({}),readNamespacedSecret: vi.fn().mockRejectedValue({ code: 404 }),readNamespacedService: vi.fn().mockResolvedValue({}),+ readNamespacedEndpoints: vi.fn().mockRejectedValue({ code: 404 }),createNamespacedSecret: vi.fn().mockResolvedValue({}),createNamespacedConfigMap: vi.fn().mockResolvedValue({}),createNamespacedService: vi.fn().mockResolvedValue({}),@@ -166,6 +168,10 @@ describe('WorkflowReconciler.reconcileDelete — orphaned Service cleanup', () =runtimeTokenRefreshBeforeSeconds: 300,},tokenFactory: mockTokenFactory,+ pluginWorkloadSdkRevocationClient: {+ revoke: vi.fn().mockResolvedValue({ state: 'missing', revoked: 0, fencedInvocations: 0 }),+ finalize: vi.fn(),+ },} as unknown as WorkflowReconcilerDepsbeforeEach(() => {@@ -1295,6 +1301,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {readNamespacedPod: vi.fn().mockResolvedValue({}),readNamespacedSecret: vi.fn().mockRejectedValue({ code: 404 }),readNamespacedService: vi.fn().mockResolvedValue({}),+ readNamespacedEndpoints: vi.fn().mockRejectedValue({ code: 404 }),createNamespacedSecret: vi.fn().mockResolvedValue({}),createNamespacedConfigMap: vi.fn().mockResolvedValue({}),createNamespacedService: vi.fn().mockResolvedValue({}),@@ -1316,14 +1323,30 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),}const mockModelConfigHandler = {- configurePluginWorkloadSdkBootstrap: vi- .fn()- .mockResolvedValue({ status: 202, body: { configured: true } }),+ configurePluginWorkloadSdkBootstrap: vi.fn().mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'zai',+ model: 'glm-4.7',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-zai',+ defaultProvider: 'zai',+ defaultModel: 'glm-4.7',+ },+ }),}const mockTokenFactory = {signWrcConfigureToken: vi.fn().mockResolvedValue('wrc-configure-token'),signWrcArtifactDeleteToken: vi.fn().mockResolvedValue('stub-token'),}+ const mockPluginWorkloadSdkRevocationClient = {+ revoke: vi.fn().mockResolvedValue({ state: 'missing', revoked: 0, fencedInvocations: 0 }),+ finalize: vi.fn(),+ }const makeDeps = () =>({@@ -1344,8 +1367,22 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {},tokenFactory: mockTokenFactory,modelConfigHandler: mockModelConfigHandler,+ pluginWorkloadSdkRevocationClient: mockPluginWorkloadSdkRevocationClient,}) as unknown as WorkflowReconcilerDeps+ const sdkBootstrapProof = () => ({+ configured: true,+ ready: true,+ provider: 'zai',+ model: 'glm-4.7',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-zai',+ defaultProvider: 'zai',+ defaultModel: 'glm-4.7',+ })+beforeEach(() => {vi.clearAllMocks()crashRecoveryMocks.getContainerWaitingReason.mockResolvedValue(undefined)@@ -1357,10 +1394,13 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {})crashRecoveryMocks.evaluateCrashRecovery.mockReturnValue({ action: 'none', message: 'healthy' })mockCoreApi.createNamespacedPod.mockResolvedValue({})+ mockCoreApi.readNamespacedService.mockRejectedValue({ code: 404 })+ mockCoreApi.readNamespacedEndpoints.mockRejectedValue({ code: 404 })+ mockNetworkingApi.readNamespacedNetworkPolicy.mockRejectedValue({ code: 404 })mockNetworkingApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({status: 202,- body: { configured: true },+ body: sdkBootstrapProof(),})vi.stubGlobal('fetch',@@ -1484,6 +1524,31 @@ 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())++ const result = await reconciler.reconcilePluginWorkloadSdkOnly(+ 'notifications-only',+ 'uid-notifications-only',+ sandboxNamespace,+ sdkSpec({+ agent: undefined,+ steps: undefined,+ pluginWorkloadSdk: {+ clientNotifications: { allowedEventTypes: ['e2e.test'] },+ allowedCallers: ['sdk-caller'],+ },+ })+ )++ expect(result.phase).toBe('active')+ const pod = mockCoreApi.createNamespacedPod.mock.calls[0]?.[0].body+ 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()+ })+it('cleans SDK-only host resources idempotently without creating workflow resources', async () => {const reconciler = new WorkflowReconciler(makeDeps())@@ -1509,16 +1574,36 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {expect(mockCoreApi.createNamespacedPod).not.toHaveBeenCalled()})+ it('fails closed after physical cleanup when the Control API revocation client is absent', async () => {+ const deps = makeDeps() as unknown as { pluginWorkloadSdkRevocationClient?: unknown }+ delete deps.pluginWorkloadSdkRevocationClient+ const reconciler = new WorkflowReconciler(deps as unknown as WorkflowReconcilerDeps)++ await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).rejects.toThrow(+ /revocation client is not configured/+ )+ expect(mockCoreApi.deleteNamespacedPod).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'sdk-only-mcp-host' })+ )+ })+it('sweeps legacy SDK network policies by recipe label during cleanup', async () => {+ let legacyPolicyPresent = truemockNetworkingApi.listNamespacedNetworkPolicy.mockImplementation(({ namespace }: { namespace: string }) =>Promise.resolve({items:- namespace === sandboxNamespace+ namespace === sandboxNamespace && legacyPolicyPresent? [{ metadata: { name: 'sdk-only-legacy-coord-to-mcp-host' } }]: [],}))+ mockNetworkingApi.deleteNamespacedNetworkPolicy.mockImplementation(+ async ({ name }: { name?: string }) => {+ if (name === 'sdk-only-legacy-coord-to-mcp-host') legacyPolicyPresent = false+ return {}+ }+ )const reconciler = new WorkflowReconciler(makeDeps())await reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')@@ -1658,7 +1743,47 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(1)})- it('does not re-broker the provider on a second reconcile of the same ready pod', async () => {+ it('reports awaiting_policy when identity bootstrap is ready but the operator grant is missing', async () => {+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({+ ready: true,+ phase: 'Running',+ uid: 'pod-uid-1',+ })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'zai',+ model: 'glm-4.7',+ contractVersion: 2,+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ },+ })+ const reconciler = new WorkflowReconciler(makeDeps())++ const result = await reconciler.reconcilePluginWorkloadSdkOnly(+ 'sdk-recipe',+ 'uid-sdk',+ sandboxNamespace,+ sdkSpec({ steps: undefined })+ )++ expect(result.phase).toBe('awaiting_policy')+ expect(result.message).toContain('operator policy pending')+ expect(result.message).toContain('grant_missing')+ expect(result.message).not.toContain('provider unavailable')+ expect(result.pluginWorkloadSdkBootstrapProof).toMatchObject({+ ready: true,+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ })+ })++ it('re-probes live bootstrap policy on every reconcile of the same ready pod', async () => {crashRecoveryMocks.getPodReadiness.mockResolvedValue({ready: true,phase: 'Running',@@ -1680,8 +1805,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {await run()await run()- // Same pod + provider/model → second pass is gated, configure runs once.- expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(1)+ // A pod UID is not proof that the operator policy is unchanged. Each+ // reconcile must obtain a fresh Control API proof so grant revocation and+ // target-order changes become effective without restarting the pod.+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(2)})it('stays pending (not registered) and retries when the provider broker fails', async () => {@@ -1715,13 +1842,40 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {// Failure must not poison the configure cache: the next reconcile retries.mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({status: 202,- body: { configured: true },+ body: sdkBootstrapProof(),})const second = await run()expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(2)expect(second.message).toContain('registered')})+ it('does not publish SDK readiness when the bootstrap contract is not v2', async () => {+ crashRecoveryMocks.getPodReadiness.mockResolvedValue({+ ready: true,+ phase: 'Running',+ uid: 'pod-uid-1',+ })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: { configured: true },+ })+ const reconciler = new WorkflowReconciler(makeDeps())+ const result = await reconciler.reconcile(+ 'sdk-recipe',+ 'uid-sdk',+ sandboxNamespace,+ sdkSpec(),+ { workflowExecution: { phase: 'initializing' } },+ undefined,+ 'sdk-recipe',+ undefined+ )++ expect(result.phase).toBe('deploying')+ expect(result.message).toContain('starting')+ expect(result.message).not.toContain('registered')+ })+it('projects provider_unavailable after repeated configure failures instead of an indefinite starting', async () => {crashRecoveryMocks.getPodReadiness.mockResolvedValue({ready: true,@@ -1772,7 +1926,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {// the unavailable condition is no longer projected.mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({status: 202,- body: { configured: true },+ body: sdkBootstrapProof(),})const recovered = await run()expect(recovered.message).toContain('registered')diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.tsindex b557801f5..7c05d713f 100644--- a/workflow-recipes/src/workflow/workflowReconciler.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.ts@@ -48,6 +48,7 @@ import {getPodPhase,getPodReadiness,isRecoverableContainerWaitingReason,+ waitForPodDeletion,} from './crashRecovery'import { JwtTokenFactory } from './jwtTokenFactory'import {@@ -58,7 +59,14 @@ import {import type { ModelConfigHandler } from './modelConfigHandler'import { NetworkPolicyConfig, buildWorkflowNetworkPolicies } from './networkPolicyFactory'import { ObjectStorageClient, StorageCredentials, StorageRef } from './objectStorageClient'-import { PluginWorkloadSdkProvisioner } from './pluginWorkloadSdkProvisioner'+import {+ type EagerSdkBootstrapProof,+ PluginWorkloadSdkProvisioner,+} from './pluginWorkloadSdkProvisioner'+import type {+ PluginWorkloadSdkRevocationClient,+ PluginWorkloadSdkRevocationReceipt,+} from './pluginWorkloadSdkRevocationClient'import {type SnippetRunnerSecretAlias,WORKFLOW_OUTPUT_CLAIM_LABEL,@@ -620,6 +628,10 @@ export interface WorkflowReconcileResult {* requeue. Propagated up through WRC's ReconcileResult.*/skipStatusPatch?: boolean+ /** Fresh Control API v2 proof tied to the current eager mcp-host pod. */+ pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProof+ /** Eager host identity is ready, but prompt policy awaits operator action. */+ pluginWorkloadSdkPolicyPending?: boolean}function mcpHostReadinessMessage(readiness: PodReadiness): string {@@ -782,6 +794,12 @@ export interface WorkflowReconcilerDeps {* mcp-host stays unconfigured until a triggered run injects a model).*/modelConfigHandler?: ModelConfigHandler+ /**+ * Recipe-scoped Control API revocation boundary for SDK-only teardown.+ * Teardown is fail-closed when this client is absent; production always+ * wires the HTTP implementation and tests provide a deterministic stub.+ */+ pluginWorkloadSdkRevocationClient: PluginWorkloadSdkRevocationClient}export class WorkflowReconciler {@@ -872,8 +890,9 @@ export class WorkflowReconciler {spec: WorkflowRecipeSpec,runtimeScopeRecipeName = recipeName): Promise<{- phase: 'active' | 'deploying' | 'failed' | 'provider_unavailable'+ phase: 'active' | 'awaiting_policy' | 'deploying' | 'failed' | 'provider_unavailable'message: string+ pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProof}> {if (!this.deps.config.pluginWorkloadSdkEnabled || !spec.pluginWorkloadSdk) {return { phase: 'active', message: 'Plugin Workload SDK runtime disabled' }@@ -901,9 +920,20 @@ export class WorkflowReconciler {runtime,{ mcpHostPhase })+ const bootstrapProof = this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)switch (status) {case 'ready':- return { phase: 'active', message: 'Plugin Workload SDK mcp-host registered' }+ return {+ phase: 'active',+ message: 'Plugin Workload SDK mcp-host registered',+ pluginWorkloadSdkBootstrapProof: bootstrapProof,+ }+ case 'awaiting_policy':+ return {+ phase: 'awaiting_policy',+ message: `Plugin Workload SDK operator policy pending (${bootstrapProof?.policyReason ?? bootstrapProof?.policyState ?? 'unknown'})`,+ pluginWorkloadSdkBootstrapProof: bootstrapProof,+ }case 'deploying':return { phase: 'deploying', message: 'Plugin Workload SDK mcp-host starting' }case 'provider_unavailable':@@ -933,27 +963,44 @@ export class WorkflowReconciler {`${recipeName}-mcp-host-to-gfs`,`${recipeName}-mcp-host-to-approval-gateway`,]- await Promise.all([- deletePodIfExists(this.deps.coreApi, `${recipeName}-mcp-host`, ns),- this.pluginWorkloadSdkProvisioner.deletePluginWorkloadSdkTokenSecret(recipeName),- // The runtime JWT Secret is created for eager SDK hosts as well as- // workflow hosts. A capability removal must revoke it with the host;- // leaving it behind would allow a deleted workload to replay broker- // requests until token expiry.- this.safeDelete(() =>- this.deps.coreApi.deleteNamespacedSecret({- name: `wf-${recipeName}-mcp-host-runtime-tokens`,- namespace: ns,- })- ),- this.safeDelete(() =>- this.deps.coreApi.deleteNamespacedService({- name: buildMcpHostServiceName(recipeName),- namespace: ns,+ let revocationError: unknown = null+ let revocationReceipt: PluginWorkloadSdkRevocationReceipt | null = null+ const revocationClient = this.deps.pluginWorkloadSdkRevocationClient+ if (!revocationClient) {+ revocationError = new Error(+ 'Plugin Workload SDK revocation client is not configured; refusing to report teardown complete'+ )+ } else {+ try {+ revocationReceipt = await revocationClient.revoke(ns, recipeName)+ if (revocationReceipt.state === 'conflict') {+ throw new Error(`Plugin Workload SDK revocation conflict for recipe "${recipeName}"`)+ }+ } catch (error) {+ // Continue with the physical boundary even if control-api is briefly+ // unavailable. The service/network teardown prevents new ingress;+ // the original error is rethrown after absence is proven so WRC does+ // not publish `disabled` and the next reconcile retries the fence.+ revocationError = error+ this.log.error('Plugin Workload SDK control-plane revocation failed', {+ recipeName,+ error: error instanceof Error ? error.message : String(error),})- ),+ }+ }+ // Close the service and network-policy edges before removing the pod or+ // token Secrets. This ordering is the revocation boundary: a live pod+ // cannot keep receiving broker traffic while its credentials are being+ // deleted, and a failed delete is requeued instead of reported as disabled.+ await this.teardownDelete(() =>+ this.deps.coreApi.deleteNamespacedService({+ name: buildMcpHostServiceName(recipeName),+ namespace: ns,+ })+ )+ await Promise.all([...networkPolicyNames.map(name =>- this.safeDelete(() =>+ this.teardownDelete(() =>this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns }))),@@ -962,19 +1009,122 @@ export class WorkflowReconciler {// label set so upgrades and dynamic policy names cannot retain a stale// isolation lane. The selector is recipe-scoped and only matches WRC-// managed policies, never the namespace-wide baseline policies.- this.safeDelete(() =>+ this.teardownDelete(() =>this.deleteNetworkPoliciesByLabelSelector(ns,`clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`)),- this.safeDelete(() =>+ this.teardownDelete(() =>this.deleteNetworkPoliciesByLabelSelector(this.deps.config.mcpServerNamespace,`clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`)),])+ await this.teardownDelete(() =>+ this.deps.coreApi.deleteNamespacedPod({+ name: `${recipeName}-mcp-host`,+ namespace: ns,+ propagationPolicy: 'Background',+ })+ )+ await Promise.all([+ this.teardownDelete(() =>+ this.deps.coreApi.deleteNamespacedSecret({+ name: buildPluginWorkloadSdkTokenSecretName(recipeName),+ namespace: ns,+ })+ ),+ // The runtime JWT Secret is created for eager SDK hosts as well as+ // workflow hosts. A capability removal must revoke it with the host;+ // leaving it behind would allow a deleted workload to replay broker+ // requests until token expiry.+ this.teardownDelete(() =>+ this.deps.coreApi.deleteNamespacedSecret({+ name: `wf-${recipeName}-mcp-host-runtime-tokens`,+ namespace: ns,+ })+ ),+ ])+ await this.assertPluginWorkloadSdkResourcesAbsent(recipeName, ns, networkPolicyNames)+ if (revocationError) throw revocationError+ if (revocationClient && revocationReceipt?.state === 'revoking') {+ if (!revocationReceipt.revocationId) {+ throw new Error(`Plugin Workload SDK revocation receipt for ${recipeName} has no epoch`)+ }+ const finalized = await revocationClient.finalize(+ ns,+ recipeName,+ revocationReceipt.revocationId+ )+ if (finalized.state !== 'disabled') {+ throw new Error(+ `Plugin Workload SDK revocation for ${recipeName} was not confirmed disabled`+ )+ }+ }+ }++ private async assertPluginWorkloadSdkResourcesAbsent(+ recipeName: string,+ namespace: string,+ networkPolicyNames: string[]+ ): Promise<void> {+ const podGone = await waitForPodDeletion(+ this.deps.coreApi,+ `${recipeName}-mcp-host`,+ namespace,+ {+ timeoutMs: 5_000,+ pollIntervalMs: 250,+ }+ )+ if (!podGone)+ throw new Error(`Plugin Workload SDK pod for ${recipeName} still exists after teardown`)+ const checks: Array<Promise<unknown>> = [+ this.deps.coreApi.readNamespacedSecret({+ name: buildPluginWorkloadSdkTokenSecretName(recipeName),+ namespace,+ }),+ this.deps.coreApi.readNamespacedSecret({+ name: `wf-${recipeName}-mcp-host-runtime-tokens`,+ namespace,+ }),+ this.deps.coreApi.readNamespacedService({+ name: buildMcpHostServiceName(recipeName),+ namespace,+ }),+ this.deps.coreApi.readNamespacedEndpoints({+ name: buildMcpHostServiceName(recipeName),+ namespace,+ }),+ ...networkPolicyNames.map(name =>+ this.deps.networkingApi.readNamespacedNetworkPolicy({ name, namespace })+ ),+ this.deps.networkingApi.listNamespacedNetworkPolicy({+ namespace,+ labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,+ }),+ this.deps.networkingApi.listNamespacedNetworkPolicy({+ namespace: this.deps.config.mcpServerNamespace,+ labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,+ }),+ ]+ const results = await Promise.allSettled(checks)+ const unexpected = results.find(result => {+ if (result.status !== 'fulfilled') return false+ const value = result.value as { items?: unknown[] } | undefined+ return Array.isArray(value?.items) ? value.items.length > 0 : true+ })+ if (unexpected) {+ throw new Error(`Plugin Workload SDK resource for ${recipeName} still exists after teardown`)+ }+ const failed = results.find(+ (result): result is PromiseRejectedResult =>+ result.status === 'rejected' && getErrorCode(result.reason) !== 404+ )+ if (failed) throw failed.reason}async reconcile(@@ -1174,6 +1324,8 @@ export class WorkflowReconciler {runtime,{ mcpHostPhase })+ const eagerBootstrapProof =+ this.pluginWorkloadSdkProvisioner.getBootstrapProof(recipeName)if (eagerStatus === 'failed') {return withWorkflowConditions({phase: 'failed',@@ -1204,10 +1356,26 @@ export class WorkflowReconciler {],}}- const eagerReady = eagerStatus === 'ready'- const eagerMessage = eagerReady- ? `Plugin Workload SDK mcp-host registered (${classification})`- : `Plugin Workload SDK mcp-host starting (${classification})`+ const eagerPolicyPending = eagerStatus === 'awaiting_policy'+ const eagerReady =+ (eagerStatus === 'ready' || eagerPolicyPending) &&+ (!spec.pluginWorkloadSdk?.promptBridge || eagerBootstrapProof !== undefined)+ if (+ eagerStatus === 'ready' &&+ spec.pluginWorkloadSdk?.promptBridge &&+ !eagerBootstrapProof+ ) {+ return withWorkflowConditions({+ phase: 'deploying',+ message: `Plugin Workload SDK bootstrap policy proof pending (${classification})`,+ clearWorkflowExecution: true,+ })+ }+ const eagerMessage = eagerPolicyPending+ ? `Plugin Workload SDK operator policy pending (${eagerBootstrapProof?.policyReason ?? eagerBootstrapProof?.policyState ?? 'unknown'}) (${classification})`+ : eagerReady+ ? `Plugin Workload SDK mcp-host registered (${classification})`+ : `Plugin Workload SDK mcp-host starting (${classification})`return withWorkflowConditions({// While the eager mcp-host is still booting (eagerStatus ===// 'deploying'), return 'deploying' — NOT 'active' — so the watcher@@ -1221,6 +1389,8 @@ export class WorkflowReconciler {phase: eagerReady ? 'active' : 'deploying',message: eagerMessage,clearWorkflowExecution: true,+ pluginWorkloadSdkBootstrapProof: eagerBootstrapProof,+ pluginWorkloadSdkPolicyPending: eagerPolicyPending,})}}@@ -3086,7 +3256,17 @@ export class WorkflowReconciler {(list.items ?? []).map(policy => policy.metadata?.name).filter((name): name is string => Boolean(name))- .map(name => this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace }))+ .map(async name => {+ try {+ await this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })+ } catch (error: unknown) {+ // A concurrent reconciler or the API server may have removed the+ // policy between list and delete. That is already the desired+ // postcondition; every other error must keep the revocation+ // transaction in progress and trigger a retry.+ if (getErrorCode(error) !== 404) throw error+ }+ }))}@@ -3993,6 +4173,21 @@ export class WorkflowReconciler {}}+ /**+ * SDK capability teardown is a revocation boundary, not best-effort+ * housekeeping. Ignore only an already-absent object; propagate every other+ * failure so the reconciler keeps the previous capability state and+ * requeues instead of publishing a false `disabled` result.+ */+ private async teardownDelete(deleteFn: () => Promise<unknown>): Promise<void> {+ try {+ await deleteFn()+ } catch (error: unknown) {+ if (getErrorCode(error) === 404) return+ throw error+ }+ }+private async deletePersistentVolumeClaimIfExists(name: string,namespace: stringdiff --git a/workflow-recipes/tests/unit/workflow/crdSchema.test.ts b/workflow-recipes/tests/unit/workflow/crdSchema.test.tsindex 81e245153..d5582cfb6 100644--- a/workflow-recipes/tests/unit/workflow/crdSchema.test.ts+++ b/workflow-recipes/tests/unit/workflow/crdSchema.test.ts@@ -128,7 +128,9 @@ describe('WorkflowRecipe CRD snippet step schema', () => {expect(rules).toContain('!has(self.pluginWorkloadSdk) || (has(self.steps) && size(self.steps) > 0) || (!has(self.triggers) && !has(self.scheduling) && !has(self.coordinatorImage))')- expect(crd).toContain('agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge')+ expect(crd).toContain(+ 'agent requires non-empty workflow steps or spec.pluginWorkloadSdk.promptBridge'+ )expect(crd).toContain('spec.pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage')diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.tsindex ef851ec39..2b8d740ef 100644--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts@@ -108,7 +108,18 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {configure: vi.fn(async () => ({ status: 500, body: {} })),configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({status: 200,- body: { configured: true },+ body: {+ configured: true,+ ready: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-openai',+ defaultProvider: 'openai',+ defaultModel: 'gpt-5.4-mini',+ },})),}const k8s = reader()@@ -122,7 +133,18 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {expect(result).toEqual({status: 202,- body: { configured: true, provider: 'openai', model: 'gpt-5.4-mini' },+ body: {+ configured: true,+ ready: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyRevision: 1,+ policyHash: 'a'.repeat(64),+ defaultTargetRef: 'primary-openai',+ defaultProvider: 'openai',+ defaultModel: 'gpt-5.4-mini',+ },})expect(mcpHost.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith('http://mcp-host:8090',@@ -132,4 +154,48 @@ describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()expect(k8s.readSecret).not.toHaveBeenCalled()})++ it('publishes identity readiness while an operator prompt grant is still missing', async () => {+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: {+ configured: true,+ ready: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ },+ })),+ }+ const k8s = reader()+ const handler = new ModelConfigHandler(k8s, mcpHost)++ const result = await handler.configurePluginWorkloadSdkBootstrap(+ 'openai',+ 'gpt-5.4-mini',+ 'http://mcp-host:8090',+ 'wrc-token'+ )++ expect(result).toEqual({+ status: 202,+ body: {+ configured: true,+ ready: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ contractVersion: 2,+ policyReady: false,+ policyState: 'missing',+ policyReason: 'grant_missing',+ },+ })+ expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()+ expect(k8s.readSecret).not.toHaveBeenCalled()+ })})diff --git a/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts b/workflow-recipes/tests/unit/workflow/workflowAuth.test.tsindex 0021eb872..f9e72a2b2 100644--- a/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts+++ b/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts@@ -99,6 +99,9 @@ describe('workflow auth token verification', () => {recipeName: 'recipe-one',recipeNamespace: 'sandbox-recipes',invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',provider: 'zai',model: 'glm-5.1',@@ -117,6 +120,9 @@ describe('workflow auth token verification', () => {await expect(auth.verifyPluginSdkCredentialTicket(ticket)).resolves.toMatchObject({invocationId: 'inv-1',+ attemptGeneration: 1,+ providerAttemptId: 'provider-attempt-1',+ providerAttemptIndex: 1,targetRef: 'primary-zai',policyRevision: 4,policyHash: 'a'.repeat(64),