Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(plugin-sdk): support stepless multiprovider prompt bridge
Alfredo Lopezdcfb9b7a25a9
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yamlindex ae0cb0d7f..9a563eba6 100644--- a/charts/clerum-crds/crds/workflowrecipe.yaml+++ b/charts/clerum-crds/crds/workflowrecipe.yaml@@ -44,9 +44,14 @@ spec:type: object# workloads is not required when steps is present (workflow-only recipes)x-kubernetes-validations:- # R1: agent{} requires steps[] — no agent without workflow- - rule: "!has(self.agent) || has(self.steps)"- message: "agent requires steps: cannot define agent without workflow steps"+ # 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"+ # 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))"+ message: "spec.pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage"# R2: recipe must have workloads or steps (not empty)- rule: "(has(self.workloads) && size(self.workloads) > 0) || has(self.steps)"message: "recipe must define at least workloads or steps"diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex f2a21da38..ad1b0ca0b 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -7,6 +7,7 @@ import {import { config } from './config.js'import { applyMemberRegistrationCredentialsSchema } from './services/memberRegistrationCredentialsSchema.js'import {+ addPluginWorkloadSdkPromptTargetPolicyColumns,addPluginWorkloadSdkProviderColumn,applyPluginWorkloadSdkSchema,dropPluginWorkloadSdkSuperAdminApprovedColumn,@@ -5024,6 +5025,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [`)},},+ {+ version: '0075_plugin_workload_sdk_prompt_target_policy',+ apply: addPluginWorkloadSdkPromptTargetPolicyColumns,+ },]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 fa28ada4c..5b6231ccc 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -1,5 +1,5 @@import { type Response, Router } from 'express'-import { isLlmProviderId } from '@clerum/llm-providers'+import { PROVIDER_CREDENTIAL_SLOTS, isLlmProviderId } from '@clerum/llm-providers'import { asyncHandler } from '../../http/asyncHandler.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModels.js'@@ -11,6 +11,7 @@ import {type PluginWorkloadSdkFamily,type PluginWorkloadSdkInvocationStatus,type PluginWorkloadSdkModelPolicy,+ type PluginWorkloadSdkPromptTarget,type PluginWorkloadSdkQuotaLimits,deleteGrant,getQuotaCounters,@@ -40,6 +41,7 @@ const STATUS_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_INVOCATION_STATUSES)// grant creation so the failure is loud and immediate, not silent data loss.// (targetRefs are opaque provider identities, so they are intentionally exempt.)const USER_REF_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+const SECRET_KEY_RE = /^[-._a-zA-Z0-9]+$/function parseIsoTimestamp(value: unknown,@@ -142,6 +144,86 @@ function parseModelPolicies(return policies}+function credentialSlotBelongsToProvider(provider: string, credentialSlot: string): boolean {+ if (!isLlmProviderId(provider)) return false+ const canonicalSlots = PROVIDER_CREDENTIAL_SLOTS[provider].map(slot => slot.dataKey)+ // Extra slots are created by the additive secrets editor and remain owned by+ // their provider. A target only carries the key identity; this route never+ // reads the Secret or returns a value.+ return (+ canonicalSlots.some(slot => credentialSlot === slot || credentialSlot.startsWith(`${slot}-`)) ||+ credentialSlot.startsWith(`${provider}-`)+ )+}++function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPromptTarget[] | null {+ if (!Array.isArray(value) || value.length === 0) {+ res+ .status(400)+ .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` })+ return null+ }+ const targets: PluginWorkloadSdkPromptTarget[] = []+ const targetRefs = new Set<string>()+ // Provider + model must be unique even when two extra slots exist. Otherwise+ // the documented exact `{provider, model}` selector and modelPolicyRef would+ // choose a credential slot implicitly, which is a policy bypass.+ const providerModels = new Set<string>()+ for (let index = 0; index < value.length; index++) {+ const raw = value[index]+ if (!isPlainObject(raw)) {+ res.status(400).json({ error: `promptTargets[${index}] must be an object` })+ return null+ }+ const targetRef = typeof raw.targetRef === 'string' ? raw.targetRef.trim() : ''+ const provider = typeof raw.provider === 'string' ? raw.provider.trim() : ''+ const model = typeof raw.model === 'string' ? raw.model.trim() : ''+ const credentialSlot = typeof raw.credentialSlot === 'string' ? raw.credentialSlot.trim() : ''+ if (!targetRef || targetRef.length > MAX_ALLOWLIST_ENTRY_LENGTH || targetRef.includes('*')) {+ res+ .status(400)+ .json({ error: `promptTargets[${index}].targetRef must be a non-wildcard identifier` })+ return null+ }+ if (!isLlmProviderId(provider)) {+ res.status(400).json({ error: `promptTargets[${index}].provider is invalid` })+ return null+ }+ if (!model || model.length > 400 || model.includes('*')) {+ res+ .status(400)+ .json({ error: `promptTargets[${index}].model must be a non-wildcard model id` })+ return null+ }+ if (+ !credentialSlot ||+ credentialSlot.length > 253 ||+ !SECRET_KEY_RE.test(credentialSlot) ||+ !credentialSlotBelongsToProvider(provider, credentialSlot)+ ) {+ res.status(400).json({+ error: `promptTargets[${index}].credentialSlot must be a valid slot owned by provider "${provider}"`,+ })+ return null+ }+ const providerModel = `${provider}\u0000${model}`+ if (targetRefs.has(targetRef) || providerModels.has(providerModel)) {+ res.status(400).json({ error: `promptTargets[${index}] duplicates an existing target` })+ return null+ }+ targetRefs.add(targetRef)+ providerModels.add(providerModel)+ targets.push({ targetRef, provider, model, credentialSlot })+ }+ return targets+}+export function createAdminPluginWorkloadSdkRouter(): Router {const router = Router()@@ -216,9 +298,20 @@ export function createAdminPluginWorkloadSdkRouter(): Router {.json({ error: 'allowedEventTypes must be non-empty for clientNotifications grants' })return}- if (capabilityFamily === 'promptBridge' && allowedModels.length === 0) {- res.status(400).json({ error: 'allowedModels must be non-empty for promptBridge grants' })- return+ const promptTargets =+ capabilityFamily === 'promptBridge' ? parsePromptTargets(body.promptTargets, res) : []+ if (promptTargets === null) return+ const defaultTargetRef =+ capabilityFamily === 'promptBridge' && typeof body.defaultTargetRef === 'string'+ ? body.defaultTargetRef.trim()+ : ''+ if (capabilityFamily === 'promptBridge') {+ if (!defaultTargetRef || promptTargets[0]?.targetRef !== defaultTargetRef) {+ res.status(400).json({+ error: 'defaultTargetRef is required and must be the first promptTargets entry',+ })+ return+ }}// R1: promptBridge credentials resolve per-provider, so the grant stores an@@ -243,17 +336,48 @@ export function createAdminPluginWorkloadSdkRouter(): Router {provider = rawProvider}- // R3: close the R1 hand-off (documented in the migration notes). Every- // promptBridge model must be enabled under the grant's provider in the- // operator allowlist — reject the offenders with 400 model_not_allowed.- // (clientNotifications grants carry no models and skip this.)- if (provider && allowedModels.length > 0) {- const enabled = new Set(await listEnabledModelNamesForProvider(provider))- const offenders = allowedModels.filter(model => !enabled.has(model))- if (offenders.length > 0) {- res.status(400).json({ error: 'model_not_allowed', provider, models: offenders })+ if (capabilityFamily === 'promptBridge') {+ const defaultTarget = promptTargets[0]!+ // `provider` remains the bootstrap host binding during the compatibility+ // window. It cannot authorize routes by itself and must agree with the+ // policy default instead of being silently reconciled.+ if (provider !== defaultTarget.provider) {+ res.status(400).json({ error: 'policy_bootstrap_mismatch' })return}+ const modelsByProvider = new Map<string, string[]>()+ for (const target of promptTargets) {+ modelsByProvider.set(target.provider, [+ ...(modelsByProvider.get(target.provider) ?? []),+ target.model,+ ])+ }+ for (const [targetProvider, targetModels] of modelsByProvider) {+ const enabled = new Set(await listEnabledModelNamesForProvider(targetProvider))+ const offenders = targetModels.filter(model => !enabled.has(model))+ if (offenders.length > 0) {+ res.status(400).json({+ error: 'model_not_allowed',+ provider: targetProvider,+ models: offenders,+ })+ return+ }+ }+ // A modelPolicyRef names an already-authorized target, not a second+ // routing authority. Keep the older record shape but reject drift.+ for (const [ref, policy] of Object.entries(modelPolicies)) {+ if (+ !promptTargets.some(+ target => target.provider === policy.provider && target.model === policy.model+ )+ ) {+ res+ .status(400)+ .json({ error: `modelPolicies.${ref} does not match an authorized target` })+ return+ }+ }}if (allowedCallers.length === 0) {@@ -274,6 +398,8 @@ export function createAdminPluginWorkloadSdkRouter(): Router {allowedCallers,quotaLimits,modelPolicies,+ promptTargets,+ defaultTargetRef: defaultTargetRef || undefined,},(req as UiAuthedRequest).adminAuth!.sub)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 9504194e2..8211bee2b 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@@ -10,6 +10,7 @@ import {authorizeListRecipients,authorizePromptBridge,} from '../../services/pluginWorkloadSdkAuthorizer.js'+import { verifyPluginWorkloadSdkCredentialTicket } from '../../services/pluginWorkloadSdkCredentialTicket.js'import {DEFAULT_IDEMPOTENCY_KEY_PATTERN,DEFAULT_MAX_BODY_BYTES,@@ -22,7 +23,9 @@ import {type PluginWorkloadSdkErrorCode,} from '../../services/pluginWorkloadSdkDb.js'import {+ findGrant,getInvocationById,+ hashPromptTargetPolicy,listInvocations,resolveRecipientProfiles,} from '../../services/pluginWorkloadSdkDb.js'@@ -50,9 +53,11 @@ const AUTHZ_HTTP_STATUS: Record<PluginWorkloadSdkErrorCode, number> = {caller_not_allowed: 403,scope_denied: 403,target_not_allowed: 403,+ ambiguous_model: 409,event_type_not_allowed: 403,quota_exceeded: 429,provider_policy_denied: 403,+ provider_unavailable: 503,payload_too_large: 413,idempotency_conflict: 422,recipe_binding_mismatch: 400,@@ -113,11 +118,16 @@ function validateCallerRef(value: unknown, res: Response): string | null {interface ParsedPromptBridgeBody {callerRef: string+ bootstrapProvider: string+ bootstrapModel: stringmodel?: string+ provider?: string+ targetRef?: stringmodelPolicyRef?: stringpurpose: stringidempotencyKey: stringmessages: Array<{ role: string; content: string }>+ metadata?: Record<string, unknown>correlationId?: string}@@ -128,6 +138,16 @@ function parsePromptBridgeBody(const callerRef = validateCallerRef(body.callerRef, res)if (!callerRef) 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) {+ res.status(400).json({ error: 'bootstrap_binding_required' })+ return null+ }+const idempotencyKey = validateIdempotencyKey(body.idempotencyKey, res)if (!idempotencyKey) return null@@ -166,7 +186,37 @@ function parsePromptBridgeBody(return null}+ let metadata: Record<string, unknown> | undefined+ if (body.metadata !== undefined) {+ if (!isPlainObject(body.metadata)) {+ res.status(400).json({ error: 'metadata must be an object' })+ return null+ }+ try {+ if (Buffer.byteLength(JSON.stringify(body.metadata), 'utf8') > 16 * 1024) {+ res.status(413).json({ error: 'metadata_too_large', retryable: false })+ return null+ }+ metadata = body.metadata as Record<string, unknown>+ } catch {+ res.status(400).json({ error: 'metadata must be JSON-serializable' })+ return null+ }+ }+const model = typeof body.model === 'string' && body.model.trim() ? body.model.trim() : undefined+ const provider =+ typeof body.provider === 'string' && body.provider.trim() ? body.provider.trim() : undefined+ const targetRef =+ typeof body.targetRef === 'string' && body.targetRef.trim() ? body.targetRef.trim() : undefined+ if (targetRef && targetRef.length > MAX_TARGET_REF_LENGTH) {+ res.status(400).json({ error: `targetRef exceeds maximum length of ${MAX_TARGET_REF_LENGTH}` })+ return null+ }+ if (provider && !model && !targetRef) {+ res.status(400).json({ error: 'provider requires model or targetRef' })+ return null+ }const modelPolicyRef =typeof body.modelPolicyRef === 'string' && body.modelPolicyRef.trim()? body.modelPolicyRef.trim()@@ -178,11 +228,16 @@ function parsePromptBridgeBody(return {callerRef,+ bootstrapProvider,+ bootstrapModel,model,+ provider,+ targetRef,modelPolicyRef,purpose: body.purpose,idempotencyKey,messages,+ ...(metadata ? { metadata } : {}),correlationId,}}@@ -350,14 +405,22 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {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,})@@ -372,6 +435,11 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {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,+ authorizedTargetTickets: result.value.authorizedTargetTickets,maxOutputTokens: result.value.maxOutputTokens,})})@@ -476,6 +544,63 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {}))+ // TOCTOU guard for cross-provider credential resolution. The mcp-host must+ // re-check a short-lived signed target ticket immediately before reading its+ // credential slot. This endpoint returns no target data and never redeems a+ // secret; it only attests that the ticket still matches the current policy.+ router.post(+ '/mcp-host/plugin-workload-sdk/credential-ticket/introspect',+ requireMcpHostJwt,+ asyncHandler(async (req, res) => {+ const claims = req.mcpHostJwt!+ const body = isPlainObject(req.body) ? req.body : {}+ const ticket = typeof body.credentialTicket === 'string' ? body.credentialTicket : ''+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId : ''+ const targetRef = typeof body.targetRef === 'string' ? body.targetRef : ''+ if (!ticket || !invocationId || !targetRef) {+ res.status(400).json({ error: 'credentialTicket, invocationId and targetRef are required' })+ return+ }+ const ticketClaims = verifyPluginWorkloadSdkCredentialTicket(ticket)+ if (+ !ticketClaims ||+ ticketClaims.recipeNamespace !== claims.recipeNamespace ||+ ticketClaims.recipeName !== claims.recipeName ||+ ticketClaims.sub !== `${claims.recipeNamespace}/${claims.recipeName}` ||+ ticketClaims.invocationId !== invocationId ||+ ticketClaims.targetRef !== targetRef+ ) {+ res.status(403).json({ error: 'provider_policy_denied', retryable: false })+ return+ }+ const invocation = await getInvocationById(invocationId)+ if (+ !invocation ||+ invocation.recipeNamespace !== claims.recipeNamespace ||+ invocation.recipeName !== claims.recipeName ||+ invocation.method !== 'promptBridge'+ ) {+ 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 ||+ !target ||+ grant.policyRevision !== ticketClaims.policyRevision ||+ hashPromptTargetPolicy(grant) !== ticketClaims.policyHash ||+ target.provider !== ticketClaims.provider ||+ target.model !== ticketClaims.model ||+ target.credentialSlot !== ticketClaims.credentialSlot+ ) {+ res.status(403).json({ error: 'provider_policy_denied', retryable: false })+ return+ }+ res.status(200).json({ active: true })+ })+ )+// Invocation status reporting (plan §2.4 lifecycle): the mcp-host SDK// server reports promptBridge outcomes so the audit trail tracks// in_progress → complete | failed | provider_unavailable.diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.tsindex 9d5df4144..fec5ea5ea 100644--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts@@ -1,10 +1,13 @@import { pluginWorkloadSdkAuthDecisionsTotal } from '../observability/metrics.js'import type { McpHostAccessClaims } from '../utils/auth/mcpHostJwtToken.js'+import { issuePluginWorkloadSdkCredentialTicket } from './pluginWorkloadSdkCredentialTicket.js'import {type PluginWorkloadSdkErrorCode,type PluginWorkloadSdkGrant,type PluginWorkloadSdkModelPolicy,+ type PluginWorkloadSdkPromptTarget,findGrant,+ hashPromptTargetPolicy,} from './pluginWorkloadSdkDb.js'import { markInvocationStatus, recordInvocation } from './pluginWorkloadSdkInvocationAuditor.js'import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js'@@ -73,7 +76,17 @@ function checkCaller(export interface AuthorizePromptBridgeParams {claims: McpHostAccessClaimscallerRef: string+ /**+ * Internal mcp-host bootstrap binding. This is deliberately separate from+ * the workload selector: the first ordered target must be the same provider+ * and model that the recipe-bound host was configured with. The check keeps+ * CRD/admin policy drift from reaching the credential broker.+ */+ bootstrapProvider?: string+ bootstrapModel?: stringmodel?: string+ provider?: string+ targetRef?: stringmodelPolicyRef?: stringpurpose: stringidempotencyKey: string@@ -89,9 +102,156 @@ export interface AuthorizedPromptBridge {status: stringmodel: string | nullmodelPolicy: PluginWorkloadSdkModelPolicy | null+ /** Operator-selected attempt; credentialSlot is an identity, never a value. */+ selectedTarget: PluginWorkloadSdkPromptTarget+ /** Selected target plus its strictly ordered authorized fallback suffix. */+ authorizedTargets: PluginWorkloadSdkPromptTarget[]+ policyRevision: number+ policyHash: string+ /** One short-lived signed authorization artifact per eligible target. */+ authorizedTargetTickets: Array<{ targetRef: string; credentialTicket: string }>maxOutputTokens: number | null}+function issueTargetTickets(+ claims: McpHostAccessClaims,+ invocationId: string,+ targets: PluginWorkloadSdkPromptTarget[],+ policyRevision: number,+ policyHash: string+): Array<{ targetRef: string; credentialTicket: string }> {+ return targets.map(target => ({+ targetRef: target.targetRef,+ credentialTicket: issuePluginWorkloadSdkCredentialTicket({+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ invocationId,+ target,+ policyRevision,+ policyHash,+ }),+ }))+}++type PromptTargetResolution =+ | { ok: true; selectedIndex: number; modelPolicy: PluginWorkloadSdkModelPolicy | null }+ | { ok: false; error: PluginWorkloadSdkAuthzError }++/**+ * Pure selector resolution. It deliberately runs before idempotency/audit,+ * quotas and all credential/provider seams so a denied selector cannot probe+ * which credentials happen to exist in the environment.+ */+function resolvePromptTarget(+ grant: PluginWorkloadSdkGrant,+ params: AuthorizePromptBridgeParams+): PromptTargetResolution {+ if (+ grant.promptTargets.length === 0 ||+ !grant.defaultTargetRef ||+ grant.promptTargets[0]?.targetRef !== grant.defaultTargetRef ||+ grant.policyRevision < 1+ ) {+ return {+ ok: false,+ error: deny(+ 'provider_policy_denied',+ 'promptBridge grant has no reviewed ordered target policy; migrate and re-save it'+ ),+ }+ }++ let candidates: Array<{ target: PluginWorkloadSdkPromptTarget; index: number }> =+ grant.promptTargets.map((target, index) => ({ target, index }))+ let modelPolicy: PluginWorkloadSdkModelPolicy | null = null+ if (params.modelPolicyRef !== undefined) {+ modelPolicy = grant.modelPolicies[params.modelPolicyRef] ?? null+ if (!modelPolicy) {+ return {+ ok: false,+ error: deny(+ 'provider_policy_denied',+ 'modelPolicyRef does not resolve to this grant policy'+ ),+ }+ }+ if (+ (params.model !== undefined && params.model !== modelPolicy.model) ||+ (params.provider !== undefined && params.provider !== modelPolicy.provider)+ ) {+ return {+ ok: false,+ error: deny('provider_policy_denied', 'selector does not match modelPolicyRef'),+ }+ }+ // A policy ref and target ref are two names for the same concrete target,+ // not independent selectors. Intersect them explicitly: otherwise the+ // policy-ref branch would silently ignore targetRef and authorize a target+ // different from the caller's declared intent.+ if (params.targetRef !== undefined) {+ const target = candidates.find(candidate => candidate.target.targetRef === params.targetRef)+ if (+ !target ||+ target.target.provider !== modelPolicy.provider ||+ target.target.model !== modelPolicy.model+ ) {+ return {+ ok: false,+ error: deny('provider_policy_denied', 'targetRef does not match modelPolicyRef'),+ }+ }+ candidates = [target]+ }+ candidates = candidates.filter(+ candidate =>+ candidate.target.provider === modelPolicy!.provider &&+ candidate.target.model === modelPolicy!.model+ )+ } else if (params.targetRef !== undefined) {+ candidates = candidates.filter(candidate => candidate.target.targetRef === params.targetRef)+ if (+ candidates.length === 1 &&+ ((params.model !== undefined && params.model !== candidates[0]!.target.model) ||+ (params.provider !== undefined && params.provider !== candidates[0]!.target.provider))+ ) {+ return {+ ok: false,+ error: deny('provider_policy_denied', 'selector fields are inconsistent'),+ }+ }+ } else if (params.provider !== undefined || params.model !== undefined) {+ candidates = candidates.filter(+ candidate =>+ (params.provider === undefined || candidate.target.provider === params.provider) &&+ (params.model === undefined || candidate.target.model === params.model)+ )+ } else {+ return { ok: true, selectedIndex: 0, modelPolicy: null }+ }++ if (candidates.length === 0) {+ return {+ ok: false,+ error: deny('target_not_allowed', 'requested target is not authorized by this grant'),+ }+ }+ // A bare model has no provider authority. Exact target/provider+model and+ // policy refs are necessarily unambiguous by their grammar.+ if (+ params.modelPolicyRef === undefined &&+ params.targetRef === undefined &&+ params.provider === undefined &&+ params.model !== undefined &&+ candidates.length > 1+ ) {+ return {+ ok: false,+ error: deny('ambiguous_model', 'model is authorized by multiple providers; select a target'),+ }+ }+ return { ok: true, selectedIndex: candidates[0]!.index, modelPolicy }+}+export async function authorizePromptBridge(params: AuthorizePromptBridgeParams): Promise<PluginWorkloadSdkAuthzResult<AuthorizedPromptBridge>> {@@ -122,41 +282,33 @@ async function authorizePromptBridgeInner(const callerError = checkCaller(grant, callerRef)if (callerError) return callerError- // Model policy resolution (plan §2.2): a modelPolicyRef is never a black- // box — it must resolve to a concrete record on the grant.- let modelPolicy: PluginWorkloadSdkModelPolicy | null = null- if (params.modelPolicyRef !== undefined) {- modelPolicy = grant.modelPolicies[params.modelPolicyRef] ?? null- if (!modelPolicy) {- return deny(- 'provider_policy_denied',- `modelPolicyRef "${params.modelPolicyRef}" does not resolve to a model policy record`- )- }- if (params.model !== undefined && params.model !== modelPolicy.model) {+ // The mcp-host is configured once by WRC with spec.agent. promptBridge may+ // fall back across the operator's ordered targets, but its primary target+ // must remain that same bootstrap binding. Reject drift before selector+ // resolution, audit, quota, or credential-ticket issuance.+ if (params.bootstrapProvider !== undefined || params.bootstrapModel !== undefined) {+ const bootstrapProvider = params.bootstrapProvider?.trim() ?? ''+ const bootstrapModel = params.bootstrapModel?.trim() ?? ''+ const primaryTarget = grant.promptTargets[0]+ if (+ !bootstrapProvider ||+ !bootstrapModel ||+ !primaryTarget ||+ primaryTarget.provider !== bootstrapProvider ||+ primaryTarget.model !== bootstrapModel+ ) {return deny('provider_policy_denied',- `model "${params.model}" does not match modelPolicyRef "${params.modelPolicyRef}"`+ 'promptBridge default target does not match the mcp-host bootstrap binding')}}- const requestedModel = modelPolicy?.model ?? params.model ?? null- if (grant.allowedModels.length === 0) {- return deny('provider_policy_denied', 'grant has no allowedModels configured for promptBridge')- }- if (requestedModel === null) {- return deny(- 'provider_policy_denied',- 'promptBridge requests must provide a model or a modelPolicyRef that resolves to one'- )- }- if (!grant.allowedModels.includes(requestedModel)) {- return deny(- 'provider_policy_denied',- `model "${requestedModel}" is not in the grant's allowedModels`- )- }+ const resolution = resolvePromptTarget(grant, params)+ if (!resolution.ok) return resolution.error+ const selectedTarget = grant.promptTargets[resolution.selectedIndex]!+ const authorizedTargets = grant.promptTargets.slice(resolution.selectedIndex)+ const resolvedPolicyHash = hashPromptTargetPolicy(grant)const recorded = await recordInvocation({recipeNamespace: claims.recipeNamespace,@@ -164,7 +316,7 @@ async function authorizePromptBridgeInner(callerRef,correlationId: params.correlationId,method: 'promptBridge',- detail: requestedModel ?? 'provider-default',+ detail: selectedTarget.model,purpose: params.purpose,idempotencyKey: params.idempotencyKey,payload: params.payload,@@ -192,8 +344,19 @@ async function authorizePromptBridgeInner(invocationId: recorded.invocation.id,replay: true,status: recorded.invocation.status,- model: requestedModel,- modelPolicy,+ model: selectedTarget.model,+ modelPolicy: resolution.modelPolicy,+ selectedTarget,+ authorizedTargets,+ policyRevision: grant.policyRevision,+ policyHash: resolvedPolicyHash,+ authorizedTargetTickets: issueTargetTickets(+ claims,+ recorded.invocation.id,+ authorizedTargets,+ grant.policyRevision,+ resolvedPolicyHash+ ),maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,},}@@ -236,16 +399,20 @@ async function authorizePromptBridgeInner(invocationId: recorded.invocation.id,replay: recorded.kind === 'replay',status: recorded.kind === 'replay' ? 'in_progress' : recorded.invocation.status,- model: requestedModel,- modelPolicy,+ model: selectedTarget.model,+ modelPolicy: resolution.modelPolicy,+ selectedTarget,+ authorizedTargets,+ policyRevision: grant.policyRevision,+ policyHash: resolvedPolicyHash,+ authorizedTargetTickets: issueTargetTickets(+ claims,+ recorded.invocation.id,+ authorizedTargets,+ grant.policyRevision,+ resolvedPolicyHash+ ),maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,- // TODO(R5-F6): this is the promptBridge failover STOP-POINT. The bridge's- // same-provider failover (mcp-host `LlmBridge`) reads `allowedModels` off- // this authorize response; today NO build populates it, so the bridge- // always receives `undefined` → zero fallback candidates → the F6 path is- // inert end-to-end. Exposing `allowedModels: grant.allowedModels` HERE is- // what activates it (fail over only within the grant, spec §3-R5.7).- // Deliberately NOT wired yet — out of R5 scope.},}}diff --git a/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts b/control-api/src/services/pluginWorkloadSdkCredentialTicket.tsnew file mode 100644index 000000000..2d09712a8--- /dev/null+++ b/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts@@ -0,0 +1,90 @@+import jwt from 'jsonwebtoken'+import { createPublicKey, randomUUID } from 'node:crypto'+import { config } from '../config.js'+import type { PluginWorkloadSdkPromptTarget } from './pluginWorkloadSdkDb.js'++// This is an authorization artifact, not a credential. It binds the exact+// already-authorized target to one invocation so mcp-host cannot be tricked+// into resolving a different slot from a caller-supplied policy response.+export const PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE = 'plugin-sdk-credential-broker'+const CREDENTIAL_TICKET_TTL_SECONDS = 60++export type PluginWorkloadSdkCredentialTicketClaims = {+ sub: string+ recipeNamespace: string+ recipeName: string+ invocationId: string+ targetRef: string+ provider: string+ model: string+ credentialSlot: string+ policyRevision: number+ policyHash: string+ typ: 'plugin-sdk-credential-ticket'+}++export function issuePluginWorkloadSdkCredentialTicket(input: {+ recipeNamespace: string+ recipeName: string+ invocationId: string+ target: PluginWorkloadSdkPromptTarget+ policyRevision: number+ policyHash: string+}): string {+ const claims: PluginWorkloadSdkCredentialTicketClaims = {+ sub: `${input.recipeNamespace}/${input.recipeName}`,+ recipeNamespace: input.recipeNamespace,+ recipeName: input.recipeName,+ invocationId: input.invocationId,+ targetRef: input.target.targetRef,+ provider: input.target.provider,+ model: input.target.model,+ credentialSlot: input.target.credentialSlot,+ policyRevision: input.policyRevision,+ policyHash: input.policyHash,+ typ: 'plugin-sdk-credential-ticket',+ }+ return jwt.sign(claims, config.adminJwtPrivateKey, {+ algorithm: 'RS256',+ issuer: config.adminJwtIssuer,+ audience: PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,+ jwtid: randomUUID(),+ expiresIn: CREDENTIAL_TICKET_TTL_SECONDS,+ })+}++export function verifyPluginWorkloadSdkCredentialTicket(+ ticket: string+): PluginWorkloadSdkCredentialTicketClaims | null {+ try {+ const publicKey = createPublicKey(config.adminJwtPrivateKey).export({+ type: 'spki',+ format: 'pem',+ })+ const verified = jwt.verify(ticket, publicKey, {+ algorithms: ['RS256'],+ issuer: config.adminJwtIssuer,+ audience: PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,+ })+ if (typeof verified !== 'object' || verified === null) return null+ const claims = verified as jwt.JwtPayload+ if (+ typeof claims.sub !== 'string' ||+ typeof claims.recipeNamespace !== 'string' ||+ typeof claims.recipeName !== 'string' ||+ typeof claims.invocationId !== 'string' ||+ typeof claims.targetRef !== 'string' ||+ typeof claims.provider !== 'string' ||+ typeof claims.model !== 'string' ||+ typeof claims.credentialSlot !== 'string' ||+ typeof claims.policyRevision !== 'number' ||+ typeof claims.policyHash !== 'string' ||+ claims.typ !== 'plugin-sdk-credential-ticket'+ ) {+ return null+ }+ return claims as unknown as PluginWorkloadSdkCredentialTicketClaims+ } catch {+ return null+ }+}diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex 370188234..fcabee050 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -33,9 +33,11 @@ export const PLUGIN_WORKLOAD_SDK_ERROR_CODES = ['caller_not_allowed','scope_denied','target_not_allowed',+ 'ambiguous_model','event_type_not_allowed','quota_exceeded','provider_policy_denied',+ 'provider_unavailable','payload_too_large','idempotency_conflict','recipe_binding_mismatch',@@ -91,6 +93,15 @@ export interface PluginWorkloadSdkModelPolicy {maxCostUsd?: number}+/** A single operator-authorized promptBridge attempt target. */+export interface PluginWorkloadSdkPromptTarget {+ targetRef: string+ provider: string+ model: string+ /** Secret data-key identity only; never its value. */+ credentialSlot: string+}+export interface PluginWorkloadSdkGrant {id: stringrecipeNamespace: string@@ -110,6 +121,10 @@ export interface PluginWorkloadSdkGrant {allowedCallers: string[]quotaLimits: PluginWorkloadSdkQuotaLimitsmodelPolicies: Record<string, PluginWorkloadSdkModelPolicy>+ /** Empty/null means a legacy grant and is deliberately not routable. */+ promptTargets: PluginWorkloadSdkPromptTarget[]+ defaultTargetRef: string | null+ policyRevision: numbercreatedAt: stringupdatedAt: string}@@ -154,12 +169,51 @@ export function hashPayload(payload: unknown): string {return createHash('sha256').update(stableStringify(payload)).digest('hex')}+/** Stable fingerprint of the complete ordered policy; contains no secret values. */+export function hashPromptTargetPolicy(+ grant: Pick<PluginWorkloadSdkGrant, 'policyRevision' | 'defaultTargetRef' | 'promptTargets'>+): string {+ return createHash('sha256')+ .update(+ stableStringify({+ revision: grant.policyRevision,+ defaultTargetRef: grant.defaultTargetRef,+ targets: grant.promptTargets,+ })+ )+ .digest('hex')+}+// ─── Row mapping ─────────────────────────────────────────────────────────function stringArray(value: unknown): string[] {return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []}+function promptTargets(value: unknown): PluginWorkloadSdkPromptTarget[] {+ if (!Array.isArray(value)) return []+ return value.flatMap(raw => {+ if (typeof raw !== 'object' || raw === null) return []+ const target = raw as Record<string, unknown>+ if (+ typeof target.targetRef !== 'string' ||+ typeof target.provider !== 'string' ||+ typeof target.model !== 'string' ||+ typeof target.credentialSlot !== 'string'+ ) {+ return []+ }+ return [+ {+ targetRef: target.targetRef,+ provider: target.provider,+ model: target.model,+ credentialSlot: target.credentialSlot,+ },+ ]+ })+}+function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {const family = row.capability_familyif (!PLUGIN_WORKLOAD_SDK_FAMILIES.includes(family as PluginWorkloadSdkFamily)) {@@ -188,6 +242,12 @@ function mapGrantRow(row: Record<string, unknown>): PluginWorkloadSdkGrant {allowedCallers: stringArray(row.allowed_callers),quotaLimits,modelPolicies,+ promptTargets: promptTargets(row.prompt_targets),+ defaultTargetRef: row.default_target_ref == null ? null : String(row.default_target_ref),+ policyRevision:+ typeof row.policy_revision === 'number' && Number.isInteger(row.policy_revision)+ ? row.policy_revision+ : 0,createdAt: new Date(row.created_at as string).toISOString(),updatedAt: new Date(row.updated_at as string).toISOString(),}@@ -248,6 +308,8 @@ export interface UpsertGrantParams {allowedCallers?: string[]quotaLimits?: PluginWorkloadSdkQuotaLimitsmodelPolicies?: Record<string, PluginWorkloadSdkModelPolicy>+ promptTargets?: PluginWorkloadSdkPromptTarget[]+ defaultTargetRef?: string}export async function upsertGrant(@@ -271,9 +333,9 @@ export async function upsertGrant(const result = await db.query(`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)- VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb, $10::jsonb, $11::jsonb)+ allowed_event_types, allowed_target_refs, allowed_user_refs, allowed_callers,+ 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 SETprovider = EXCLUDED.provider,@@ -284,6 +346,9 @@ export async function upsertGrant(allowed_callers = EXCLUDED.allowed_callers,quota_limits = EXCLUDED.quota_limits,model_policies = EXCLUDED.model_policies,+ prompt_targets = EXCLUDED.prompt_targets,+ default_target_ref = EXCLUDED.default_target_ref,+ policy_revision = plugin_workload_sdk_grants.policy_revision + 1,updated_at = now()RETURNING *`,[@@ -298,6 +363,8 @@ export async function upsertGrant(JSON.stringify(params.allowedCallers ?? []),JSON.stringify(params.quotaLimits ?? {}),JSON.stringify(params.modelPolicies ?? {}),+ JSON.stringify(params.promptTargets ?? []),+ params.defaultTargetRef ?? null,])const grant = mapGrantRow(result.rows[0] as Record<string, unknown>)diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.tsindex b95b73170..2af3791b8 100644--- a/control-api/src/services/pluginWorkloadSdkSchema.ts+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts@@ -23,6 +23,12 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>allowed_callers JSONB NOT NULL DEFAULT '[]'::jsonb,quota_limits JSONB NOT NULL DEFAULT '{}'::jsonb,model_policies JSONB NOT NULL DEFAULT '{}'::jsonb,+ -- Ordered operator-authorized promptBridge routing policy. This stays+ -- separate from legacy provider/allowed_models so old rows can be+ -- inventoried without accidentally becoming a routable policy.+ prompt_targets JSONB NOT NULL DEFAULT '[]'::jsonb,+ default_target_ref TEXT NULL,+ policy_revision INTEGER NOT NULL DEFAULT 1,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE (recipe_namespace, recipe_name, capability_family)@@ -87,3 +93,17 @@ export async function addPluginWorkloadSdkProviderColumn(db: DbClient): Promise<ADD COLUMN IF NOT EXISTS provider TEXT;`)}++/**+ * Adds the explicit ordered promptBridge target policy. JSONB arrays retain+ * operator-authored order; the writer updates every policy field together in+ * one transaction and increments the revision on every replacement.+ */+export async function addPluginWorkloadSdkPromptTargetPolicyColumns(db: DbClient): Promise<void> {+ await db.query(`+ ALTER TABLE plugin_workload_sdk_grants+ ADD COLUMN IF NOT EXISTS prompt_targets JSONB NOT NULL DEFAULT '[]'::jsonb,+ ADD COLUMN IF NOT EXISTS default_target_ref TEXT NULL,+ ADD COLUMN IF NOT EXISTS policy_revision INTEGER NOT NULL DEFAULT 1;+ `)+}diff --git a/control-api/test/db.ready.test.ts b/control-api/test/db.ready.test.tsindex 4fcb65b17..a440a8a53 100644--- a/control-api/test/db.ready.test.ts+++ b/control-api/test/db.ready.test.ts@@ -7,7 +7,7 @@ describe('assertDbReady', () => {await expect(assertDbReady({ query })).resolves.toBeUndefined()expect(query).toHaveBeenCalledWith(expect.stringContaining('schema_migrations'), [- '0074_gfs_runtime_role_exact_contract',+ '0075_plugin_workload_sdk_prompt_target_policy',])})@@ -15,7 +15,7 @@ describe('assertDbReady', () => {const query = vi.fn().mockResolvedValue({ rows: [{ ready: false }], rowCount: 1 })await expect(assertDbReady({ query })).rejects.toThrow(- 'migration 0074_gfs_runtime_role_exact_contract is required'+ 'migration 0075_plugin_workload_sdk_prompt_target_policy is required')})})diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.tsindex b12f2eeab..669c2ec7e 100644--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts@@ -74,9 +74,11 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {try {await client.query('BEGIN')await client.query(- `DELETE FROM schema_migrations WHERE version='0074_gfs_runtime_role_exact_contract'`+ `DELETE FROM schema_migrations WHERE version='0075_plugin_workload_sdk_prompt_target_policy'`+ )+ await expect(assertDbReady(client)).rejects.toThrow(+ /0075_plugin_workload_sdk_prompt_target_policy/)- await expect(assertDbReady(client)).rejects.toThrow(/0074_gfs_runtime_role_exact_contract/)} finally {await client.query('ROLLBACK').catch(() => undefined)client.release()diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex 249bd4705..3a7b5aa20 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -46,6 +46,15 @@ const validGrantBody = {capabilityFamily: 'promptBridge',provider: 'zai',allowedModels: ['glm-4.7'],+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ defaultTargetRef: 'primary-zai',allowedCallers: ['api'],}@@ -121,15 +130,60 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {expect(res.status).toBe(400)})- it('requires non-empty allowedModels for promptBridge grants', async () => {+ it('requires an explicit ordered target policy for promptBridge grants', async () => {const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')- .send({ ...validGrantBody, allowedModels: [] })+ .send({ ...validGrantBody, promptTargets: [] })expect(res.status).toBe(400)- expect(res.body.error).toBe('allowedModels must be non-empty for promptBridge grants')+ expect(res.body.error).toBe('promptTargets must be a non-empty array for promptBridge grants')expect(sdkDb.upsertGrant).not.toHaveBeenCalled()})+ it('rejects a default that is not the first operator-authored target', async () => {+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send({ ...validGrantBody, defaultTargetRef: 'another-target' })+ expect(res.status).toBe(400)+ expect(res.body.error).toContain('defaultTargetRef')+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })++ it('persists an ordered multiprovider policy without exposing a credential value', async () => {+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'multiprovider' } as never)+ vi.mocked(pool.query).mockImplementation(((_sql: string, values?: unknown[]) => {+ const provider = values?.[0]+ return Promise.resolve({+ rows: [{ model: provider === 'openai' ? 'gpt-5.4' : 'glm-4.7' }],+ rowCount: 1,+ })+ }) as never)+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ promptTargets: [+ ...validGrantBody.promptTargets,+ {+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key-fb1',+ },+ ],+ })+ expect(res.status).toBe(200)+ expect(sdkDb.upsertGrant).toHaveBeenCalledWith(+ expect.objectContaining({+ defaultTargetRef: 'primary-zai',+ promptTargets: expect.arrayContaining([+ expect.objectContaining({ targetRef: 'openai-fallback', provider: 'openai' }),+ ]),+ }),+ '11111111-1111-4111-8111-111111111111'+ )+ expect(JSON.stringify(vi.mocked(sdkDb.upsertGrant).mock.calls)).not.toContain('secret-value')+ })+it('requires an explicit provider for promptBridge grants (R1)', async () => {const { provider: _omit, ...bodyWithoutProvider } = validGrantBodyconst res = await request(buildApp())@@ -167,7 +221,20 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {} as never)const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')- .send({ ...validGrantBody, provider: 'vertex', allowedModels: ['gemini-2.5-pro'] })+ .send({+ ...validGrantBody,+ provider: 'vertex',+ allowedModels: ['gemini-2.5-pro'],+ promptTargets: [+ {+ targetRef: 'primary-vertex',+ provider: 'vertex',+ model: 'gemini-2.5-pro',+ credentialSlot: 'vertex-service-account-json',+ },+ ],+ defaultTargetRef: 'primary-vertex',+ })expect(res.status).toBe(200)expect(sdkDb.upsertGrant).toHaveBeenCalledWith(expect.objectContaining({ provider: 'vertex' }),@@ -240,13 +307,24 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {)})- it('rejects promptBridge allowedModels outside the provider allowlist (R3)', async () => {+ it('rejects promptBridge targets outside the provider allowlist', async () => {// Allowlist for provider `zai` enables only glm-4.7; the request asks for a// model that is not enabled → 400 model_not_allowed listing the offenders.vi.mocked(pool.query).mockResolvedValue({ rows: [{ model: 'glm-4.7' }], rowCount: 1 } as never)const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')- .send({ ...validGrantBody, allowedModels: ['glm-4.7', 'glm-9-not-allowed'] })+ .send({+ ...validGrantBody,+ promptTargets: [+ ...validGrantBody.promptTargets,+ {+ targetRef: 'not-allowed',+ provider: 'zai',+ model: 'glm-9-not-allowed',+ credentialSlot: 'zai-api-key-fb1',+ },+ ],+ })expect(res.status).toBe(400)expect(res.body.error).toBe('model_not_allowed')expect(res.body.provider).toBe('zai')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 98fdebb13..9c818b331 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@@ -79,6 +79,8 @@ const validPromptBody = {recipeNamespace: NS,recipeName: RECIPE,callerRef: 'api',+ bootstrapProvider: 'zai',+ bootstrapModel: 'glm-4.7',purpose: 'summarization',idempotencyKey: 'key-1',messages: [{ role: 'user', content: 'summarize this' }],@@ -111,6 +113,23 @@ beforeEach(() => {status: 'in_progress',model: 'glm-4.7',modelPolicy: null,+ selectedTarget: {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ authorizedTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ policyRevision: 1,+ policyHash: 'policy-hash',+ authorizedTargetTickets: [{ targetRef: 'primary-zai', credentialTicket: 'signed-ticket' }],maxOutputTokens: null,},})@@ -225,6 +244,39 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {.send(validPromptBody)expect(res.status).toBe(201)expect(res.body).toMatchObject({ invocationId: 'inv-1', replay: false, model: 'glm-4.7' })+ expect(res.body).toMatchObject({+ selectedTarget: { targetRef: 'primary-zai', credentialSlot: 'zai-api-key' },+ authorizedTargetTickets: [{ targetRef: 'primary-zai' }],+ })+ })++ it('forwards an exact provider/model selector without accepting a raw credential', async () => {+ await request(buildApp())+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge')+ .set('Authorization', `Bearer ${issueSdkToken()}`)+ .send({ ...validPromptBody, provider: 'openai', model: 'gpt-5.4' })+ .expect(201)+ expect(authorizer.authorizePromptBridge).toHaveBeenCalledWith(+ expect.objectContaining({ provider: 'openai', model: 'gpt-5.4', targetRef: undefined })+ )+ expect(authorizer.authorizePromptBridge).not.toHaveBeenCalledWith(+ expect.objectContaining({ credentialSlot: expect.anything() })+ )+ })++ it('includes caller metadata in the canonical payload used for idempotency', async () => {+ await request(buildApp())+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge')+ .set('Authorization', `Bearer ${issueSdkToken()}`)+ .send({ ...validPromptBody, metadata: { traceId: 'trace-1', source: 'sandbox-ui' } })++ expect(authorizer.authorizePromptBridge).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ metadata: { traceId: 'trace-1', source: 'sandbox-ui' },+ }),+ })+ )})it('returns 200 on idempotent replay', async () => {@@ -236,6 +288,23 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {status: 'complete',model: 'glm-4.7',modelPolicy: null,+ selectedTarget: {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ authorizedTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ policyRevision: 1,+ policyHash: 'policy-hash',+ authorizedTargetTickets: [{ targetRef: 'primary-zai', credentialTicket: 'signed-ticket' }],maxOutputTokens: null,},})@@ -556,3 +625,15 @@ describe('GET /mcp-host/plugin-workload-sdk/invocations/:recipeRef', () => {})})})++describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () => {+ it('fails closed for an invalid ticket and never returns credential metadata', async () => {+ 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' })+ expect(res.status).toBe(403)+ expect(res.body).toEqual({ error: 'provider_policy_denied', retryable: false })+ expect(JSON.stringify(res.body)).not.toContain('credentialSlot')+ })+})diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.tsindex ceff496a6..00af72e4b 100644--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts@@ -55,6 +55,7 @@ function grant(recipeNamespace: NS,recipeName: RECIPE,capabilityFamily: 'promptBridge',+ provider: 'zai',allowedModels: ['glm-4.7'],allowedEventTypes: [],allowedTargetRefs: [],@@ -62,6 +63,16 @@ function grant(allowedCallers: ['api'],quotaLimits: {},modelPolicies: {},+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ defaultTargetRef: 'primary-zai',+ policyRevision: 1,createdAt: '2026-06-09T00:00:00.000Z',updatedAt: '2026-06-09T00:00:00.000Z',...overrides,@@ -146,24 +157,26 @@ describe('authorizePromptBridge', () => {expect(result).toMatchObject({ ok: false, error: 'caller_not_allowed' })})- it('returns provider_policy_denied for a model outside allowedModels', async () => {+ it('returns target_not_allowed for a model outside the ordered policy', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ allowedModels: ['glm-4.7'] }))const result = await authorizePromptBridge({claims: claims(),...basePromptParams,model: 'gpt-4o',})- expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect(result).toMatchObject({ ok: false, error: 'target_not_allowed' })})- it('fails closed when a promptBridge grant has no allowedModels', async () => {- vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ allowedModels: [] }))+ it('fails closed when a legacy promptBridge grant has no ordered policy', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({ promptTargets: [], defaultTargetRef: null, policyRevision: 0 })+ )const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })expect(sdkDb.insertInvocation).not.toHaveBeenCalled()})- it('fails closed when the request has no concrete model', async () => {+ it('uses the ordered default when the request omits a selector', async () => {const paramsWithoutModel = {callerRef: basePromptParams.callerRef,purpose: basePromptParams.purpose,@@ -172,18 +185,87 @@ describe('authorizePromptBridge', () => {}vi.mocked(sdkDb.findGrant).mockResolvedValue(grant())const result = await authorizePromptBridge({ claims: claims(), ...paramsWithoutModel })- expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect(result).toMatchObject({+ ok: true,+ value: { selectedTarget: { targetRef: 'primary-zai', model: 'glm-4.7' } },+ })+ })++ it('returns an explicit approved target and only its fallback suffix', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({+ promptTargets: [+ {+ targetRef: 'zai-primary',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key',+ },+ ],+ defaultTargetRef: 'zai-primary',+ })+ )+ const result = await authorizePromptBridge({+ claims: claims(),+ callerRef: basePromptParams.callerRef,+ purpose: basePromptParams.purpose,+ idempotencyKey: basePromptParams.idempotencyKey,+ payload: basePromptParams.payload,+ targetRef: 'openai-fallback',+ })+ expect(result).toMatchObject({+ ok: true,+ value: {+ selectedTarget: { targetRef: 'openai-fallback', provider: 'openai' },+ authorizedTargets: [{ targetRef: 'openai-fallback' }],+ policyRevision: 1,+ },+ })+ })++ it('rejects a bare model shared by two authorized providers before recording an invocation', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({+ promptTargets: [+ {+ targetRef: 'zai-primary',+ provider: 'zai',+ model: 'shared',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'shared',+ credentialSlot: 'openai-api-key',+ },+ ],+ defaultTargetRef: 'zai-primary',+ })+ )+ const result = await authorizePromptBridge({+ claims: claims(),+ ...basePromptParams,+ model: 'shared',+ })+ expect(result).toMatchObject({ ok: false, error: 'ambiguous_model' })expect(sdkDb.insertInvocation).not.toHaveBeenCalled()})- it('rejects wildcard allowedModels entries', async () => {+ it('does not treat a legacy wildcard allowedModels entry as routing authority', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ allowedModels: ['*'] }))const result = await authorizePromptBridge({claims: claims(),...basePromptParams,model: 'gpt-4o',})- expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect(result).toMatchObject({ ok: false, error: 'target_not_allowed' })})it('returns provider_policy_denied for an unresolvable modelPolicyRef', async () => {@@ -196,6 +278,19 @@ describe('authorizePromptBridge', () => {expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })})+ it('rejects bootstrap/default drift before recording an invocation', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(grant())+ const result = await authorizePromptBridge({+ claims: claims(),+ ...basePromptParams,+ bootstrapProvider: 'openai',+ bootstrapModel: 'gpt-5.4-mini',+ })+ expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect((result as { ok: false; message: string }).message).toContain('bootstrap binding')+ expect(sdkDb.insertInvocation).not.toHaveBeenCalled()+ })+it('denies a request model that does not match the referenced model policy', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({@@ -236,6 +331,55 @@ describe('authorizePromptBridge', () => {})})+ it('rejects inconsistent targetRef and modelPolicyRef before recording an invocation', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({+ modelPolicies: { 'support-summary-v1': { provider: 'zai', model: 'glm-4.7' } },+ promptTargets: [+ {+ targetRef: 'zai-primary',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ {+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key',+ },+ ],+ defaultTargetRef: 'zai-primary',+ })+ )+ const result = await authorizePromptBridge({+ claims: claims(),+ ...basePromptParams,+ targetRef: 'openai-fallback',+ modelPolicyRef: 'support-summary-v1',+ })+ expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })+ expect(sdkDb.insertInvocation).not.toHaveBeenCalled()+ })++ it('accepts targetRef and modelPolicyRef only when they resolve to the same target', async () => {+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({+ modelPolicies: { 'support-summary-v1': { provider: 'zai', model: 'glm-4.7' } },+ })+ )+ const result = await authorizePromptBridge({+ claims: claims(),+ ...basePromptParams,+ targetRef: 'primary-zai',+ modelPolicyRef: 'support-summary-v1',+ })+ expect(result).toMatchObject({+ ok: true,+ value: { selectedTarget: { targetRef: 'primary-zai' } },+ })+ })+it('returns quota_exceeded when the per-minute rate limit is exceeded', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ quotaLimits: { maxInvocationsPerMinute: 5 } })@@ -313,7 +457,18 @@ describe('authorizePromptBridge', () => {it('authorizes an explicitly approved non-default model', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(- grant({ allowedModels: ['glm-5.1'], quotaLimits: { maxRequestsPerRun: 10 } })+ grant({+ promptTargets: [+ {+ targetRef: 'zai-glm-5-1',+ provider: 'zai',+ model: 'glm-5.1',+ credentialSlot: 'zai-api-key',+ },+ ],+ defaultTargetRef: 'zai-glm-5-1',+ quotaLimits: { maxRequestsPerRun: 10 },+ }))const result = await authorizePromptBridge({claims: claims(),diff --git a/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.tsnew file mode 100644index 000000000..3c3db5492--- /dev/null+++ b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest'+import jwt from 'jsonwebtoken'+import { createPublicKey } from 'node:crypto'+import { config } from '../src/config.js'+import {+ PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,+ issuePluginWorkloadSdkCredentialTicket,+} from '../src/services/pluginWorkloadSdkCredentialTicket.js'++describe('plugin workload SDK credential ticket', () => {+ it('binds one authorized target without exposing any credential value', () => {+ const ticket = issuePluginWorkloadSdkCredentialTicket({+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'prompt-notify',+ invocationId: 'invocation-1',+ target: {+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key-fb1',+ },+ policyRevision: 7,+ policyHash: 'policy-hash',+ })+ const publicKey = createPublicKey(config.adminJwtPrivateKey).export({+ type: 'spki',+ format: 'pem',+ })+ const claims = jwt.verify(ticket, publicKey, {+ algorithms: ['RS256'],+ issuer: config.adminJwtIssuer,+ audience: PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,+ }) as jwt.JwtPayload+ expect(claims).toMatchObject({+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'prompt-notify',+ invocationId: 'invocation-1',+ targetRef: 'openai-fallback',+ provider: 'openai',+ model: 'gpt-5.4',+ credentialSlot: 'openai-api-key-fb1',+ policyRevision: 7,+ typ: 'plugin-sdk-credential-ticket',+ })+ expect(JSON.stringify(claims)).not.toContain('secret-value')+ })+})diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.tsindex a7cb849fc..36d3871b3 100644--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts@@ -157,6 +157,62 @@ describe('upsertGrant — provider column (R1)', () => {)expect(grant.provider).toBeNull()})++ it('writes ordered targets and default atomically while incrementing the policy revision', async () => {+ vi.mocked(pool.query).mockResolvedValue({+ rows: [+ {+ ...grantRow,+ prompt_targets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ default_target_ref: 'primary-zai',+ policy_revision: 2,+ },+ ],+ rowCount: 1,+ } as never)+ const grant = await upsertGrant(+ {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'sdk-recipe',+ capabilityFamily: 'promptBridge',+ provider: 'zai',+ allowedCallers: ['api'],+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ defaultTargetRef: 'primary-zai',+ },+ 'operator-1'+ )+ const [sql, params] = vi+ .mocked(pool.query)+ .mock.calls.find(([statement]) =>+ String(statement).includes('INSERT INTO plugin_workload_sdk_grants')+ ) as unknown as [string, unknown[]]+ expect(sql).toContain('prompt_targets, default_target_ref')+ expect(sql).toContain('policy_revision = plugin_workload_sdk_grants.policy_revision + 1')+ expect(JSON.parse(params[11] as string)).toEqual([+ expect.objectContaining({ targetRef: 'primary-zai', credentialSlot: 'zai-api-key' }),+ ])+ expect(params[12]).toBe('primary-zai')+ expect(grant).toMatchObject({+ defaultTargetRef: 'primary-zai',+ policyRevision: 2,+ promptTargets: [{ targetRef: 'primary-zai', provider: 'zai' }],+ })+ })})describe('resolveRecipientProfiles', () => {diff --git a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.tsindex 966e190ae..9fed48010 100644--- a/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts+++ b/control-api/test/services.pluginWorkloadSdkQuotaTracker.test.ts@@ -30,6 +30,7 @@ const grant = (recipeNamespace: 'sandbox-recipes',recipeName: 'sdk-recipe',capabilityFamily: 'promptBridge',+ provider: 'zai',allowedModels: [],allowedEventTypes: [],allowedTargetRefs: [],@@ -37,6 +38,9 @@ const grant = (allowedCallers: ['api'],quotaLimits: { maxRequestsPerRun: 10 },modelPolicies: {},+ promptTargets: [],+ defaultTargetRef: null,+ policyRevision: 0,createdAt: '',updatedAt: '',...overrides,diff --git a/control-ui/app/plugin-workload-sdk/Views.tsx b/control-ui/app/plugin-workload-sdk/Views.tsxindex 8bb983f9e..44308d74b 100644--- a/control-ui/app/plugin-workload-sdk/Views.tsx+++ b/control-ui/app/plugin-workload-sdk/Views.tsx@@ -91,7 +91,10 @@ export function GrantsView({{grants.map(grant => {const allowlist =grant.capabilityFamily === 'promptBridge'- ? grant.allowedModels+ ? (grant.promptTargets ?? []).map(+ (target, index) =>+ `${index === 0 ? 'default' : `fallback ${index}`}: ${target.provider}/${target.model} (${target.credentialSlot})`+ ): grant.allowedEventTypesconst quotaParts: string[] = []if (grant.quotaLimits.maxRequestsPerRun)@@ -116,7 +119,7 @@ export function GrantsView({<span className="cu-badge">{grant.capabilityFamily}</span></td><td>- {allowlist.length === 0 ? '- (any declared)' : allowlist.join(', ')}+ {allowlist.length === 0 ? '- (migration required)' : allowlist.join(', ')}{userRefsDisplay ? (<span className="cu-field__hint"> · users: {userRefsDisplay}</span>) : null}diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsxindex 7a556e24a..307139ebf 100644--- a/control-ui/app/plugin-workload-sdk/page.tsx+++ b/control-ui/app/plugin-workload-sdk/page.tsx@@ -1,6 +1,6 @@'use client'-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import React, { useCallback, useEffect, useMemo, useState } from 'react'import { useRouter } from 'next/navigation'import { useAuth } from '@components/AuthContext'import { useConfirmDialog } from '@components/ConfirmDialog'@@ -19,11 +19,13 @@ import {type PluginWorkloadSdkGrant,type PluginWorkloadSdkGrantInput,type PluginWorkloadSdkInvocation,+ type PluginWorkloadSdkPromptTarget,type WorkflowRecipeResource,deletePluginWorkloadSdkGrant,getAdminUsers,getRecipes,isSilentApiError,+ listLlmHostSecrets,listPluginWorkloadSdkGrants,listWorkflowGrants,searchPluginWorkloadSdkInvocations,@@ -34,17 +36,11 @@ import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'import {LLM_PROVIDER_OPTIONS,type LlmProvider,+ getCredentialSlotOptions,getModelOptions,getProviderLabel,- inferProviderFromModels,normalizeProvider,} from '@lib/llm'-import {- appendCustomPluginWorkloadSdkModel,- buildPluginWorkloadSdkModelOptions,- getCustomPluginWorkloadSdkModelError,- validateCustomPluginWorkloadSdkModel,-} from '@lib/pluginWorkloadSdkModels'import { GrantsView, InvocationsView } from './Views'type SdkView = 'grants' | 'invocations'@@ -412,24 +408,20 @@ function GrantFormModal({grant?.capabilityFamily ?? 'promptBridge')const { models: allowedCatalog } = useLlmAllowedModels()- // Prefer the grant's explicit provider (R1), then the recipe spec's provider.- const providerExplicit = Boolean(grant?.provider) || Boolean(initialRecipeInfo?.provider)const [modelProvider, setModelProvider] = useState<LlmProvider>((grant?.provider ? normalizeProvider(grant.provider) : undefined) ??initialRecipeInfo?.provider ??LLM_PROVIDER_OPTIONS[0].value)- // Legacy grants have neither an explicit nor a recipe provider — infer it from- // the allowed models once the allowlist loads, so the picklist filters to the- // right provider. One-shot, and never overrides an explicit source.- const didInferProviderRef = useRef(false)- useEffect(() => {- if (providerExplicit || didInferProviderRef.current || allowedCatalog.length === 0) return- didInferProviderRef.current = true- setModelProvider(inferProviderFromModels(grant?.allowedModels ?? [], allowedCatalog))- }, [providerExplicit, allowedCatalog, grant?.allowedModels])- const [allowedModels, setAllowedModels] = useState<string[]>(grant?.allowedModels ?? [])- const [customModel, setCustomModel] = useState('')+ // Legacy grants deliberately start empty: they must be explicitly migrated by+ // an operator, never inferred from a flat provider/model list.+ const [promptTargets, setPromptTargets] = useState<PluginWorkloadSdkPromptTarget[]>(+ grant?.promptTargets ?? []+ )+ const [targetRef, setTargetRef] = useState('')+ const [targetModel, setTargetModel] = useState('')+ const [credentialSlot, setCredentialSlot] = useState('')+ const [availableCredentialKeys, setAvailableCredentialKeys] = useState<string[]>([])const [allowedEventTypes, setAllowedEventTypes] = useState((grant?.allowedEventTypes ?? []).join(', '))@@ -466,6 +458,27 @@ function GrantFormModal({cancelled = true}}, [allowedUserRefs])+ useEffect(() => {+ let cancelled = false+ listLlmHostSecrets()+ .then(result => {+ if (cancelled) return+ setAvailableCredentialKeys(+ Array.from(new Set((result.items ?? []).flatMap(item => item.keys))).sort((a, b) =>+ a.localeCompare(b)+ )+ )+ })+ .catch(() => {+ // The save endpoint remains the source of truth. Without a readable+ // key-name catalog we fail closed in this form rather than asking an+ // operator to type a potentially unrelated slot.+ if (!cancelled) setAvailableCredentialKeys([])+ })+ return () => {+ cancelled = true+ }+ }, [])const [maxRequestsPerRun, setMaxRequestsPerRun] = useState(grant?.quotaLimits.maxRequestsPerRun?.toString() ?? '')@@ -501,8 +514,11 @@ function GrantFormModal({if (info.provider) {setModelProvider(info.provider)}- setAllowedModels(info.allowedModels)- setCustomModel('')+ // Recipe metadata only pre-fills a *new* reviewed target draft. It does+ // not turn legacy grant data into an implicit routing policy.+ setTargetModel(info.allowedModels[0] ?? '')+ setTargetRef('')+ setCredentialSlot('')try {const res = await listWorkflowGrants(info.namespace, info.name)setAllowedUserRefs((res.items ?? []).map(u => u.id))@@ -511,11 +527,14 @@ function GrantFormModal({}}- const modelsList = allowedModelsconst eventTypesList = parseList(allowedEventTypes)const callersList = parseList(allowedCallers)const wildcardPresent =- hasWildcard(modelsList) ||+ promptTargets.some(target =>+ [target.targetRef, target.provider, target.model, target.credentialSlot].some(value =>+ value.includes('*')+ )+ ) ||hasWildcard(eventTypesList) ||hasWildcard(parseList(allowedTargetRefs)) ||hasWildcard(callersList)@@ -524,20 +543,10 @@ function GrantFormModal({() => getModelOptions(allowedCatalog, modelProvider),[allowedCatalog, modelProvider])- const modelOptions = useMemo(- () =>- buildPluginWorkloadSdkModelOptions(allowedCatalog, modelProvider, allowedModels).map(- model => ({- value: model,- label: model,- description: providerModelOptions.includes(model) ? undefined : 'Configured custom model',- badge: getProviderLabel(modelProvider),- })- ),- [allowedCatalog, allowedModels, modelProvider, providerModelOptions]+ const credentialSlotOptions = useMemo(+ () => getCredentialSlotOptions(modelProvider, availableCredentialKeys),+ [availableCredentialKeys, modelProvider])- const customModelValidation = validateCustomPluginWorkloadSdkModel(customModel, allowedModels)- const customModelError = getCustomPluginWorkloadSdkModelError(customModel, allowedModels)const userOptions = useMemo(() =>users.map(user => ({@@ -548,13 +557,13 @@ function GrantFormModal({[users])const eventTypesMissing = family === 'clientNotifications' && eventTypesList.length === 0- const modelsMissing = family === 'promptBridge' && modelsList.length === 0+ const targetsMissing = family === 'promptBridge' && promptTargets.length === 0const callersMissing = callersList.length === 0const canSubmit =Boolean(recipeNamespace.trim() && recipeName.trim()) &&!wildcardPresent &&!eventTypesMissing &&- !modelsMissing &&+ !targetsMissing &&!callersMissing &&!submitting@@ -587,13 +596,17 @@ function GrantFormModal({capabilityFamily: family,// R1: persist the explicit provider (control-api requires it for// promptBridge). Omitted for clientNotifications, which has no model.- provider: family === 'promptBridge' ? modelProvider : undefined,- allowedModels: family === 'promptBridge' ? modelsList : [],+ provider: family === 'promptBridge' ? promptTargets[0]?.provider : undefined,+ // Retained only as legacy inventory metadata; runtime selection uses the+ // ordered targets below and never falls back to this flat list.+ allowedModels: family === 'promptBridge' ? promptTargets.map(target => target.model) : [],allowedEventTypes: family === 'clientNotifications' ? eventTypesList : [],allowedTargetRefs: family === 'clientNotifications' ? parseList(allowedTargetRefs) : [],allowedUserRefs: family === 'clientNotifications' ? allowedUserRefs : [],allowedCallers: callersList,quotaLimits,+ promptTargets: family === 'promptBridge' ? promptTargets : undefined,+ defaultTargetRef: family === 'promptBridge' ? promptTargets[0]?.targetRef : undefined,}// Edit mode: preserve modelPolicies, which the form does not expose, so the// full-column upsert does not wipe policies configured outside this form.@@ -611,10 +624,40 @@ function GrantFormModal({}}- function addCustomModel() {- if (!customModelValidation.ok) return- setAllowedModels(current => appendCustomPluginWorkloadSdkModel(current, customModel))- setCustomModel('')+ function addPromptTarget() {+ const model = targetModel.trim()+ const slot = credentialSlot.trim()+ const ref = targetRef.trim() || `${modelProvider}-${model}-${promptTargets.length + 1}`+ if (!model || !slot || !ref) return+ if (+ promptTargets.some(+ target =>+ target.targetRef === ref || (target.provider === modelProvider && target.model === model)+ )+ ) {+ setError('Each promptBridge target must have a unique ref and provider/model pair.')+ return+ }+ setPromptTargets(current => [+ ...current,+ { targetRef: ref, provider: modelProvider, model, credentialSlot: slot },+ ])+ setTargetRef('')+ setTargetModel('')+ setCredentialSlot('')+ setError('')+ }++ function moveTarget(index: number, direction: -1 | 1) {+ const nextIndex = index + direction+ if (nextIndex < 0 || nextIndex >= promptTargets.length) return+ setPromptTargets(current => {+ const next = [...current]+ const currentTarget = next[index]!+ next[index] = next[nextIndex]!+ next[nextIndex] = currentTarget+ return next+ })}return (@@ -704,9 +747,9 @@ function GrantFormModal({{family === 'promptBridge' ? (<FormSection title="promptBridge policy"><Field- label="Provider"+ label="Target provider"htmlFor="sdk-provider"- description="Must match the provider bound to the recipe's mcp-host. promptBridge can only use models from this provider."+ description="Add one reviewed target at a time. The first target is the default and later targets are the only permitted fallback order."><SelectInputid="sdk-provider"@@ -715,13 +758,8 @@ function GrantFormModal({onChange={e => {const next = normalizeProvider(e.target.value)setModelProvider(next)- // Unknown custom models are provider-scoped by this form:- // if the provider changes, the operator must re-add the- // exact configured model for the new provider.- setAllowedModels(prev =>- prev.filter(model => getModelOptions(allowedCatalog, next).includes(model))- )- setCustomModel('')+ setTargetModel('')+ setCredentialSlot('')}}>{LLM_PROVIDER_OPTIONS.map(option => (@@ -732,53 +770,116 @@ function GrantFormModal({</SelectInput></Field><Field- label="Allowed models"- htmlFor="sdk-models"+ label="Target model"+ htmlFor="sdk-target-model"required- error={modelsMissing ? 'Select at least one model for promptBridge.' : undefined}- description="Models the workload may request. Only explicitly selected models are allowed."+ error={+ targetsMissing+ ? 'Add at least one reviewed target for promptBridge.'+ : undefined+ }+ description="The model must be enabled for the selected provider."+ >+ <SelectInput+ id="sdk-target-model"+ compact+ value={targetModel}+ onChange={e => setTargetModel(e.target.value)}+ >+ <option value="">Select enabled model…</option>+ {providerModelOptions.map(model => (+ <option key={model} value={model}>+ {model}+ </option>+ ))}+ </SelectInput>+ </Field>+ <Field+ label="Credential slot"+ htmlFor="sdk-credential-slot"+ required+ description="Sanitized Secret data-key identity owned by this provider. Its value is never displayed or sent to the workload."+ >+ <SelectInput+ id="sdk-credential-slot"+ compact+ value={credentialSlot}+ onChange={e => setCredentialSlot(e.target.value)}+ >+ <option value="">Select provider-owned slot…</option>+ {credentialSlotOptions.map(slot => (+ <option key={slot} value={slot}>+ {slot}+ </option>+ ))}+ </SelectInput>+ </Field>+ <Field+ label="Target reference"+ htmlFor="sdk-target-ref"+ description="Stable caller-selectable identifier. Empty creates a deterministic local suggestion.">- <SelectionDropdown- id="sdk-models"- value={allowedModels}- onChange={setAllowedModels}- options={modelOptions}- placeholder="Select approved models"- searchPlaceholder="Search models..."- selectionLabel="Selected models"- emptyLabel="No models for this provider."- /><div className="cu-sdk-custom-model-row"><TextInput- id="sdk-custom-model"+ id="sdk-target-ref"compactmonospace- value={customModel}- onChange={e => setCustomModel(e.target.value)}- onKeyDown={e => {- if (e.key === 'Enter') {- e.preventDefault()- addCustomModel()- }- }}- invalid={Boolean(customModelError)}- aria-label="Configured model name"- aria-invalid={Boolean(customModelError) || undefined}- placeholder="configured-model-id"+ value={targetRef}+ onChange={e => setTargetRef(e.target.value)}+ aria-label="PromptBridge target reference"+ placeholder="primary-zai"/><Buttontype="button"size="sm"- onClick={addCustomModel}- disabled={!customModelValidation.ok}+ onClick={addPromptTarget}+ disabled={!targetModel.trim() || !credentialSlot.trim()}>- Add model+ Add target</Button></div>- {customModelError ? (- <span className="cu-field__error">{customModelError}</span>- ) : null}</Field>+ {promptTargets.length > 0 ? (+ <div className="cu-field__hint" aria-label="Ordered promptBridge targets">+ {promptTargets.map((target, index) => (+ <div key={target.targetRef} className="cu-sdk-custom-model-row">+ <code>+ {index === 0 ? 'default · ' : `fallback ${index} · `}+ {target.targetRef}: {getProviderLabel(target.provider as LlmProvider)} /{' '}+ {target.model} / {target.credentialSlot}+ </code>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={() => moveTarget(index, -1)}+ disabled={index === 0}+ >+ Up+ </Button>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={() => moveTarget(index, 1)}+ disabled={index === promptTargets.length - 1}+ >+ Down+ </Button>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={() =>+ setPromptTargets(current => current.filter((_, i) => i !== index))+ }+ >+ Remove+ </Button>+ </div>+ ))}+ </div>+ ) : null}</FormSection>) : (<FormSection title="clientNotifications policy">diff --git a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.tsindex ced1f4192..95c382abe 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,10 @@* 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 eager mcp-host to validate the SDK capability+ * 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 manual intervention.+ * it self-validate without a keepalive step or manual intervention.* 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.@@ -128,9 +128,7 @@ function recipeManifest(name: string, userRef: string): Record<string, unknown>kind: 'WorkflowRecipe',metadata: { name },spec: {- triggers: { onDemand: {} },agent: { provider: PROVIDER, model: MODEL },- steps: [{ id: 'keepalive', instruction: 'Acknowledge in one word.', toolChoice: 'none' }],workloads: [{id: 'sdk-caller',@@ -145,7 +143,11 @@ function recipeManifest(name: string, userRef: string): Record<string, unknown>},],pluginWorkloadSdk: {- promptBridge: { allowedModels: [], maxRequestsPerRun: 10, maxInvocationsPerMinute: 60 },+ promptBridge: {+ allowedModels: [MODEL],+ maxRequestsPerRun: 10,+ maxInvocationsPerMinute: 60,+ },clientNotifications: {allowedEventTypes: [EVENT_TYPE],allowedUserRefs: true,@@ -236,7 +238,16 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installawait waitForSdkValidated(token, installedRecipeName)// 4. promptBridge grant — configured through the grant page UI.- await page.goto('/plugin-workload-sdk')+ // Navigate through the visible application shell so this test proves the+ // operator journey rather than jumping directly to the grant route.+ await page.getByRole('link', { name: 'Plugins', exact: true }).click()+ await expect(page.getByRole('button', { name: 'Plugins SDK' })).toBeVisible({+ timeout: 15_000,+ })+ await page.getByRole('button', { name: 'Plugins SDK' }).click()+ await expect(page.getByRole('button', { name: 'New grant' })).toBeVisible({+ timeout: 15_000,+ })await dismissAdminEmailReminder(page)await page.getByRole('button', { name: 'New grant' }).click()await page@@ -245,12 +256,10 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installawait expect(page.locator('#sdk-family')).toHaveValue('promptBridge')await page.locator('#sdk-callers').fill('sdk-caller')const saveGrantButton = page.getByRole('button', { name: 'Save grant' })- await expect(page.getByText('Select at least one model for promptBridge.')).toBeVisible()- await expect(saveGrantButton).toBeDisabled()- const modelsDropdown = page.locator('#sdk-models')- await modelsDropdown.click()- await page.getByPlaceholder('Search models...').fill(MODEL)- await page.getByRole('option', { name: MODEL }).click()+ await expect(page.locator('#sdk-target-model')).toHaveValue(MODEL)+ await page.locator('#sdk-credential-slot').selectOption(`${PROVIDER}-api-key`)+ await page.locator('#sdk-target-ref').fill(`primary-${PROVIDER}`)+ await page.getByRole('button', { name: 'Add target' }).click()await expect(saveGrantButton).toBeEnabled()await saveGrantButton.click()const promptRow = page.locator('tr', { hasText: installedRecipeName }).filter({diff --git a/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts b/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.tsindex ee0a8a26b..ac3e57530 100644--- a/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts+++ b/control-ui/lib/__tests__/pluginWorkloadSdkApi.test.ts@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import {deletePluginWorkloadSdkGrant,getPluginWorkloadSdkQuota,+ listLlmHostSecrets,listPluginWorkloadSdkGrants,searchPluginWorkloadSdkInvocations,upsertPluginWorkloadSdkGrant,@@ -19,6 +20,16 @@ afterEach(() => {})describe('Plugin Workload SDK admin api — URL shape', () => {+ it('loads credential slot names from host Secrets, never recipe-scoped Secrets', async () => {+ const fetchMock = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(jsonResponse(200, { items: [{ name: 'chatllm-api-keys', keys: [] }] }))+ await listLlmHostSecrets()+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/api/v1/admin/secrets')+ expect(url).not.toContain('/recipe-secrets')+ })+it('listPluginWorkloadSdkGrants hits the grants endpoint with cookie credentials', async () => {const fetchMock = vi.spyOn(globalThis, 'fetch')@@ -50,6 +61,15 @@ describe('Plugin Workload SDK admin api — URL shape', () => {capabilityFamily: 'promptBridge',provider: 'zai',allowedModels: ['glm-4.7'],+ promptTargets: [+ {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ },+ ],+ defaultTargetRef: 'primary-zai',})const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]expect(url).toContain('/api/v1/admin/plugin-workload-sdk/grants')@@ -59,6 +79,9 @@ describe('Plugin Workload SDK admin api — URL shape', () => {capabilityFamily: 'promptBridge',provider: 'zai',allowedModels: ['glm-4.7'],+ promptTargets: [+ expect.objectContaining({ targetRef: 'primary-zai', credentialSlot: 'zai-api-key' }),+ ],})})diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.tsindex 53275036b..bed88c146 100644--- a/control-ui/lib/api.ts+++ b/control-ui/lib/api.ts@@ -886,6 +886,16 @@ export type AdminUser = {// `keys` are the Secret's data-key NAMES only (never values); the detail bundle// populates them via listHostSecrets. Optional for compat with older payloads.export type HostSecretResource = { name: string; keys?: string[] }++/**+ * Host/LLM Secret metadata only. `keys` are Kubernetes data-key names; values+ * are never returned. SDK target editors use this rather than recipe-scoped+ * sandbox secrets because promptBridge credentials resolve from host Secrets.+ */+export async function listLlmHostSecrets() {+ return apiGet('/api/v1/admin/secrets') as Promise<{ items?: HostSecretResource[] }>+}+export type HostDetailBundle = {host: HostResourcecontexts: ContextResource[]@@ -3187,6 +3197,14 @@ export type PluginWorkloadSdkModelPolicy = {maxCostUsd?: number}+export type PluginWorkloadSdkPromptTarget = {+ targetRef: string+ provider: string+ model: string+ // Identity of a provider-owned secret data key; never a secret value.+ credentialSlot: string+}+export type PluginWorkloadSdkQuotaLimits = {maxRequestsPerRun?: numbermaxNotificationsPerRun?: number@@ -3211,6 +3229,9 @@ export type PluginWorkloadSdkGrant = {allowedCallers: string[]quotaLimits: PluginWorkloadSdkQuotaLimitsmodelPolicies: Record<string, PluginWorkloadSdkModelPolicy>+ promptTargets: PluginWorkloadSdkPromptTarget[]+ defaultTargetRef: string | null+ policyRevision: numbercreatedAt: stringupdatedAt: string}@@ -3228,6 +3249,8 @@ export type PluginWorkloadSdkGrantInput = {allowedCallers?: string[]quotaLimits?: PluginWorkloadSdkQuotaLimitsmodelPolicies?: Record<string, PluginWorkloadSdkModelPolicy>+ promptTargets?: PluginWorkloadSdkPromptTarget[]+ defaultTargetRef?: string}export type PluginWorkloadSdkQuotaCounter = {diff --git a/deploy/base/control-plane/networkpolicies.yaml b/deploy/base/control-plane/networkpolicies.yamlindex bff1c8a27..acc345ad4 100644--- a/deploy/base/control-plane/networkpolicies.yaml+++ b/deploy/base/control-plane/networkpolicies.yaml@@ -645,8 +645,9 @@ spec:- port: 8082protocol: TCP----# Allow workflow coordinators (sandbox-recipes) to reach WRC for status-# reporting and /configure-model calls. The per-recipe egress NPs are+# Allow workflow coordinators and SDK-enabled workflow mcp-hosts+# (sandbox-recipes) to reach WRC. Coordinators report status/configure models;+# mcp-hosts redeem one signed prompt target credential per attempt. Per-recipe egress NPs are# created dynamically by WRC in sandbox-recipes; this static NP opens# the ingress side in control-plane (WRC cannot self-modify its own ns).apiVersion: networking.k8s.io/v1@@ -670,6 +671,12 @@ spec:podSelector:matchLabels:clerum.io/component: workflow-coordinator+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: sandbox-recipes+ podSelector:+ matchLabels:+ clerum.io/component: workflow-mcp-hostports:- port: 8082protocol: TCPdiff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex 9597b8544..5021ed01a 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.323",+ "version": "0.1.324","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.323",+ "version": "0.1.324","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex f07aa132d..4e86e78c8 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.323",+ "version": "0.1.324","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",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.tsnew file mode 100644index 000000000..0058b389b--- /dev/null+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts@@ -0,0 +1,276 @@+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'+import { execFileSync } from 'node:child_process'+import {+ EXTERNAL_REST_API_BASE_URL,+ RPC_PROXY_BASE_URL,+ assertAllowedTarget,+ desktopCredentials,+ finalizeRecording,+ launchDesktopApp,+ login,+ requireRecorderConfirm,+} from './qa-recorder-helpers'++const RUN_ENABLED = process.env.E2E_PLUGIN_SDK_DESKTOP === '1'+const APP_TITLE = process.env.E2E_PLUGIN_SDK_APP_TITLE || 'Prompt & Notify'+const RECIPE_NAME = process.env.E2E_PLUGIN_SDK_RECIPE_NAME || 'evenfire-prompt-notify-app'+const RECIPE_NAMESPACE = process.env.E2E_PLUGIN_SDK_RECIPE_NAMESPACE || 'sandbox-recipes'++test.skip(+ !RUN_ENABLED,+ 'Set E2E_PLUGIN_SDK_DESKTOP=1 for the branch-owned Electron/Apps/WebContentsView gate.'+)++type EmbeddedContents = { id: number; url: string }+type Rect = { x: number; y: number; width: number; height: number }++function assertSteplessSdkRecipePrecondition(): 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 stepless recipe precondition.')+ if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(RECIPE_NAME)) {+ throw new Error(`Unsafe E2E_PLUGIN_SDK_RECIPE_NAME: ${RECIPE_NAME}`)+ }+ if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(RECIPE_NAMESPACE)) {+ throw new Error(`Unsafe E2E_PLUGIN_SDK_RECIPE_NAMESPACE: ${RECIPE_NAMESPACE}`)+ }+ const raw = execFileSync(+ 'kubectl',+ [+ '--context',+ context,+ '-n',+ RECIPE_NAMESPACE,+ 'get',+ 'workflowrecipe',+ RECIPE_NAME,+ '-o',+ 'json',+ ],+ { encoding: 'utf8', timeout: 30_000 }+ )+ const recipe = JSON.parse(raw) as {+ spec?: {+ steps?: unknown+ triggers?: unknown+ agent?: { provider?: unknown; model?: unknown }+ workloads?: unknown+ pluginWorkloadSdk?: { promptBridge?: Record<string, unknown> }+ }+ }+ const spec = recipe.spec ?? {}+ if (spec.steps !== undefined || spec.triggers !== undefined) {+ throw new Error(+ 'Desktop candidate must be SDK-only: spec.steps and spec.triggers must be absent.'+ )+ }+ if (+ typeof spec.agent?.provider !== 'string' ||+ !spec.agent.provider ||+ typeof spec.agent.model !== 'string' ||+ !spec.agent.model+ ) {+ throw new Error('Desktop candidate must declare a resolvable spec.agent bootstrap.')+ }+ if (!Array.isArray(spec.workloads) || spec.workloads.length === 0) {+ throw new Error('Desktop candidate must declare at least one plugin workload.')+ }+ if (+ typeof spec.pluginWorkloadSdk?.promptBridge !== 'object' ||+ spec.pluginWorkloadSdk.promptBridge === null+ ) {+ throw new Error('Desktop candidate must declare the pluginWorkloadSdk.promptBridge object.')+ }+}++async function findPromptNotifyContents(+ app: ElectronApplication+): Promise<EmbeddedContents | null> {+ return app.evaluate(async ({ webContents }, expectedTitle) => {+ for (const contents of webContents.getAllWebContents()) {+ if (contents.isDestroyed()) continue+ const url = contents.getURL()+ if (!url.includes('/api/v1/sandbox-ui/') || !url.includes('/view/')) continue+ const title = await contents.executeJavaScript('document.title').catch(() => '')+ if (title === expectedTitle) return { id: contents.id, url }+ }+ return null+ }, APP_TITLE)+}++async function embeddedRect(+ app: ElectronApplication,+ webContentsId: number,+ selector: string+): Promise<Rect | null> {+ return app.evaluate(+ async ({ webContents }, args) => {+ const contents = webContents.fromId(args.webContentsId)+ if (!contents || contents.isDestroyed()) return null+ const script = `(() => {+ const el = document.querySelector(${JSON.stringify(args.selector)});+ if (!el) return null;+ const r = el.getBoundingClientRect();+ const style = getComputedStyle(el);+ if (r.width <= 0 || r.height <= 0 || style.visibility === 'hidden' || style.display === 'none') return null;+ return { x: r.x, y: r.y, width: r.width, height: r.height };+ })()`+ return contents.executeJavaScript(script)+ },+ { webContentsId, selector }+ )+}++async function embeddedText(+ app: ElectronApplication,+ webContentsId: number,+ selector: string+): Promise<string> {+ return app.evaluate(+ async ({ webContents }, args) => {+ const contents = webContents.fromId(args.webContentsId)+ if (!contents || contents.isDestroyed()) return ''+ const script = `document.querySelector(${JSON.stringify(args.selector)})?.textContent ?? ''`+ return String(await contents.executeJavaScript(script))+ },+ { webContentsId, selector }+ )+}++async function embeddedValue(+ app: ElectronApplication,+ webContentsId: number,+ selector: string+): Promise<string> {+ return app.evaluate(+ async ({ webContents }, args) => {+ const contents = webContents.fromId(args.webContentsId)+ if (!contents || contents.isDestroyed()) return ''+ const script = `String(document.querySelector(${JSON.stringify(args.selector)})?.value ?? '')`+ return String(await contents.executeJavaScript(script))+ },+ { webContentsId, selector }+ )+}++async function clickEmbedded(+ app: ElectronApplication,+ webContentsId: number,+ selector: string+): Promise<void> {+ const rect = await embeddedRect(app, webContentsId, selector)+ if (!rect) throw new Error(`Embedded control ${selector} is missing or not visible.`)+ const point = { x: Math.round(rect.x + rect.width / 2), y: Math.round(rect.y + rect.height / 2) }+ await app.evaluate(+ ({ webContents }, args) => {+ const contents = webContents.fromId(args.webContentsId)+ if (!contents || contents.isDestroyed()) throw new Error('Embedded WebContentsView closed')+ contents.sendInputEvent({ type: 'mouseMove', x: args.x, y: args.y })+ contents.sendInputEvent({+ type: 'mouseDown',+ x: args.x,+ y: args.y,+ button: 'left',+ clickCount: 1,+ })+ contents.sendInputEvent({+ type: 'mouseUp',+ x: args.x,+ y: args.y,+ button: 'left',+ clickCount: 1,+ })+ },+ { webContentsId, ...point }+ )+}++async function typeEmbedded(+ app: ElectronApplication,+ webContentsId: number,+ selector: string,+ value: string+): Promise<void> {+ await clickEmbedded(app, webContentsId, selector)+ await app.evaluate(+ ({ webContents }, args) => {+ const contents = webContents.fromId(args.webContentsId)+ if (!contents || contents.isDestroyed()) throw new Error('Embedded WebContentsView closed')+ contents.insertText(args.value)+ },+ { webContentsId, value }+ )+}++test('Desktop Apps executes promptBridge and clientNotifications inside the real WebContentsView', async ({}, testInfo) => {+ requireRecorderConfirm(+ 'E2E_PLUGIN_SDK_WRITE_CONFIRM',+ 'This journey performs one paid promptBridge call and sends one test notification.'+ )+ assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)+ assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)+ // Read-only setup assertion. Every functional action that follows is through+ // the real Desktop UI and its native WebContentsView.+ assertSteplessSdkRecipePrecondition()++ let app: ElectronApplication | undefined+ let page: Page | undefined+ try {+ const launched = await launchDesktopApp(testInfo)+ app = launched.app+ page = launched.page+ await login(page, desktopCredentials())++ await page.getByTestId('nav-sandbox-ui').click()+ await expect(page.getByRole('heading', { name: 'Apps', exact: true })).toBeVisible()+ const appCard = page.getByRole('button', { name: `Open ${APP_TITLE}`, exact: true })+ await expect(appCard).toBeVisible({ timeout: 30_000 })+ await appCard.click()+ await expect(page.getByRole('button', { name: 'Back to apps' })).toBeVisible({+ timeout: 30_000,+ })++ let embedded: EmbeddedContents | null = null+ await expect+ .poll(async () => {+ embedded = await findPromptNotifyContents(app!)+ return embedded?.url ?? ''+ })+ .toContain('/api/v1/sandbox-ui/')+ const webContentsId = embedded!.id+ await expect.poll(() => embeddedRect(app!, webContentsId, '#run')).not.toBeNull()++ const marker = `desktop-sdk-${Date.now()}`+ await typeEmbedded(+ app,+ webContentsId,+ '#prompt',+ `Reply with a short confirmation for test marker ${marker}.`+ )+ await clickEmbedded(app, webContentsId, '#run')+ await expect+ .poll(() => embeddedText(app!, webContentsId, '#prompt-out'), { timeout: 120_000 })+ .not.toMatch(/^(?:|Running…|Enter a prompt first\.)$/)+ const promptResult = await embeddedText(app, webContentsId, '#prompt-out')+ expect(promptResult).not.toMatch(/"error"|provider_unavailable|requires a resolvable agent/i)++ // Business signal for notifications: the real app loaded an authorized+ // opaque recipient, then the native view submitted and rendered acceptance.+ await expect+ .poll(() => embeddedValue(app!, webContentsId, '#userRef'), { timeout: 30_000 })+ .not.toBe('')+ await typeEmbedded(app, webContentsId, '#title', `Evenfire E2E ${marker}`)+ await typeEmbedded(app, webContentsId, '#message', 'Plugin Workload SDK Desktop validation.')+ await clickEmbedded(app, webContentsId, '#notify')+ await expect+ .poll(() => embeddedText(app!, webContentsId, '#notify-out'), { timeout: 30_000 })+ .toMatch(/notificationId|accepted|delivered/i)++ // Renderer chrome + native view both remain alive after the two backend+ // operations, proving the Desktop Apps path rather than a direct proxy call.+ await expect(page.getByRole('button', { name: 'Back to apps' })).toBeVisible()+ expect(await findPromptNotifyContents(app)).toMatchObject({ id: webContentsId })+ } finally {+ await finalizeRecording(app, page)+ }+})diff --git a/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts b/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.tsindex 2c47f173d..53bb2cd28 100644--- a/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts+++ b/desktop-app/test/e2e-playwright/sdk-client-notification/sdkWorkloadFixture.ts@@ -20,6 +20,7 @@ const EVENT_TYPE = 'e2e.test.notification'const MODEL_PROVIDER =process.env.E2E_WORKFLOW_MODEL_PROVIDER || process.env.CLURUM_MODEL_PROVIDER || 'zai'const MODEL_NAME = process.env.E2E_WORKFLOW_MODEL_NAME || process.env.CLURUM_MODEL_NAME || 'glm-5.1'+const CREDENTIAL_SLOT = process.env.E2E_WORKFLOW_CREDENTIAL_SLOT || `${MODEL_PROVIDER}-api-key`function requireAdminPassword(): string {const password =@@ -101,7 +102,17 @@ export async function createSdkWorkloadGrants(recipeName: string, userRef: strinrecipeNamespace: RECIPE_NS,recipeName,capabilityFamily: 'promptBridge',- allowedModels: [],+ provider: MODEL_PROVIDER,+ allowedModels: [MODEL_NAME],+ promptTargets: [+ {+ targetRef: `primary-${MODEL_PROVIDER}`,+ provider: MODEL_PROVIDER,+ model: MODEL_NAME,+ credentialSlot: CREDENTIAL_SLOT,+ },+ ],+ defaultTargetRef: `primary-${MODEL_PROVIDER}`,allowedCallers: [WORKLOAD_ID],quotaLimits: { maxRequestsPerRun: 3 },}),diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.mdindex f8d47c28b..80e6443d8 100644--- a/docs/crds/workflowrecipe.md+++ b/docs/crds/workflowrecipe.md@@ -1023,7 +1023,7 @@ spec:**What gets rejected**-- **CEL R1** — `agent requires steps: cannot define agent without workflow steps`. There is no "agent for a workloads-only recipe".+- **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.- A `provider` outside the four-value enum.- An `instruction` step with no resolvable agent: _"step requires an agent configuration"_.@@ -1360,7 +1360,8 @@ 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 — and since CEL R1 forbids `spec.agent` without `spec.steps`, a workloads-only recipe cannot supply one. A `clientNotifications`-only recipe needs no agent.+- `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.+- 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`)@@ -2840,7 +2841,8 @@ The spec-level rules in the shipped CRD are numbered in comments (R1-R18, W1, O1| ID | Message || --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| R1 | `agent requires steps: cannot define agent without workflow steps` |+| R1 | `agent requires workflow steps or spec.pluginWorkloadSdk.promptBridge` |+| R1a | `spec.pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage` || R2 | `recipe must define at least workloads or steps` || R3 | `duplicate step IDs are not allowed` || R4 | `spec.scheduling requires spec.steps to be non-empty` |diff --git a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts b/mcp-host/src/__tests__/workflow/workflowRouter.test.tsindex 8c978bc6e..8e335a5b4 100644--- a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts+++ b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts@@ -66,6 +66,7 @@ async function createTestApp(serviceOverride?: {executeStep?: ReturnType<typeof vi.fn>configure?: ReturnType<typeof vi.fn>+ configurePluginWorkloadSdkBootstrap?: ReturnType<typeof vi.fn>getStatus?: ReturnType<typeof vi.fn>}): Promise<{ baseUrl: string; server: http.Server }> {@@ -83,6 +84,11 @@ async function createTestApp(const service = {executeStep: vi.fn().mockResolvedValue({ stepId: 's1', status: 'completed' }),configure: vi.fn().mockReturnValue({ configured: true }),+ configurePluginWorkloadSdkBootstrap: vi.fn().mockReturnValue({+ configured: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ }),getStatus: vi.fn().mockReturnValue({ ready: true, configured: true }),...serviceOverride,}@@ -358,6 +364,33 @@ 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({+ configured: true,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ })+ const { baseUrl, server } = await createTestApp(publicKeyPem, true, {+ configurePluginWorkloadSdkBootstrap: bootstrap,+ })+ try {+ const res = await fetch(`${baseUrl}/api/v1/workflow/plugin-workload-sdk/bootstrap`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({+ provider: 'openai',+ model: 'gpt-5.4-mini',+ apiKey: 'must-not-pass',+ }),+ })+ expect(res.status).toBe(200)+ expect(bootstrap).toHaveBeenCalledWith({ provider: 'openai', model: 'gpt-5.4-mini' })+ } finally {+ server.close()+ }+ })+it('GET /mode with missing mode_read scope returns 403', async () => {const token = await signWorkflowToken({ scopes: ['execute'] })const { baseUrl, server } = await createTestApp(publicKeyPem)diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.tsindex cb4f825f1..0eb484686 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -219,6 +219,8 @@ export interface Config {podNamespace: string/** Overrides mcpHostGatewayUrl for SDK → control-api calls when set. */pluginWorkloadSdkGatewayUrl?: string+ /** WRC endpoint that redeems one signed prompt target ticket per attempt. */+ pluginWorkloadSdkCredentialBrokerUrl: string/** Recipe-scoped shared token workloads present to the SDK server. @deprecated use tokensDir */pluginWorkloadSdkWorkloadToken?: string/** Dev-only caller binding when using a single legacy workload token env var. */@@ -747,6 +749,7 @@ export const config: Config = {pluginWorkloadSdkPort: parseInt(getEnv('MCP_HOST_PLUGIN_SDK_PORT', '8099')!, 10),podNamespace: getEnv('MCP_HOST_POD_NAMESPACE', '')!,pluginWorkloadSdkGatewayUrl: getEnv('CONTROL_API_GATEWAY_URL', ''),+ pluginWorkloadSdkCredentialBrokerUrl: getEnv('CLERUM_WRC_URL', '') ?? '',pluginWorkloadSdkWorkloadToken: getEnv('PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKEN', ''),pluginWorkloadSdkBoundCallerRef: getEnv('PLUGIN_WORKLOAD_SDK_BOUND_CALLER_REF', ''),pluginWorkloadSdkWorkloadTokensDir: getEnv('PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKENS_DIR', ''),diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 9ae322c02..91a116e1c 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2887,7 +2887,6 @@ async function main(): Promise<void> {// WorkflowService.configure() — never a public getter, so the apiKey// stays unreachable through the service's public API surface.let pluginSdkLlmContext: {- keys: ApiKeysprovider: LlmProviderdefaultModel: string} | null = null@@ -2899,6 +2898,9 @@ async function main(): Promise<void> {onLlmConfigured: context => {pluginSdkLlmContext = context},+ onPluginWorkloadSdkBootstrapConfigured: context => {+ pluginSdkLlmContext = context+ },})rpcServer.setWorkflowService(workflowService)wireWorkflowApprovalRuntimeRoutes(rpcServer, {diff --git a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts b/mcp-host/src/pluginWorkloadSdk/domain/errors.tsindex 98ff6f4c0..90cd3e15c 100644--- a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts+++ b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts@@ -12,6 +12,7 @@ export const PLUGIN_WORKLOAD_ERROR_CODES = ['caller_not_allowed','scope_denied','target_not_allowed',+ 'ambiguous_model','event_type_not_allowed','quota_exceeded','provider_policy_denied',@@ -28,6 +29,7 @@ const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {caller_not_allowed: 403,scope_denied: 403,target_not_allowed: 403,+ ambiguous_model: 409,event_type_not_allowed: 403,quota_exceeded: 429,provider_policy_denied: 403,diff --git a/mcp-host/src/pluginWorkloadSdk/domain/types.ts b/mcp-host/src/pluginWorkloadSdk/domain/types.tsindex 5df491500..2a876c70e 100644--- a/mcp-host/src/pluginWorkloadSdk/domain/types.ts+++ b/mcp-host/src/pluginWorkloadSdk/domain/types.ts@@ -25,6 +25,8 @@ export const DEFAULT_MAX_BODY_BYTES = 4096export interface PromptBridgeRequest {model?: string+ provider?: string+ targetRef?: stringmodelPolicyRef?: stringmessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>maxTokens?: number@@ -34,9 +36,19 @@ export interface PromptBridgeRequest {metadata?: Record<string, unknown>}+export interface PromptBridgeTarget {+ targetRef: string+ provider: string+ model: string+ credentialSlot: string+}+export interface PromptBridgeResult {invocationId: stringmodel: string+ servedTarget: PromptBridgeTarget+ fallbackUsed: boolean+ policyRevision: numberusage: { inputTokens: number; outputTokens: number }content: stringfinishReason: 'complete' | 'length' | 'content_filter'diff --git a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts b/mcp-host/src/pluginWorkloadSdk/metrics.test.tsindex ae650b599..e390ec990 100644--- a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/metrics.test.ts@@ -18,6 +18,12 @@ const validBody = {}function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {+ const target = {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ }const controlApiClient = {authorizePromptBridge: vi.fn().mockResolvedValue({invocationId: 'inv-1',@@ -25,6 +31,11 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {status: 'in_progress',model: 'glm-4.7',modelPolicy: null,+ selectedTarget: target,+ authorizedTargets: [target],+ authorizedTargetTickets: [{ targetRef: target.targetRef, credentialTicket: 'ticket' }],+ policyRevision: 1,+ policyHash: 'a'.repeat(64),maxOutputTokens: null,}),reportInvocationStatus: vi.fn().mockResolvedValue(undefined),@@ -34,6 +45,9 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {complete ??vi.fn().mockResolvedValue({model: 'glm-4.7',+ servedTarget: target,+ fallbackUsed: false,+ llmSecretName: 'zai-secret',content: 'ok',usage: { inputTokens: 7, outputTokens: 3 },finishReason: 'complete',diff --git a/mcp-host/src/pluginWorkloadSdk/metrics.ts b/mcp-host/src/pluginWorkloadSdk/metrics.tsindex f2d3f7535..059321bcd 100644--- a/mcp-host/src/pluginWorkloadSdk/metrics.ts+++ b/mcp-host/src/pluginWorkloadSdk/metrics.ts@@ -27,7 +27,7 @@ export const pluginSdkClientNotificationsTotal = new Counter({export const pluginSdkCircuitBreakerState = new Gauge({name: 'clerum_plugin_workload_sdk_circuit_breaker_state',- help: 'Circuit breaker state per gateway (1 = the labeled state is active).',+ help: 'Circuit breaker state per gateway or authorized target (1 = the labeled state is active).',labelNames: ['gateway', 'state'] as const,})diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.tsindex 93598bfa0..f19637d76 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts@@ -11,6 +11,28 @@ const promptBody = {idempotencyKey: 'k1',messages: [{ role: 'user', content: 'hi' }],}+const target = {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-5.1',+ credentialSlot: 'zai-api-key',+}++function authorizedBody(invocationId: string) {+ return {+ invocationId,+ replay: false,+ status: 'in_progress',+ model: target.model,+ modelPolicy: null,+ selectedTarget: target,+ authorizedTargets: [target],+ authorizedTargetTickets: [{ targetRef: target.targetRef, credentialTicket: 'signed-ticket' }],+ policyRevision: 2,+ policyHash: 'a'.repeat(64),+ maxOutputTokens: null,+ }+}function jsonResponse(status: number, body: unknown): Response {return new Response(JSON.stringify(body), {@@ -32,16 +54,7 @@ function makeClient(fetchImpl: typeof fetch, breaker?: CircuitBreaker) {describe('PluginWorkloadSdkControlApiClient', () => {it('posts to the gateway with the mcp-host bearer token', async () => {- const fetchImpl = vi.fn().mockResolvedValue(- jsonResponse(201, {- invocationId: 'inv-1',- replay: false,- status: 'in_progress',- model: null,- modelPolicy: null,- maxOutputTokens: null,- })- )+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, authorizedBody('inv-1')))const client = makeClient(fetchImpl as unknown as typeof fetch)const result = await client.authorizePromptBridge(promptBody)expect(result.invocationId).toBe('inv-1')@@ -64,6 +77,32 @@ describe('PluginWorkloadSdkControlApiClient', () => {expect(fetchImpl).toHaveBeenCalledTimes(1) // 4xx is not retried})+ it('fails closed when authorization omits target tickets', async () => {+ const { authorizedTargetTickets: _omitted, ...missingTickets } = authorizedBody('inv-1')+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, missingTickets))+ const client = makeClient(fetchImpl as unknown as typeof fetch)+ await expect(client.authorizePromptBridge(promptBody)).rejects.toMatchObject({+ code: 'provider_unavailable',+ })+ })++ it('serializes provider and target selectors without supplying a host default', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, authorizedBody('inv-1')))+ const client = makeClient(fetchImpl as unknown as typeof fetch)+ await client.authorizePromptBridge({+ ...promptBody,+ provider: 'zai',+ model: 'glm-5.1',+ targetRef: 'primary-zai',+ })+ const init = fetchImpl.mock.calls[0]?.[1] as RequestInit+ expect(JSON.parse(String(init.body))).toMatchObject({+ provider: 'zai',+ model: 'glm-5.1',+ targetRef: 'primary-zai',+ })+ })+it('retries 5xx and returns provider_unavailable after exhausting retries', async () => {const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(503, {}))const client = makeClient(fetchImpl as unknown as typeof fetch)@@ -78,16 +117,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {const fetchImpl = vi.fn().mockRejectedValueOnce(new Error('ECONNREFUSED'))- .mockResolvedValueOnce(- jsonResponse(201, {- invocationId: 'inv-2',- replay: false,- status: 'in_progress',- model: null,- modelPolicy: null,- maxOutputTokens: null,- })- )+ .mockResolvedValueOnce(jsonResponse(201, authorizedBody('inv-2')))const client = makeClient(fetchImpl as unknown as typeof fetch)const result = await client.authorizePromptBridge(promptBody)expect(result.invocationId).toBe('inv-2')@@ -117,14 +147,7 @@ describe('PluginWorkloadSdkControlApiClient', () => {})describe('refresh-on-401 (runtime-token durability)', () => {- const successBody = {- invocationId: 'inv-ok',- replay: false,- status: 'in_progress',- model: null,- modelPolicy: null,- maxOutputTokens: null,- }+ const successBody = authorizedBody('inv-ok')function makeRefreshingClient(fetchImpl: typeof fetch,diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.tsindex ad6218af8..99a4571da 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts@@ -1,5 +1,6 @@import { CircuitBreaker } from '../domain/circuitBreaker'import { PluginWorkloadError, isKnownPluginWorkloadErrorCode } from '../domain/errors'+import type { PromptBridgeTarget } from '../domain/types'/*** Anti-corruption layer (plan §3.4): encapsulates the HTTP call to@@ -36,19 +37,14 @@ export interface AuthorizePromptBridgeResponse {invocationId: stringreplay: booleanstatus: string- model: string | null+ model: stringmodelPolicy: { provider: string; model: string; temperature?: number; maxCostUsd?: number } | null+ selectedTarget: PromptBridgeTarget+ authorizedTargets: PromptBridgeTarget[]+ authorizedTargetTickets: Array<{ targetRef: string; credentialTicket: string }>+ policyRevision: number+ policyHash: stringmaxOutputTokens: number | null- /**- * R5 F6 — the grant's `allowed_models` (same-provider), if control-api- * surfaces it. OPTIONAL by design, but currently NO control-api build populates- * it (the authorize response omits it — see the `TODO(R5-F6)` stop-point in- * control-api `pluginWorkloadSdkAuthorizer.ts`). Until that field is wired, the- * bridge always receives `undefined` → no same-provider fallback candidates →- * the promptBridge failover path is inert. When present, the bridge fails over- * only among these models (never outside the grant — spec §3-R5.7).- */- allowedModels?: string[]}export interface SubmitClientNotificationResponse {@@ -77,19 +73,41 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridgetypeof r.invocationId === 'string' &&typeof r.replay === 'boolean' &&typeof r.status === 'string' &&- (r.model === null || typeof r.model === 'string') &&+ typeof r.model === 'string' &&(r.modelPolicy === null ||(typeof r.modelPolicy === 'object' &&r.modelPolicy !== null &&typeof (r.modelPolicy as Record<string, unknown>).provider === 'string' &&typeof (r.modelPolicy as Record<string, unknown>).model === 'string')) &&- (r.maxOutputTokens === null || typeof r.maxOutputTokens === 'number') &&- // Optional (R5 F6): absent (undefined or null), or a string array. Tolerating- // `null` matters — a gateway that serializes the absent field as `null`- // must not fail the WHOLE authorize response, only disable failover.- (r.allowedModels === undefined ||- r.allowedModels === null ||- (Array.isArray(r.allowedModels) && r.allowedModels.every(m => typeof m === 'string')))+ isPromptBridgeTarget(r.selectedTarget) &&+ Array.isArray(r.authorizedTargets) &&+ r.authorizedTargets.length > 0 &&+ r.authorizedTargets.every(isPromptBridgeTarget) &&+ Array.isArray(r.authorizedTargetTickets) &&+ r.authorizedTargetTickets.length === r.authorizedTargets.length &&+ r.authorizedTargetTickets.every(+ ticket =>+ typeof ticket === 'object' &&+ ticket !== null &&+ typeof (ticket as Record<string, unknown>).targetRef === 'string' &&+ typeof (ticket as Record<string, unknown>).credentialTicket === 'string'+ ) &&+ Number.isInteger(r.policyRevision) &&+ (r.policyRevision as number) >= 1 &&+ typeof r.policyHash === 'string' &&+ /^[a-f0-9]{64}$/.test(r.policyHash) &&+ (r.maxOutputTokens === null || typeof r.maxOutputTokens === 'number')+ )+}++function isPromptBridgeTarget(value: unknown): value is PromptBridgeTarget {+ if (typeof value !== 'object' || value === null) return false+ const target = value as Record<string, unknown>+ return (+ typeof target.targetRef === 'string' &&+ typeof target.provider === 'string' &&+ typeof target.model === 'string' &&+ typeof target.credentialSlot === 'string')}@@ -265,11 +283,16 @@ export class PluginWorkloadSdkControlApiClient {recipeNamespace: stringrecipeName: stringcallerRef: string+ bootstrapProvider?: string+ bootstrapModel?: stringmodel?: string+ provider?: string+ targetRef?: stringmodelPolicyRef?: stringpurpose: stringidempotencyKey: stringmessages: Array<{ role: string; content: string }>+ metadata?: Record<string, unknown>correlationId?: string}): Promise<AuthorizePromptBridgeResponse> {const result = await this.post('/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge', body)diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.tsnew file mode 100644index 000000000..6bd48d030--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it, vi } from 'vitest'+import type { PromptBridgeTarget } from '../domain/types'+import { PluginWorkloadSdkCredentialBrokerClient } from './credentialBrokerClient'++const target: PromptBridgeTarget = {+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+}++function response(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ })+}++describe('PluginWorkloadSdkCredentialBrokerClient', () => {+ it('redeems one exact target ticket using the live runtime token', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ response(200, {+ provider: target.provider,+ model: target.model,+ credentialSlot: target.credentialSlot,+ credentials: { 'openai-api-key': 'provider-secret' },+ llmSecretName: 'chatllm-api-keys',+ })+ )+ const client = new PluginWorkloadSdkCredentialBrokerClient({+ baseUrl: 'http://wrc:8082/',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'recipe-a',+ getAccessToken: () => 'runtime-jwt',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })++ const result = await client.resolve({+ invocationId: 'inv-1',+ target,+ credentialTicket: 'signed-ticket',+ })++ expect(result.keys.openai?.['openai-api-key']).toBe('provider-secret')+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url).toBe('http://wrc:8082/api/v1/workflow/recipe-a/plugin-workload-sdk/credentials')+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer runtime-jwt')+ expect(JSON.parse(String(init.body))).toEqual({+ recipeNamespace: 'sandbox-recipes',+ invocationId: 'inv-1',+ target,+ credentialTicket: 'signed-ticket',+ })+ })++ it.each([403, 503])('collapses broker %s into a terminal non-enumerable error', async status => {+ const fetchImpl = vi+ .fn()+ .mockResolvedValue(response(status, { error: 'secret-name-that-must-not-leak' }))+ const client = new PluginWorkloadSdkCredentialBrokerClient({+ baseUrl: 'http://wrc:8082',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'recipe-a',+ getAccessToken: () => 'runtime-jwt',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ const error = await client+ .resolve({ invocationId: 'inv-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')+ })++ it('rejects a response for a different target and never returns its credentials', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(+ response(200, {+ provider: 'claude',+ model: target.model,+ credentialSlot: target.credentialSlot,+ credentials: { 'claude-api-key': 'wrong-secret' },+ llmSecretName: 'wrong-secret-name',+ })+ )+ const client = new PluginWorkloadSdkCredentialBrokerClient({+ baseUrl: 'http://wrc:8082',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'recipe-a',+ getAccessToken: () => 'runtime-jwt',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ await expect(+ client.resolve({ invocationId: 'inv-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.tsnew file mode 100644index 000000000..21c379437--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts@@ -0,0 +1,104 @@+import type { ApiKeys } from '../../types'+import { PluginWorkloadError } from '../domain/errors'+import type { PromptBridgeTarget } from '../domain/types'++export interface BrokeredCredential {+ target: PromptBridgeTarget+ keys: ApiKeys+ llmSecretName: string+}++export interface CredentialBrokerClientOptions {+ baseUrl: string+ recipeNamespace: string+ recipeName: string+ getAccessToken: () => string+ fetchImpl?: typeof fetch+}++/**+ * Redeems one short-lived, target-bound authorization ticket at WRC. The+ * response contains credentials for exactly one provider attempt and is never+ * cached. Errors are deliberately collapsed to a terminal public error so the+ * caller cannot use promptBridge to enumerate provider configuration.+ */+export class PluginWorkloadSdkCredentialBrokerClient {+ constructor(private readonly opts: CredentialBrokerClientOptions) {}++ async resolve(input: {+ invocationId: string+ target: PromptBridgeTarget+ credentialTicket: string+ }): Promise<BrokeredCredential> {+ const fetchImpl = this.opts.fetchImpl ?? fetch+ const url = `${this.opts.baseUrl.replace(/\/+$/, '')}/api/v1/workflow/${encodeURIComponent(+ this.opts.recipeName+ )}/plugin-workload-sdk/credentials`++ let response: Response+ try {+ response = await fetchImpl(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${this.opts.getAccessToken()}`,+ },+ body: JSON.stringify({+ recipeNamespace: this.opts.recipeNamespace,+ invocationId: input.invocationId,+ target: input.target,+ credentialTicket: input.credentialTicket,+ }),+ })+ } catch {+ throw unavailable()+ }++ if (!response.ok) throw unavailable()+ const raw = await response.json().catch(() => null)+ if (!isBrokerResponse(raw, input.target)) throw unavailable()++ return {+ target: input.target,+ keys: { [input.target.provider]: raw.credentials } as ApiKeys,+ llmSecretName: raw.llmSecretName,+ }+ }+}++function isBrokerResponse(+ raw: unknown,+ expected: PromptBridgeTarget+): raw is { credentials: Record<string, string>; llmSecretName: string } {+ if (typeof raw !== 'object' || raw === null) return false+ const body = raw as Record<string, unknown>+ if (+ body.provider !== expected.provider ||+ body.model !== expected.model ||+ body.credentialSlot !== expected.credentialSlot ||+ typeof body.llmSecretName !== 'string' ||+ body.llmSecretName.length === 0 ||+ typeof body.credentials !== 'object' ||+ body.credentials === null ||+ Array.isArray(body.credentials)+ ) {+ return false+ }+ const credentials = body.credentials as Record<string, unknown>+ const entries = Object.entries(credentials)+ return (+ entries.length > 0 &&+ entries.every(+ ([key, value]) =>+ /^[a-z0-9][a-z0-9-]{0,127}$/.test(key) && typeof value === 'string' && value.length > 0+ )+ )+}++function unavailable(): PluginWorkloadError {+ return new PluginWorkloadError(+ 'provider_unavailable',+ 'authorized provider credentials are unavailable',+ false+ )+}diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.tsindex 23bade797..d068afb0f 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { PluginWorkloadError } from '../domain/errors'+import type { PromptBridgeTarget } from '../domain/types'import type { PluginWorkloadSdkControlApiClient } from './controlApiClient'import { PromptBridgeHandler } from './handler'import type { LlmBridge } from './llmBridge'@@ -9,74 +10,91 @@ const validBody = {idempotencyKey: 'key-1',messages: [{ role: 'user', content: 'summarize this' }],}+const primary: PromptBridgeTarget = {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+}+const fallback: PromptBridgeTarget = {+ targetRef: 'fallback-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+}++function authorization(overrides: Record<string, unknown> = {}) {+ return {+ invocationId: 'inv-1',+ replay: false,+ status: 'in_progress',+ model: primary.model,+ modelPolicy: null,+ selectedTarget: primary,+ authorizedTargets: [primary, fallback],+ authorizedTargetTickets: [+ { targetRef: primary.targetRef, credentialTicket: 'ticket-primary' },+ { targetRef: fallback.targetRef, credentialTicket: 'ticket-fallback' },+ ],+ policyRevision: 7,+ policyHash: 'a'.repeat(64),+ maxOutputTokens: 2048,+ ...overrides,+ }+}function makeDeps(overrides: {authorize?: ReturnType<typeof vi.fn>complete?: ReturnType<typeof vi.fn>report?: ReturnType<typeof vi.fn>- defaultModel?: string | null- onUsage?: (usage: {- model: string- inputTokens: number- outputTokens: number- callerRef: string- }) => void+ bootstrap?: () => { provider: string; model: string } | null+ onUsage?: (usage: any) => void} = {}) {- const authorize =- overrides.authorize ??- vi.fn().mockResolvedValue({- invocationId: 'inv-1',- replay: false,- status: 'in_progress',- model: 'glm-4.7',- modelPolicy: null,- maxOutputTokens: 2048,- })+ const authorize = overrides.authorize ?? vi.fn().mockResolvedValue(authorization())const report = overrides.report ?? vi.fn().mockResolvedValue(undefined)const complete =overrides.complete ??vi.fn().mockResolvedValue({- model: 'glm-4.7',+ model: fallback.model,+ servedTarget: fallback,+ fallbackUsed: true,+ llmSecretName: 'provider-secret',content: 'summary text',usage: { inputTokens: 10, outputTokens: 5 },finishReason: 'complete',})- const controlApiClient = {- authorizePromptBridge: authorize,- reportInvocationStatus: report,- } as unknown as PluginWorkloadSdkControlApiClient- const llmBridge = { complete } as unknown as LlmBridgeconst handler = new PromptBridgeHandler({- controlApiClient,- llmBridge,+ controlApiClient: {+ authorizePromptBridge: authorize,+ reportInvocationStatus: report,+ } as unknown as PluginWorkloadSdkControlApiClient,+ llmBridge: { complete } as unknown as LlmBridge,recipeNamespace: 'sandbox-recipes',recipeName: 'r1',promptTimeoutMs: 120_000,- resolveDefaultModel: () => overrides.defaultModel ?? 'glm-4.7',+ ...(overrides.bootstrap ? { getBootstrapTarget: overrides.bootstrap } : {}),onUsage: overrides.onUsage,})return { handler, authorize, complete, report }}describe('PromptBridgeHandler', () => {- it('rejects an invalid purpose before authorizing', async () => {+ it('rejects invalid input before authorizing', async () => {const { handler, authorize } = makeDeps()await expect(handler.handle({ ...validBody, purpose: 'jailbreak' }, 'api')- ).rejects.toMatchObject({ code: 'invalid_request' })- expect(authorize).not.toHaveBeenCalled()- })-- it('rejects a malformed idempotency key', async () => {- const { handler } = makeDeps()+ ).rejects.toMatchObject({+ code: 'invalid_request',+ })await expect(handler.handle({ ...validBody, idempotencyKey: 'has spaces!' }, 'api')).rejects.toMatchObject({ code: 'invalid_request' })+ expect(authorize).not.toHaveBeenCalled()})- it('rejects oversized message content with payload_too_large', async () => {+ it('rejects oversized content before authorizing', async () => {const { handler, authorize } = makeDeps()await expect(handler.handle(@@ -87,87 +105,124 @@ describe('PromptBridgeHandler', () => {expect(authorize).not.toHaveBeenCalled()})- it('returns the spec §10 result shape and reports completion', async () => {+ it('lets the operator default resolve omission and forwards selectors unchanged', async () => {+ const { handler, authorize } = makeDeps()+ await handler.handle(validBody, 'api')+ expect(authorize).toHaveBeenCalledWith(+ expect.objectContaining({ model: undefined, provider: undefined, targetRef: undefined })+ )++ await handler.handle(+ { ...validBody, idempotencyKey: 'key-2', provider: 'openai', model: 'gpt-5.4-mini' },+ 'api'+ )+ expect(authorize).toHaveBeenLastCalledWith(+ expect.objectContaining({ provider: 'openai', model: 'gpt-5.4-mini' })+ )+ })++ it('forwards the live spec.agent binding to authorization', async () => {+ const { handler, authorize } = makeDeps({+ bootstrap: () => ({ provider: 'zai', model: 'glm-4.7' }),+ })+ await handler.handle(validBody, 'api')+ expect(authorize).toHaveBeenCalledWith(+ expect.objectContaining({ bootstrapProvider: 'zai', bootstrapModel: 'glm-4.7' })+ )+ })++ it('fails before authorization while the host bootstrap binding is not ready', async () => {+ const { handler, authorize } = makeDeps({ bootstrap: () => null })+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'provider_unavailable',+ retryable: true,+ })+ expect(authorize).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 })const result = await handler.handle(validBody, 'api')++ expect(complete).toHaveBeenCalledWith(+ expect.objectContaining({+ invocationId: 'inv-1',+ maxTokens: 2048,+ targets: [+ { target: primary, credentialTicket: 'ticket-primary' },+ { target: fallback, credentialTicket: 'ticket-fallback' },+ ],+ })+ )expect(result).toMatchObject({invocationId: 'inv-1',- model: 'glm-4.7',+ model: fallback.model,+ servedTarget: fallback,+ fallbackUsed: true,+ policyRevision: 7,content: 'summary text',- usage: { inputTokens: 10, outputTokens: 5 },- finishReason: 'complete',})- expect(result.correlationId).toBeTruthy()- expect(result.createdAt).toBeTruthy()- // maxOutputTokens from the grant clamps the request- expect(complete).toHaveBeenCalledWith(expect.objectContaining({ maxTokens: 2048 }))expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'complete')- expect(onUsage).toHaveBeenCalledWith({- model: 'glm-4.7',- inputTokens: 10,- outputTokens: 5,- callerRef: 'api',- })- })-- it('clamps requested maxTokens to the grant cap', async () => {- const { handler, complete } = makeDeps()- await handler.handle({ ...validBody, maxTokens: 9999 }, 'api')- expect(complete).toHaveBeenCalledWith(expect.objectContaining({ maxTokens: 2048 }))- })-- it('authorizes the mcp-host default model when the request omits model', async () => {- const { handler, authorize } = makeDeps({ defaultModel: 'glm-5.1' })- await handler.handle(validBody, 'api')- expect(authorize).toHaveBeenCalledWith(expect.objectContaining({ model: 'glm-5.1' }))+ expect(onUsage).toHaveBeenCalledWith(+ expect.objectContaining({+ provider: 'openai',+ model: fallback.model,+ servedTarget: fallback,+ fallbackUsed: true,+ llmSecretName: 'provider-secret',+ })+ )})- it('keeps modelPolicyRef authoritative instead of replacing it with the default model', async () => {- const { handler, authorize } = makeDeps({ defaultModel: 'glm-5.1' })- await handler.handle({ ...validBody, modelPolicyRef: 'policy-a' }, 'api')- expect(authorize).toHaveBeenCalledWith(- expect.objectContaining({ model: undefined, modelPolicyRef: 'policy-a' })+ it('fails closed on inconsistent tickets before credential or provider access', async () => {+ const authorize = vi.fn().mockResolvedValue(+ authorization({+ authorizedTargetTickets: [+ { targetRef: primary.targetRef, credentialTicket: 'ticket-primary' },+ ],+ }))+ const { handler, complete } = makeDeps({ authorize })+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'provider_unavailable',+ retryable: false,+ })+ expect(complete).not.toHaveBeenCalled()})- it('keeps an explicit request model over the mcp-host default model', async () => {- const { handler, authorize } = makeDeps({ defaultModel: 'glm-5.1' })- await handler.handle({ ...validBody, model: 'glm-4.7' }, 'api')- expect(authorize).toHaveBeenCalledWith(expect.objectContaining({ model: 'glm-4.7' }))+ it('does not repeat a provider charge for an existing non-failed replay', async () => {+ const authorize = vi.fn().mockResolvedValue(authorization({ replay: true, status: 'complete' }))+ const { handler, complete } = makeDeps({ authorize })+ await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({+ code: 'idempotency_conflict',+ retryable: false,+ })+ expect(complete).not.toHaveBeenCalled()})it('propagates authorization errors without calling the LLM', async () => {const authorize = vi.fn()- .mockRejectedValue(new PluginWorkloadError('quota_exceeded', 'limit', false))+ .mockRejectedValue(new PluginWorkloadError('ambiguous_model', 'ambiguous', false))const { handler, complete } = makeDeps({ authorize })await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({- code: 'quota_exceeded',+ code: 'ambiguous_model',})expect(complete).not.toHaveBeenCalled()})- it('reports provider_unavailable status when the LLM call times out', async () => {+ it('reports terminal provider configuration failures without widening fallback', async () => {const complete = vi.fn()- .mockRejectedValue(new PluginWorkloadError('provider_unavailable', 'timeout', true))+ .mockRejectedValue(+ new PluginWorkloadError('provider_unavailable', 'credentials unavailable', false)+ )const { handler, report } = makeDeps({ complete })await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({code: 'provider_unavailable',- retryable: true,+ retryable: false,})expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'provider_unavailable')})-- it('reports failed status for non-provider errors', async () => {- const complete = vi- .fn()- .mockRejectedValue(new PluginWorkloadError('payload_too_large', 'response too big'))- const { handler, report } = makeDeps({ complete })- await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({- code: 'payload_too_large',- })- expect(report).toHaveBeenCalledWith('inv-1', 'sandbox-recipes', 'r1', 'failed')- })})diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.tsindex 54b3655d2..921069852 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts@@ -7,6 +7,7 @@ import {PLUGIN_WORKLOAD_SDK_PURPOSES,type PromptBridgeRequest,type PromptBridgeResult,+ type PromptBridgeTarget,} from '../domain/types'import {pluginSdkPromptBridgeDurationSeconds,@@ -30,6 +31,7 @@ import type { LlmBridge } from './llmBridge'const IDEMPOTENCY_KEY_RE = new RegExp(DEFAULT_IDEMPOTENCY_KEY_PATTERN)const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)+const MAX_METADATA_BYTES = 16 * 1024export interface PromptBridgeHandlerDeps {controlApiClient: PluginWorkloadSdkControlApiClient@@ -38,9 +40,14 @@ export interface PromptBridgeHandlerDeps {recipeName: stringpromptTimeoutMs: numbermaxRequestContentBytes?: number- resolveDefaultModel?: () => string | null+ /** Public provider/model identity from the live spec.agent binding. */+ getBootstrapTarget?: () => { provider: string; model: string } | nullonUsage?: (usage: {+ provider: stringmodel: string+ servedTarget: PromptBridgeTarget+ fallbackUsed: boolean+ llmSecretName: stringinputTokens: numberoutputTokens: numbercallerRef: string@@ -93,6 +100,12 @@ export function validatePromptBridgeRequest(raw: unknown): PromptBridgeRequest {if (body.model !== undefined && typeof body.model !== 'string') {throw new PluginWorkloadError('invalid_request', 'model must be a string')}+ if (body.provider !== undefined && typeof body.provider !== 'string') {+ throw new PluginWorkloadError('invalid_request', 'provider must be a string')+ }+ if (body.targetRef !== undefined && typeof body.targetRef !== 'string') {+ throw new PluginWorkloadError('invalid_request', 'targetRef must be a string')+ }if (body.modelPolicyRef !== undefined && typeof body.modelPolicyRef !== 'string') {throw new PluginWorkloadError('invalid_request', 'modelPolicyRef must be a string')}@@ -108,12 +121,25 @@ export function validatePromptBridgeRequest(raw: unknown): PromptBridgeRequest {) {throw new PluginWorkloadError('invalid_request', 'metadata must be an object')}+ if (body.metadata !== undefined) {+ let metadataBytes: number+ try {+ metadataBytes = Buffer.byteLength(JSON.stringify(body.metadata), 'utf8')+ } catch {+ throw new PluginWorkloadError('invalid_request', 'metadata must be JSON-serializable')+ }+ if (metadataBytes > MAX_METADATA_BYTES) {+ throw new PluginWorkloadError('payload_too_large', 'metadata exceeds size limit')+ }+ }return {idempotencyKey: body.idempotencyKey as string,purpose: body.purpose as string,messages,model: typeof body.model === 'string' ? body.model : undefined,+ provider: typeof body.provider === 'string' ? body.provider : undefined,+ targetRef: typeof body.targetRef === 'string' ? body.targetRef : undefined,modelPolicyRef: typeof body.modelPolicyRef === 'string' ? body.modelPolicyRef : undefined,maxTokens: typeof body.maxTokens === 'number' ? body.maxTokens : undefined,temperature: typeof body.temperature === 'number' ? body.temperature : undefined,@@ -171,37 +197,79 @@ export class PromptBridgeHandler {}const correlationId = randomUUID()- const fallbackModel =- request.model === undefined && request.modelPolicyRef === undefined- ? this.deps.resolveDefaultModel?.()?.trim() || undefined- : undefined-+ const bootstrapTarget = this.deps.getBootstrapTarget?.()+ if (this.deps.getBootstrapTarget && !bootstrapTarget) {+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'mcp-host LLM bootstrap is not ready',+ true+ )+ }const authorized = await this.deps.controlApiClient.authorizePromptBridge({recipeNamespace: this.deps.recipeNamespace,recipeName: this.deps.recipeName,callerRef,- model: request.model ?? fallbackModel,+ ...(bootstrapTarget+ ? {+ bootstrapProvider: bootstrapTarget.provider,+ bootstrapModel: bootstrapTarget.model,+ }+ : {}),+ model: request.model,+ provider: request.provider,+ targetRef: request.targetRef,modelPolicyRef: request.modelPolicyRef,purpose: request.purpose,idempotencyKey: request.idempotencyKey,messages: request.messages,+ ...(request.metadata ? { metadata: request.metadata } : {}),correlationId,})+ // A successful replay is never sent to a provider again. The current+ // audit API does not persist completion content, so surface a stable+ // conflict instead of creating a duplicate billable call.+ if (authorized.replay && authorized.status !== 'failed') {+ throw new PluginWorkloadError(+ 'idempotency_conflict',+ 'idempotent invocation already exists; no provider call was repeated',+ false+ )+ }++ const selected = authorized.authorizedTargets[0]+ if (!selected || !sameTarget(selected, authorized.selectedTarget)) {+ throw unexpectedAuthorizationResponse()+ }+ const ticketByTarget = new Map(+ authorized.authorizedTargetTickets.map(ticket => [ticket.targetRef, ticket.credentialTicket])+ )+ if (+ ticketByTarget.size !== authorized.authorizedTargets.length ||+ authorized.authorizedTargets.some(target => !ticketByTarget.has(target.targetRef))+ ) {+ throw unexpectedAuthorizationResponse()+ }+try {const completion = await this.deps.llmBridge.complete({- model: authorized.model,+ invocationId: authorized.invocationId,+ targets: authorized.authorizedTargets.map(target => ({+ target,+ credentialTicket: ticketByTarget.get(target.targetRef)!,+ })),messages: request.messages,maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),temperature: request.temperature ?? authorized.modelPolicy?.temperature,timeoutMs: this.deps.promptTimeoutMs,- // R5 F6 — same-provider failover gated by the grant's allowed models.- // The bridge never switches provider, so these stay inside the grant.- fallbackModels: authorized.allowedModels?.filter(m => m !== authorized.model),})this.deps.onUsage?.({+ provider: completion.servedTarget.provider,model: completion.model,+ servedTarget: completion.servedTarget,+ fallbackUsed: completion.fallbackUsed,+ llmSecretName: completion.llmSecretName,inputTokens: completion.usage.inputTokens,outputTokens: completion.usage.outputTokens,callerRef,@@ -218,6 +286,9 @@ export class PromptBridgeHandler {return {invocationId: authorized.invocationId,model: completion.model,+ servedTarget: completion.servedTarget,+ fallbackUsed: completion.fallbackUsed,+ policyRevision: authorized.policyRevision,usage: completion.usage,content: completion.content,finishReason: completion.finishReason,@@ -240,6 +311,23 @@ export class PromptBridgeHandler {}}+function sameTarget(a: PromptBridgeTarget, b: PromptBridgeTarget): boolean {+ return (+ a.targetRef === b.targetRef &&+ a.provider === b.provider &&+ a.model === b.model &&+ a.credentialSlot === b.credentialSlot+ )+}++function unexpectedAuthorizationResponse(): PluginWorkloadError {+ return new PluginWorkloadError(+ 'provider_unavailable',+ 'control-api returned an inconsistent authorized target set',+ false+ )+}+function clampMaxTokens(requested: number | undefined,grantCap: number | nulldiff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex f5098caca..e1cd5010a 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -1,139 +1,250 @@import { describe, expect, it, vi } from 'vitest'+import { register } from 'prom-client'import { LlmErrorCode } from '../../core/errors'import { FinishReason } from '../../core/types'import type { SingleTurnProvider, createLLMProvider } from '../../llm'import type { ApiKeys, ModelConfig } from '../../types'+import { CircuitBreaker } from '../domain/circuitBreaker'import { PluginWorkloadError } from '../domain/errors'-import { LlmBridge, type LlmBridgeContext } from './llmBridge'--/**- * Provider-fallback (R5 F6) — promptBridge `LlmBridge`.- *- * The bridge switches only among the caller-supplied `fallbackModels` (which- * the handler derives from the grant's `allowedModels`) and NEVER switches- * provider — so a fallback model is, by construction, always inside the grant.- */+import type { PromptBridgeTarget } from '../domain/types'+import { recordCircuitBreakerState } from '../metrics'+import { LlmBridge, type PromptBridgeCredentialResolver } from './llmBridge'const OK = {content: 'ok',usage: { input_tokens: 3, output_tokens: 4, total_tokens: 7 },finish_reason: FinishReason.Stop,}+const primary: PromptBridgeTarget = {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-5.1',+ credentialSlot: 'zai-api-key',+}+const fallback: PromptBridgeTarget = {+ targetRef: 'fallback-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+}class FakeProvider implements Partial<SingleTurnProvider> {constructor(private readonly behavior: () => Promise<typeof OK>,- private readonly classify: { code: LlmErrorCode; retryable: boolean } = {+ private readonly classification: { code: LlmErrorCode; retryable: boolean } = {code: LlmErrorCode.RateLimited,retryable: true,}) {}completeSingleTurn = vi.fn(async () => this.behavior())-- classifyError(_err: unknown) {- return { code: this.classify.code, retryable: this.classify.retryable, message: 'x' }+ classifyError() {+ return { ...this.classification, message: 'redacted' }}}-function makeContext(): LlmBridgeContext {- const keys: ApiKeys = { openai: { 'openai-api-key': 'sk-test' } } as unknown as ApiKeys- return { keys, provider: 'openai' as ModelConfig['provider'], defaultModel: 'gpt-primary' }-}--/** Build a bridge whose per-model provider behavior is driven by `byModel`. */-function makeBridge(byModel: Record<string, FakeProvider>) {- const calls: string[] = []- const createProvider = ((_keys: ApiKeys, modelConfig: ModelConfig) => {- calls.push(modelConfig.name)- return (byModel[modelConfig.name] ?? null) as unknown as SingleTurnProvider | null+function makeBridge(+ providers: Record<string, FakeProvider>,+ resolve?: PromptBridgeCredentialResolver['resolve'],+ createBreaker?: (target: PromptBridgeTarget) => CircuitBreaker+) {+ const providerCalls: string[] = []+ const credentialCalls: string[] = []+ const resolver: PromptBridgeCredentialResolver = {+ resolve:+ resolve ??+ vi.fn(async ({ target }) => {+ credentialCalls.push(target.targetRef)+ const key = `${target.provider}-api-key`+ return {+ target,+ keys: { [target.provider]: { [key]: `secret-${target.targetRef}` } } as ApiKeys,+ llmSecretName: `${target.provider}-secret`,+ }+ }),+ }+ const createProvider = ((_keys: ApiKeys, model: ModelConfig) => {+ providerCalls.push(`${model.provider}/${model.name}`)+ return (providers[model.name] ?? null) as unknown as SingleTurnProvider | null}) as typeof createLLMProvider- const bridge = new LlmBridge(() => makeContext(), { createProvider })- return { bridge, calls }+ return {+ bridge: new LlmBridge(resolver, { createProvider, createBreaker }),+ providerCalls,+ credentialCalls,+ resolver,+ }}-const baseReq = {+const request = {+ invocationId: 'inv-1',+ targets: [+ { target: primary, credentialTicket: 'ticket-primary' },+ { target: fallback, credentialTicket: 'ticket-fallback' },+ ],messages: [{ role: 'user' as const, content: 'hi' }],timeoutMs: 5_000,}-describe('LlmBridge provider-fallback (R5 F6)', () => {- it('switches to a fallback model within the grant on an eligible failure', async () => {- const primary = new FakeProvider(() => Promise.reject(new Error('429')), {- code: LlmErrorCode.RateLimited,- retryable: true,+describe('LlmBridge authorized multi-provider fallback', () => {+ it('redeems credentials per attempt and serves the next authorized provider', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('provider response')))+ const second = new FakeProvider(() => Promise.resolve(OK))+ const { bridge, providerCalls, credentialCalls } = makeBridge({+ [primary.model]: first,+ [fallback.model]: second,+ })++ const result = await bridge.complete(request)++ expect(credentialCalls).toEqual([primary.targetRef, fallback.targetRef])+ expect(providerCalls).toEqual([+ `${primary.provider}/${primary.model}`,+ `${fallback.provider}/${fallback.model}`,+ ])+ expect(result).toMatchObject({+ servedTarget: fallback,+ fallbackUsed: true,+ model: fallback.model,+ usage: { inputTokens: 3, outputTokens: 4 },})- const fallback = new FakeProvider(() => Promise.resolve(OK))- const { bridge, calls } = makeBridge({ 'gpt-primary': primary, 'gpt-fallback': fallback })+ })- const result = await bridge.complete({- ...baseReq,- model: 'gpt-primary',- fallbackModels: ['gpt-fallback'],+ it('treats credential resolution failure as terminal and never redeems a fallback', async () => {+ const resolve = vi.fn(async () => {+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'authorized provider credentials are unavailable',+ false+ )})+ const { bridge, providerCalls } = makeBridge({}, resolve)- // The winning (served) pair is the fallback, and only it is returned.- expect(result.model).toBe('gpt-fallback')- expect(result.content).toBe('ok')- expect(calls).toEqual(['gpt-primary', 'gpt-fallback'])- expect(primary.completeSingleTurn).toHaveBeenCalledTimes(1)- expect(fallback.completeSingleTurn).toHaveBeenCalledTimes(1)+ await expect(bridge.complete(request)).rejects.toMatchObject({+ code: 'provider_unavailable',+ retryable: false,+ })+ expect(resolve).toHaveBeenCalledTimes(1)+ expect(providerCalls).toEqual([])})- it('does NOT switch when no fallbackModels are provided — original error propagates', async () => {- const primary = new FakeProvider(() => Promise.reject(new Error('429')), {- code: LlmErrorCode.RateLimited,- retryable: true,+ it('does not fallback on a provider error outside triggerOn', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('429')))+ const second = new FakeProvider(() => Promise.resolve(OK))+ const { bridge, providerCalls } = makeBridge({+ [primary.model]: first,+ [fallback.model]: second,})- const { bridge, calls } = makeBridge({ 'gpt-primary': primary })- await expect(bridge.complete({ ...baseReq, model: 'gpt-primary' })).rejects.toMatchObject({+ await expect(bridge.complete({ ...request, triggerOn: ['auth'] })).rejects.toMatchObject({code: 'provider_unavailable',})- expect(calls).toEqual(['gpt-primary'])+ expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])})- it('does NOT switch on a non-eligible (400/validation) failure — propagates immediately', async () => {- const primary = new FakeProvider(() => Promise.reject(new Error('bad request')), {- code: LlmErrorCode.ApiCallFailed,- retryable: false, // 400 → not eligible+ it('fails terminally when an authorized target cannot construct its provider', async () => {+ const { bridge } = makeBridge({})+ await expect(bridge.complete(request)).rejects.toMatchObject({+ code: 'provider_unavailable',+ retryable: false,})- const fallback = new FakeProvider(() => Promise.resolve(OK))- const { bridge, calls } = makeBridge({ 'gpt-primary': primary, 'gpt-fallback': fallback })+ })+ it('never attempts a target outside the exact authorized list', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('429')))+ const { bridge, providerCalls } = makeBridge({ [primary.model]: first })await expect(- bridge.complete({ ...baseReq, model: 'gpt-primary', fallbackModels: ['gpt-fallback'] })- ).rejects.toBeInstanceOf(PluginWorkloadError)- // The fallback is never attempted.- expect(calls).toEqual(['gpt-primary'])- expect(fallback.completeSingleTurn).not.toHaveBeenCalled()+ bridge.complete({ ...request, targets: [request.targets[0]] })+ ).rejects.toMatchObject({ code: 'provider_unavailable' })+ expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])})- it('returns exactly one result (only the winner) so the handler meters once', async () => {- const primary = new FakeProvider(() => Promise.reject(new Error('429')))- const fallback = new FakeProvider(() =>- Promise.resolve({ ...OK, usage: { input_tokens: 11, output_tokens: 22, total_tokens: 33 } })+ it('isolates target breakers so a failing primary still reaches a healthy fallback', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('429')))+ const second = new FakeProvider(() => Promise.resolve(OK))+ const breakers = new Map<string, CircuitBreaker>()+ const { bridge } = makeBridge(+ { [primary.model]: first, [fallback.model]: second },+ undefined,+ target => {+ const breaker = new CircuitBreaker({ minSamples: 4 })+ breakers.set(target.targetRef, breaker)+ return breaker+ })- const { bridge } = makeBridge({ 'gpt-primary': primary, 'gpt-fallback': fallback })- const result = await bridge.complete({- ...baseReq,- model: 'gpt-primary',- fallbackModels: ['gpt-primary', 'gpt-fallback'], // primary deduped out- })+ for (let attempt = 0; attempt < 3; attempt += 1) {+ const result = await bridge.complete({ ...request, invocationId: `inv-${attempt}` })+ expect(result.servedTarget).toEqual(fallback)+ }+ expect(breakers.get(primary.targetRef)?.isOpen()).toBe(false)++ const fourth = await bridge.complete({ ...request, invocationId: 'inv-4' })+ expect(fourth.servedTarget).toEqual(fallback)+ expect(fourth.fallbackUsed).toBe(true)+ expect(breakers.get(primary.targetRef)?.isOpen()).toBe(true)+ expect(first.completeSingleTurn).toHaveBeenCalledTimes(4)+ expect(second.completeSingleTurn).toHaveBeenCalledTimes(4)+ })- expect(result.model).toBe('gpt-fallback')- expect(result.usage).toEqual({ inputTokens: 11, outputTokens: 22 })+ it('skips credential redemption for an open primary and isolates the fallback target', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('429')))+ const second = new FakeProvider(() => Promise.resolve(OK))+ const breakers = new Map<string, CircuitBreaker>()+ const { bridge, credentialCalls } = makeBridge(+ { [primary.model]: first, [fallback.model]: second },+ undefined,+ target => {+ const breaker = new CircuitBreaker({ minSamples: 4 })+ if (target.targetRef === primary.targetRef) {+ for (let attempt = 0; attempt < 4; attempt += 1) breaker.record(false)+ }+ breakers.set(target.targetRef, breaker)+ return breaker+ }+ )++ const result = await bridge.complete(request)++ expect(result.servedTarget).toEqual(fallback)+ expect(credentialCalls).toEqual([fallback.targetRef])+ expect(first.completeSingleTurn).not.toHaveBeenCalled()+ expect(second.completeSingleTurn).toHaveBeenCalledOnce()+ expect(breakers.get(primary.targetRef)?.isOpen()).toBe(true)+ expect(breakers.get(fallback.targetRef)?.isOpen()).toBe(false)})- it('propagates the last error when every fallback also fails', async () => {- const primary = new FakeProvider(() => Promise.reject(new Error('429')))- const fallback = new FakeProvider(() => Promise.reject(new Error('429 again')))- const { bridge, calls } = makeBridge({ 'gpt-primary': primary, 'gpt-fallback': fallback })+ it('publishes circuit state under the effective target label', async () => {+ const target = { ...primary, targetRef: `metric-${Date.now()}` }+ const failing = new FakeProvider(() => Promise.reject(new Error('429')))+ const { bridge } = makeBridge(+ { [target.model]: failing },+ undefined,+ effectiveTarget =>+ new CircuitBreaker({+ minSamples: 4,+ onStateChange: open =>+ recordCircuitBreakerState(`llm-provider:${effectiveTarget.targetRef}`, open),+ })+ )- await expect(- bridge.complete({ ...baseReq, model: 'gpt-primary', fallbackModels: ['gpt-fallback'] })- ).rejects.toMatchObject({ code: 'provider_unavailable' })- expect(calls).toEqual(['gpt-primary', 'gpt-fallback'])+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await expect(+ bridge.complete({+ ...request,+ invocationId: `metric-${attempt}`,+ targets: [{ target, credentialTicket: `ticket-${attempt}` }],+ })+ ).rejects.toMatchObject({ code: 'provider_unavailable' })+ }++ const metric = register.getSingleMetric('clerum_plugin_workload_sdk_circuit_breaker_state')+ const data = await metric?.get()+ expect(+ data?.values.find(+ value =>+ value.labels.gateway === `llm-provider:${target.targetRef}` &&+ value.labels.state === 'open'+ )?.value+ ).toBe(1)})})diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.tsindex 9bc1fa4ad..1f0c3cbcf 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts@@ -5,85 +5,51 @@ import {ALL_FAILOVER_CLASSES,type ClassifiedLike,type FailoverClass,- FailoverEngine,- type LlmPolicy,- type ModelPair,+ classifyFailoverClass,} from '../../llm/failover'-import type { ApiKeys, ModelConfig } from '../../types'+import { isLlmProvider } from '../../llm/registryCore'import { CircuitBreaker } from '../domain/circuitBreaker'import { PluginWorkloadError } from '../domain/errors'+import type { PromptBridgeTarget } from '../domain/types'+import type { BrokeredCredential } from './credentialBrokerClient'-/**- * LLM bridge (plan §3.3 step 5, OQ-2): executes the authorized one-shot- * completion against the provider bound to THIS mcp-host. The provider is- * never selectable per request — only the model within it. Inference-only:- * no tools, no session state (v1 invariant).- *- * Provider circuit breaker (plan §3.4): >50% failures over 30s opens the- * circuit; subsequent calls return provider_unavailable until a 60s quiet- * period elapses.- *- * Provider-fallback (R5 F6, spec §3-R5.7): when the caller supplies- * `fallbackModels` (derived from the grant's `allowedModels`), an eligible- * classified failure (`triggerOn`) switches to the next allowed model of the- * SAME provider and retries the request. The bridge NEVER switches provider —- * so, by construction, a fallback model always belongs to the grant's allowlist- * (outside the grant = no switch, the original error propagates). The failover- * decision runs on `classifyError(err).code`; the existing circuit breaker still- * records every attempt (all classes) but stays OUTSIDE the trigger mechanism —- * the reusable {@link FailoverEngine} decides the switch. Only the winning call- * returns (and therefore meters, in the handler's `onUsage`).- */--/**- * Internal carrier: an attempt that failed with a provider error, holding both- * the failover classification (for the engine) and the ready- * {@link PluginWorkloadError} to surface once the ordered list is exhausted.- * Non-eligible failures (our own guardrails) are thrown as `PluginWorkloadError`- * directly and propagate unchanged — the engine's classifier returns `null`.- */class ClassifiedProviderError extends Error {constructor(readonly classified: ClassifiedLike,- private readonly pwe: PluginWorkloadError+ private readonly publicError: PluginWorkloadError) {- super(pwe.message)+ super(publicError.message)this.name = 'ClassifiedProviderError'}toPluginWorkloadError(): PluginWorkloadError {- return this.pwe+ return this.publicError}}-export interface LlmBridgeContext {- keys: ApiKeys- provider: ModelConfig['provider']- defaultModel: string+export interface PromptBridgeCredentialResolver {+ resolve(input: {+ invocationId: string+ target: PromptBridgeTarget+ credentialTicket: string+ }): Promise<BrokeredCredential>}export interface LlmBridgeRequest {- model: string | null+ invocationId: string+ targets: Array<{ target: PromptBridgeTarget; credentialTicket: string }>messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>maxTokens?: numbertemperature?: numbertimeoutMs: number- /**- * R5 F6 — ordered same-provider fallback models. Each MUST be a model the- * grant permits (the caller derives this from the grant's `allowedModels`);- * the bridge never switches provider, so a fallback is always inside the- * grant. Empty/absent = no failover = byte-identical to today's single call.- */- fallbackModels?: string[]- /**- * R5 F6 — failover classes that trigger a switch. Default: all four- * ({@link ALL_FAILOVER_CLASSES}). 400/validation is never eligible.- */triggerOn?: FailoverClass[]}export interface LlmBridgeResult {model: string+ servedTarget: PromptBridgeTarget+ fallbackUsed: boolean+ llmSecretName: stringcontent: stringusage: { inputTokens: number; outputTokens: number }finishReason: 'complete' | 'length' | 'content_filter'@@ -97,112 +63,143 @@ function mapFinishReason(reason: FinishReason): LlmBridgeResult['finishReason']return 'complete'}+/**+ * Executes only the ordered target suffix authorized by control-api. Each+ * attempt redeems its own signed ticket and credential; credential/config+ * failures are terminal, while eligible provider failures alone advance to+ * the next authorized target.+ */export class LlmBridge {- private readonly breaker: CircuitBreaker+ private readonly breakers = new Map<string, CircuitBreaker>()+ private static readonly MAX_TARGET_BREAKERS = 512constructor(- private readonly getContext: () => LlmBridgeContext | null,+ private readonly credentials: PromptBridgeCredentialResolver,private readonly opts: {maxResponseBytes?: number- breaker?: CircuitBreaker+ /** Creates an isolated breaker for each effective provider target. */+ createBreaker?: (target: PromptBridgeTarget) => CircuitBreakercreateProvider?: typeof createLLMProvider} = {}) {- this.breaker = opts.breaker ?? new CircuitBreaker()+ // Breaker state is intentionally keyed by the complete target identity.+ // A provider/model/credential-slot policy can change while the mcp-host+ // remains alive, so targetRef alone is not sufficient isolation.}- async complete(request: LlmBridgeRequest): Promise<LlmBridgeResult> {- if (!this.breaker.allow()) {- throw new PluginWorkloadError(- 'provider_unavailable',- 'LLM provider circuit breaker is open',- true- )+ private breakerKey(target: PromptBridgeTarget): string {+ return [target.targetRef, target.provider, target.model, target.credentialSlot].join('\u0000')+ }++ private breakerFor(target: PromptBridgeTarget): CircuitBreaker {+ const key = this.breakerKey(target)+ const existing = this.breakers.get(key)+ if (existing) return existing++ const breaker = this.opts.createBreaker?.(target) ?? new CircuitBreaker()+ // A recipe policy is bounded, but the policy can be edited repeatedly over+ // the lifetime of a host. Keep this process-local cache bounded as well.+ if (this.breakers.size >= LlmBridge.MAX_TARGET_BREAKERS) {+ const oldest = this.breakers.keys().next().value+ if (typeof oldest === 'string') this.breakers.delete(oldest)}+ this.breakers.set(key, breaker)+ return breaker+ }- const context = this.getContext()- if (!context) {- throw new PluginWorkloadError(- 'provider_unavailable',- 'no LLM provider is configured on this mcp-host',- true- )+ async complete(request: LlmBridgeRequest): Promise<LlmBridgeResult> {+ if (request.targets.length === 0) {+ throw new PluginWorkloadError('provider_unavailable', 'no authorized provider target', false)}+ const triggerOn = new Set(request.triggerOn ?? ALL_FAILOVER_CLASSES)+ let lastProviderError: ClassifiedProviderError | null = null- const primaryModel = request.model ?? context.defaultModel- const fallbackModels = this.resolveFallbackModels(request.fallbackModels, primaryModel)+ for (const [index, authorized] of request.targets.entries()) {+ if (!isLlmProvider(authorized.target.provider)) {+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'authorized provider configuration is unavailable',+ false+ )+ }- // No fallback configured → the single-attempt path, byte-identical to before- // (R5 §3-R5.1: "sin política = comportamiento actual").- if (fallbackModels.length === 0) {- try {- return await this.attempt(context, primaryModel, request)- } catch (err) {- throw err instanceof ClassifiedProviderError ? err.toPluginWorkloadError() : err+ const breaker = this.breakerFor(authorized.target)+ if (!breaker.allow()) {+ const error = new ClassifiedProviderError(+ { code: LlmErrorCode.ApiCallFailed, retryable: true },+ new PluginWorkloadError(+ 'provider_unavailable',+ 'LLM provider is temporarily unavailable',+ true+ )+ )+ lastProviderError = error+ const failureClass = classifyFailoverClass(+ error.classified.code,+ error.classified.retryable+ )+ const eligible = failureClass !== null && triggerOn.has(failureClass)+ if (!eligible || index === request.targets.length - 1) throw error.toPluginWorkloadError()+ continue}- }- // Per-call engine: a promptBridge request is a stateless one-shot, so the- // sticky cooldown across requests is irrelevant — the engine is used purely- // for its ordered attempt loop + eligibility classification + metric.- const policy: LlmPolicy = {- cooldownSeconds: 0,- triggerOn: request.triggerOn ?? [...ALL_FAILOVER_CLASSES],- fallbacks: fallbackModels.map(model => ({ provider: context.provider, model })),- }- const engine = new FailoverEngine(policy)- const primaryPair: ModelPair = { provider: context.provider, model: primaryModel }- try {- return await engine.run(- primaryPair,- target => () => this.attempt(context, target.model, request),- err => (err instanceof ClassifiedProviderError ? err.classified : null)- )- } catch (err) {- throw err instanceof ClassifiedProviderError ? err.toPluginWorkloadError() : err- }- }+ // Ticket redemption is deliberately inside the attempt loop. This value+ // is held only for the provider call and is never exposed in SDK output.+ const credential = await this.credentials.resolve({+ invocationId: request.invocationId,+ target: authorized.target,+ credentialTicket: authorized.credentialTicket,+ })- /**- * Dedupe fallback models against the primary + each other, preserving order.- * The list arrives already gated to the grant's `allowedModels`, so nothing- * here can widen it.- */- private resolveFallbackModels(raw: string[] | undefined, primaryModel: string): string[] {- if (!raw || raw.length === 0) return []- const seen = new Set<string>([primaryModel])- const out: string[] = []- for (const model of raw) {- if (typeof model === 'string' && model.length > 0 && !seen.has(model)) {- seen.add(model)- out.push(model)+ try {+ const completion = await this.attempt(credential, request, breaker)+ return {+ ...completion,+ servedTarget: authorized.target,+ fallbackUsed: index > 0,+ llmSecretName: credential.llmSecretName,+ }+ } catch (error) {+ if (!(error instanceof ClassifiedProviderError)) throw error+ lastProviderError = error+ const failureClass = classifyFailoverClass(+ error.classified.code,+ error.classified.retryable+ )+ const eligible = failureClass !== null && triggerOn.has(failureClass)+ if (!eligible || index === request.targets.length - 1) throw error.toPluginWorkloadError()}}- return out++ throw (+ lastProviderError?.toPluginWorkloadError() ??+ new PluginWorkloadError('provider_unavailable', 'authorized providers are unavailable', true)+ )}- /**- * One completion attempt against `model` (same provider). On success records- * the breaker + returns the served pair; on an eligible provider failure- * throws a {@link ClassifiedProviderError} (so the engine can switch); on a- * guardrail failure (payload/usage/no-key) throws a `PluginWorkloadError`- * (non-eligible → propagates unchanged).- */private async attempt(- context: LlmBridgeContext,- model: string,- request: LlmBridgeRequest- ): Promise<LlmBridgeResult> {+ credential: BrokeredCredential,+ request: LlmBridgeRequest,+ breaker: CircuitBreaker+ ): Promise<Pick<LlmBridgeResult, 'model' | 'content' | 'usage' | 'finishReason'>> {const factory = this.opts.createProvider ?? createLLMProvider- const provider: SingleTurnProvider | null = factory(context.keys, {- provider: context.provider,- name: model,+ const providerId = credential.target.provider+ if (!isLlmProvider(providerId)) {+ throw new PluginWorkloadError(+ 'provider_unavailable',+ 'authorized provider configuration is unavailable',+ false+ )+ }+ const provider: SingleTurnProvider | null = factory(credential.keys, {+ provider: providerId,+ name: credential.target.model,})if (!provider) {throw new PluginWorkloadError('provider_unavailable',- 'LLM provider could not be constructed (missing API key)',- true+ 'authorized provider credentials are unavailable',+ false)}@@ -214,8 +211,7 @@ export class LlmBridge {temperature: request.temperature,signal: controller.signal,})- this.breaker.record(true)-+ breaker.record(true)const maxBytes = this.opts.maxResponseBytes ?? DEFAULT_MAX_LLM_RESPONSE_BYTESif (Buffer.byteLength(response.content, 'utf8') > maxBytes) {throw new PluginWorkloadError(@@ -229,24 +225,20 @@ export class LlmBridge {throw new PluginWorkloadError('provider_unavailable','provider returned invalid usage',- true+ false)}-return {- model,+ model: credential.target.model,content: response.content,usage: { inputTokens, outputTokens },finishReason: mapFinishReason(response.finish_reason),}- } catch (err) {- // Our own guardrails (payload/usage/no-key) are not provider failures:- // propagate unchanged, never fail over.- if (err instanceof PluginWorkloadError) throw err- this.breaker.record(false)+ } catch (error) {+ if (error instanceof PluginWorkloadError) throw error+ breaker.record(false)if (controller.signal.aborted) {throw new ClassifiedProviderError(- // A timeout is a retryable transport failure → provider_unavailable.{ code: LlmErrorCode.ApiCallFailed, retryable: true },new PluginWorkloadError('provider_unavailable',@@ -255,7 +247,7 @@ export class LlmBridge {))}- const classified = provider.classifyError(err)+ const classified = provider.classifyError(error)throw new ClassifiedProviderError({ code: classified.code, retryable: classified.retryable },new PluginWorkloadError(diff --git a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.tsindex 0b4ede23d..a1b044a2d 100644--- a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts@@ -33,6 +33,12 @@ function deepKeys(value: unknown, acc: Set<string> = new Set()): Set<string> {describe('Plugin Workload SDK — §6.2 response-shape security invariants', () => {it('promptBridge result contains no provider key, token, or user-info', async () => {+ const target = {+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-4.7',+ credentialSlot: 'zai-api-key',+ }const controlApiClient = {authorizePromptBridge: vi.fn().mockResolvedValue({invocationId: 'inv-1',@@ -42,6 +48,13 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()// Even if control-api leaked a key into the authorization envelope,// the handler must not surface it in the result.modelPolicy: { provider: 'zai', model: 'glm-4.7', apiKey: 'sk-provider-secret' },+ selectedTarget: target,+ authorizedTargets: [target],+ authorizedTargetTickets: [+ { targetRef: target.targetRef, credentialTicket: 'signed-ticket' },+ ],+ policyRevision: 1,+ policyHash: 'a'.repeat(64),maxOutputTokens: null,}),reportInvocationStatus: vi.fn().mockResolvedValue(undefined),@@ -49,6 +62,9 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()const llmBridge = {complete: vi.fn().mockResolvedValue({model: 'glm-4.7',+ servedTarget: target,+ fallbackUsed: false,+ llmSecretName: 'zai-secret',content: 'the summary',usage: { inputTokens: 4, outputTokens: 2 },finishReason: 'complete',@@ -76,11 +92,12 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()for (const forbidden of FORBIDDEN_SUBSTRINGS) {expect(serialized).not.toContain(forbidden)}- // Credential selection invariant: no provider/apiKey fields on the result.+ // Provider identity is deliberately returned as non-secret servedTarget+ // telemetry; credential values/tickets and policy internals must not leak.const keys = deepKeys(result)expect(keys.has('apiKey')).toBe(false)- expect(keys.has('provider')).toBe(false)expect(keys.has('modelPolicy')).toBe(false)+ expect(keys.has('credentialTicket')).toBe(false)// User-info invariant: no user identity fields surface.for (const userInfoField of ['userId', 'email', 'phone', 'teamId', 'sender']) {expect(keys.has(userInfoField)).toBe(false)diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.tsindex 1c0f9fb07..c4bbf54de 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts@@ -1,8 +1,5 @@import { randomUUID } from 'crypto'import type { Config } from '../../config'-import { apiKeysFromEnv } from '../../llm'-import { isLlmProvider } from '../../llm/registryCore'-import type { ApiKeys, ModelConfig } from '../../types'import type { LlmUsageEvent, UsageReporter } from '../../usage/usageReporter'import { getJwtRuntimeBinding } from '../../workflow/mcpHostRuntimeJwt'import { type McpHostRuntimeAuth, refreshWithRecovery } from '../../workflow/userApprovalRequester'@@ -10,8 +7,9 @@ import { ClientNotificationsHandler } from '../clientNotifications/handler'import { CircuitBreaker } from '../domain/circuitBreaker'import { recordCircuitBreakerState } from '../metrics'import { PluginWorkloadSdkControlApiClient } from '../promptBridge/controlApiClient'+import { PluginWorkloadSdkCredentialBrokerClient } from '../promptBridge/credentialBrokerClient'import { PromptBridgeHandler } from '../promptBridge/handler'-import { LlmBridge, type LlmBridgeContext } from '../promptBridge/llmBridge'+import { LlmBridge } from '../promptBridge/llmBridge'import { PluginWorkloadSdkServer, shouldStartPluginWorkloadSdk } from './sdkServer'import {loadWorkloadTokenRegistryFromDir,@@ -126,12 +124,15 @@ export function maybeCreatePluginWorkloadSdkServer(runtimeAuth: McpHostRuntimeAuth | null,opts: {/**- * Live LLM binding source. Workflow-mode mcp-hosts receive their API- * key via POST /configure (never env), so main.ts wires this to the- * WorkflowService onLlmConfigured holder. Falls back to env-derived- * keys for dev usage.+ * Live public LLM binding source. Workflow-mode mcp-hosts receive their+ * provider/model via POST /configure (credentials never cross this+ * callback), so main.ts wires this to the WorkflowService holder. A+ * missing binding keeps promptBridge fail-closed until configure is ready.*/- getLlmContext?: () => LlmBridgeContext | null+ getLlmContext?: () => {+ provider: string+ defaultModel: string+ } | null/*** Usage reporting (plan §5.6): when wired, every successful* promptBridge call ships one LlmUsageEvent (source_kind='workflow')@@ -209,37 +210,19 @@ export function maybeCreatePluginWorkloadSdkServer(})recordCircuitBreakerState('control-api', false)- // OQ-2: the provider bound to this mcp-host is the single source of truth.- // promptBridge may select a model within it but never the provider. The set- // of known providers is the registry's `ALL_PROVIDERS`.- const envLlmContext = (): LlmBridgeContext | null => {- const rawProvider = config.devModelProvider ?? 'openai'- let provider: ModelConfig['provider']- if (isLlmProvider(rawProvider)) {- provider = rawProvider- } else {- console.warn(- `[PluginWorkloadSdk] Unknown devModelProvider '${rawProvider}', falling back to 'openai'`- )- provider = 'openai'- }- // Registry-driven & multi-slot (R4): collect each provider's dev- // credential slots from the env (a provider is included only when all its- // required slots are present).- const keys: ApiKeys = apiKeysFromEnv()- const defaultModel = config.devModelName ?? ''- if (!defaultModel) return null- return { keys, provider, defaultModel }- }- const getLlmContext = (): LlmBridgeContext | null => opts.getLlmContext?.() ?? envLlmContext()-- const llmBridge = new LlmBridge(getLlmContext, {+ const credentialBroker = new PluginWorkloadSdkCredentialBrokerClient({+ baseUrl: config.pluginWorkloadSdkCredentialBrokerUrl,+ recipeNamespace: binding.recipeNamespace,+ recipeName: binding.recipeName,+ getAccessToken: () => runtimeAuth?.accessToken ?? config.mcpHostRuntimeAccessToken ?? '',+ })+ const llmBridge = new LlmBridge(credentialBroker, {maxResponseBytes: config.pluginWorkloadSdkMaxLlmResponseBytes,- breaker: new CircuitBreaker({- onStateChange: open => recordCircuitBreakerState('llm-provider', open),- }),+ createBreaker: target =>+ new CircuitBreaker({+ onStateChange: open => recordCircuitBreakerState(`llm-provider:${target.targetRef}`, open),+ }),})- recordCircuitBreakerState('llm-provider', false)const usageReporter = opts.usageReporter ?? nullconst promptBridgeHandler = new PromptBridgeHandler({@@ -248,22 +231,27 @@ export function maybeCreatePluginWorkloadSdkServer(recipeNamespace: binding.recipeNamespace,recipeName: binding.recipeName,promptTimeoutMs: config.pluginWorkloadSdkPromptTimeoutSeconds * 1000,- resolveDefaultModel: () => getLlmContext()?.defaultModel ?? null,+ getBootstrapTarget: opts.getLlmContext+ ? () => {+ const context = opts.getLlmContext?.()+ if (!context) return null+ return { provider: context.provider, model: context.defaultModel }+ }+ : undefined,onUsage: usage => {if (!usageReporter) return- const provider = getLlmContext()?.provider ?? 'unknown'const event = buildPromptBridgeUsageEvent({binding: {hostRef: runtimeAuth?.hostRef ?? binding.hostRef,recipeNamespace: binding.recipeNamespace,recipeName: binding.recipeName,},- provider,+ provider: usage.provider,model: usage.model,inputTokens: usage.inputTokens,outputTokens: usage.outputTokens,callerRef: usage.callerRef,- metadata: usage.metadata,+ metadata: { ...usage.metadata, llmSecretName: usage.llmSecretName },})if (event) usageReporter.enqueue(event)},diff --git a/mcp-host/src/pluginWorkloadSdk/server/middleware/workloadAuth.ts b/mcp-host/src/pluginWorkloadSdk/server/middleware/workloadAuth.tsindex c1853975e..650ad955f 100644--- a/mcp-host/src/pluginWorkloadSdk/server/middleware/workloadAuth.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/middleware/workloadAuth.ts@@ -14,9 +14,11 @@ import { PluginWorkloadError } from '../../domain/errors'* authorizes every call against the recipe grant regardless.*/-declare module 'express-serve-static-core' {- interface Request {- pluginWorkloadCallerRef?: string+declare global {+ namespace Express {+ interface Request {+ pluginWorkloadCallerRef?: string+ }}}diff --git a/mcp-host/src/workflow/__tests__/configureHandler.test.ts b/mcp-host/src/workflow/__tests__/configureHandler.test.tsindex 0e3cb62f5..411627934 100644--- a/mcp-host/src/workflow/__tests__/configureHandler.test.ts+++ b/mcp-host/src/workflow/__tests__/configureHandler.test.ts@@ -55,6 +55,23 @@ describe('POST /configure — JWT scope', () => {expect(result.configured).toBe(true)expect(result.provider).toBe('openai')})++ it('publishes SDK bootstrap identity without making the workflow service ready or receiving a key', () => {+ const onBootstrap = vi.fn()+ const svc = new WorkflowService('test', {+ llmFactory: mockLlmFactory(),+ onPluginWorkloadSdkBootstrapConfigured: onBootstrap,+ })+ const result = svc.configurePluginWorkloadSdkBootstrap({+ provider: 'openai',+ model: 'gpt-4',+ // @ts-expect-error the public bootstrap contract intentionally has no apiKey+ apiKey: 'must-not-be-consumed',+ })+ expect(result).toEqual({ configured: true, provider: 'openai', model: 'gpt-4' })+ expect(onBootstrap).toHaveBeenCalledWith({ provider: 'openai', defaultModel: 'gpt-4' })+ expect(svc.isReady()).toBe(false)+ })})describe('POST /configure — provider hot-swap', () => {diff --git a/mcp-host/src/workflow/types.ts b/mcp-host/src/workflow/types.tsindex 8887c4b3e..d186979b6 100644--- a/mcp-host/src/workflow/types.ts+++ b/mcp-host/src/workflow/types.ts@@ -108,6 +108,12 @@ export interface ConfigureResponse {message?: string}+/** Public identity handshake for a stepless Plugin Workload SDK host. */+export interface PluginWorkloadSdkBootstrapRequest {+ provider?: LlmProvider+ model?: string+}+// ─── Internal Tools (clerum__*) ──────────────────────────────────────export interface ArtifactMetadata {diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex ed561f1d5..07eefa024 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -25,7 +25,7 @@ import {resolveExistingArtifactFile,} from './artifactPaths'import { getOutputDir } from './internalTools'-import { ConfigureRequest, ExecuteStepRequest } from './types'+import { ConfigureRequest, ExecuteStepRequest, PluginWorkloadSdkBootstrapRequest } from './types'import { WorkflowService } from './workflowService'// ─── V1 fix: JWT auth middleware for workflow endpoints ──────────────────@@ -236,6 +236,27 @@ export function createWorkflowRouter(service: WorkflowService): Router {res.json(result)})+ // POST /plugin-workload-sdk/bootstrap — publish only the public+ // provider/model binding for a stepless SDK host. No API key is accepted or+ // resolved here; prompt credentials are brokered per attempt by WRC.+ router.post(+ '/plugin-workload-sdk/bootstrap',+ requireWorkflowAuth('configure'),+ (req: Request, res: Response) => {+ if (!validateWorkflowBinding(req, res, { expectedSub: 'wrc' })) return+ const raw = req.body as PluginWorkloadSdkBootstrapRequest+ // Deliberately project the request to the identity-only contract. Any+ // apiKey/secret-shaped field supplied by a caller is ignored before the+ // service boundary and can never reach the SDK context holder.+ const body: PluginWorkloadSdkBootstrapRequest = {+ provider: raw?.provider,+ model: raw?.model,+ }+ const result = service.configurePluginWorkloadSdkBootstrap(body)+ res.status(result.configured ? 200 : 400).json(result)+ }+ )+// GET /mode — workflow mode status (requires valid workflow token)router.get('/mode', requireWorkflowAuth('mode_read'), (req: Request, res: Response) => {if (!validateWorkflowBinding(req, res)) returndiff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex 7416b718b..320c7114b 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -32,6 +32,7 @@ import {ConfigureResponse,ExecuteStepRequest,ExecuteStepResponse,+ PluginWorkloadSdkBootstrapRequest,ToolCallRecord,} from './types'import { type McpHostRuntimeAuth, gateStep, refreshWithRecovery } from './userApprovalRequester'@@ -294,6 +295,11 @@ export class WorkflowService {provider: import('../types').ModelConfig['provider']defaultModel: string}) => void+ /** Public identity-only callback for stepless Plugin Workload SDK mode. */+ onPluginWorkloadSdkBootstrapConfigured?: (context: {+ provider: import('../types').ModelConfig['provider']+ defaultModel: string+ }) => void}) {this.recipeName = recipeName@@ -310,6 +316,8 @@ export class WorkflowService {this.injectedBudgetClient = opts?.budgetClientthis.workflowMaxOutputTokens = opts?.workflowMaxOutputTokens ?? resolveWorkflowMaxOutputTokens()this.onLlmConfigured = opts?.onLlmConfigured ?? null+ this.onPluginWorkloadSdkBootstrapConfigured =+ opts?.onPluginWorkloadSdkBootstrapConfigured ?? null}private readonly onLlmConfigured:@@ -320,6 +328,13 @@ export class WorkflowService {}) => void)| null = null+ private readonly onPluginWorkloadSdkBootstrapConfigured:+ | ((context: {+ provider: import('../types').ModelConfig['provider']+ defaultModel: string+ }) => void)+ | 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.@@ -331,6 +346,30 @@ export class WorkflowService {})}+ /**+ * Accept only the public provider/model identity for the eager SDK host.+ * This intentionally does not touch `currentApiKey`, `currentProvider`, or+ * workflow readiness: stepless SDK traffic resolves credentials per attempt+ * through the WRC broker rather than loading them into this service.+ */+ configurePluginWorkloadSdkBootstrap(req: PluginWorkloadSdkBootstrapRequest): ConfigureResponse {+ if (!req.provider) {+ return { configured: false, message: 'provider is required' }+ }+ if (!isLlmProvider(req.provider)) {+ return { configured: false, message: `Unknown provider: ${req.provider}` }+ }+ const model = typeof req.model === 'string' ? req.model.trim() : ''+ if (!/^[a-zA-Z0-9._:/-]{1,128}$/.test(model)) {+ return { configured: false, message: 'model is required and has an invalid format' }+ }+ this.onPluginWorkloadSdkBootstrapConfigured?.({+ provider: req.provider as import('../types').ModelConfig['provider'],+ defaultModel: model,+ })+ return { configured: true, provider: req.provider, model }+ }+isReady(): boolean {return this.configured && this.currentProvider !== null}diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex 2d5bc553d..ca1aff470 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.50",+ "version": "1.0.51","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.50",+ "version": "1.0.51","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex 521c90436..8e03149f1 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.50",+ "version": "1.0.51","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",diff --git a/tests/e2e/fixtures/plugin-workload-sdk-recipe.yaml b/tests/e2e/fixtures/plugin-workload-sdk-recipe.yamlindex 791663c3f..4b8ce8aa8 100644--- a/tests/e2e/fixtures/plugin-workload-sdk-recipe.yaml+++ b/tests/e2e/fixtures/plugin-workload-sdk-recipe.yaml@@ -1,8 +1,9 @@# Plugin Workload SDK E2E fixture.## Declares BOTH SDK capability families and a plugin workload (sdk-caller)-# that exercises them. The recipe also declares an agent + a minimal step so-# WRC spawns the recipe mcp-host (which hosts the SDK server on :8099).+# that exercises them. The recipe is intentionally stepless: WRC provisions+# the eager recipe-bound mcp-host for the SDK capability, not for workflow+# execution.## WRC auto-injects into the sdk-caller pod:# PLUGIN_WORKLOAD_SDK_ENDPOINT, PLUGIN_WORKLOAD_SDK_TOKEN@@ -19,15 +20,9 @@ metadata:name: PLACEHOLDER_RECIPE_NAMEnamespace: sandbox-recipesspec:- triggers:- onDemand: {}agent:provider: PLACEHOLDER_PROVIDERmodel: PLACEHOLDER_MODEL- steps:- - id: keepalive- instruction: 'Return a one-word acknowledgement for the SDK runtime smoke check.'- toolChoice: noneworkloads:- id: sdk-callertype: deployment@@ -43,7 +38,8 @@ spec:value: '3'pluginWorkloadSdk:promptBridge:- allowedModels: []+ allowedModels:+ - PLACEHOLDER_MODELmaxRequestsPerRun: 10maxInvocationsPerMinute: 60clientNotifications:diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex f73e6fb39..a4d0a0b62 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","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 c618b11d4..e225b0095 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.256",+ "version": "0.1.257","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.tsnew file mode 100644index 000000000..d27b3fcc5--- /dev/null+++ b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from 'vitest'+import { ClerumMcpServer, revalidatePluginSdkCredentialTicket } from './server'++function response(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ })+}++describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {+ it('consumes each verified ticket jti only once within its TTL', () => {+ const server = new ClerumMcpServer({} as never, 8082, {} as never, 'sandbox-recipes')+ const consume = (+ server as unknown as { consumePluginSdkTicket: (jti: string) => boolean }+ ).consumePluginSdkTicket.bind(server)+ expect(consume('ticket-jti')).toBe(true)+ expect(consume('ticket-jti')).toBe(false)+ expect(consume('another-ticket-jti')).toBe(true)+ })++ it('calls control-api immediately with runtime auth and accepts only active=true', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(response(200, { active: true }))+ await expect(+ revalidatePluginSdkCredentialTicket({+ runtimeToken: 'runtime-jwt',+ credentialTicket: 'signed-ticket',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ controlApiBaseUrl: 'http://control-api:8090/',+ })+ ).resolves.toBe(true)+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url).toBe(+ 'http://control-api:8090/api/v1/mcp-host/plugin-workload-sdk/credential-ticket/introspect'+ )+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer runtime-jwt')+ expect(JSON.parse(String(init.body))).toEqual({+ credentialTicket: 'signed-ticket',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ })+ })++ it.each([+ [200, { active: false }],+ [403, { error: 'provider_policy_denied' }],+ [503, { error: 'unavailable' }],+ ])('fails closed for status/body %#', async (status, body) => {+ const fetchImpl = vi.fn().mockResolvedValue(response(status as number, body))+ await expect(+ revalidatePluginSdkCredentialTicket({+ runtimeToken: 'runtime-jwt',+ credentialTicket: 'signed-ticket',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ controlApiBaseUrl: 'http://control-api:8090',+ })+ ).resolves.toBe(false)+ })++ it('fails closed on network failure without exposing the ticket', async () => {+ const fetchImpl = vi.fn().mockRejectedValue(new Error('network detail'))+ await expect(+ revalidatePluginSdkCredentialTicket({+ runtimeToken: 'runtime-jwt',+ credentialTicket: 'signed-ticket',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ fetchImpl: fetchImpl as unknown as typeof fetch,+ })+ ).resolves.toBe(false)+ })+})diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.tsindex 2343e89fe..707f0834a 100644--- a/workflow-recipes/src/mcp/server.ts+++ b/workflow-recipes/src/mcp/server.ts@@ -16,8 +16,12 @@ import { registry } from '../metrics'import { HttpMcpHostClient } from '../workflow/httpMcpHostClient'import { JwtTokenFactory } from '../workflow/jwtTokenFactory'import { K8sSecretReaderImpl } from '../workflow/k8sSecretReaderImpl'-import { ModelConfigHandler } from '../workflow/modelConfigHandler'+import { ModelConfigHandler, type PluginSdkCredentialTarget } from '../workflow/modelConfigHandler'import { createWorkflowEndpointHandlers, verifyIncomingToken } from '../workflow/restEndpoints'+import {+ verifyPluginSdkBrokerCallerToken,+ verifyPluginSdkCredentialTicket,+} from '../workflow/workflowAuth'import {CallerIdentity,handleDeleteRecipe,@@ -35,6 +39,41 @@ const MAX_SESSIONS = 100// Previous 64KB limit caused `req.destroy()` → coordinator received `socket hang up`// instead of a proper 413 response, triggering false step retries.const MAX_BODY_BYTES = 512 * 1024 // 512KB+const CONTROL_API_BASE_URL =+ process.env.CONTROL_API_BASE_URL || 'http://control-api.control-plane.svc.cluster.local:8090'++export async function revalidatePluginSdkCredentialTicket(input: {+ runtimeToken: string+ credentialTicket: string+ invocationId: string+ targetRef: string+ fetchImpl?: typeof fetch+ controlApiBaseUrl?: string+}): Promise<boolean> {+ const fetchImpl = input.fetchImpl ?? fetch+ try {+ const response = await fetchImpl(+ `${(input.controlApiBaseUrl ?? CONTROL_API_BASE_URL).replace(/\/+$/, '')}/api/v1/mcp-host/plugin-workload-sdk/credential-ticket/introspect`,+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${input.runtimeToken}`,+ },+ body: JSON.stringify({+ credentialTicket: input.credentialTicket,+ invocationId: input.invocationId,+ targetRef: input.targetRef,+ }),+ }+ )+ if (!response.ok) return false+ const body = (await response.json().catch(() => null)) as { active?: unknown } | null+ return body?.active === true+ } catch {+ return false+ }+}type ParseResult =| { ok: true; body: Record<string, unknown> }@@ -77,6 +116,8 @@ function parseJsonBody(req: http.IncomingMessage): Promise<ParseResult> {export class ClerumMcpServer {private httpServer: http.Server | null = nullprivate sessions: Map<string, StreamableHTTPServerTransport> = new Map()+ /** One-shot broker redemption cache; tickets are short-lived (60s). */+ private readonly consumedPluginSdkTicketJtis = new Map<string, number>()private provider: WorkflowRecipeProviderprivate port: numberprivate customApi: k8s.CustomObjectsApi@@ -110,6 +151,23 @@ export class ClerumMcpServer {this.modelConfigHandler = k8sReader ? new ModelConfigHandler(k8sReader, mcpHostClient) : null}+ private consumePluginSdkTicket(jti: string): boolean {+ const now = Date.now()+ for (const [entry, expiresAt] of this.consumedPluginSdkTicketJtis) {+ if (expiresAt <= now) this.consumedPluginSdkTicketJtis.delete(entry)+ }+ const existing = this.consumedPluginSdkTicketJtis.get(jti)+ if (existing !== undefined && existing > now) return false+ // Keep the cache bounded even if a compromised host floods distinct+ // signed tickets within their TTL.+ if (this.consumedPluginSdkTicketJtis.size >= 10_000) {+ const oldest = this.consumedPluginSdkTicketJtis.keys().next().value+ if (typeof oldest === 'string') this.consumedPluginSdkTicketJtis.delete(oldest)+ }+ this.consumedPluginSdkTicketJtis.set(jti, now + 60_000)+ return true+ }+private createMcpServer(): McpServer {const server = new McpServer({name: 'workflow-recipes',@@ -319,6 +377,124 @@ export class ClerumMcpServer {return}+ // Plugin Workload SDK credential broker. This route deliberately uses a+ // different audience from the workflow REST API: an mcp-host runtime JWT+ // authenticates the caller and a second short-lived signed ticket binds+ // the exact target that control-api already authorized.+ if (req.method === 'POST' && subPath === '/plugin-workload-sdk/credentials') {+ const authHeader = req.headers.authorization+ const runtimeToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''+ let callerClaims+ try {+ callerClaims = await verifyPluginSdkBrokerCallerToken(runtimeToken)+ } catch {+ res.writeHead(401, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Unauthorized' }))+ return+ }+ if (+ callerClaims.recipeName !== recipeName ||+ callerClaims.recipeNamespace !== this.sandboxNamespace ||+ !callerClaims.workflowControlScopes.includes('plugin-workload-sdk')+ ) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential broker scope denied' }))+ return+ }++ const parseResult = await parseJsonBody(req)+ if (!parseResult.ok) {+ res.writeHead(parseResult.reason === 'too_large' ? 413 : 400, {+ 'Content-Type': 'application/json',+ })+ res.end(JSON.stringify({ error: 'Invalid credential broker request' }))+ return+ }+ const body = parseResult.body+ const target = body.target as PluginSdkCredentialTarget | undefined+ if (+ body.recipeNamespace !== this.sandboxNamespace ||+ typeof body.invocationId !== 'string' ||+ !target ||+ typeof target.targetRef !== 'string' ||+ typeof target.provider !== 'string' ||+ typeof target.model !== 'string' ||+ typeof target.credentialSlot !== 'string' ||+ typeof body.credentialTicket !== 'string'+ ) {+ res.writeHead(400, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Invalid credential broker request' }))+ return+ }++ let ticket+ try {+ ticket = await verifyPluginSdkCredentialTicket(body.credentialTicket)+ } catch {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ 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) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ // 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.+ const ticketStillActive = await revalidatePluginSdkCredentialTicket({+ runtimeToken,+ credentialTicket: body.credentialTicket,+ invocationId: body.invocationId,+ targetRef: target.targetRef,+ })+ if (!ticketStillActive) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ if (!this.modelConfigHandler) {+ res.writeHead(503, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential broker unavailable' }))+ return+ }+ const result = await this.modelConfigHandler.resolvePluginSdkCredential(target)+ // 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+ // revocation observed during resolution never returns credentials.+ if (result.status === 200) {+ const ticketStillActiveAfterResolve = await revalidatePluginSdkCredentialTicket({+ runtimeToken,+ credentialTicket: body.credentialTicket,+ invocationId: body.invocationId,+ targetRef: target.targetRef,+ })+ if (!ticketStillActiveAfterResolve) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ if (!this.consumePluginSdkTicket(ticket.jti)) {+ res.writeHead(403, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: 'Credential ticket denied' }))+ return+ }+ }+ res.writeHead(result.status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(result.body))+ return+ }+// JWT authentication — dual-issuer aware (clerum-wrc OR control-api)const authHeader = req.headers.authorizationconst token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.tsindex 5cb39d56c..55d2df0c4 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts@@ -170,6 +170,32 @@ describe('validatePluginWorkloadSdkSpec', () => {expect(errors).toEqual([])})+ it.each([+ ['triggers', { triggers: { onDemand: {} } }],+ ['scheduling', { scheduling: { cron: '0 * * * *' } }],+ [+ 'coordinatorImage',+ {+ coordinatorImage:+ 'example.com/coordinator@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ },+ ],+ ] as const)('rejects SDK-only %s before resource construction', (_field, override) => {+ const errors = validatePluginWorkloadSdkSpec(baseSpec({ promptBridge: {} }, { ...override }))+ expect(errors).toContain(+ 'pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage'+ )+ })++ it('rejects SDK-only workflow fields when steps is the empty-array compatibility input', () => {+ const errors = validatePluginWorkloadSdkSpec(+ baseSpec({ promptBridge: {} }, { steps: [], triggers: { onDemand: {} } })+ )+ expect(errors).toContain(+ 'pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage'+ )+ })+it('accepts clientNotifications-only without any agent', () => {const errors = validatePluginWorkloadSdkSpec(baseSpec({ clientNotifications: { allowedEventTypes: ['e2e.test'] } }, { agent: undefined })diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.tsindex 09448347f..886cf0a78 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts@@ -21,6 +21,15 @@ export const DEFAULT_IDEMPOTENCY_KEY_PATTERN = '^[a-zA-Z0-9_-]{1,128}$'/** Condition type owned by the Plugin Workload SDK reconcile pass. */export const PLUGIN_WORKLOAD_SDK_CONDITION_TYPE = 'PluginWorkloadSdkCapability'+/**+ * WorkflowRecipe remains the CRD that carries Plugin Workload SDK, but an SDK+ * workload is not a workflow. Keep the small set of workflow-only fields+ * closed when the recipe has no executable steps. CEL is the first line of+ * defence; this pure check preserves the same boundary for direct and+ * mixed-version inputs that bypass admission.+ */+export const SDK_ONLY_WORKFLOW_FIELDS = ['triggers', 'scheduling', 'coordinatorImage'] as const+function rejectWildcards(field: string, values: string[] | undefined, errors: string[]): void {for (const value of values ?? []) {if (value.includes('*')) {@@ -48,6 +57,25 @@ export function validatePluginWorkloadSdkSpec(spec: WorkflowRecipeSpec): string[const errors: string[] = []+ const hasWorkflowSteps = (spec.steps?.length ?? 0) > 0+ if (!hasWorkflowSteps) {+ const configuredWorkflowFields = SDK_ONLY_WORKFLOW_FIELDS.filter(field => {+ switch (field) {+ case 'triggers':+ return spec.triggers !== undefined+ case 'scheduling':+ return spec.scheduling !== undefined+ case 'coordinatorImage':+ return spec.coordinatorImage !== undefined+ }+ })+ if (configuredWorkflowFields.length > 0) {+ errors.push(+ 'pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage'+ )+ }+ }+if (!sdk.promptBridge && !sdk.clientNotifications) {errors.push('pluginWorkloadSdk must declare at least one capability family (promptBridge or clientNotifications)'diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.tsindex 098710e33..1f3495515 100644--- a/workflow-recipes/src/reconciler/reconciler.test.ts+++ b/workflow-recipes/src/reconciler/reconciler.test.ts@@ -254,6 +254,114 @@ describe('WorkflowRecipeReconciler', () => {expect(result.workloadStatuses[0].ready).toBe(true)})+ it('uses the SDK-only runtime adapter without invoking workflow reconciliation', async () => {+ const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({+ phase: 'active',+ message: 'Plugin Workload SDK mcp-host registered',+ })+ const workflowReconcile = vi.fn()+ ;(+ reconciler as unknown as {+ config: { pluginWorkloadSdkEnabled: boolean }+ workflowReconciler: {+ reconcile: typeof workflowReconcile+ reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly+ }+ }+ ).config.pluginWorkloadSdkEnabled = true+ ;(+ reconciler as unknown as {+ workflowReconciler: {+ reconcile: typeof workflowReconcile+ reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly+ }+ }+ ).workflowReconciler = { reconcile: workflowReconcile, reconcilePluginWorkloadSdkOnly }++ const recipe = makeRecipe({+ spec: {+ agent: { provider: 'zai', model: 'glm-4.7' },+ workloads: [{ id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 }],+ pluginWorkloadSdk: { promptBridge: {}, allowedCallers: ['app'] },+ },+ })++ const result = await reconciler.reconcile(recipe)++ expect(result.phase).toBe('active')+ expect(reconcilePluginWorkloadSdkOnly).toHaveBeenCalledWith(+ 'test-recipe',+ 'uid-123',+ 'sandbox-recipes',+ recipe.spec+ )+ expect(workflowReconcile).not.toHaveBeenCalled()+ })++ it('keeps an SDK-only recipe deploying and requeues while the eager host boots', async () => {+ const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({+ phase: 'deploying',+ message: 'Plugin Workload SDK mcp-host starting',+ })+ ;(+ reconciler as unknown as {+ config: { pluginWorkloadSdkEnabled: boolean }+ workflowReconciler: {+ reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly+ }+ }+ ).config.pluginWorkloadSdkEnabled = true+ ;(+ reconciler as unknown as {+ workflowReconciler: {+ reconcilePluginWorkloadSdkOnly: typeof reconcilePluginWorkloadSdkOnly+ }+ }+ ).workflowReconciler = { reconcilePluginWorkloadSdkOnly }++ const result = await reconciler.reconcile(+ makeRecipe({+ spec: {+ agent: { provider: 'zai', model: 'glm-4.7' },+ workloads: [{ id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 }],+ pluginWorkloadSdk: { promptBridge: {}, allowedCallers: ['app'] },+ },+ })+ )++ expect(result).toMatchObject({+ phase: 'deploying',+ message: 'Plugin Workload SDK mcp-host starting',+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,+ })+ })++ it('cleans SDK-only runtime resources after the capability is removed without invoking workflow reconciliation', async () => {+ const cleanupPluginWorkloadSdkOnly = vi.fn().mockResolvedValue(undefined)+ const workflowReconcile = vi.fn()+ ;(+ 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 },+ },+ })+ )++ expect(result.phase).toBe('active')+ 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 },diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex b5518ba25..ae233097b 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -1839,6 +1839,14 @@ export class WorkflowRecipeReconciler {// Step 2: Validate specthis.validateSpec(recipe)+ // A removed SDK declaration must release the resources that were owned+ // by the SDK-only runtime before this recipe settles as a plain workload.+ // 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)+ }+// Step 2.5: Policy enforcement already ran at the top of reconcile()// so both workflow and non-workflow recipes are gated uniformly. No// duplicate check here.@@ -2282,9 +2290,42 @@ export class WorkflowRecipeReconciler {const webhookOutcome = await this.reconcileWebhookGateway(recipe)const webhookHealthy = webhookOutcome.handled === false || webhookOutcome.ready- const allReady = workloadStatuses.every(ws => ws.ready) && webhookHealthy+ // SDK-only recipes are capability runtimes. Provision the eager host only+ // after workloads and their resources exist, and never route this case+ // through WorkflowReconciler.reconcile() (which owns coordinator/run+ // lifecycle). The adapter owns the same host/token/network/configure+ // semantics as the existing workflow eager path.+ const isSdkOnly =+ !isWorkflow &&+ this.config.pluginWorkloadSdkEnabled &&+ recipe.spec.pluginWorkloadSdk !== undefined+ const sdkOnlyRuntime = isSdkOnly+ ? await this.reconcilePluginWorkloadSdkOnly(recipe)+ : undefined+ if (sdkOnlyRuntime?.phase === 'failed') {+ return {+ phase: 'failed',+ message: sdkOnlyRuntime.message,+ workloadStatuses,+ webhookConditions: webhookOutcome.conditions,+ internalDependencyConditions,+ secretOwnershipConditions: secretOwnership.conditions,+ workloadConditions,+ }+ }++ const allReady =+ workloadStatuses.every(ws => ws.ready) &&+ webhookHealthy &&+ sdkOnlyRuntime?.phase !== 'deploying' &&+ sdkOnlyRuntime?.phase !== 'provider_unavailable'let finalPhase: RecipePhase- if (allReady) {+ if (sdkOnlyRuntime?.phase === 'deploying') {+ // A level-triggered SDK host must stay in a progress phase until it is+ // Ready so the watcher requeues provider configuration. `degraded`+ // would incorrectly describe a normal first boot as workload failure.+ finalPhase = 'deploying'+ } else if (allReady) {// Advance through valid state machine transitions to reach "active".// deploying → test-pass → testing → success → active// degraded → recover → active@@ -2298,13 +2339,17 @@ export class WorkflowRecipeReconciler {finalPhase = 'degraded'}const 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 === 'provider_unavailable'+ ? sdkOnlyRuntime.message+ : 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,@@ -2316,7 +2361,12 @@ export class WorkflowRecipeReconciler {// 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 ? TRANSIENT_REQUEUE_BASE_MS : undefined,+ legacyRawCleanupPending ||+ deniedTeardownFailed ||+ sdkOnlyRuntime?.phase === 'deploying' ||+ sdkOnlyRuntime?.phase === 'provider_unavailable'+ ? TRANSIENT_REQUEUE_BASE_MS+ : undefined,}} catch (error) {// Transient failures must not brick a healthy recipe at the terminal,@@ -2382,6 +2432,24 @@ export class WorkflowRecipeReconciler {}}+ private async reconcilePluginWorkloadSdkOnly(recipe: WorkflowRecipeCRD): Promise<{+ phase: 'active' | 'deploying' | 'failed' | 'provider_unavailable'+ message: string+ }> {+ if (!this.workflowReconciler) {+ return {+ phase: 'failed',+ message: 'Plugin Workload SDK subsystem not initialized — missing clerum-wrc-signing-key',+ }+ }+ return this.workflowReconciler.reconcilePluginWorkloadSdkOnly(+ recipe.metadata.name,+ recipe.metadata.uid ?? '',+ recipe.metadata.namespace,+ recipe.spec+ )+ }+// ─── Webhook Gateway Reconcile ─────────────────────────────────────//// Per recipe with spec.webhooks[] non-empty:@@ -3038,6 +3106,16 @@ export class WorkflowRecipeReconciler {return}+ // 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)+ }+await this.cleanupDelegationIfNeeded(recipe)await this.cleanupDeclaredRuntimeResources(recipe)}diff --git a/workflow-recipes/src/workflow/httpMcpHostClient.ts b/workflow-recipes/src/workflow/httpMcpHostClient.tsindex 5cbda8a15..51f9675b7 100644--- a/workflow-recipes/src/workflow/httpMcpHostClient.ts+++ b/workflow-recipes/src/workflow/httpMcpHostClient.ts@@ -1,15 +1,18 @@/*** Concrete McpHostClient implementation for WRC → mcp_host Pod communication.*- * Sends POST /configure to the mcp_host Pod with the resolved apiKey.- * This is the WRC-side client (NOT the SDK's McpHostClient which executes steps).+ * Implements both the credential-bearing workflow `/configure` call and the+ * identity-only Plugin Workload SDK bootstrap call. This is the WRC-side+ * client (NOT the SDK's McpHostClient which executes steps).*- * Security invariant: model credentials travel only on the WRC→mcp_host- * configure request and are never returned to the coordinator.+ * Security invariant: workflow model credentials travel only on the+ * WRC→mcp_host configure request and are never returned to the coordinator;+ * the SDK bootstrap request carries provider/model identity only.*/import type { McpHostClient } from './modelConfigHandler'const CONFIGURE_PATH = '/api/v1/workflow/configure'+const PLUGIN_SDK_BOOTSTRAP_PATH = '/api/v1/workflow/plugin-workload-sdk/bootstrap'const TIMEOUT_MS = 10_000export class HttpMcpHostClient implements McpHostClient {@@ -50,4 +53,35 @@ export class HttpMcpHostClient implements McpHostClient {clearTimeout(timeoutId)}}++ async configurePluginWorkloadSdkBootstrap(+ endpoint: string,+ token: string,+ body: { provider: string; model: string }+ ): Promise<{ status: number; body: Record<string, unknown> }> {+ const url = `${endpoint}${PLUGIN_SDK_BOOTSTRAP_PATH}`+ const controller = new AbortController()+ const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS)+ try {+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify(body),+ signal: controller.signal,+ })+ const text = await response.text()+ let responseBody: Record<string, unknown>+ try {+ responseBody = JSON.parse(text) as Record<string, unknown>+ } catch {+ responseBody = { raw: text }+ }+ return { status: response.status, body: responseBody }+ } finally {+ clearTimeout(timeoutId)+ }+ }}diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.tsindex 471362c62..d91cfe526 100644--- a/workflow-recipes/src/workflow/modelConfigHandler.ts+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts@@ -1,13 +1,15 @@/**- * Model Config Handler — WRC-side Secret Broker for model hot-swap.+ * Model Config Handler — WRC-side Secret Broker for workflow model hot-swap.** The coordinator sends { provider, model, stepId } (never apiKey).* WRC resolves the API key from K8s Secrets and forwards to mcp_host.*- * Security invariant: model credentials travel only on the WRC→mcp_host- * configure request and are never returned to the coordinator.+ * Security invariant: workflow model credentials travel only on the WRC→mcp_host+ * configure request and are never returned to the coordinator. Plugin Workload+ * SDK bootstrap is identity-only; its prompt credentials stay behind the+ * per-attempt broker.*/-import { isLlmProviderId } from '@clerum/llm-providers'+import { PROVIDER_CREDENTIAL_SLOTS, isLlmProviderId } from '@clerum/llm-providers'import { createLogger } from '../observability/logger'// ─── Types ──────────────────────────────────────────────────────────────@@ -49,6 +51,13 @@ export interface ConfigureModelResult {body: Record<string, unknown>}+export interface PluginSdkCredentialTarget {+ targetRef: string+ provider: string+ model: string+ credentialSlot: string+}+/*** Result of a presence-aware ConfigMap read. Distinguishes "the CM does not* exist" (404) from "the CM exists but its `data` is empty/omitted" — a@@ -76,6 +85,12 @@ export interface McpHostClient {token: string,body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }>+ /** Publish only the public provider/model bootstrap identity for SDK mode. */+ configurePluginWorkloadSdkBootstrap?(+ endpoint: string,+ token: string,+ body: { provider: string; model: string }+ ): Promise<{ status: number; body: Record<string, unknown> }>}export interface ObjectStorageReader {@@ -164,6 +179,129 @@ export class ModelConfigHandler {private readonly objectStorage?: ObjectStorageReader) {}+ /**+ * Publish an SDK host's public bootstrap binding without resolving a Secret.+ * Prompt credentials are resolved by the per-attempt broker instead; using+ * the normal workflow `handle()` path here would load and forward a provider+ * key into the eager mcp-host.+ */+ async configurePluginWorkloadSdkBootstrap(+ provider: string,+ model: string,+ mcpHostEndpoint: string,+ wrcConfigureToken: string+ ): Promise<ConfigureModelResult> {+ const MODEL_PATTERN = /^[a-zA-Z0-9._:/-]{1,128}$/+ if (!isLlmProviderId(provider) || !MODEL_PATTERN.test(model)) {+ return { status: 400, body: { error: 'Invalid Plugin Workload SDK bootstrap target' } }+ }+ if (!this.mcpHost.configurePluginWorkloadSdkBootstrap) {+ return { status: 503, body: { error: 'Plugin Workload SDK bootstrap unavailable' } }+ }+ try {+ const result = await this.mcpHost.configurePluginWorkloadSdkBootstrap(+ mcpHostEndpoint,+ wrcConfigureToken,+ { provider, model }+ )+ if (result.status >= 400) {+ return { status: 502, body: { error: 'mcp_host bootstrap failed' } }+ }+ return { status: 202, body: { configured: true, provider, model } }+ } catch {+ return { status: 502, body: { error: 'mcp_host bootstrap unreachable' } }+ }+ }++ /**+ * Resolve exactly one ticket-authorized Plugin Workload SDK target. Unlike+ * workflow `/configure`, this path has no degraded mode and never skips a+ * missing slot: configuration failures are terminal for the current attempt.+ */+ async resolvePluginSdkCredential(+ target: PluginSdkCredentialTarget+ ): Promise<ConfigureModelResult> {+ const MODEL_PATTERN = /^[a-zA-Z0-9._:/-]{1,128}$/+ const SECRET_KEY_PATTERN = /^[A-Za-z0-9._-]{1,253}$/+ if (+ !isLlmProviderId(target.provider) ||+ !MODEL_PATTERN.test(target.model) ||+ !SECRET_KEY_PATTERN.test(target.credentialSlot)+ ) {+ return { status: 400, body: { error: 'Invalid credential target' } }+ }++ const slots = PROVIDER_CREDENTIAL_SLOTS[target.provider]+ const canonicalDataKeys = slots.map(slot => slot.dataKey)+ const singleSlotProvider = slots.length === 1+ const slotBelongsToProvider = canonicalDataKeys.some(+ dataKey =>+ target.credentialSlot === dataKey || target.credentialSlot.startsWith(`${dataKey}-`)+ )+ if (+ !slotBelongsToProvider ||+ (!singleSlotProvider && !canonicalDataKeys.includes(target.credentialSlot))+ ) {+ return { status: 400, body: { error: 'Invalid credential target' } }+ }++ // SDK prompt targets are reviewed operator policy. Absence of the global+ // allowlist must fail closed here; workflow degraded-mode semantics do not+ // apply to a cross-provider SDK request.+ const allowlistCm = await this.k8s.readConfigMapWithPresence(+ CONFIGMAP_NAMESPACE,+ ALLOWLIST_CONFIGMAP_NAME+ )+ if (!allowlistCm.exists) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }+ const allowed = parseAllowedModels(allowlistCm.data[target.provider], target.provider)+ if (!allowed.has(target.model)) {+ return { status: 403, body: { error: 'Provider target is not enabled' } }+ }++ const configMap = await this.k8s.readConfigMap(CONFIGMAP_NAMESPACE, CONFIGMAP_NAME)+ if (!configMap) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }+ const mapping = configMap[target.provider] ?? configMap[`${target.provider}__${target.model}`]+ if (!mapping) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }+ const slash = mapping.indexOf('/')+ if (slash <= 0 || slash === mapping.length - 1) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }+ const secretName = mapping.slice(0, slash)+ const secret = await this.k8s.readSecret(CONFIGMAP_NAMESPACE, secretName)+ if (!secret) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }++ const credentials: Record<string, string> = {}+ for (const [index, slot] of slots.entries()) {+ const sourceKey = singleSlotProvider && index === 0 ? target.credentialSlot : slot.dataKey+ const value = Object.prototype.hasOwnProperty.call(secret, sourceKey)+ ? secret[sourceKey]+ : undefined+ if (typeof value !== 'string' || value.length === 0) {+ return { status: 503, body: { error: 'Provider configuration unavailable' } }+ }+ credentials[slot.dataKey] = value+ }++ return {+ status: 200,+ body: {+ provider: target.provider,+ model: target.model,+ credentialSlot: target.credentialSlot,+ credentials,+ llmSecretName: secretName,+ },+ }+ }+async handle(req: ConfigureModelRequest,mcpHostEndpoint: string,diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.ts b/workflow-recipes/src/workflow/networkPolicyFactory.tsindex bee2ec91c..03594a2b2 100644--- a/workflow-recipes/src/workflow/networkPolicyFactory.ts+++ b/workflow-recipes/src/workflow/networkPolicyFactory.ts@@ -600,6 +600,34 @@ export function buildWorkflowNetworkPolicies(],},} as k8s.V1NetworkPolicy,+ {+ apiVersion: 'networking.k8s.io/v1',+ kind: 'NetworkPolicy',+ metadata: {+ name: `${config.recipeName}-mcp-host-to-wrc-sdk-broker`,+ namespace: config.sandboxNamespace,+ labels: commonLabels,+ },+ spec: {+ podSelector: mcpHostPodSelector,+ policyTypes: ['Egress'],+ egress: [+ {+ to: [+ {+ namespaceSelector: {+ matchLabels: {+ 'kubernetes.io/metadata.name': config.controlPlaneNamespace,+ },+ },+ podSelector: { matchLabels: { app: 'workflow-recipes' } },+ },+ ],+ ports: [{ port: config.wrcPort, protocol: 'TCP' }],+ },+ ],+ },+ } as k8s.V1NetworkPolicy,]: []@@ -920,9 +948,9 @@ export function buildWorkflowNetworkPolicies(],},},- // 8. Plugin Workload SDK (plan §6.1, OQ-4): same-recipe workloads <-> mcp-host- // on the SDK port. Empty unless the recipe declares the capability and the- // feature flag is on (config.pluginWorkloadSdkSandboxAccess).+ // 8. Plugin Workload SDK: same-recipe workloads <-> mcp-host on the SDK+ // port plus mcp-host -> WRC for per-attempt credential ticket redemption.+ // Empty unless the capability and feature flag are both enabled....pluginWorkloadSdkPolicies,]}diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex b384937ba..59dbbfbd0 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -33,7 +33,7 @@ import type { WorkflowConfig } from './types'export type EagerSdkMcpHostStatus = 'ready' | 'deploying' | 'failed' | 'provider_unavailable'/**- * Consecutive eager `/configure` failures tolerated before the provider is+ * Consecutive eager SDK bootstrap failures tolerated before the provider is* surfaced as unavailable instead of an indefinite `deploying`. Mirrors the* crash-recovery MAX_ATTEMPTS bound so a permanently-failing provider broker* (e.g. a bad secretRef) is not indistinguishable from "still booting".@@ -77,24 +77,24 @@ export type PluginWorkloadSdkProvisionerDeps = {*/export class PluginWorkloadSdkProvisioner {/**- * In-memory record of the last successful eager-SDK provider configure, keyed+ * 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 (idempotent) /configure is skipped to- * avoid a ConfigMap read + Secret read + RS256 sign + HTTP POST on every- * level-triggered reconcile. Lost on WRC restart, which just re-configures- * once (still idempotent); a pod restart changes the UID and forces a refresh.+ * 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>()/**- * Consecutive eager `/configure` failures per recipe and stable configure+ * Consecutive eager SDK bootstrap failures per recipe and stable bootstrap* identity. The budget counts only repeated failures for the same* `<podUid>:<provider>:<model>`; a pod replacement or agent model/provider* change starts from one without needing WRC to observe the roll directly.- * Reset on a successful configure (and on recipe cleanup). Once the matching+ * Reset on a successful bootstrap (and on recipe cleanup). Once the matching* key reaches MAX_EAGER_CONFIGURE_ATTEMPTS the provisioner projects* `provider_unavailable` instead of an indefinite `deploying`. Lost on WRC- * restart, which just re-attempts from zero (configure is idempotent).+ * restart, which just re-attempts from zero (bootstrap is idempotent).*/private readonly eagerSdkConfigureFailuresByRecipe = new Map<string,@@ -110,7 +110,7 @@ export class PluginWorkloadSdkProvisioner {/*** Deletes the eager mcp-host pod (wedge recovery or image-drift roll) and- * clears the per-recipe `/configure` failure budget. The failure map is also+ * clears the per-recipe bootstrap failure budget. The failure map is also* identity-keyed, but explicit WRC rolls are a clear boundary where the prior* pod's broker state is no longer relevant.*/@@ -128,13 +128,13 @@ export class PluginWorkloadSdkProvisioner {** Creates the recipe mcp-host before any run is triggered so the always-on* SDK server (:8099) is reachable, then — only when the recipe declares the- * promptBridge family — brokers the provider API key into it via POST- * /configure. clientNotifications-only recipes need no provider, so the- * configure step is skipped for them.+ * promptBridge family — publishes the public provider/model bootstrap binding+ * via a credential-free endpoint. Credentials stay behind the per-attempt+ * WRC broker; clientNotifications-only recipes need no provider bootstrap.*- * Idempotent: safe to call on every reconcile. The mcp-host /configure is a- * hot-swap, so re-delivering the same provider/model after a pod restart- * simply re-arms the SDK LLM binding.+ * Idempotent: safe to call on every reconcile. The mcp-host bootstrap is an+ * identity-only handshake, so re-delivering the same provider/model after a+ * pod restart simply re-arms the SDK LLM binding.*/async ensureEagerSdkMcpHost(recipeName: string,@@ -218,7 +218,7 @@ export class PluginWorkloadSdkProvisioner {// Requeue: the pod is recreated from the platform image on a later// reconcile once the prior pod has terminated. Returning here avoids// racing createIfNotExists against the still-terminating pod and- // avoids brokering /configure into a pod that is about to be replaced.+ // avoids bootstrapping a pod that is about to be replaced.return 'deploying'}}@@ -259,7 +259,7 @@ export class PluginWorkloadSdkProvisioner {if (!readiness.uid) {log.warn(- 'Plugin Workload SDK eager mcp-host reported Ready without a pod UID; waiting for stable configure identity'+ 'Plugin Workload SDK eager mcp-host reported Ready without a pod UID; waiting for stable bootstrap identity')return 'deploying'}@@ -276,19 +276,16 @@ export class PluginWorkloadSdkProvisioner {namespace)const mcpHostEndpoint = buildMcpHostUrl(recipeName, this.deps.config.sandboxNamespace)- const result = await this.deps.modelConfigHandler.handle(- {- stepId: 'plugin-workload-sdk-bootstrap',- provider: mcpHostAgent.provider,- model: mcpHostAgent.model,- },+ const result = await this.deps.modelConfigHandler.configurePluginWorkloadSdkBootstrap(+ mcpHostAgent.provider,+ mcpHostAgent.model,mcpHostEndpoint,wrcConfigureToken)if (result.status >= 400) {this.eagerSdkConfiguredByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {- reason: 'Plugin Workload SDK eager mcp-host configure returned an error',+ reason: 'Plugin Workload SDK eager mcp-host bootstrap returned an error',detail: { status: result.status },})}@@ -297,11 +294,11 @@ export class PluginWorkloadSdkProvisioner {} catch (err) {this.eagerSdkConfiguredByRecipe.delete(recipeName)return this.recordEagerConfigureFailure(recipeName, configureKey, log, {- reason: 'Plugin Workload SDK eager mcp-host configure failed',+ reason: 'Plugin Workload SDK eager mcp-host bootstrap failed',detail: { error: err instanceof Error ? err.message : String(err) },})}- // Reuse the readiness captured above: configure does not recreate the pod,+ // 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@@ -330,7 +327,7 @@ export class PluginWorkloadSdkProvisioner {}/**- * Records a consecutive eager `/configure` failure and decides the projected+ * Records a consecutive eager SDK bootstrap failure and decides the projected* status. Below MAX_EAGER_CONFIGURE_ATTEMPTS the recipe stays `deploying` so* the level-triggered reconcile keeps retrying (a transient mcp-host blip or* slow boot recovers on its own). Once the bound is reached, the failure is a@@ -366,7 +363,7 @@ export class PluginWorkloadSdkProvisioner {maxAttempts: MAX_EAGER_CONFIGURE_ATTEMPTS,})// Not ready until the provider is brokered; stay pending so the- // level-triggered reconcile retries the configure.+ // level-triggered reconcile retries the bootstrap.return 'deploying'}diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.tsindex e441336e5..8addc4fb9 100644--- a/workflow-recipes/src/workflow/podFactory.ts+++ b/workflow-recipes/src/workflow/podFactory.ts@@ -682,6 +682,9 @@ export function buildMcpHostPod(name: 'MCP_HOST_GATEWAY_URL',value: 'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092',},+ // PromptBridge resolves exactly one signed target credential per+ // attempt through WRC; no provider key is preloaded for this lane.+ { name: 'CLERUM_WRC_URL', value: config.wrcEndpoint },{name: 'MCP_HOST_WORKFLOW_CONTROL_TOKEN_FILE',value: MCP_HOST_WORKFLOW_CONTROL_TOKEN_FILE_PATH,diff --git a/workflow-recipes/src/workflow/workflowAuth.ts b/workflow-recipes/src/workflow/workflowAuth.tsindex 346d816a8..5e1222f4b 100644--- a/workflow-recipes/src/workflow/workflowAuth.ts+++ b/workflow-recipes/src/workflow/workflowAuth.ts@@ -13,6 +13,28 @@ export interface AuthenticatedRequest {}}+export interface PluginSdkBrokerCallerClaims {+ sub: string+ /** Access JWT scope; refresh JWTs must never redeem SDK credential tickets. */+ scope: 'workflow:approval:request'+ recipeName: string+ recipeNamespace: string+ workflowControlScopes: string[]+}++export interface PluginSdkCredentialTicketClaims {+ jti: string+ recipeName: string+ recipeNamespace: string+ invocationId: string+ targetRef: string+ provider: string+ model: string+ credentialSlot: string+ policyRevision: number+ policyHash: string+}+export const WRC_ISSUER = 'clerum-wrc'export const CONTROL_API_ISSUER = 'control-api'@@ -85,3 +107,86 @@ export async function verifyIncomingToken(scopes,}}++/** Verify the mcp-host runtime JWT without weakening the workflow REST audience. */+export async function verifyPluginSdkBrokerCallerToken(+ token: string+): Promise<PluginSdkBrokerCallerClaims> {+ if (!token) throw new Error('Missing token')+ if (!cachedControlApiPublicKey) throw new Error('Control API public key not initialized')+ const { payload } = await jwtVerify(token, cachedControlApiPublicKey, {+ audience: 'workflow-approvals',+ issuer: CONTROL_API_ISSUER,+ })+ const claims = payload as JWTPayload & {+ scope?: unknown+ recipeName?: unknown+ recipeNamespace?: unknown+ workflowControlScopes?: unknown+ }+ if (+ typeof claims.sub !== 'string' ||+ claims.scope !== 'workflow:approval:request' ||+ typeof claims.recipeName !== 'string' ||+ typeof claims.recipeNamespace !== 'string' ||+ !Array.isArray(claims.workflowControlScopes) ||+ !claims.workflowControlScopes.every(scope => typeof scope === 'string')+ ) {+ throw new Error('JWT missing required broker claims')+ }+ if (claims.sub !== `${claims.recipeNamespace}/${claims.recipeName}`) {+ throw new Error('JWT broker subject binding mismatch')+ }+ return {+ sub: claims.sub,+ scope: 'workflow:approval:request',+ recipeName: claims.recipeName,+ recipeNamespace: claims.recipeNamespace,+ workflowControlScopes: claims.workflowControlScopes,+ }+}++/** Verify the short-lived ticket and return only its exact target binding. */+export async function verifyPluginSdkCredentialTicket(+ token: string+): Promise<PluginSdkCredentialTicketClaims> {+ if (!token) throw new Error('Missing credential ticket')+ if (!cachedControlApiPublicKey) throw new Error('Control API public key not initialized')+ const { payload } = await jwtVerify(token, cachedControlApiPublicKey, {+ audience: 'plugin-sdk-credential-broker',+ issuer: CONTROL_API_ISSUER,+ })+ const claims = payload as JWTPayload & Record<string, unknown>+ if (+ typeof claims.jti !== 'string' ||+ claims.typ !== 'plugin-sdk-credential-ticket' ||+ typeof claims.recipeName !== 'string' ||+ typeof claims.recipeNamespace !== 'string' ||+ typeof claims.invocationId !== 'string' ||+ typeof claims.targetRef !== 'string' ||+ typeof claims.provider !== 'string' ||+ typeof claims.model !== 'string' ||+ typeof claims.credentialSlot !== 'string' ||+ !Number.isInteger(claims.policyRevision) ||+ (claims.policyRevision as number) < 1 ||+ typeof claims.policyHash !== 'string' ||+ !/^[a-f0-9]{64}$/.test(claims.policyHash)+ ) {+ throw new Error('Credential ticket has invalid claims')+ }+ if (claims.sub !== `${claims.recipeNamespace}/${claims.recipeName}`) {+ throw new Error('Credential ticket subject binding mismatch')+ }+ return {+ jti: claims.jti as string,+ recipeName: claims.recipeName,+ recipeNamespace: claims.recipeNamespace,+ invocationId: claims.invocationId,+ targetRef: claims.targetRef,+ provider: claims.provider,+ model: claims.model,+ credentialSlot: claims.credentialSlot,+ policyRevision: claims.policyRevision as number,+ policyHash: claims.policyHash,+ }+}diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.tsindex d9b5d1754..8a2d24e0b 100644--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts@@ -1301,6 +1301,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {createNamespacedPod: vi.fn().mockResolvedValue({}),patchNamespacedSecret: vi.fn().mockResolvedValue({}),deleteNamespacedPod: vi.fn().mockResolvedValue({}),+ deleteNamespacedSecret: vi.fn().mockResolvedValue({}),+ deleteNamespacedService: vi.fn().mockResolvedValue({}),}const mockCustomApi = {patchNamespacedCustomObject: vi.fn().mockResolvedValue({}),@@ -1314,7 +1316,9 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {listNamespacedNetworkPolicy: vi.fn().mockResolvedValue({ items: [] }),}const mockModelConfigHandler = {- handle: vi.fn().mockResolvedValue({ status: 202, body: { configured: true } }),+ configurePluginWorkloadSdkBootstrap: vi+ .fn()+ .mockResolvedValue({ status: 202, body: { configured: true } }),}const mockTokenFactory = {signWrcConfigureToken: vi.fn().mockResolvedValue('wrc-configure-token'),@@ -1354,7 +1358,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {crashRecoveryMocks.evaluateCrashRecovery.mockReturnValue({ action: 'none', message: 'healthy' })mockCoreApi.createNamespacedPod.mockResolvedValue({})mockNetworkingApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })- mockModelConfigHandler.handle.mockResolvedValue({ status: 202, body: { configured: true } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: { configured: true },+ })vi.stubGlobal('fetch',vi.fn().mockResolvedValue({ ok: true, status: 204 } as unknown as Response)@@ -1445,15 +1452,11 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {it('creates eager mcp-host for SDK-only recipes without agentic steps', async () => {const reconciler = new WorkflowReconciler(makeDeps())- await reconciler.reconcile(+ const result = await reconciler.reconcilePluginWorkloadSdkOnly('sdk-only','uid-sdk-only',sandboxNamespace,- sdkSpec({ steps: [] }),- { workflowExecution: { phase: 'initializing' } },- undefined,- 'sdk-only',- undefined+ sdkSpec({ steps: undefined }))const podNames = mockCoreApi.createNamespacedPod.mock.calls.map(@@ -1461,6 +1464,38 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {)expect(podNames).toContain('sdk-only-mcp-host')expect(podNames).not.toContain('sdk-only-coordinator')+ expect(result.phase).toBe('active')+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(+ 'zai',+ 'glm-4.7',+ expect.any(String),+ 'wrc-configure-token'+ )+ })++ it('cleans SDK-only host resources idempotently without creating workflow resources', async () => {+ const reconciler = new WorkflowReconciler(makeDeps())++ await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).resolves.toBeUndefined()+ await expect(reconciler.cleanupPluginWorkloadSdkOnly('sdk-only')).resolves.toBeUndefined()++ expect(mockCoreApi.deleteNamespacedService).toHaveBeenCalledWith({+ name: 'wf-sdk-only-mcp-host',+ namespace: sandboxNamespace,+ })+ expect(mockCoreApi.deleteNamespacedSecret).toHaveBeenCalledWith({+ name: 'wf-sdk-only-plugin-workload-sdk-token',+ namespace: sandboxNamespace,+ })+ expect(mockCoreApi.deleteNamespacedSecret).toHaveBeenCalledWith({+ name: 'wf-sdk-only-mcp-host-runtime-tokens',+ namespace: sandboxNamespace,+ })+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: 'sdk-only-workload-to-mcp-host-sdk-ingress',+ namespace: sandboxNamespace,+ })+ expect(mockCoreApi.createNamespacedPod).not.toHaveBeenCalled()})it('brokers the provider into the eager mcp-host for promptBridge recipes', async () => {@@ -1477,13 +1512,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {undefined)- expect(mockModelConfigHandler.handle).toHaveBeenCalledTimes(1)- expect(mockModelConfigHandler.handle).toHaveBeenCalledWith(- expect.objectContaining({- stepId: 'plugin-workload-sdk-bootstrap',- provider: 'zai',- model: 'glm-4.7',- }),+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(1)+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(+ 'zai',+ 'glm-4.7',expect.any(String),'wrc-configure-token')@@ -1512,7 +1544,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {call => call[0].body.metadata.name)expect(podNames).toContain('notif-recipe-mcp-host')- expect(mockModelConfigHandler.handle).not.toHaveBeenCalled()+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).not.toHaveBeenCalled()})it('skips the provider broker while the eager mcp-host is not ready', async () => {@@ -1530,7 +1562,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {undefined)- expect(mockModelConfigHandler.handle).not.toHaveBeenCalled()+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).not.toHaveBeenCalled()})it('returns phase=deploying while the eager mcp-host boots so the watcher requeues the configure', async () => {@@ -1584,7 +1616,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {expect(result.phase).toBe('active')expect(result.message).toContain('registered')- expect(mockModelConfigHandler.handle).toHaveBeenCalledTimes(1)+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(1)})it('does not re-broker the provider on a second reconcile of the same ready pod', async () => {@@ -1610,7 +1642,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {await run()// Same pod + provider/model → second pass is gated, configure runs once.- expect(mockModelConfigHandler.handle).toHaveBeenCalledTimes(1)+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(1)})it('stays pending (not registered) and retries when the provider broker fails', async () => {@@ -1619,7 +1651,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {phase: 'Running',uid: 'pod-uid-1',})- mockModelConfigHandler.handle.mockResolvedValue({ status: 500, body: { error: 'boom' } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 500,+ body: { error: 'boom' },+ })const reconciler = new WorkflowReconciler(makeDeps())const run = () =>reconciler.reconcile(@@ -1639,9 +1674,12 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {expect(first.message).not.toContain('registered')// Failure must not poison the configure cache: the next reconcile retries.- mockModelConfigHandler.handle.mockResolvedValue({ status: 202, body: { configured: true } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: { configured: true },+ })const second = await run()- expect(mockModelConfigHandler.handle).toHaveBeenCalledTimes(2)+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(2)expect(second.message).toContain('registered')})@@ -1652,7 +1690,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {uid: 'pod-uid-1',})// Provider broker is permanently broken (e.g. bad secretRef).- mockModelConfigHandler.handle.mockResolvedValue({ status: 500, body: { error: 'boom' } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 500,+ body: { error: 'boom' },+ })const reconciler = new WorkflowReconciler(makeDeps())const run = () =>reconciler.reconcile(@@ -1690,7 +1731,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {// It keeps retrying — recovers as soon as the broker config is fixed, and// the unavailable condition is no longer projected.- mockModelConfigHandler.handle.mockResolvedValue({ status: 202, body: { configured: true } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 202,+ body: { configured: true },+ })const recovered = await run()expect(recovered.message).toContain('registered')expect(recovered.workflowConditions ?? []).not.toEqual(@@ -1708,7 +1752,10 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {}return { ready: true, phase: 'Running' }})- mockModelConfigHandler.handle.mockResolvedValue({ status: 500, body: { error: 'boom' } })+ mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({+ status: 500,+ body: { error: 'boom' },+ })const reconciler = new WorkflowReconciler(makeDeps())const run = () =>reconciler.reconcile(@@ -1771,7 +1818,7 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {undefined)- expect(mockModelConfigHandler.handle).toHaveBeenCalledTimes(2)+ expect(mockModelConfigHandler.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledTimes(2)})it('recreates a wedged (CrashLoopBackOff) eager mcp-host pod', async () => {diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.tsindex 896be52a2..a4ed4ef32 100644--- a/workflow-recipes/src/workflow/workflowReconciler.ts+++ b/workflow-recipes/src/workflow/workflowReconciler.ts@@ -859,6 +859,107 @@ export class WorkflowReconciler {return undefined}+ /**+ * Reconcile the always-on Plugin Workload SDK host for a recipe that has no+ * executable workflow steps. This deliberately does not call `reconcile()`:+ * SDK-only workloads must not acquire coordinator, run, step, or output-PVC+ * lifecycle merely because they share the WorkflowRecipe CRD.+ */+ async reconcilePluginWorkloadSdkOnly(+ recipeName: string,+ recipeUid: string,+ namespace: string,+ spec: WorkflowRecipeSpec,+ runtimeScopeRecipeName = recipeName+ ): Promise<{+ phase: 'active' | 'deploying' | 'failed' | 'provider_unavailable'+ message: string+ }> {+ if (!this.deps.config.pluginWorkloadSdkEnabled || !spec.pluginWorkloadSdk) {+ return { phase: 'active', message: 'Plugin Workload SDK runtime disabled' }+ }+ if ((spec.steps?.length ?? 0) > 0) {+ throw new Error('SDK-only runtime requires spec.steps to be absent or empty')+ }++ const runtime = deriveWorkflowRuntimePlan(spec, {+ recipeName,+ runtimeScopeRecipeName,+ pluginWorkloadSdkEnabled: true,+ })+ const mcpHostPhase = await getPodPhase(+ this.deps.coreApi,+ `${recipeName}-mcp-host`,+ this.deps.config.sandboxNamespace+ )+ const status = await this.pluginWorkloadSdkProvisioner.ensureEagerSdkMcpHost(+ recipeName,+ recipeUid,+ namespace,+ runtimeScopeRecipeName,+ spec,+ runtime,+ { mcpHostPhase }+ )+ switch (status) {+ case 'ready':+ return { phase: 'active', message: 'Plugin Workload SDK mcp-host registered' }+ case 'deploying':+ return { phase: 'deploying', message: 'Plugin Workload SDK mcp-host starting' }+ case 'provider_unavailable':+ return {+ phase: 'provider_unavailable',+ message: 'Plugin Workload SDK mcp-host provider unavailable',+ }+ case 'failed':+ return { phase: 'failed', message: 'Plugin Workload SDK mcp-host could not start' }+ }+ }++ /**+ * Remove resources owned exclusively by the SDK-only eager host. This is+ * intentionally narrower than workflow deletion so dropping the capability+ * cannot create or tear down workflow execution state.+ */+ async cleanupPluginWorkloadSdkOnly(recipeName: string): Promise<void> {+ const ns = this.deps.config.sandboxNamespace+ this.pluginWorkloadSdkProvisioner.clearRecipeState(recipeName)+ const networkPolicyNames = [+ `${recipeName}-workload-to-mcp-host-sdk-ingress`,+ `${recipeName}-workload-to-mcp-host-sdk-egress`,+ `${recipeName}-mcp-host-to-wrc-sdk-broker`,+ `${recipeName}-mcp-host-to-servers`,+ `${recipeName}-mcp-host-to-llm-api`,+ `${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,+ })+ ),+ ...networkPolicyNames.map(name =>+ this.safeDelete(() =>+ this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })+ )+ ),+ ])+ }+async reconcile(recipeName: string,recipeUid: string,diff --git a/workflow-recipes/tests/unit/workflow/crdSchema.test.ts b/workflow-recipes/tests/unit/workflow/crdSchema.test.tsindex 010bcd15a..81e245153 100644--- a/workflow-recipes/tests/unit/workflow/crdSchema.test.ts+++ b/workflow-recipes/tests/unit/workflow/crdSchema.test.ts@@ -111,6 +111,29 @@ describe('WorkflowRecipe CRD snippet step schema', () => {expect(mcpServersSchema).toContain('maxItems: 20')})+ it('admits the explicit stepless promptBridge binding and closes SDK-only workflow fields', () => {+ const validations = readSchemaPath(workflowRecipeSchema, [+ 'properties',+ 'spec',+ 'x-kubernetes-validations',+ ])+ expect(Array.isArray(validations)).toBe(true)+ const rules = (validations as Array<{ rule?: string; message?: string }>).map(validation =>+ String(validation.rule ?? '')+ )++ expect(rules).toContain(+ '!has(self.agent) || (has(self.steps) && size(self.steps) > 0) || (has(self.pluginWorkloadSdk) && has(self.pluginWorkloadSdk.promptBridge))'+ )+ 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(+ 'spec.pluginWorkloadSdk without workflow steps cannot define triggers, scheduling, or coordinatorImage'+ )+ })+it('keeps expensive step graph checks in control-api and WRC instead of CRD CEL', () => {expect(crd).not.toContain('s.dependsOn.all(dep, self.steps.exists(t, t.id == dep))')expect(crd).toContain('duplicate step IDs are not allowed')diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.tsnew file mode 100644index 000000000..ef851ec39--- /dev/null+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts@@ -0,0 +1,135 @@+import { describe, expect, it, vi } from 'vitest'+import {+ type K8sSecretReader,+ type McpHostClient,+ ModelConfigHandler,+} from '../../../src/workflow/modelConfigHandler'++function reader(+ overrides: {+ allowlist?: Record<string, string> | null+ mappings?: Record<string, string> | null+ secret?: Record<string, string> | null+ } = {}+): K8sSecretReader {+ const allowlist =+ overrides.allowlist === undefined+ ? { openai: JSON.stringify([{ model: 'gpt-5.4-mini' }]) }+ : overrides.allowlist+ return {+ readConfigMapWithPresence: vi.fn(async () =>+ allowlist === null+ ? ({ exists: false } as const)+ : ({ exists: true, data: allowlist } as const)+ ),+ readConfigMap: vi.fn(async () =>+ overrides.mappings === undefined+ ? { openai: 'chatllm-api-keys/openai-api-key' }+ : overrides.mappings+ ),+ readSecret: vi.fn(async () =>+ overrides.secret === undefined+ ? { 'openai-api-key': 'primary-secret', 'openai-api-key-blue': 'blue-secret' }+ : overrides.secret+ ),+ }+}++const unusedMcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+}++describe('ModelConfigHandler Plugin SDK per-attempt credential broker', () => {+ it('returns only the selected slot remapped to the provider canonical key', async () => {+ const handler = new ModelConfigHandler(reader(), unusedMcpHost)+ const result = await handler.resolvePluginSdkCredential({+ targetRef: 'openai-blue',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key-blue',+ })++ expect(result).toEqual({+ status: 200,+ body: {+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key-blue',+ credentials: { 'openai-api-key': 'blue-secret' },+ llmSecretName: 'chatllm-api-keys',+ },+ })+ expect(JSON.stringify(result.body)).not.toContain('primary-secret')+ })++ it('fails closed before Secret lookup when the global allowlist is absent', async () => {+ const k8s = reader({ allowlist: null })+ const handler = new ModelConfigHandler(k8s, unusedMcpHost)+ const result = await handler.resolvePluginSdkCredential({+ targetRef: 'primary-openai',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key',+ })+ expect(result.status).toBe(503)+ expect(k8s.readSecret).not.toHaveBeenCalled()+ })++ it('fails terminally without slot discovery when the signed slot is missing', async () => {+ const handler = new ModelConfigHandler(reader({ secret: {} }), unusedMcpHost)+ const result = await handler.resolvePluginSdkCredential({+ targetRef: 'openai-blue',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'openai-api-key-blue',+ })+ expect(result).toEqual({+ status: 503,+ body: { error: 'Provider configuration unavailable' },+ })+ expect(JSON.stringify(result.body)).not.toContain('openai-api-key-blue')+ })++ it('rejects a slot owned by a different provider before any K8s lookup', async () => {+ const k8s = reader()+ const handler = new ModelConfigHandler(k8s, unusedMcpHost)+ const result = await handler.resolvePluginSdkCredential({+ targetRef: 'bad-slot',+ provider: 'openai',+ model: 'gpt-5.4-mini',+ credentialSlot: 'claude-api-key',+ })+ expect(result.status).toBe(400)+ expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()+ })++ it('publishes SDK bootstrap identity without reading ConfigMaps or Secrets', async () => {+ const mcpHost: McpHostClient = {+ configure: vi.fn(async () => ({ status: 500, body: {} })),+ configurePluginWorkloadSdkBootstrap: vi.fn(async () => ({+ status: 200,+ body: { configured: true },+ })),+ }+ 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, provider: 'openai', model: 'gpt-5.4-mini' },+ })+ expect(mcpHost.configurePluginWorkloadSdkBootstrap).toHaveBeenCalledWith(+ 'http://mcp-host:8090',+ 'wrc-token',+ { provider: 'openai', model: 'gpt-5.4-mini' }+ )+ expect(k8s.readConfigMapWithPresence).not.toHaveBeenCalled()+ expect(k8s.readSecret).not.toHaveBeenCalled()+ })+})diff --git a/workflow-recipes/tests/unit/workflow/pluginWorkloadSdkNetworkPolicy.test.ts b/workflow-recipes/tests/unit/workflow/pluginWorkloadSdkNetworkPolicy.test.tsindex e2b26c512..c49d1a529 100644--- a/workflow-recipes/tests/unit/workflow/pluginWorkloadSdkNetworkPolicy.test.ts+++ b/workflow-recipes/tests/unit/workflow/pluginWorkloadSdkNetworkPolicy.test.ts@@ -32,6 +32,10 @@ const ingressPolicy = (config: NetworkPolicyConfig) =>sdkPolicies(config).find(p => p.metadata?.name?.endsWith('-sdk-ingress'))const egressPolicy = (config: NetworkPolicyConfig) =>sdkPolicies(config).find(p => p.metadata?.name?.endsWith('-sdk-egress'))+const brokerPolicy = (config: NetworkPolicyConfig) =>+ buildWorkflowNetworkPolicies(config).find(p =>+ p.metadata?.name?.endsWith('-mcp-host-to-wrc-sdk-broker')+ )describe('Plugin Workload SDK NetworkPolicies', () => {it('emits no SDK policies when the capability access flag is unset', () => {@@ -51,6 +55,28 @@ describe('Plugin Workload SDK NetworkPolicies', () => {])})+ it('opens the SDK mcp-host credential broker only to WRC', () => {+ const policy = brokerPolicy({ ...baseConfig, pluginWorkloadSdkSandboxAccess: true })!+ expect(policy.spec?.podSelector?.matchLabels).toEqual({+ 'clerum.io/recipe': 'test-wf',+ 'clerum.io/component': 'workflow-mcp-host',+ })+ expect(policy.spec?.egress).toEqual([+ {+ to: [+ {+ namespaceSelector: {+ matchLabels: { 'kubernetes.io/metadata.name': 'control-plane' },+ },+ podSelector: { matchLabels: { app: 'workflow-recipes' } },+ },+ ],+ ports: [{ port: 8082, protocol: 'TCP' }],+ },+ ])+ expect(brokerPolicy({ ...baseConfig, pluginWorkloadSdkSandboxAccess: false })).toBeUndefined()+ })+it('does NOT emit SDK policies on the coordinator-only path (includeMcpHost false)', () => {// The SDK server only runs on the recipe mcp-host; when it is absent the// factory returns early and never includes the SDK lane.diff --git a/workflow-recipes/tests/unit/workflow/podFactory.test.ts b/workflow-recipes/tests/unit/workflow/podFactory.test.tsindex 050b2ce67..5ae47cef4 100644--- a/workflow-recipes/tests/unit/workflow/podFactory.test.ts+++ b/workflow-recipes/tests/unit/workflow/podFactory.test.ts@@ -414,6 +414,26 @@ describe('Pod Factory', () => {})})+ describe('buildMcpHostPod Plugin SDK broker wiring', () => {+ it('injects the real WRC endpoint into the mcp-host', () => {+ const pod = buildMcpHostPod(+ 'my-wf',+ agent,+ config,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ { mountWorkflowOutput: false, pluginWorkloadSdkEnabled: true }+ )+ expect(pod.spec?.containers?.[0].env).toContainEqual({+ name: 'CLERUM_WRC_URL',+ value: 'http://wrc:8082',+ })+ })+ })+describe('buildMcpHostPod', () => {const pod = buildMcpHostPod('my-wf',diff --git a/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts b/workflow-recipes/tests/unit/workflow/workflowAuth.test.tsindex 26633fb04..0021eb872 100644--- a/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts+++ b/workflow-recipes/tests/unit/workflow/workflowAuth.test.ts@@ -44,6 +44,86 @@ describe('workflow auth token verification', () => {await expect(auth.verifyIncomingToken(token)).rejects.toThrow(/aud/i)})+ it('separates the SDK broker caller audience from the workflow REST audience', async () => {+ const auth = await freshAuthModule()+ const controlApiKey = await createSigningPair()+ await auth.initializeControlApiPublicKey(controlApiKey.publicKeyPem)+ const token = await new SignJWT({+ recipeName: 'recipe-one',+ recipeNamespace: 'sandbox-recipes',+ scope: 'workflow:approval:request',+ workflowControlScopes: ['plugin-workload-sdk'],+ })+ .setProtectedHeader({ alg: 'RS256' })+ .setIssuer(auth.CONTROL_API_ISSUER)+ .setAudience('workflow-approvals')+ .setSubject('sandbox-recipes/recipe-one')+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(controlApiKey.privateKey)++ await expect(auth.verifyPluginSdkBrokerCallerToken(token)).resolves.toMatchObject({+ recipeName: 'recipe-one',+ workflowControlScopes: ['plugin-workload-sdk'],+ })+ await expect(auth.verifyIncomingToken(token)).rejects.toThrow(/aud/i)+ })++ it('rejects a refresh JWT from the SDK credential broker audience', async () => {+ const auth = await freshAuthModule()+ const controlApiKey = await createSigningPair()+ await auth.initializeControlApiPublicKey(controlApiKey.publicKeyPem)+ const token = await new SignJWT({+ recipeName: 'recipe-one',+ recipeNamespace: 'sandbox-recipes',+ scope: 'workflow:approval:refresh',+ workflowControlScopes: ['plugin-workload-sdk'],+ })+ .setProtectedHeader({ alg: 'RS256' })+ .setIssuer(auth.CONTROL_API_ISSUER)+ .setAudience('workflow-approvals')+ .setSubject('sandbox-recipes/recipe-one')+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(controlApiKey.privateKey)++ await expect(auth.verifyPluginSdkBrokerCallerToken(token)).rejects.toThrow(/broker claims/i)+ })++ it('verifies the exact short-lived SDK credential ticket binding', async () => {+ const auth = await freshAuthModule()+ const controlApiKey = await createSigningPair()+ await auth.initializeControlApiPublicKey(controlApiKey.publicKeyPem)+ const ticket = await new SignJWT({+ typ: 'plugin-sdk-credential-ticket',+ recipeName: 'recipe-one',+ recipeNamespace: 'sandbox-recipes',+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ provider: 'zai',+ model: 'glm-5.1',+ credentialSlot: 'zai-api-key',+ policyRevision: 4,+ policyHash: 'a'.repeat(64),+ })+ .setProtectedHeader({ alg: 'RS256' })+ .setIssuer(auth.CONTROL_API_ISSUER)+ .setAudience('plugin-sdk-credential-broker')+ .setSubject('sandbox-recipes/recipe-one')+ .setJti('ticket-jti')+ .setIssuedAt()+ .setExpirationTime('60s')+ .sign(controlApiKey.privateKey)++ await expect(auth.verifyPluginSdkCredentialTicket(ticket)).resolves.toMatchObject({+ invocationId: 'inv-1',+ targetRef: 'primary-zai',+ policyRevision: 4,+ policyHash: 'a'.repeat(64),+ })+ await expect(auth.verifyPluginSdkBrokerCallerToken(ticket)).rejects.toThrow(/aud/i)+ })+it('rejects a control-api token signed with the WRC key', async () => {const auth = await freshAuthModule()const wrcKey = await createSigningPair()