Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: harden stepless prompt bridge review findings
Alfredo Lopezc031c5944e92
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yamlindex 3ef975b18..255f4450e 100644--- a/charts/clerum-crds/crds/workflowrecipe.yaml+++ b/charts/clerum-crds/crds/workflowrecipe.yaml@@ -466,6 +466,7 @@ spec:items:type: stringmaxLength: 128+ pattern: "^[A-Za-z0-9._:/-]{1,128}$"maxOutputTokens:type: integerminimum: 1@@ -1692,6 +1693,7 @@ spec:items:type: stringmaxLength: 128+ pattern: "^[A-Za-z0-9._:/-]{1,128}$"maxOutputTokens:type: integerminimum: 1diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex f52b8d497..e274676d8 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex a85e64e68..342e9df2e 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.398",+ "version": "0.1.399","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex 5ecbeac5d..6e4800412 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -1,5 +1,9 @@import { type Response, Router } from 'express'-import { isCredentialSlotOwnedByProvider, isLlmProviderId } from '@clerum/llm-providers'+import {+ isCredentialSlotOwnedByProvider,+ isLlmProviderId,+ isRunnableLlmModelId,+} from '@clerum/llm-providers'import { asyncHandler } from '../../http/asyncHandler.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModels.js'@@ -127,7 +131,7 @@ function parseModelPolicies(typeof raw.provider !== 'string' ||!raw.provider.trim() ||typeof raw.model !== 'string' ||- !raw.model.trim()+ !isRunnableLlmModelId(raw.model.trim())) {res.status(400).json({error: `modelPolicies.${ref} must declare provider and model`,@@ -190,7 +194,7 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkProres.status(400).json({ error: `promptTargets[${index}].provider is invalid` })return null}- if (!model || model.length > 400 || model.includes('*')) {+ if (!isRunnableLlmModelId(model) || model.includes('*')) {res.status(400).json({ error: `promptTargets[${index}].model must be a non-wildcard model id` })diff --git a/control-api/src/routes/internal/usageEvents.ts b/control-api/src/routes/internal/usageEvents.tsindex 2aa43e6a1..39296bd79 100644--- a/control-api/src/routes/internal/usageEvents.ts+++ b/control-api/src/routes/internal/usageEvents.ts@@ -2,6 +2,7 @@ import { Router } from 'express'import { config } from '../../config.js'import type { DbClient } from '../../db.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'+import { getInvocationById } from '../../services/pluginWorkloadSdkDb.js'import { withTraceIngestTransaction } from '../../services/tracing/pools.js'import { projectAcceptedUsageEvents } from '../../services/tracing/usageProjection.js'import { ingestUsageEventsInTransaction } from '../../services/usageEvents.js'@@ -25,6 +26,7 @@ type BindingViolation = {| 'recipe_token_host_ref_mismatch'| 'recipe_token_missing_canonical_task_id'| 'recipe_token_missing_llm_secret_name'+ | 'recipe_token_invalid_sdk_usage_binding'| 'unrecognized_token_binding'}@@ -125,15 +127,24 @@ function checkClaimBinding(if (recipeName !== claims.recipeName) {return { index: i, reason: 'recipe_token_recipe_name_mismatch' }}- if (sourceKind !== 'workflow') {+ if (sourceKind === 'workflow') {+ if (!UUID_PREFIX_REGEX.test(taskId)) {+ return { index: i, reason: 'recipe_token_missing_canonical_task_id' }+ }+ if (!llmSecretName) {+ return { index: i, reason: 'recipe_token_missing_llm_secret_name' }+ }+ } else if (+ sourceKind !== 'unknown' ||+ (e as { channel_type?: unknown }).channel_type !== 'plugin_workload_sdk' ||+ taskId ||+ !llmSecretName ||+ typeof (e as { prompt_bridge_metadata?: unknown }).prompt_bridge_metadata !== 'object' ||+ (e as { prompt_bridge_metadata?: { invocation_id?: unknown } }).prompt_bridge_metadata+ ?.invocation_id === undefined+ ) {return { index: i, reason: 'recipe_token_non_workflow_source' }}- if (!UUID_PREFIX_REGEX.test(taskId)) {- return { index: i, reason: 'recipe_token_missing_canonical_task_id' }- }- if (!llmSecretName) {- return { index: i, reason: 'recipe_token_missing_llm_secret_name' }- }}// host_ref binding only fires for events that could pass validation.@@ -154,6 +165,41 @@ function checkClaimBinding(return null}+async function checkSdkOnlyUsageBinding(+ events: unknown[],+ claims: McpHostAccessClaims,+ db: DbClient+): Promise<BindingViolation | null> {+ for (let index = 0; index < events.length; index += 1) {+ const event = events[index]+ if (!event || typeof event !== 'object') continue+ const record = event as Record<string, unknown>+ if (record.source_kind !== 'unknown') continue+ const metadata = record.prompt_bridge_metadata+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) continue+ const invocationId = (metadata as { invocation_id?: unknown }).invocation_id+ if (typeof invocationId !== 'string') continue+ const invocation = await getInvocationById(invocationId, db)+ if (+ !invocation ||+ invocation.recipeNamespace !== claims.recipeNamespace ||+ invocation.recipeName !== claims.recipeName ||+ invocation.method !== 'promptBridge' ||+ // UsageReporter enqueues before the handler's terminal status POST; an+ // in-flight invocation is therefore a valid server-bound usage source.+ !['in_progress', 'complete'].includes(invocation.status) ||+ invocation.authorizationDecision !== 'authorized' ||+ !invocation.promptAuthorization ||+ !invocation.promptAuthorization.authorizedTargetRefs.includes(+ String((metadata as { target_ref?: unknown }).target_ref ?? '')+ )+ ) {+ return { index, reason: 'recipe_token_invalid_sdk_usage_binding' }+ }+ }+ return null+}+function collectWorkflowUsageCandidates(events: unknown[]): WorkflowUsageCandidate[] {const candidates: WorkflowUsageCandidate[] = []for (let i = 0; i < events.length; i++) {@@ -262,6 +308,8 @@ export function createInternalUsageEventsRouter(): Router {return res.status(403).json({ error: 'claim_binding_mismatch', ...violation })}const transactionResult = await withTraceIngestTransaction(async db => {+ const sdkBinding = await checkSdkOnlyUsageBinding(events, req.mcpHostJwt!, db)+ if (sdkBinding) return { violation: sdkBinding }const workflowBinding = await checkWorkflowRunBinding(events, req.mcpHostJwt!, db)if (workflowBinding.violation) return { violation: workflowBinding.violation }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 a95104038..19b0f61f4 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@@ -2,6 +2,7 @@ import { type Response, Router } from 'express'import { pool } from '../../db.js'import { asyncHandler } from '../../http/asyncHandler.js'import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'+import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { pluginWorkloadSdkNotificationAuthDurationSeconds } from '../../observability/metrics.js'import { enqueuePluginWorkloadSdkNotification } from '../../services/notificationEmitter.js'import {@@ -51,6 +52,20 @@ const PURPOSE_SET = new Set<string>(PLUGIN_WORKLOAD_SDK_PURPOSES)const EMAIL_LIKE_RE = /@/const PHONE_LIKE_RE = /^\+?[0-9][0-9\s().-]{6,}$/+// Credential-ticket introspection and reissue both perform signature checks,+// database reads, and (for reissue) signing work before the provider call.+// Bound the cost per recipe after JWT authentication, while the authorizer's+// grant rate/quota remains the product-level invocation limit.+const pluginWorkloadSdkCredentialRateLimit = rateLimitMiddleware({+ bucketType: 'plugin_workload_sdk_credential',+ maxPerMinute: 120,+ getBucketKey: req => {+ const claims = req.mcpHostJwt+ if (!claims) return null+ return `plugin_workload_sdk_credential:${claims.recipeNamespace}/${claims.recipeName}`+ },+})+const AUTHZ_HTTP_STATUS: Record<PluginWorkloadSdkErrorCode, number> = {capability_not_declared: 403,caller_not_allowed: 403,@@ -404,6 +419,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {// invocation, verifies current policy, and emits a new one-shot jti.'/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket',requireMcpHostJwt,+ pluginWorkloadSdkCredentialRateLimit,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}@@ -467,6 +483,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {res.status(result.value.replay ? 200 : 201).json({invocationId: result.value.invocationId,replay: result.value.replay,+ providerCallRequired: result.value.providerCallRequired,status: result.value.status,model: result.value.model,modelPolicy: result.value.modelPolicy,@@ -585,6 +602,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {router.post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect',requireMcpHostJwt,+ pluginWorkloadSdkCredentialRateLimit,asyncHandler(async (req, res) => {const claims = req.mcpHostJwt!const body = isPlainObject(req.body) ? req.body : {}diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.tsindex 8b82492fa..ddc89ad5f 100644--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts@@ -31,6 +31,7 @@ import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js// flipped to failed so the trail shows the denied attempt.const PLUGIN_WORKLOAD_SDK_SCOPE = 'plugin-workload-sdk'+const MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS = 4export type PluginWorkloadSdkAuthzError = {ok: false@@ -104,6 +105,8 @@ export interface AuthorizedPromptBridge {invocationId: string/** True when this idempotency key already produced an invocation. */replay: boolean+ /** Whether this response won authorization for a provider execution. */+ providerCallRequired: booleanstatus: stringmodel: string | nullmodelPolicy: PluginWorkloadSdkModelPolicy | null@@ -290,7 +293,13 @@ async function authorizePromptBridgeInner(const resolution = resolvePromptTarget(grant, params)if (!resolution.ok) return resolution.errorconst selectedTarget = grant.promptTargets[resolution.selectedIndex]!- const authorizedTargets = grant.promptTargets.slice(resolution.selectedIndex)+ // A grant may list many targets for operator choice, but one logical+ // invocation must never fan out across an unbounded suffix. The hard cap is+ // independent of the persisted allowlist size and applies to every retry.+ const authorizedTargets = grant.promptTargets.slice(+ resolution.selectedIndex,+ resolution.selectedIndex + MAX_PROMPT_BRIDGE_PROVIDER_ATTEMPTS+ )const resolvedPolicyHash = hashPromptTargetPolicy(grant)const recorded = await recordInvocation({@@ -331,6 +340,7 @@ async function authorizePromptBridgeInner(value: {invocationId: recorded.invocation.id,replay: true,+ providerCallRequired: false,status: recorded.invocation.status,model: selectedTarget.model,modelPolicy: resolution.modelPolicy,@@ -343,6 +353,43 @@ async function authorizePromptBridgeInner(}}+ // A failed idempotency record may be retried, but only under the exact+ // policy snapshot that created it. Compare before charging quota, then use+ // a conditional status transition so concurrent retries cannot both win.+ let providerCallRequired = true+ if (recorded.kind === 'replay') {+ const snapshot = recorded.invocation.promptAuthorization+ const currentTargetRefs = authorizedTargets.map(target => target.targetRef)+ const sameTargetRefs =+ snapshot?.authorizedTargetRefs.length === currentTargetRefs.length &&+ snapshot.authorizedTargetRefs.every((ref, index) => ref === currentTargetRefs[index])+ if (+ !snapshot ||+ snapshot.policyRevision !== grant.policyRevision ||+ snapshot.policyHash !== resolvedPolicyHash ||+ !sameTargetRefs+ ) {+ return deny(+ 'idempotency_conflict',+ 'idempotency key belongs to an older promptBridge policy; retry with a new idempotency key'+ )+ }+ const revived = await markInvocationStatus(recorded.invocation.id, 'in_progress', {+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ expectedCurrentStatus: 'failed',+ })+ // Older unit doubles did not return a boolean. Treat only an explicit+ // false as a lost CAS; the real DB helper always returns true/false.+ if (revived === false) {+ return deny(+ 'idempotency_conflict',+ 'idempotent retry is already being handled; use a new idempotency key if it fails again',+ true+ )+ }+ }+const rate = await checkRateLimit(claims.recipeNamespace,claims.recipeName,@@ -353,6 +400,7 @@ async function authorizePromptBridgeInner(await markInvocationStatus(recorded.invocation.id, 'failed', {recipeNamespace: claims.recipeNamespace,recipeName: claims.recipeName,+ ...(recorded.kind === 'replay' ? { expectedCurrentStatus: 'in_progress' as const } : {}),})return deny(rate.error, rate.message)}@@ -362,23 +410,17 @@ async function authorizePromptBridgeInner(await markInvocationStatus(recorded.invocation.id, 'failed', {recipeNamespace: claims.recipeNamespace,recipeName: claims.recipeName,+ ...(recorded.kind === 'replay' ? { expectedCurrentStatus: 'in_progress' as const } : {}),})return deny(quota.error, quota.message)}- // Revive a previously-failed invocation that has now passed quota.- if (recorded.kind === 'replay') {- await markInvocationStatus(recorded.invocation.id, 'in_progress', {- recipeNamespace: claims.recipeNamespace,- recipeName: claims.recipeName,- })- }-return {ok: true,value: {invocationId: recorded.invocation.id,replay: recorded.kind === 'replay',+ providerCallRequired,status: recorded.kind === 'replay' ? 'in_progress' : recorded.invocation.status,model: selectedTarget.model,modelPolicy: resolution.modelPolicy,diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex 56bc2864f..51967bc28 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto'-import { pool, withTransaction } from '../db.js'+import { type DbClient, pool, withTransaction } from '../db.js'import { stableStringify } from '../utils/stableStringify.js'import {type ControlApiPermissionChange,@@ -654,11 +654,10 @@ export async function insertInvocation(}export async function getInvocationById(- id: string+ id: string,+ db: DbClient = pool): Promise<PluginWorkloadSdkInvocationRecord | null> {- const result = await pool.query(`SELECT * FROM plugin_workload_sdk_invocations WHERE id = $1`, [- id,- ])+ const result = await db.query(`SELECT * FROM plugin_workload_sdk_invocations WHERE id = $1`, [id])const row = result.rows[0] as Record<string, unknown> | undefinedreturn row ? mapInvocationRow(row) : null}diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.tsindex 0cb04e485..572e03a6f 100644--- a/control-api/src/services/usageEvents.ts+++ b/control-api/src/services/usageEvents.ts@@ -27,6 +27,7 @@ export type LlmUsageEvent = {cache_write_tokens: numbercache_tokens_reported: booleanprompt_bridge_metadata: {+ invocation_id?: stringtarget_ref: stringcredential_slot: stringfallback_used: boolean@@ -82,6 +83,7 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metaif (typeof value !== 'object' || Array.isArray(value)) return nullconst record = value as Record<string, unknown>const targetRef = typeof record.target_ref === 'string' ? record.target_ref.trim() : ''+ const invocationId = typeof record.invocation_id === 'string' ? record.invocation_id.trim() : ''const credentialSlot =typeof record.credential_slot === 'string' ? record.credential_slot.trim() : ''const fallbackUsed = record.fallback_used@@ -94,11 +96,12 @@ function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metatypeof fallbackUsed !== 'boolean' ||attemptCount === null ||attemptCount < 1 ||- attemptCount > 64+ attemptCount > 4) {return null}return {+ ...(invocationId ? { invocation_id: invocationId } : {}),target_ref: targetRef,credential_slot: credentialSlot,fallback_used: fallbackUsed,@@ -164,11 +167,21 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {const task_id = trimOrNull(r.task_id)const run_id = trimOrNull(r.run_id)if (run_id && !UUID_REGEX.test(run_id)) return null+ const isSdkOnly =+ source_kind_raw === 'unknown' &&+ r.channel_type === 'plugin_workload_sdk' &&+ recipe_name !== null &&+ run_id === null &&+ task_id === null &&+ llm_secret_name !== null &&+ prompt_bridge_metadata?.invocation_id !== undefinedif (source_kind_raw === 'workflow') {const taskRunId = workflowRunIdFromTaskId(task_id)if (!recipe_name || !llm_secret_name || !run_id || !taskRunId) return nullif (taskRunId.toLowerCase() !== run_id.toLowerCase()) return null}+ if (r.channel_type === 'plugin_workload_sdk' && !isSdkOnly) return null+ if (isSdkOnly && !UUID_REGEX.test(prompt_bridge_metadata?.invocation_id ?? '')) return nullreturn {request_id,diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex 9193f2d50..01dfea97f 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -102,6 +102,20 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {expect(sdkDb.upsertGrant).not.toHaveBeenCalled()})+ it('rejects model ids outside the shared runnable grammar', async () => {+ const oversized = 'm'.repeat(129)+ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send({+ ...validGrantBody,+ allowedModels: [oversized],+ promptTargets: [{ ...validGrantBody.promptTargets[0], model: oversized }],+ })+ expect(res.status).toBe(400)+ expect(res.body.error).toContain('promptTargets[0].model')+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()+ })+it('rejects allowedUserRefs that are not control-plane UUIDs', async () => {const res = await request(buildApp()).post('/admin/plugin-workload-sdk/grants')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 37280ad65..6e4d3c0bd 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@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'+import { pool } from '../src/db.js'import { createMcpHostPluginWorkloadSdkRoutes } from '../src/routes/mcp-host/plugin-workload-sdk.routes.js'import * as notificationEmitter from '../src/services/notificationEmitter.js'import * as authorizer from '../src/services/pluginWorkloadSdkAuthorizer.js'@@ -787,4 +788,15 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =expect(replay.status).toBe(403)expect(replay.body).toEqual({ error: 'provider_policy_denied', retryable: false })})++ it('rate-limits credential-ticket introspection before expensive ticket work', async () => {+ vi.mocked(pool.query).mockResolvedValueOnce({ rows: [{ count: 121 }], rowCount: 1 } as never)+ 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(429)+ expect(res.headers['retry-after']).toBeTruthy()+ expect(authorizer.authorizePromptBridge).not.toHaveBeenCalled()+ })})diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.tsindex a6d4c725d..2491e2de0 100644--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts@@ -266,6 +266,34 @@ describe('authorizePromptBridge', () => {expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).not.toHaveBeenCalled()})+ it('caps the authorized provider suffix even when the grant lists many targets', async () => {+ const targets = [+ ['primary-zai', 'zai', 'glm-4.7', 'zai-api-key'],+ ['fallback-openai', 'openai', 'gpt-5.4', 'openai-api-key'],+ ['fallback-claude', 'claude', 'claude-sonnet-4-6', 'claude-api-key'],+ ['fallback-gemini', 'gemini', 'gemini-2.5-pro', 'gemini-api-key'],+ ['fallback-groq', 'groq', 'llama-3.3-70b', 'groq-api-key'],+ ['fallback-mistral', 'mistral', 'mistral-large', 'mistral-api-key'],+ ].map(([targetRef, provider, model, credentialSlot]) => ({+ targetRef,+ provider,+ model,+ credentialSlot,+ }))+ vi.mocked(sdkDb.findGrant).mockResolvedValue(+ grant({ promptTargets: targets, defaultTargetRef: 'primary-zai' })+ )+ const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })+ expect(result).toMatchObject({ ok: true })+ if (!result.ok) return+ expect(result.value.authorizedTargets.map(target => target.targetRef)).toEqual([+ 'primary-zai',+ 'fallback-openai',+ 'fallback-claude',+ 'fallback-gemini',+ ])+ })+it('rejects a bare model shared by two authorized providers before recording an invocation', async () => {vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({@@ -534,10 +562,19 @@ describe('authorizePromptBridge', () => {})it('re-consumes quota and revives status for a failed-replay retry', async () => {- vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ quotaLimits: { maxRequestsPerRun: 10 } }))+ const currentGrant = grant({ quotaLimits: { maxRequestsPerRun: 10 } })+ vi.mocked(sdkDb.findGrant).mockResolvedValue(currentGrant)+ vi.mocked(sdkDb.updateInvocationStatus).mockResolvedValue(true)vi.mocked(sdkDb.insertInvocation).mockResolvedValue({kind: 'replay',- invocation: invocation({ status: 'failed' }),+ invocation: invocation({+ status: 'failed',+ promptAuthorization: {+ policyRevision: currentGrant.policyRevision,+ policyHash: sdkDb.hashPromptTargetPolicy(currentGrant),+ authorizedTargetRefs: currentGrant.promptTargets.map(target => target.targetRef),+ },+ }),})const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })// quota must be re-consumed for a failed retry@@ -547,10 +584,16 @@ describe('authorizePromptBridge', () => {completed: false,recipeNamespace: NS,recipeName: RECIPE,+ expectedCurrentStatus: 'failed',})expect(result).toMatchObject({ok: true,- value: { invocationId: 'inv-1', replay: true, status: 'in_progress' },+ value: {+ invocationId: 'inv-1',+ replay: true,+ providerCallRequired: true,+ status: 'in_progress',+ },})})diff --git a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.tsindex c0859b2b3..9aabd8e58 100644--- a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts+++ b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts@@ -22,15 +22,16 @@* must be loaded in the profile (built by scripts/minikube/build-images.sh).*/import { type Page, expect, test } from '@playwright/test'+import { execFileSync } from 'node:child_process'import { setTimeout as delay } from 'node:timers/promises'const BASE_API =process.env.CONTROL_API_BASE_URL ||process.env.CONTROL_API_URL ||process.env.E2E_CONTROL_API_URL ||- 'http://localhost:8090'-const REGISTRY_BASE =- process.env.REGISTRY_API_BASE_URL || process.env.REGISTRY_URL || 'http://localhost:8085'+ ''+const REGISTRY_BASE = process.env.REGISTRY_API_BASE_URL || process.env.REGISTRY_URL || ''+const CONTROL_UI_BASE = process.env.CONTROL_UI_BASE_URL || process.env.CONTROL_UI_URL || ''const ADMIN_USER =process.env.E2E_ADMIN_USERNAME ||process.env.ADMIN_USER ||@@ -67,6 +68,44 @@ let adminSessionHeader = ''/** When set, the journey writes labelled success screenshots here (evidence/demo only). */const EVIDENCE_DIR = process.env.E2E_EVIDENCE_DIR+function assertMutableBranchProfile(): void {+ if (process.env.E2E_PLUGIN_SDK_WRITE_CONFIRM !== '1') {+ throw new Error('Mutable Plugin Workload SDK E2E requires E2E_PLUGIN_SDK_WRITE_CONFIRM=1.')+ }+ const context =+ process.env.E2E_K8S_CONTEXT || process.env.KUBECONTEXT || process.env.K8S_CONTEXT || ''+ if (!context) throw new Error('E2E_K8S_CONTEXT is required for the mutable operator journey.')+ const currentContext = execFileSync(+ 'kubectl',+ ['--context', context, 'config', 'current-context'],+ { encoding: 'utf8', timeout: 15_000 }+ ).trim()+ if (currentContext !== context) {+ throw new Error(`kubectl context mismatch: expected ${context}, got ${currentContext}`)+ }++ const urls = [+ ['CONTROL_UI_BASE_URL', CONTROL_UI_BASE],+ ['CONTROL_API_BASE_URL', BASE_API],+ ['REGISTRY_API_BASE_URL', REGISTRY_BASE],+ ] as const+ for (const [name, raw] of urls) {+ if (!raw) throw new Error(`${name} is required; shared localhost defaults are forbidden.`)+ let parsed: URL+ try {+ parsed = new URL(raw)+ } catch {+ throw new Error(`${name} must be a valid loopback URL.`)+ }+ if (!['127.0.0.1', 'localhost', '::1'].includes(parsed.hostname)) {+ throw new Error(`${name} must target loopback for a mutable branch profile.`)+ }+ if ([3000, 8085, 8090].includes(Number(parsed.port))) {+ throw new Error(`${name} uses a shared fixed port (${parsed.port}); use branch ports.env.`)+ }+ }+}+function uniqueName(base: string): string {return `${base}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`.slice(0, 50)@@ -201,33 +240,6 @@ function recipeManifest(name: string, userRef: string): Record<string, unknown>}}-async function publishRecipeToMarketplace(- token: string,- entryName: string,- manifest: Record<string, unknown>-): Promise<void> {- // Mirrors PublishToRegistryForm: entryType=recipe, recipe is a YAML string- // (JSON is valid YAML), published through control-api's admin registry proxy.- const entry = {- name: entryName,- version: '1.0.0',- entryType: 'recipe',- description: 'Operator-journey SDK recipe (promptBridge + clientNotifications).',- author: 'e2e-test',- origin: 'human-authored',- category: 'tools',- tags: ['sdk', 'e2e'],- contentCreatorTag: 'community',- configCreatorTag: 'community',- visibility: 'public',- recipe: JSON.stringify(manifest),- }- const { status, data } = await api(token, 'POST', '/api/v1/admin/registry/entries', entry)- if (status >= 300) {- throw new Error(`publish failed: ${status} ${JSON.stringify(data)}`)- }-}-async function waitForSdkValidated(token: string, recipeName: string): Promise<void> {for (let attempt = 1; attempt <= 60; attempt += 1) {const { status, data } = await api(token, 'GET', `/api/v1/admin/recipes/${recipeName}`)@@ -242,8 +254,11 @@ async function waitForSdkValidated(token: string, recipeName: string): Promise<v}test.describe('Plugin Workload SDK — operator journey (Marketplace → install → grants)', () => {- test('operator publishes, installs and grants an SDK recipe end to end', async ({ page }) => {+ test('operator publishes, installs and grants an SDK recipe end to end', async ({+ page,+ }, testInfo) => {test.setTimeout(240_000)+ assertMutableBranchProfile()if (PROVIDER === 'zai' || FALLBACK_PROVIDER === 'zai') {throw new Error('Plugin Workload SDK T3 requires OpenAI or Claude targets; Z.AI is disabled for this lane.'@@ -253,15 +268,43 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installconst token = await loginApiToken()const userRef = await resolveUserRef(token)let installedRecipeName = ''+ const cleanupErrors: string[] = []try {- // 1. Publish to the Marketplace (through control-api's admin registry proxy).- await publishRecipeToMarketplace(token, entryName, recipeManifest(entryName, userRef))+ // 1. Publish to the Marketplace through the operator's visible form.+ await uiLogin(page)+ await page.locator('text=Marketplace').first().click()+ await expect(page.getByRole('button', { name: '+ Publish to Marketplace' })).toBeVisible({+ timeout: 15_000,+ })+ await page.getByRole('button', { name: '+ Publish to Marketplace' }).click()+ await expect(page.getByRole('heading', { name: 'Publish to Marketplace' })).toBeVisible({+ timeout: 15_000,+ })+ await page.getByRole('radio', { name: 'Plugin' }).click()+ await page.locator('#pub-name').fill(entryName)+ await page.getByRole('button', { name: 'Continue' }).click()+ await page.locator('#pub-author').fill('e2e-test')+ await page+ .locator('#pub-description')+ .fill('Operator-journey SDK recipe (promptBridge + clientNotifications).')+ await page.getByRole('button', { name: 'Continue' }).click()+ await page+ .locator('#pub-recipe-yaml')+ .fill(JSON.stringify(recipeManifest(entryName, userRef)))+ await page.getByRole('button', { name: 'Continue' }).click()+ const publishResponse = page.waitForResponse(+ response =>+ response.url().includes('/api/v1/admin/registry/entries') &&+ response.request().method() === 'POST',+ { timeout: 60_000 }+ )+ await page.getByRole('button', { name: 'Publish to Marketplace' }).click()+ expect((await publishResponse).status()).toBeLessThan(300)+ await expect(page.getByText('Published successfully.')).toBeVisible({ timeout: 15_000 })// 2. Operator instantiates it from the Marketplace UI. Recipe entries install// directly from the catalog, unlike connector entries that open the wizard.- await uiLogin(page)- await page.locator('text=Marketplace').first().click()const pluginsTab = page.getByRole('tab', { name: 'Plugins', exact: true })await expect(pluginsTab).toBeVisible({ timeout: 15_000 })await pluginsTab.click()@@ -424,37 +467,72 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → installexpect(JSON.stringify(promptGrant)).not.toMatch(/secret|token/i)} finally {if (installedRecipeName) {- const grantList = await api(- token,- 'GET',- `/api/v1/admin/plugin-workload-sdk/grants?recipeNamespace=${RECIPE_NS}&recipeName=${installedRecipeName}`- ).catch(() => ({ status: 0, data: {} as Record<string, unknown> }))- const residualGrants = (grantList.data.data ??- grantList.data.items ??- grantList.data.grants ??- []) as Array<{ id?: string }>- for (const grant of residualGrants) {- if (grant.id) {- const deleted = await api(- token,- 'DELETE',- `/api/v1/admin/plugin-workload-sdk/grants/${encodeURIComponent(grant.id)}?recipeNamespace=${encodeURIComponent(RECIPE_NS)}&recipeName=${encodeURIComponent(installedRecipeName)}`- )- if (deleted.status !== 200) {- throw new Error(`operator journey cleanup failed to delete grant: ${deleted.status}`)+ try {+ const grantList = await api(+ token,+ 'GET',+ `/api/v1/admin/plugin-workload-sdk/grants?recipeNamespace=${RECIPE_NS}&recipeName=${installedRecipeName}`+ )+ if (grantList.status >= 300) {+ cleanupErrors.push(`list grants: ${grantList.status}`)+ } else {+ const residualGrants = (grantList.data.data ??+ grantList.data.items ??+ grantList.data.grants ??+ []) as Array<{ id?: string }>+ for (const grant of residualGrants) {+ if (!grant.id) continue+ try {+ const deleted = await api(+ token,+ 'DELETE',+ `/api/v1/admin/plugin-workload-sdk/grants/${encodeURIComponent(grant.id)}?recipeNamespace=${encodeURIComponent(RECIPE_NS)}&recipeName=${encodeURIComponent(installedRecipeName)}`+ )+ if (deleted.status >= 300) {+ cleanupErrors.push(`delete grant ${grant.id}: ${deleted.status}`)+ }+ } catch (error) {+ cleanupErrors.push(`delete grant ${grant.id}: ${String(error)}`)+ }}}+ } catch (error) {+ cleanupErrors.push(`list/delete grants: ${String(error)}`)+ }+ try {+ const uninstalled = await api(+ token,+ 'DELETE',+ `/api/v1/admin/registry/uninstall/${installedRecipeName}?type=recipe`+ )+ if (uninstalled.status >= 300 && uninstalled.status !== 404) {+ cleanupErrors.push(`uninstall ${installedRecipeName}: ${uninstalled.status}`)+ }+ } catch (error) {+ cleanupErrors.push(`uninstall ${installedRecipeName}: ${String(error)}`)+ }+ }+ try {+ const deletedEntry = await fetch(+ `${REGISTRY_BASE}/api/v1/entries/${encodeURIComponent(entryName)}/versions/1.0.0`,+ { method: 'DELETE' }+ )+ if (!deletedEntry.ok && deletedEntry.status !== 404) {+ cleanupErrors.push(`delete registry entry ${entryName}: ${deletedEntry.status}`)+ }+ } catch (error) {+ cleanupErrors.push(`delete registry entry ${entryName}: ${String(error)}`)+ }+ if (cleanupErrors.length > 0) {+ await testInfo.attach('operator-journey-cleanup-errors', {+ body: cleanupErrors.join('\n'),+ contentType: 'text/plain',+ })+ if (testInfo.errors.length === 0) {+ throw new Error(`operator journey cleanup failed:\n${cleanupErrors.join('\n')}`)}- await api(- token,- 'DELETE',- `/api/v1/admin/registry/uninstall/${installedRecipeName}?type=recipe`- ).catch(() => undefined)+ console.error(`operator journey cleanup failed:\n${cleanupErrors.join('\n')}`)}- await fetch(- `${REGISTRY_BASE}/api/v1/entries/${encodeURIComponent(entryName)}/versions/1.0.0`,- { method: 'DELETE' }- ).catch(() => undefined)}})})diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex efa56e867..d78d2a0a9 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.328",+ "version": "0.1.329","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.328",+ "version": "0.1.329","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 66dbf7754..e25374665 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.328",+ "version": "0.1.329","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/test/e2e-playwright/playwright.config.ts b/desktop-app/test/e2e-playwright/playwright.config.tsindex 7595eee33..8be64574b 100644--- a/desktop-app/test/e2e-playwright/playwright.config.ts+++ b/desktop-app/test/e2e-playwright/playwright.config.ts@@ -3,10 +3,19 @@ import { defineConfig } from '@playwright/test'import fs from 'node:fs'import path from 'node:path'-/** Load a dotenv-style file without overwriting an explicit process value. */-function loadEnvFile(envPath: string): void {- if (!fs.existsSync(envPath)) return- const lines = fs.readFileSync(envPath, 'utf8').split('\n')+/** Read a local file once, treating a missing optional file as absent. */+function readOptionalFile(filePath: string): string | null {+ try {+ return fs.readFileSync(filePath, 'utf8')+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error+ }+}++/** Parse dotenv data without overwriting an explicit process value. */+function loadEnvContents(contents: string): void {+ const lines = contents.split('\n')for (const line of lines) {const trimmed = line.trim()if (!trimmed || trimmed.startsWith('#')) continue@@ -24,6 +33,12 @@ function loadEnvFile(envPath: string): void {}}+/** Load a dotenv-style file without a check-then-read race. */+function loadEnvFile(envPath: string): void {+ const contents = readOptionalFile(envPath)+ if (contents !== null) loadEnvContents(contents)+}+/*** Resolve the canonical repository .env for a secondary worktree. Direct* Playwright invocations do not inherit the shell wrapper's environment, so@@ -36,22 +51,31 @@ function loadCanonicalRootEnv(): void {// worktree: the canonical .env lives in the primary Evenfire checkout.const repoRoot = path.resolve(__dirname, '../../..')const localEnv = path.join(repoRoot, '.env')- if (fs.existsSync(localEnv)) {- loadEnvFile(localEnv)+ const localEnvContents = readOptionalFile(localEnv)+ if (localEnvContents !== null) {+ loadEnvContents(localEnvContents)return}const gitFile = path.join(repoRoot, '.git')- if (!fs.existsSync(gitFile) || !fs.statSync(gitFile).isFile()) return- const gitdirMatch = fs- .readFileSync(gitFile, 'utf8')- .trim()- .match(/^gitdir:\s*(.+)$/)+ let gitFileContents: string+ try {+ gitFileContents = fs.readFileSync(gitFile, 'utf8')+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ // A normal checkout has a file-form worktree pointer here. If `.git` is a+ // directory (for example in a non-worktree checkout), there is no safe+ // common-dir traversal to perform from this config file.+ if ((error as NodeJS.ErrnoException).code === 'EISDIR') return+ throw error+ }+ const gitdirMatch = gitFileContents.trim().match(/^gitdir:\s*(.+)$/)if (!gitdirMatch) returnconst worktreeGitDir = path.resolve(repoRoot, gitdirMatch[1])const commonDirFile = path.join(worktreeGitDir, 'commondir')- if (!fs.existsSync(commonDirFile)) return- const commonDir = path.resolve(worktreeGitDir, fs.readFileSync(commonDirFile, 'utf8').trim())+ const commonDirValue = readOptionalFile(commonDirFile)+ if (commonDirValue === null) return+ const commonDir = path.resolve(worktreeGitDir, commonDirValue.trim())loadEnvFile(path.join(commonDir, '..', '.env'))}diff --git a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.tsindex dc588853e..fcb8ea963 100644--- a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts@@ -577,6 +577,25 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real.poll(() => notificationDeliverySignal(notificationId!), { timeout: 30_000 }).toMatch(/^plugin_workload_sdk\.notification\|(queued|retrying|sent)$/)+ // Prove the end-user journey in the Desktop shell, not only the embedded+ // app response or the persisted delivery signal: the notification must be+ // visible in the authenticated inbox with the unique marker from this run.+ await test.step('open the Desktop notification inbox and read the delivered item', async () => {+ const bell = page!.getByTestId('notification-bell')+ await expect(bell).toBeVisible({ timeout: 20_000 })+ await bell.click()+ await expect(bell).toHaveAttribute('aria-expanded', 'true', { timeout: 20_000 })+ const inbox = page!.getByRole('dialog', { name: 'Notifications and approvals' })+ await expect(inbox).toBeVisible({ timeout: 20_000 })+ const deliveredItem = inbox+ .getByTestId('notification-menu-item')+ .filter({ hasText: `Evenfire E2E ${marker}` })+ await expect(deliveredItem).toBeVisible({ timeout: 30_000 })+ await expect(inbox).not.toContainText('No notifications or pending approvals right now.')+ await bell.click()+ await expect(bell).toHaveAttribute('aria-expanded', 'false', { timeout: 20_000 })+ })+if (CAPTURE_VISUALS) {await page.screenshot({path: testInfo.outputPath('desktop-app-sandbox-ui-complete.png'),diff --git a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts b/mcp-host/src/__tests__/workflow/workflowRouter.test.tsindex 8e335a5b4..71557d332 100644--- a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts+++ b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts@@ -391,6 +391,36 @@ describe('workflowRouter — JWT auth middleware', () => {}})+ it('rate-limits repeated SDK bootstrap calls per verified recipe', async () => {+ const recipeName = 'rate-limit-wf'+ const previousRecipe = process.env.CLERUM_WORKFLOW_RECIPE+ process.env.CLERUM_WORKFLOW_RECIPE = recipeName+ const token = await signWorkflowToken({+ sub: 'wrc',+ recipeName,+ scopes: ['configure'],+ })+ const { baseUrl, server } = await createTestApp(publicKeyPem, true)+ try {+ const request = () =>+ 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' }),+ })+ for (let index = 0; index < 60; index += 1) {+ expect((await request()).status).toBe(200)+ }+ const limited = await request()+ expect(limited.status).toBe(429)+ expect(limited.headers.get('retry-after')).toBeTruthy()+ } finally {+ server.close()+ if (previousRecipe === undefined) delete process.env.CLERUM_WORKFLOW_RECIPE+ else process.env.CLERUM_WORKFLOW_RECIPE = previousRecipe+ }+ })+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 0eb484686..43592577e 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -214,6 +214,7 @@ export interface Config {// (flag + runtime JWT recipeNamespace + downward-API pod namespace, all// fail-closed — see pluginWorkloadSdk/server/sdkServer.ts).pluginWorkloadSdkEnabled: boolean+ pluginWorkloadSdkRuntimeMode: 'workflow' | 'sdk-only'pluginWorkloadSdkPort: number/** Pod namespace via Kubernetes downward API (defense-in-depth). */podNamespace: string@@ -260,6 +261,14 @@ function getEnvNumber(key: string, defaultValue: number): number {return parsed}+function getPluginWorkloadSdkRuntimeMode(): 'workflow' | 'sdk-only' {+ const mode = getEnv('PLUGIN_WORKLOAD_SDK_RUNTIME_MODE', 'workflow')+ if (mode === 'workflow' || mode === 'sdk-only') return mode+ throw new Error(+ `Invalid PLUGIN_WORKLOAD_SDK_RUNTIME_MODE="${mode}"; expected workflow or sdk-only`+ )+}+/*** Stage 3 (stateless-agents) — parse CLERUM_STATELESS_HEARTBEAT_INTERVAL_MS.*@@ -746,6 +755,9 @@ export const config: Config = {// Plugin Workload SDK (plan §3.5 config table)pluginWorkloadSdkEnabled: getEnvBool('PLUGIN_WORKLOAD_SDK_ENABLED', false),+ // Workflow is the backwards-compatible default for pre-runtime-mode pods;+ // WRC explicitly sets sdk-only on the stepless adapter.+ pluginWorkloadSdkRuntimeMode: getPluginWorkloadSdkRuntimeMode(),pluginWorkloadSdkPort: parseInt(getEnv('MCP_HOST_PLUGIN_SDK_PORT', '8099')!, 10),podNamespace: getEnv('MCP_HOST_POD_NAMESPACE', '')!,pluginWorkloadSdkGatewayUrl: getEnv('CONTROL_API_GATEWAY_URL', ''),diff --git a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts b/mcp-host/src/pluginWorkloadSdk/metrics.test.tsindex f6c63a353..ec2cd08f6 100644--- a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/metrics.test.ts@@ -28,6 +28,7 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {authorizePromptBridge: vi.fn().mockResolvedValue({invocationId: 'inv-1',replay: false,+ providerCallRequired: true,status: 'in_progress',model: 'glm-4.7',modelPolicy: null,diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.tsindex 0eacc63bb..6567845a1 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts@@ -22,6 +22,7 @@ function authorizedBody(invocationId: string) {return {invocationId,replay: false,+ providerCallRequired: true,status: 'in_progress',model: target.model,modelPolicy: null,@@ -85,6 +86,16 @@ describe('PluginWorkloadSdkControlApiClient', () => {})})+ it('derives the provider-call disposition for an older control-api response', async () => {+ const { providerCallRequired: _omitted, ...legacyBody } = authorizedBody('legacy-invocation')+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, legacyBody))+ const client = makeClient(fetchImpl as unknown as typeof fetch)+ await expect(client.authorizePromptBridge(promptBody)).resolves.toMatchObject({+ replay: false,+ providerCallRequired: true,+ })+ })+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)diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.tsindex 878bb2999..38142a123 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts@@ -40,6 +40,7 @@ export interface ControlApiClientOptions {export interface AuthorizePromptBridgeResponse {invocationId: stringreplay: boolean+ providerCallRequired: booleanstatus: stringmodel: stringmodelPolicy: { provider: string; model: string; temperature?: number; maxCostUsd?: number } | null@@ -84,6 +85,7 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridgereturn (typeof r.invocationId === 'string' &&typeof r.replay === 'boolean' &&+ (r.providerCallRequired === undefined || typeof r.providerCallRequired === 'boolean') &&typeof r.status === 'string' &&typeof r.model === 'string' &&(r.modelPolicy === null ||@@ -329,7 +331,19 @@ export class PluginWorkloadSdkControlApiClient {true)}- return result+ // N/N-1 compatibility: control-api versions predating the explicit+ // provider-call disposition omitted this field. Their idempotency contract+ // already made non-replay responses executable and replay responses+ // non-executable, so derive the same fail-closed decision while rejecting+ // any malformed non-boolean value.+ return {+ ...result,+ providerCallRequired:+ typeof (result as unknown as { providerCallRequired?: unknown }).providerCallRequired ===+ 'boolean'+ ? result.providerCallRequired+ : !result.replay,+ }}/**diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.tsindex f585b620a..3212fed6e 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts@@ -27,6 +27,7 @@ function authorization(overrides: Record<string, unknown> = {}) {return {invocationId: 'inv-1',replay: false,+ providerCallRequired: true,status: 'in_progress',model: primary.model,modelPolicy: null,@@ -171,7 +172,11 @@ describe('PromptBridgeHandler', () => {})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 authorize = vi+ .fn()+ .mockResolvedValue(+ authorization({ replay: true, providerCallRequired: false, status: 'complete' })+ )const { handler, complete } = makeDeps({ authorize })await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({code: 'idempotency_conflict',diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.tsindex 066dc7789..08a2fc630 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts@@ -43,6 +43,7 @@ export interface PromptBridgeHandlerDeps {/** Public provider/model identity from the live spec.agent binding. */getBootstrapTarget?: () => { provider: string; model: string } | nullonUsage?: (usage: {+ invocationId: stringprovider: stringmodel: stringservedTarget: PromptBridgeTarget@@ -230,7 +231,10 @@ export class PromptBridgeHandler {// 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') {+ if (!authorized.replay && !authorized.providerCallRequired) {+ throw unexpectedAuthorizationResponse()+ }+ if (authorized.replay && !authorized.providerCallRequired) {throw new PluginWorkloadError('idempotency_conflict','idempotent invocation already exists; no provider call was repeated',@@ -266,6 +270,7 @@ export class PromptBridgeHandler {})this.deps.onUsage?.({+ invocationId: authorized.invocationId,provider: completion.servedTarget.provider,model: completion.model,servedTarget: completion.servedTarget,diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex cb9d126d9..822d8ec60 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -223,6 +223,25 @@ describe('LlmBridge authorized multi-provider fallback', () => {expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])})+ it('does not use auth failures as an implicit fallback trigger', async () => {+ const first = new FakeProvider(() => Promise.reject(new Error('401')), {+ code: LlmErrorCode.AuthenticationFailed,+ retryable: false,+ })+ const second = new FakeProvider(() => Promise.resolve(OK))+ const { bridge, providerCalls } = makeBridge({+ [primary.model]: first,+ [fallback.model]: second,+ })++ await expect(bridge.complete(request)).rejects.toMatchObject({+ code: 'provider_unavailable',+ retryable: false,+ reason: 'auth',+ })+ expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])+ })+it('surfaces only a safe provider reason and never the provider body', async () => {const failing = new FakeProvider(() =>Promise.reject(new Error('provider secret response body must stay private'))diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.tsindex 530f641ff..0ef0cc9ca 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts@@ -1,12 +1,7 @@import { LlmErrorCode } from '../../core/errors'import { type ChatMessage, FinishReason } from '../../core/types'import { type SingleTurnProvider, createLLMProvider } from '../../llm'-import {- ALL_FAILOVER_CLASSES,- type ClassifiedLike,- type FailoverClass,- classifyFailoverClass,-} from '../../llm/failover'+import { type ClassifiedLike, type FailoverClass, classifyFailoverClass } from '../../llm/failover'import { isLlmProvider } from '../../llm/registryCore'import { CircuitBreaker } from '../domain/circuitBreaker'import { PluginWorkloadError } from '../domain/errors'@@ -70,6 +65,13 @@ export interface LlmBridgeResult {}const DEFAULT_MAX_LLM_RESPONSE_BYTES = 1024 * 1024+// Authentication and quota failures are operator/configuration signals, not+// safe automatic failover triggers. Provider-unavailable and rate-limited are+// the only conservative defaults until an explicit grant-level policy exists.+const DEFAULT_PROMPT_BRIDGE_FAILOVER_CLASSES: readonly FailoverClass[] = [+ 'provider_unavailable',+ 'rate_limited',+]function remainingTimeoutMs(deadlineAt: number): number {return deadlineAt - Date.now()@@ -171,7 +173,7 @@ export class LlmBridge {'configuration')}- const triggerOn = new Set(request.triggerOn ?? ALL_FAILOVER_CLASSES)+ const triggerOn = new Set(request.triggerOn ?? DEFAULT_PROMPT_BRIDGE_FAILOVER_CLASSES)const deadlineAt = Date.now() + request.timeoutMslet lastProviderError: ClassifiedProviderError | null = nulldiff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.tsindex ff57e3c9f..6da1ce40e 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/runtime-http.test.ts@@ -139,6 +139,7 @@ function makeHarness(scenario: Scenario): RuntimeHarness {return {invocationId: 'inv-runtime-http',replay: false,+ providerCallRequired: true,status: 'in_progress',model: PRIMARY.model,modelPolicy: null,diff --git a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.tsindex 303d3ffe2..ab18608ed 100644--- a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts@@ -43,6 +43,7 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()authorizePromptBridge: vi.fn().mockResolvedValue({invocationId: 'inv-1',replay: false,+ providerCallRequired: true,status: 'in_progress',model: 'glm-4.7',// Even if control-api leaked a key into the authorization envelope,diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts b/mcp-host/src/pluginWorkloadSdk/server/index.test.tsindex f5b58520e..783682269 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts@@ -58,6 +58,41 @@ describe('PluginWorkloadSdk server usage attribution', () => {})})+ it('emits a server-bound SDK-only usage shape without inventing a workflow run', () => {+ const invocationId = '00000000-0000-4000-8000-000000000099'+ const event = buildPromptBridgeUsageEvent({+ binding: {+ hostRef: 'sandbox-recipes/stepless',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'stepless',+ },+ runtimeMode: 'sdk-only',+ invocationId,+ provider: 'openai',+ model: 'gpt-5.4-mini',+ inputTokens: 10,+ outputTokens: 5,+ callerRef: 'backend-worker',+ promptBridgeMetadata: {+ targetRef: 'openai-primary',+ credentialSlot: 'openai-api-key',+ fallbackUsed: false,+ attemptCount: 1,+ },+ metadata: { llmSecretName: 'openai-api-key' },+ })++ expect(event).toMatchObject({+ source_kind: 'unknown',+ channel_type: 'plugin_workload_sdk',+ recipe_name: 'stepless',+ run_id: null,+ task_id: null,+ llm_secret_name: 'openai-api-key',+ prompt_bridge_metadata: { invocation_id: invocationId },+ })+ })+it('records actual promptBridge target attribution without credential values', () => {const event = buildPromptBridgeUsageEvent({binding: {diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.tsindex 74971ab8d..d2a92d568 100644--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts@@ -20,6 +20,7 @@ export { shouldStartPluginWorkloadSdk } from './sdkServer'const WORKFLOW_RECIPE_NAMESPACE = 'sandbox-recipes'const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+export type PluginWorkloadSdkRuntimeMode = 'workflow' | 'sdk-only'function nonEmptyMetadataString(metadata: Record<string, unknown> | undefined,@@ -41,6 +42,8 @@ function workflowRunIdFromExecutionId(value: string | null): string | null {export function buildPromptBridgeUsageEvent(input: {binding: { hostRef: string; recipeNamespace: string; recipeName: string }+ runtimeMode?: PluginWorkloadSdkRuntimeMode+ invocationId?: stringprovider: stringmodel: stringinputTokens: number@@ -54,8 +57,14 @@ export function buildPromptBridgeUsageEvent(input: {}metadata?: Record<string, unknown>}): LlmUsageEvent | null {- const isWorkflowRecipe = input.binding.recipeNamespace === WORKFLOW_RECIPE_NAMESPACE- if (!isWorkflowRecipe) {+ // Explicit runtime mode is authoritative for recipe-bound hosts. The+ // namespace fallback remains only for older non-recipe callers that do not+ // yet inject the mode into their pod.+ const isSdkOnly = input.runtimeMode === 'sdk-only'+ const isWorkflowRecipe = input.runtimeMode+ ? input.runtimeMode === 'workflow'+ : input.binding.recipeNamespace === WORKFLOW_RECIPE_NAMESPACE+ if (!isWorkflowRecipe && !isSdkOnly) {return {request_id: randomUUID(),ts: new Date().toISOString(),@@ -88,6 +97,42 @@ export function buildPromptBridgeUsageEvent(input: {: {}),}}+ if (isSdkOnly) {+ const invocationId = input.invocationId?.trim() ?? ''+ if (!UUID_RE.test(invocationId)) return null+ return {+ request_id: randomUUID(),+ ts: new Date().toISOString(),+ run_id: null,+ host_ref: input.binding.hostRef,+ context_ref: null,+ team_id: null,+ provider: input.provider,+ model: input.model,+ source_kind: 'unknown',+ user_id: null,+ sender: input.callerRef,+ channel_type: 'plugin_workload_sdk',+ recipe_name: input.binding.recipeName,+ cron_job_id: null,+ task_id: null,+ iteration: null,+ input_tokens: input.inputTokens,+ output_tokens: input.outputTokens,+ llm_secret_name: input.metadata?.llmSecretName ? String(input.metadata.llmSecretName) : null,+ ...(input.promptBridgeMetadata+ ? {+ prompt_bridge_metadata: {+ invocation_id: invocationId,+ target_ref: input.promptBridgeMetadata.targetRef,+ credential_slot: input.promptBridgeMetadata.credentialSlot,+ fallback_used: input.promptBridgeMetadata.fallbackUsed,+ attempt_count: input.promptBridgeMetadata.attemptCount,+ },+ }+ : {}),+ }+ }const executionId = nonEmptyMetadataString(input.metadata, ['workflowExecutionId',@@ -283,6 +328,8 @@ export function maybeCreatePluginWorkloadSdkServer(fallbackUsed: usage.fallbackUsed,attemptCount: usage.attemptCount,},+ runtimeMode: config.pluginWorkloadSdkRuntimeMode === 'sdk-only' ? 'sdk-only' : 'workflow',+ invocationId: usage.invocationId,metadata: { ...usage.metadata, llmSecretName: usage.llmSecretName },})if (event) usageReporter.enqueue(event)diff --git a/mcp-host/src/usage/usageReporter.ts b/mcp-host/src/usage/usageReporter.tsindex 5e8a2d257..c67df6ca6 100644--- a/mcp-host/src/usage/usageReporter.ts+++ b/mcp-host/src/usage/usageReporter.ts@@ -46,6 +46,8 @@ export type LlmUsageEvent = {* event.*/prompt_bridge_metadata?: {+ /** Server-issued Plugin Workload SDK invocation identity, when applicable. */+ invocation_id?: stringtarget_ref: stringcredential_slot: stringfallback_used: booleandiff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex 07eefa024..57eeeca18 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -165,6 +165,45 @@ function validateWorkflowBinding(}const EXECUTE_HEARTBEAT_MS = 15_000+const WORKFLOW_CONTROL_RATE_LIMIT_WINDOW_MS = 60_000+const WORKFLOW_CONTROL_RATE_LIMIT_MAX = 60+const WORKFLOW_CONTROL_RATE_LIMIT_MAX_BUCKETS = 10_000+const workflowControlRateLimitBuckets = new Map<string, { windowStart: number; count: number }>()++/**+ * Bound WRC-only control operations (including SDK bootstrap) per recipe.+ * Authentication runs first, so the bucket key is server-verified JWT+ * identity rather than a request header or body field. The unauthenticated+ * key is retained only for the local auth-disabled mode and remains bounded.+ */+function workflowControlRateLimit(req: Request, res: Response, next: NextFunction): void {+ const claims = workflowClaims(req)+ const key = claims+ ? `workflow-control:${claims.recipeNamespace}/${claims.recipeName}:${claims.sub}`+ : 'workflow-control:unauthenticated'+ const now = Date.now()+ const existing = workflowControlRateLimitBuckets.get(key)+ const bucket =+ existing && now - existing.windowStart < WORKFLOW_CONTROL_RATE_LIMIT_WINDOW_MS+ ? existing+ : { windowStart: now, count: 0 }+ if (bucket.count >= WORKFLOW_CONTROL_RATE_LIMIT_MAX) {+ const retryAfterSeconds = Math.max(+ 1,+ Math.ceil((bucket.windowStart + WORKFLOW_CONTROL_RATE_LIMIT_WINDOW_MS - now) / 1000)+ )+ res.setHeader('Retry-After', String(retryAfterSeconds))+ res.status(429).json({ error: 'Too Many Requests', retryAfterSeconds })+ return+ }+ bucket.count += 1+ workflowControlRateLimitBuckets.set(key, bucket)+ if (workflowControlRateLimitBuckets.size > WORKFLOW_CONTROL_RATE_LIMIT_MAX_BUCKETS) {+ const oldest = workflowControlRateLimitBuckets.keys().next().value+ if (typeof oldest === 'string') workflowControlRateLimitBuckets.delete(oldest)+ }+ next()+}function writeSse(res: Response, event: string, data: unknown): void {res.write(`event: ${event}\n`)@@ -242,6 +281,7 @@ export function createWorkflowRouter(service: WorkflowService): Router {router.post('/plugin-workload-sdk/bootstrap',requireWorkflowAuth('configure'),+ workflowControlRateLimit,(req: Request, res: Response) => {if (!validateWorkflowBinding(req, res, { expectedSub: 'wrc' })) returnconst raw = req.body as PluginWorkloadSdkBootstrapRequestdiff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex d9132e34a..bc63adda3 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -7,6 +7,7 @@* - Model/provider can be swapped per-step without restart* - SOUL content can be overridden per-step, reverted after execution*/+import { isRunnableLlmModelId } from '@clerum/llm-providers'import { BudgetClient } from '../budget/budgetClient'import type { BudgetVerdict } from '../budget/types'import { createGetCapabilitiesTool } from '../capabilities/getCapabilitiesTool'@@ -360,7 +361,7 @@ export class WorkflowService {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)) {+ if (!isRunnableLlmModelId(model)) {return { configured: false, message: 'model is required and has an invalid format' }}this.onPluginWorkloadSdkBootstrapConfigured?.({diff --git a/packages/llm-providers/index.cjs b/packages/llm-providers/index.cjsindex c25299b2e..7e9989c6f 100644--- a/packages/llm-providers/index.cjs+++ b/packages/llm-providers/index.cjs@@ -52,6 +52,15 @@ const PROVIDER_IDS = Object.freeze(['azure',])+// Model identifiers are transport selectors, not arbitrary user text. Keep+// one executable grammar shared by authoring, WRC admission and mcp-host.+const RUNNABLE_LLM_MODEL_ID_MAX_LENGTH = 128+const RUNNABLE_LLM_MODEL_ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/++function isRunnableLlmModelId(value) {+ return typeof value === 'string' && RUNNABLE_LLM_MODEL_ID_PATTERN.test(value)+}+/** A single-API-key slot: `<provider>-api-key` → `<PROVIDER>_API_KEY`. */function apiKeySlot(dataKey, envName) {return Object.freeze([Object.freeze({ dataKey, envName, required: true })])@@ -203,9 +212,12 @@ function isCredentialSlotOwnedByProvider(provider, credentialSlot) {module.exports = {PROVIDER_IDS,+ RUNNABLE_LLM_MODEL_ID_MAX_LENGTH,+ RUNNABLE_LLM_MODEL_ID_PATTERN,PROVIDER_CREDENTIAL_SLOTS,PROVIDER_DISPLAY_LABELS,PROVIDER_NON_SECRET_ENV,isCredentialSlotOwnedByProvider,isLlmProviderId,+ isRunnableLlmModelId,}diff --git a/packages/llm-providers/index.d.ts b/packages/llm-providers/index.d.tsindex fbf9030cd..9aeb47789 100644--- a/packages/llm-providers/index.d.ts+++ b/packages/llm-providers/index.d.ts@@ -32,6 +32,15 @@ export declare const PROVIDER_IDS: readonly [/** Union of the canonical provider ids. */export type LlmProviderId = (typeof PROVIDER_IDS)[number]+/** Maximum length accepted by all runnable provider/model selectors. */+export declare const RUNNABLE_LLM_MODEL_ID_MAX_LENGTH: 128++/** Executable grammar for provider model identifiers. */+export declare const RUNNABLE_LLM_MODEL_ID_PATTERN: RegExp++/** Returns true when a model identifier is executable by the runtime contract. */+export declare function isRunnableLlmModelId(value: unknown): value is string+/*** One credential a provider loads from the K8s LLM Secret, mapped to a* shell-style env var name.diff --git a/scripts/e2e/e2e-plugin-workload-sdk.sh b/scripts/e2e/e2e-plugin-workload-sdk.shindex d2c4b8738..7285f1e2f 100755--- a/scripts/e2e/e2e-plugin-workload-sdk.sh+++ b/scripts/e2e/e2e-plugin-workload-sdk.sh@@ -31,11 +31,11 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"## process environment > canonical root .env > safe test defaults#-# The filtered temporary file lets us source the trusted dotenv file without-# allowing it to overwrite a value supplied by the caller. It is removed-# before this function returns and never appears in test output.+# The dotenv file is parsed as data without sourcing or evaluating it. Values+# supplied by the caller remain authoritative, and shell expressions in the+# canonical file are preserved literally.load_canonical_root_env() {- local repo_root env_file common_dir main_repo_dir filtered raw_line line key+ local repo_root env_file common_dir main_repo_dir raw_line line keyrepo_root="$(cd "${SCRIPT_DIR}/../.." && pwd)"env_file=""@@ -58,8 +58,9 @@ load_canonical_root_env() {return 0fi- filtered="$(mktemp "${TMPDIR:-/tmp}/evenfire-plugin-sdk-env.XXXXXX")"+ local line_number=0 value quotewhile IFS= read -r raw_line || [ -n "$raw_line" ]; do+ line_number=$((line_number + 1))line="${raw_line#"${raw_line%%[![:space:]]*}"}"case "$line" in''|'#'*) continue ;;@@ -68,36 +69,37 @@ load_canonical_root_env() {line="${line#export}"line="${line#"${line%%[![:space:]]*}"}"fi- case "$line" in- *=*) ;;- *) continue ;;- esac+ if [[ "$line" != *=* ]]; then+ printf 'Ignoring invalid canonical .env line %s (expected KEY=value)\n' "$line_number" >&2+ return 1+ fikey="${line%%=*}"- key="$(printf '%s' "$key" | tr -d '[:space:]')"- case "$key" in- [A-Za-z_][A-Za-z0-9_]*) ;;- *) continue ;;- esac+ key="${key#"${key%%[![:space:]]*}"}"+ key="${key%"${key##*[![:space:]]}"}"+ if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then+ printf 'Ignoring invalid canonical .env key on line %s\n' "$line_number" >&2+ return 1+ fiif [ "${!key+x}" = x ]; thencontinuefi- printf '%s\n' "$raw_line" >> "$filtered"+ value="${line#*=}"+ value="${value#"${value%%[![:space:]]*}"}"+ value="${value%"${value##*[![:space:]]}"}"+ if [[ "$value" == \"*\" || "$value" == \'*\' ]]; then+ quote="${value:0:1}"+ if [[ "${value: -1}" != "$quote" ]]; then+ printf 'Ignoring unterminated quoted value on canonical .env line %s\n' "$line_number" >&2+ return 1+ fi+ value="${value:1:${#value}-2}"+ fi+ # Treat dotenv as data. In particular, command substitutions, backticks,+ # globbing and variable references remain literal text and are never+ # evaluated by a shell.+ printf -v "$key" '%s' "$value"+ export "$key"done < "$env_file"-- # Temporarily disable errexit so the temporary file is removed even when a- # malformed local dotenv assignment is encountered.- set +e- set -a- # shellcheck disable=SC1090- . "$filtered"- local source_status=$?- set +a- set -e- rm -f "$filtered"- if [ "$source_status" -ne 0 ]; then- printf 'Failed to load canonical .env from %s\n' "$env_file" >&2- return "$source_status"- fi}load_canonical_root_envdiff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex a548ea6e7..fed15dfad 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.260",+ "version": "0.1.261","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.260",+ "version": "0.1.261","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 cc30447db..3a2048c90 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.260",+ "version": "0.1.261","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.ts b/workflow-recipes/src/mcp/server.tsindex 5db61eeb3..07a0cf55f 100644--- a/workflow-recipes/src/mcp/server.ts+++ b/workflow-recipes/src/mcp/server.ts@@ -384,6 +384,11 @@ export class ClerumMcpServer {// 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.+ // lgtm[js/user-controlled-bypass]+ // The request path only selects the handler. Before any Secret read, the+ // handler verifies the JWT issuer/audience/scope, binds the token claims+ // to the server-owned namespace and recipe, and then validates the+ // signed invocation/target ticket against the current control-api policy.if (req.method === 'POST' && subPath === '/plugin-workload-sdk/credentials') {const authHeader = req.headers.authorizationconst runtimeToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''@@ -451,14 +456,24 @@ export class ClerumMcpServer {res.end(JSON.stringify({ error: 'Credential ticket denied' }))return}+ // The request body is only an equality check. Once the signed ticket+ // is verified, use its claims as the sole identity passed to the+ // Secret resolver and to all subsequent policy revalidation calls.+ const boundInvocationId = ticket.invocationId+ const boundTarget: PluginSdkCredentialTarget = {+ targetRef: ticket.targetRef,+ provider: ticket.provider,+ model: ticket.model,+ credentialSlot: ticket.credentialSlot,+ }// TOCTOU gate: ticket signature proves what was authorized, while this// control-api read proves that the invocation and policy revision/hash// are still current immediately before the Secret lookup.const ticketStillActive = await revalidatePluginSdkCredentialTicket({runtimeToken,credentialTicket: body.credentialTicket,- invocationId: body.invocationId,- targetRef: target.targetRef,+ invocationId: boundInvocationId,+ targetRef: boundTarget.targetRef,})if (!ticketStillActive) {res.writeHead(403, { 'Content-Type': 'application/json' })@@ -470,7 +485,7 @@ export class ClerumMcpServer {res.end(JSON.stringify({ error: 'Credential broker unavailable' }))return}- const result = await this.modelConfigHandler.resolvePluginSdkCredential(target)+ const result = await this.modelConfigHandler.resolvePluginSdkCredential(boundTarget)// 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@@ -479,8 +494,8 @@ export class ClerumMcpServer {const ticketStillActiveAfterResolve = await revalidatePluginSdkCredentialTicket({runtimeToken,credentialTicket: body.credentialTicket,- invocationId: body.invocationId,- targetRef: target.targetRef,+ invocationId: boundInvocationId,+ targetRef: boundTarget.targetRef,redeem: true,})if (!ticketStillActiveAfterResolve) {diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.tsindex f11edd318..31ecb111d 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts@@ -111,6 +111,14 @@ describe('validatePluginWorkloadSdkSpec', () => {expect(errors[0]).toContain('must not contain wildcards')})+ it('rejects model ids outside the shared runnable grammar', () => {+ const errors = validatePluginWorkloadSdkSpec(+ baseSpec({ promptBridge: { allowedModels: ['model with spaces'] } })+ )+ expect(errors).toHaveLength(1)+ expect(errors[0]).toContain('invalid runnable model id')+ })+it('rejects wildcard entries in clientNotifications.allowedTargetRefs', () => {const errors = validatePluginWorkloadSdkSpec(baseSpec({diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.tsindex 79e69d3f0..b1ab38408 100644--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts@@ -1,3 +1,4 @@+import { isRunnableLlmModelId } from '@clerum/llm-providers'import type {PluginWorkloadSdkCapabilityStatus,RecipePhase,@@ -40,6 +41,14 @@ function rejectWildcards(field: string, values: string[] | undefined, errors: st}}+function rejectInvalidModels(field: string, values: string[] | undefined, errors: string[]): void {+ for (const value of values ?? []) {+ if (!value.includes('*') && !isRunnableLlmModelId(value)) {+ errors.push(`${field} entry "${value}" has an invalid runnable model id`)+ }+ }+}+/*** Validate `spec.pluginWorkloadSdk` against the rules the CRD's OpenAPI/CEL* layer cannot fully express:@@ -105,6 +114,11 @@ export function validatePluginWorkloadSdkSpec(spec: WorkflowRecipeSpec): string[sdk.promptBridge?.allowedModels,errors)+ rejectInvalidModels(+ 'pluginWorkloadSdk.promptBridge.allowedModels',+ sdk.promptBridge?.allowedModels,+ errors+ )// promptBridge issues real LLM calls, so the recipe must declare a resolvable// agent (provider + model) — either spec.agent or a step agent. The WRC usesdiff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex 17f2cab90..6dc644df7 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -1233,6 +1233,22 @@ export class WorkflowRecipeReconciler {}const isWorkflow = recipe.spec.steps !== undefined && recipe.spec.steps.length > 0+ // The feature flag is a kill switch for SDK-only runtimes. Reconcile this+ // before the non-deployable phase guard so a previously-created host cannot+ // remain reachable merely because the recipe was already latched failed.+ // Workflow recipes keep their normal mcp-host lifecycle; this cleanup is+ // intentionally restricted to the stepless adapter.+ if (!isWorkflow && recipe.spec.pluginWorkloadSdk && !this.config.pluginWorkloadSdkEnabled) {+ try {+ await this.workflowReconciler?.cleanupPluginWorkloadSdkOnly(name)+ } catch (error) {+ return {+ phase: 'failed' as RecipePhase,+ message: `Plugin Workload SDK teardown failed while the feature flag is disabled: ${String(error)}`,+ workloadStatuses: [],+ }+ }+ }if (isWorkflow) {// Revocation must precede spec/policy validation: an invalid edit that also// removes publishTargets must still close the previously opened lane.diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.tsindex 89ec43607..9cbc3c500 100644--- a/workflow-recipes/src/workflow/modelConfigHandler.ts+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts@@ -13,6 +13,7 @@ import {PROVIDER_CREDENTIAL_SLOTS,isCredentialSlotOwnedByProvider,isLlmProviderId,+ isRunnableLlmModelId,} from '@clerum/llm-providers'import { createLogger } from '../observability/logger'@@ -168,7 +169,7 @@ function parseAllowedModels(raw: string | undefined, provider: string): Set<strientry &&typeof entry === 'object' &&typeof (entry as { model?: unknown }).model === 'string' &&- (entry as { model: string }).model.length > 0+ isRunnableLlmModelId((entry as { model: string }).model)) {allowed.add((entry as { model: string }).model)}@@ -195,8 +196,7 @@ export class ModelConfigHandler {mcpHostEndpoint: string,wrcConfigureToken: string): Promise<ConfigureModelResult> {- const MODEL_PATTERN = /^[a-zA-Z0-9._:/-]{1,128}$/- if (!isLlmProviderId(provider) || !MODEL_PATTERN.test(model)) {+ if (!isLlmProviderId(provider) || !isRunnableLlmModelId(model)) {return { status: 400, body: { error: 'Invalid Plugin Workload SDK bootstrap target' } }}if (!this.mcpHost.configurePluginWorkloadSdkBootstrap) {@@ -225,11 +225,10 @@ export class ModelConfigHandler {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) ||+ !isRunnableLlmModelId(target.model) ||!SECRET_KEY_PATTERN.test(target.credentialSlot)) {return { status: 400, body: { error: 'Invalid credential target' } }diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.tsindex 59dbbfbd0..5ce6f6f28 100644--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts@@ -236,6 +236,7 @@ export class PluginWorkloadSdkProvisioner {{mountWorkflowOutput: false,pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkRuntimeMode: 'sdk-only',})await this.deps.createIfNotExists(diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.tsindex 8addc4fb9..271c6904a 100644--- a/workflow-recipes/src/workflow/podFactory.ts+++ b/workflow-recipes/src/workflow/podFactory.ts@@ -552,6 +552,8 @@ export interface McpHostPodOptions {* downward API leg of the gate must exist even when the flag is off.*/pluginWorkloadSdkEnabled?: boolean+ /** Runtime contract used by mcp-host usage attribution. */+ pluginWorkloadSdkRuntimeMode?: 'workflow' | 'sdk-only'}export function buildMcpHostPod(@@ -706,6 +708,10 @@ export function buildMcpHostPod(...(options.pluginWorkloadSdkEnabled? [{ name: 'PLUGIN_WORKLOAD_SDK_ENABLED', value: 'true' },+ {+ name: 'PLUGIN_WORKLOAD_SDK_RUNTIME_MODE',+ value: options.pluginWorkloadSdkRuntimeMode ?? 'workflow',+ },{name: 'PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKENS_DIR',value: PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKENS_DIR,