Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: isolate stepless sdk-only mcp-host runtime
Alfredo Lopez242650f04201
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex bb7007cdb..6059fe77a 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","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 4099c1caa..da67d9803 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.401",+ "version": "0.1.402","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/internal/pluginWorkloadSdk.ts b/control-api/src/routes/internal/pluginWorkloadSdk.tsindex 894e3f547..15697827e 100644--- a/control-api/src/routes/internal/pluginWorkloadSdk.ts+++ b/control-api/src/routes/internal/pluginWorkloadSdk.ts@@ -2,9 +2,11 @@ import { Router } from 'express'import { asyncHandler } from '../../http/asyncHandler.js'import { requireInternalControlJwt } from '../../middleware/internalControlJwt.js'import {+ type PluginWorkloadSdkRevocationActor,finalizePluginWorkloadSdkRevocation,revokePluginWorkloadSdkForRecipe,} from '../../services/pluginWorkloadSdkDb.js'+import type { InternalControlClaims } from '../../utils/auth/internalControlToken.js'import { isPlainObject } from '../../utils/isPlainObject.js'function recipeBinding(body: unknown): { recipeNamespace: string; recipeName: string } | null {@@ -27,6 +29,19 @@ function revocationId(body: unknown): string | null {return REVOCATION_ID_RE.test(value) ? value : null}+function wrcRevocationActor(claims: InternalControlClaims): PluginWorkloadSdkRevocationActor {+ return {+ operatorSub: claims.sub,+ internalPrincipal: {+ kind: 'wrc_internal_control',+ sourceService: 'workflow-recipes',+ serviceSub: 'wrc-provisioner',+ credentialId: claims.jti,+ allowedKinds: ['linked_outcome', 'service_action'],+ },+ }+}+/*** WRC-only revocation boundary for SDK-only recipe teardown. The first call* fences Control API authorization and active generations; the second call is@@ -51,7 +66,7 @@ export function createInternalPluginWorkloadSdkRouter(): Router {const result = await revokePluginWorkloadSdkForRecipe(binding.recipeNamespace,binding.recipeName,- internalControl.sub+ wrcRevocationActor(internalControl))res.status(200).json(result)})@@ -76,7 +91,7 @@ export function createInternalPluginWorkloadSdkRouter(): Router {binding.recipeNamespace,binding.recipeName,expectedRevocationId,- internalControl.sub+ wrcRevocationActor(internalControl))res.status(result.state === 'conflict' ? 409 : 200).json(result)})diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.tsindex 358bbbb63..ed4bec336 100644--- a/control-api/src/services/pluginWorkloadSdkDb.ts+++ b/control-api/src/services/pluginWorkloadSdkDb.ts@@ -1,5 +1,6 @@import { createHash, randomUUID } from 'node:crypto'import { type DbClient, pool, withTransaction } from '../db.js'+import type { AdministrativeEventSubmitterPrincipalV1 } from '../middleware/tracingSubmitterAuth.js'import { stableStringify } from '../utils/stableStringify.js'import {type ControlApiPermissionChange,@@ -655,6 +656,11 @@ export interface PluginWorkloadSdkRevocationReceipt {disabled?: number}+export interface PluginWorkloadSdkRevocationActor {+ operatorSub: string+ internalPrincipal: AdministrativeEventSubmitterPrincipalV1+}+/*** Fence every SDK capability for a recipe before its runtime resources are* torn down. This is deliberately recipe-scoped and transactional: the@@ -665,7 +671,7 @@ export interface PluginWorkloadSdkRevocationReceipt {export async function revokePluginWorkloadSdkForRecipe(recipeNamespace: string,recipeName: string,- operatorSub: string+ actor: PluginWorkloadSdkRevocationActor): Promise<PluginWorkloadSdkRevocationReceipt> {return withTransaction(async db => {const recipeLock = `plugin_workload_sdk:${recipeNamespace}/${recipeName}`@@ -771,7 +777,11 @@ export async function revokePluginWorkloadSdkForRecipe(status: 'revoking',}))if (changes.length > 0) {- await appendControlApiPermissionEventsInTransaction(db, { operatorSub, changes })+ await appendControlApiPermissionEventsInTransaction(db, {+ operatorSub: actor.operatorSub,+ internalPrincipal: actor.internalPrincipal,+ changes,+ })}return {state:@@ -795,7 +805,7 @@ export async function finalizePluginWorkloadSdkRevocation(recipeNamespace: string,recipeName: string,expectedRevocationId: string,- operatorSub: string+ actor: PluginWorkloadSdkRevocationActor): Promise<PluginWorkloadSdkRevocationReceipt> {return withTransaction(async db => {const recipeLock = `plugin_workload_sdk:${recipeNamespace}/${recipeName}`@@ -868,7 +878,11 @@ export async function finalizePluginWorkloadSdkRevocation(status: 'disabled',}))if (changes.length > 0) {- await appendControlApiPermissionEventsInTransaction(db, { operatorSub, changes })+ await appendControlApiPermissionEventsInTransaction(db, {+ operatorSub: actor.operatorSub,+ internalPrincipal: actor.internalPrincipal,+ changes,+ })}return {state: 'disabled',diff --git a/control-api/src/services/tracing/controlApiPermissionEvents.ts b/control-api/src/services/tracing/controlApiPermissionEvents.tsindex 9e22978ba..c645d92f8 100644--- a/control-api/src/services/tracing/controlApiPermissionEvents.ts+++ b/control-api/src/services/tracing/controlApiPermissionEvents.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto'import { config } from '../../config.js'import type { DbClient } from '../../db.js'+import type { AdministrativeEventSubmitterPrincipalV1 } from '../../middleware/tracingSubmitterAuth.js'import { currentAdministrativeRequestContext } from './adminOperationContext.js'import { AdministrativeEventService } from './administrativeEvents.js'import type {@@ -51,6 +52,12 @@ export async function appendControlApiPermissionEventsInTransaction(changes: readonly ControlApiPermissionChange[]operationId?: stringoperatorKind?: 'control_admin' | 'platform_user'+ /**+ * Authenticated technical principal for an internal control-plane+ * mutation. Its service subject is auditable but is never coerced into the+ * UUID-only operator_user_id column.+ */+ internalPrincipal?: AdministrativeEventSubmitterPrincipalV1requestId?: string | nulldependencies?: PermissionEventDependencies}@@ -60,10 +67,15 @@ export async function appendControlApiPermissionEventsInTransaction(const operationId = params.operationId ?? randomUUID()const now = params.dependencies?.now ?? (() => new Date())const requestContext = currentAdministrativeRequestContext()+ const internalPrincipal = params.internalPrincipal+ if (internalPrincipal && internalPrincipal.serviceSub !== params.operatorSub) {+ throw new Error('internal permission-event principal does not match operatorSub')+ }const localAdminRequest =- params.operatorKind === 'control_admin' ||- (params.operatorKind === undefined &&- Boolean(requestContext && requestContext.operatorSub === params.operatorSub))+ !internalPrincipal &&+ (params.operatorKind === 'control_admin' ||+ (params.operatorKind === undefined &&+ Boolean(requestContext && requestContext.operatorSub === params.operatorSub)))const events = new AdministrativeEventService({transaction: async () => {throw new Error('permission event append requires the caller transaction')@@ -92,7 +104,7 @@ export async function appendControlApiPermissionEventsInTransaction(action: change.action === 'grant' ? 'permission_grant' : 'permission_revoke',outcome,operatorSub: params.operatorSub,- operatorUserId: params.operatorSub,+ operatorUserId: internalPrincipal ? null : params.operatorSub,operationId,relatedRunId: null,requestId:@@ -111,8 +123,18 @@ export async function appendControlApiPermissionEventsInTransaction(targetIdentityIssuer: targetsUser ? config.jwtIssuer : null,targetHumanSub: targetsUser ? change.subject.id : null,targetUserId: targetsUser ? change.subject.id : null,- identityIssuer: localAdminRequest ? config.adminJwtIssuer : config.jwtIssuer,- resourceAud: localAdminRequest ? config.adminJwtAudience : config.jwtAudience,+ identityIssuer: internalPrincipal+ ? internalPrincipal.kind === 'wrc_internal_control'+ ? 'wrc'+ : 'hcc'+ : localAdminRequest+ ? config.adminJwtIssuer+ : config.jwtIssuer,+ resourceAud: internalPrincipal+ ? 'control-api'+ : localAdminRequest+ ? config.adminJwtAudience+ : config.jwtAudience,effectiveScopes: [],authorizationDecision,decisionActorSub: params.operatorSub,@@ -150,7 +172,7 @@ export async function appendControlApiPermissionEventsInTransaction(for (let start = 0; start < entries.length; start += PERMISSION_EVENT_BATCH_SIZE) {await events.appendManyInTransaction(db,- CONTROL_API_PERMISSION_ADMINISTRATIVE_PRINCIPAL_V1,+ internalPrincipal ?? CONTROL_API_PERMISSION_ADMINISTRATIVE_PRINCIPAL_V1,entries.slice(start, start + PERMISSION_EVENT_BATCH_SIZE))}diff --git a/control-api/test/routes.internalPluginWorkloadSdk.test.ts b/control-api/test/routes.internalPluginWorkloadSdk.test.tsnew file mode 100644index 000000000..1fb2b8d96--- /dev/null+++ b/control-api/test/routes.internalPluginWorkloadSdk.test.ts@@ -0,0 +1,94 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import jwt from 'jsonwebtoken'+import request from 'supertest'+import { config } from '../src/config.js'+import { createInternalPluginWorkloadSdkRouter } from '../src/routes/internal/pluginWorkloadSdk.js'++const db = vi.hoisted(() => ({ revoke: vi.fn(), finalize: vi.fn() }))++vi.mock('../src/services/pluginWorkloadSdkDb.js', () => ({+ revokePluginWorkloadSdkForRecipe: (...args: unknown[]) => db.revoke(...args),+ finalizePluginWorkloadSdkRevocation: (...args: unknown[]) => db.finalize(...args),+}))++function sign(iss: 'wrc' | 'hcc'): string {+ return jwt.sign(+ { iss, aud: 'control-api', sub: `${iss}-provisioner` },+ iss === 'wrc' ? config.internalControlJwtWrcHmacSecret : config.internalControlJwtHccHmacSecret,+ { algorithm: 'HS256', expiresIn: 60, jwtid: `${iss}-revocation-test` }+ )+}++function app() {+ const instance = express()+ instance.use(express.json())+ instance.use('/api/v1', createInternalPluginWorkloadSdkRouter())+ return instance+}++describe('internal Plugin Workload SDK revocation', () => {+ beforeEach(() => {+ db.revoke.mockReset()+ db.finalize.mockReset()+ db.revoke.mockResolvedValue({+ state: 'revoking',+ revocationId: '11111111-1111-4111-8111-111111111111',+ revoked: 1,+ fencedInvocations: 0,+ })+ db.finalize.mockResolvedValue({+ state: 'disabled',+ revocationId: '11111111-1111-4111-8111-111111111111',+ revoked: 0,+ fencedInvocations: 0,+ disabled: 1,+ })+ })++ it('revoke and finalize carry the authenticated WRC technical principal', async () => {+ const authorization = `Bearer ${sign('wrc')}`+ const binding = { recipeNamespace: 'sandbox-recipes', recipeName: 'sdk-recipe' }+ const revoke = await request(app())+ .post('/api/v1/internal/plugin-workload-sdk/revoke')+ .set('Authorization', authorization)+ .send(binding)+ expect(revoke.status).toBe(200)+ expect(db.revoke).toHaveBeenCalledWith(+ 'sandbox-recipes',+ 'sdk-recipe',+ expect.objectContaining({+ operatorSub: 'wrc-provisioner',+ internalPrincipal: expect.objectContaining({+ kind: 'wrc_internal_control',+ serviceSub: 'wrc-provisioner',+ credentialId: 'wrc-revocation-test',+ }),+ })+ )++ const finalize = await request(app())+ .post('/api/v1/internal/plugin-workload-sdk/finalize-revocation')+ .set('Authorization', authorization)+ .send({ ...binding, revocationId: '11111111-1111-4111-8111-111111111111' })+ expect(finalize.status).toBe(200)+ expect(db.finalize).toHaveBeenCalledWith(+ 'sandbox-recipes',+ 'sdk-recipe',+ '11111111-1111-4111-8111-111111111111',+ expect.objectContaining({+ operatorSub: 'wrc-provisioner',+ internalPrincipal: expect.objectContaining({ credentialId: 'wrc-revocation-test' }),+ })+ )+ })++ it('rejects a different internal issuer before the mutation boundary', async () => {+ const response = await request(app())+ .post('/api/v1/internal/plugin-workload-sdk/revoke')+ .set('Authorization', `Bearer ${sign('hcc')}`)+ .send({ recipeNamespace: 'sandbox-recipes', recipeName: 'sdk-recipe' })+ expect(response.status).toBe(403)+ expect(db.revoke).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/services.controlApiPermissionEvents.test.ts b/control-api/test/services.controlApiPermissionEvents.test.tsindex 18811f638..be52adba7 100644--- a/control-api/test/services.controlApiPermissionEvents.test.ts+++ b/control-api/test/services.controlApiPermissionEvents.test.ts@@ -155,6 +155,66 @@ describe('appendControlApiPermissionEventsInTransaction', () => {)})+ it('records WRC as a technical principal without coercing its subject into a user UUID', async () => {+ const internalPrincipal = {+ kind: 'wrc_internal_control',+ sourceService: 'workflow-recipes',+ serviceSub: 'wrc-provisioner',+ credentialId: 'wrc-jti-1',+ allowedKinds: ['linked_outcome', 'service_action'],+ } as const++ await appendControlApiPermissionEventsInTransaction(db, {+ operatorSub: 'wrc-provisioner',+ internalPrincipal,+ changes: [+ {+ action: 'revoke',+ resourceClass: 'plugin_workload_sdk_access',+ resourceRef: 'plugin_workload_sdk:sandbox-recipes/example:promptBridge',+ subject: { kind: 'service', id: 'promptBridge' },+ namespace: 'sandbox-recipes',+ },+ ],+ })++ const [, principal, entries] = eventAppender.appendMany.mock.calls[0]!+ expect(principal).toBe(internalPrincipal)+ expect(entries[0].binding).toEqual(+ expect.objectContaining({+ operatorSub: 'wrc-provisioner',+ operatorUserId: null,+ identityIssuer: 'wrc',+ resourceAud: 'control-api',+ decisionActorSub: 'wrc-provisioner',+ })+ )+ })++ it('fails closed when an internal principal does not match operatorSub', async () => {+ await expect(+ appendControlApiPermissionEventsInTransaction(db, {+ operatorSub: 'different-service',+ internalPrincipal: {+ kind: 'wrc_internal_control',+ sourceService: 'workflow-recipes',+ serviceSub: 'wrc-provisioner',+ credentialId: 'wrc-jti-1',+ allowedKinds: ['linked_outcome', 'service_action'],+ },+ changes: [+ {+ action: 'revoke',+ resourceClass: 'plugin_workload_sdk_access',+ resourceRef: 'plugin_workload_sdk:sandbox-recipes/example:promptBridge',+ subject: { kind: 'service', id: 'promptBridge' },+ },+ ],+ })+ ).rejects.toThrow(/principal does not match operatorSub/)+ expect(eventAppender.appendMany).not.toHaveBeenCalled()+ })+it('does not append a synthetic event when the mutation produced no diff', async () => {await expect(appendControlApiPermissionEventsInTransaction(db, {diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.tsindex 36ce2bbfd..451832511 100644--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts@@ -4,10 +4,12 @@ import {consumePeriodQuota,deleteGrant,failStaleInvocations,+ finalizePluginWorkloadSdkRevocation,getPluginWorkloadSdkLegacyGrantInventory,redeemPluginWorkloadSdkCredentialTicketJti,registerPluginWorkloadSdkCredentialTicketJti,resolveRecipientProfiles,+ revokePluginWorkloadSdkForRecipe,updateInvocationStatus,upsertGrant,} from '../src/services/pluginWorkloadSdkDb.js'@@ -552,3 +554,90 @@ describe('Plugin Workload SDK governed permission events', () => {])})})++describe('Plugin Workload SDK internal revocation audit actor', () => {+ const REVOCATION_ID = '55555555-5555-4555-8555-555555555555'+ const internalPrincipal = {+ kind: 'wrc_internal_control',+ sourceService: 'workflow-recipes',+ serviceSub: 'wrc-provisioner',+ credentialId: 'wrc-revocation-jti',+ allowedKinds: ['linked_outcome', 'service_action'],+ } as const+ const actor = { operatorSub: 'wrc-provisioner', internalPrincipal }++ beforeEach(() => {+ vi.mocked(pool.query).mockReset()+ permissionEvents.append.mockReset()+ permissionEvents.append.mockResolvedValue('operation-id')+ })++ it('forwards the WRC principal through the transactional revoke audit', async () => {+ vi.mocked(pool.query)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({+ rows: [+ {+ id: '33333333-3333-4333-8333-333333333333',+ capability_family: 'promptBridge',+ policy_state: 'active',+ revocation_id: null,+ },+ ],+ rowCount: 1,+ } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 1 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)++ await expect(+ revokePluginWorkloadSdkForRecipe('sandbox-recipes', 'sdk-recipe', actor)+ ).resolves.toMatchObject({ state: 'revoking', revoked: 1 })+ expect(permissionEvents.append).toHaveBeenCalledWith(+ expect.objectContaining({ query: pool.query }),+ expect.objectContaining({+ operatorSub: 'wrc-provisioner',+ internalPrincipal,+ changes: [expect.objectContaining({ status: 'revoking' })],+ })+ )+ })++ it('forwards the same WRC principal when finalizing the fenced epoch', async () => {+ vi.mocked(pool.query)+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)+ .mockResolvedValueOnce({+ rows: [+ {+ id: '33333333-3333-4333-8333-333333333333',+ capability_family: 'promptBridge',+ policy_state: 'revoking',+ revocation_id: REVOCATION_ID,+ },+ ],+ rowCount: 1,+ } as never)+ .mockResolvedValueOnce({+ rows: [+ {+ id: '33333333-3333-4333-8333-333333333333',+ capability_family: 'promptBridge',+ },+ ],+ rowCount: 1,+ } as never)++ await expect(+ finalizePluginWorkloadSdkRevocation('sandbox-recipes', 'sdk-recipe', REVOCATION_ID, actor)+ ).resolves.toMatchObject({ state: 'disabled', disabled: 1 })+ expect(permissionEvents.append).toHaveBeenCalledWith(+ expect.objectContaining({ query: pool.query }),+ expect.objectContaining({+ operatorSub: 'wrc-provisioner',+ internalPrincipal,+ changes: [expect.objectContaining({ status: 'disabled' })],+ })+ )+ })+})diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex d9881a75c..74878c544 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.221",+ "version": "0.1.222","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.221",+ "version": "0.1.222","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 97668f9f5..61ac20f36 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.221",+ "version": "0.1.222","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/config.runtimeKind.test.ts b/mcp-host/src/config.runtimeKind.test.tsnew file mode 100644index 000000000..fe039d906--- /dev/null+++ b/mcp-host/src/config.runtimeKind.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest'+import { resolveMcpHostRuntimeKind } from './config'++describe('resolveMcpHostRuntimeKind', () => {+ it('derives legacy workflow and standalone pods when no explicit mode exists', () => {+ expect(resolveMcpHostRuntimeKind({ workflowEnabled: true })).toBe('workflow')+ expect(resolveMcpHostRuntimeKind({ workflowEnabled: false })).toBe('standalone')+ })++ it('selects sdk-only only from an explicit non-workflow contract', () => {+ expect(+ resolveMcpHostRuntimeKind({+ workflowEnabled: false,+ pluginWorkloadSdkRuntimeMode: 'sdk-only',+ })+ ).toBe('sdk-only')+ })++ it.each([+ [true, 'sdk-only'],+ [false, 'workflow'],+ ])('fails closed for contradictory workflow=%s mode=%s', (workflowEnabled, mode) => {+ expect(() =>+ resolveMcpHostRuntimeKind({+ workflowEnabled,+ pluginWorkloadSdkRuntimeMode: mode,+ })+ ).toThrow(/Contradictory mcp-host runtime configuration/)+ })++ it('rejects unknown runtime modes', () => {+ expect(() =>+ resolveMcpHostRuntimeKind({+ workflowEnabled: false,+ pluginWorkloadSdkRuntimeMode: 'legacy',+ })+ ).toThrow(/Invalid PLUGIN_WORKLOAD_SDK_RUNTIME_MODE/)+ })+})diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.tsindex 43592577e..6dd2fa209 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -187,7 +187,12 @@ export interface Config {approvalPromptHistoryEnabled: booleanapprovalPromptHistoryMaxBytes: number- // Workflow mode — set by WRC via CLERUM_WORKFLOW_ENABLED=true on the Pod+ // Canonical process runtime. `workflowEnabled` is retained as a derived+ // compatibility view for code that only needs the workflow yes/no answer;+ // startup dispatch MUST use `runtimeKind` so sdk-only can never fall through+ // to the standalone host.+ runtimeKind: 'standalone' | 'workflow' | 'sdk-only'+ // Workflow mode — derived from runtimeKind, never independently trusted.workflowEnabled: booleanworkflowRecipeName: stringuserApprovalRequestRecipeName: string@@ -261,12 +266,36 @@ 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`- )+export type McpHostRuntimeKind = 'standalone' | 'workflow' | 'sdk-only'++/**+ * Resolve the one authoritative startup kind from the two historical env+ * signals. Explicit SDK/runtime mode and CLERUM_WORKFLOW_ENABLED must agree;+ * contradictory combinations fail at config load instead of silently+ * exposing workflow or standalone routes from an sdk-only Pod.+ */+export function resolveMcpHostRuntimeKind(input: {+ workflowEnabled: boolean+ pluginWorkloadSdkRuntimeMode?: string+}): McpHostRuntimeKind {+ const rawMode = input.pluginWorkloadSdkRuntimeMode?.trim()+ if (!rawMode) return input.workflowEnabled ? 'workflow' : 'standalone'+ if (rawMode !== 'workflow' && rawMode !== 'sdk-only') {+ throw new Error(+ `Invalid PLUGIN_WORKLOAD_SDK_RUNTIME_MODE="${rawMode}"; expected workflow or sdk-only`+ )+ }+ if (rawMode === 'workflow' && !input.workflowEnabled) {+ throw new Error(+ 'Contradictory mcp-host runtime configuration: PLUGIN_WORKLOAD_SDK_RUNTIME_MODE=workflow requires CLERUM_WORKFLOW_ENABLED=true'+ )+ }+ if (rawMode === 'sdk-only' && input.workflowEnabled) {+ throw new Error(+ 'Contradictory mcp-host runtime configuration: PLUGIN_WORKLOAD_SDK_RUNTIME_MODE=sdk-only requires CLERUM_WORKFLOW_ENABLED=false'+ )+ }+ return rawMode}/**@@ -345,6 +374,11 @@ function buildDevHostConfig(provider?: LlmProvider, modelName?: string): HostSpe}const devMode = getEnvBool('CLERUM_DEV_MODE', false)+const configuredWorkflowEnabled = getEnvBool('CLERUM_WORKFLOW_ENABLED', false)+const configuredRuntimeKind = resolveMcpHostRuntimeKind({+ workflowEnabled: configuredWorkflowEnabled,+ pluginWorkloadSdkRuntimeMode: getEnv('PLUGIN_WORKLOAD_SDK_RUNTIME_MODE'),+})// Raw CLERUM_MODEL_PROVIDER env var. NOT validated here: this runs at module top// level (imported very early, in prod too), so a stray/invalid value must never@@ -726,8 +760,10 @@ export const config: Config = {getEnv('TRACING_APPROVAL_PROMPT_HISTORY_MAX_BYTES', '16384')!),- // Workflow mode- workflowEnabled: getEnvBool('CLERUM_WORKFLOW_ENABLED', false),+ // Canonical runtime mode. Keep the boolean derived from the discriminant so+ // downstream code cannot observe an impossible sdk-only+workflow pairing.+ runtimeKind: configuredRuntimeKind,+ workflowEnabled: configuredRuntimeKind === 'workflow',workflowRecipeName: getEnv('CLERUM_WORKFLOW_RECIPE', '')!,userApprovalRequestRecipeName: getEnv('CLERUM_WORKFLOW_APPROVAL_RECIPE', '')!,userApprovalRequestRecipeNamespace: getEnv(@@ -755,9 +791,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(),+ // Workflow is the backwards-compatible SDK mode for workflow/standalone+ // processes; WRC explicitly sets sdk-only on the stepless adapter.+ pluginWorkloadSdkRuntimeMode: configuredRuntimeKind === 'sdk-only' ? 'sdk-only' : 'workflow',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/main.ts b/mcp-host/src/main.tsindex f38e2a152..e14597dd8 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -75,6 +75,8 @@ import {} from './mcp/authoritativeFleet'import { startMcpInitializationInBackground } from './mcpBackgroundInit'import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'+import { configurePluginWorkloadSdkBootstrapIdentity } from './pluginWorkloadSdk/bootstrapIdentity'+import { PluginWorkloadSdkBootstrapServer } from './pluginWorkloadSdk/bootstrapServer'import { maybeCreatePluginWorkloadSdkServer } from './pluginWorkloadSdk/server'import type { PluginWorkloadSdkServer } from './pluginWorkloadSdk/server/sdkServer'import { getDisplayName, sanitizeError } from './progress/intentExtraction'@@ -83,6 +85,7 @@ import { MessageQueue, Task, TaskResponsePayload } from './queue'import { ResultStore } from './resultStore'import { markFileAttachmentsDelivered } from './runtime/fileAttachmentDelivery'import { isUndeliveredResult, markResultDelivered } from './runtime/resultDelivery'+import { dispatchMcpHostRuntime } from './runtimeDispatch'import {HostActivityEvent,HostActivitySnapshotResponse,@@ -192,6 +195,7 @@ let statelessHeartbeat: StatelessHeartbeat | null = null// Null when env is absent (dev mode without HCC/WRC).let runtimeAuth: McpHostRuntimeAuth | null = nulllet pluginWorkloadSdkServer: PluginWorkloadSdkServer | null = null+let pluginWorkloadSdkBootstrapServer: PluginWorkloadSdkBootstrapServer | null = nulllet usageReporter: UsageReporter | null = nulllet governedRunReporter: GovernedRunReporter | null = null@@ -2565,6 +2569,7 @@ async function shutdown(signal: string): Promise<void> {spilloverStorage?.stopGc()await mcpClosePromiseawait mcpFleetCoordinator.drainForShutdown()+ await pluginWorkloadSdkBootstrapServer?.stop()await pluginWorkloadSdkServer?.stop()await rpcServer?.stop()@@ -2734,6 +2739,80 @@ async function startProductionMode(): Promise<void> {process.once('SIGINT', () => shutdown('SIGINT'))}+/**+ * Start the dedicated stepless Plugin Workload SDK runtime. This is neither a+ * WorkflowService nor a standalone Host: port 8080 exposes only health and the+ * WRC-authenticated public bootstrap identity, while port 8099 serves the+ * workload SDK. Prompt credentials remain behind the per-attempt WRC broker.+ */+async function startPluginWorkloadSdkOnlyMode(): Promise<void> {+ if (!config.pluginWorkloadSdkEnabled || config.pluginWorkloadSdkRuntimeMode !== 'sdk-only') {+ throw new Error(+ 'sdk-only runtime requires PLUGIN_WORKLOAD_SDK_ENABLED=true and PLUGIN_WORKLOAD_SDK_RUNTIME_MODE=sdk-only'+ )+ }++ console.log(`[Main] Starting in SDK-ONLY MODE (recipe: ${config.workflowRecipeName})`)++ if (!runtimeAuth) runtimeAuth = createMcpHostRuntimeAuth()+ if (!runtimeAuth) {+ throw new Error(+ 'sdk-only runtime requires MCP_HOST_RUNTIME_ACCESS_TOKEN, MCP_HOST_RUNTIME_REFRESH_TOKEN and MCP_HOST_GATEWAY_URL'+ )+ }+ startRuntimeAuthProactiveRefresh(runtimeAuth)++ if (!usageReporter) {+ const auth = runtimeAuth+ usageReporter = new UsageReporter({+ baseUrl: auth.baseUrl,+ getAccessToken: () => auth.accessToken,+ refreshOnUnauthorized: () => refreshWithRecovery(auth),+ })+ }++ let bootstrapContext: { provider: LlmProvider; defaultModel: string } | null = null+ pluginWorkloadSdkServer = maybeCreatePluginWorkloadSdkServer(config, runtimeAuth, {+ getLlmContext: () => bootstrapContext,+ usageReporter,+ })+ if (!pluginWorkloadSdkServer) {+ throw new Error('sdk-only runtime activation gate rejected the Plugin Workload SDK server')+ }++ await pluginWorkloadSdkServer.start()+ pluginWorkloadSdkBootstrapServer = new PluginWorkloadSdkBootstrapServer({+ port: config.serverPort,+ configure: request =>+ configurePluginWorkloadSdkBootstrapIdentity(request, {+ onConfigured: context => {+ bootstrapContext = context+ },+ verify: async (provider, model) => {+ if (!pluginWorkloadSdkServer) return null+ try {+ return await pluginWorkloadSdkServer.verifyPromptBridgeBootstrapV2(provider, model)+ } catch {+ return null+ }+ },+ }),+ })+ try {+ // Kubernetes readiness becomes reachable only after the SDK listener and+ // the bootstrap surface are both bound, preventing a Ready-but-unusable Pod.+ await pluginWorkloadSdkBootstrapServer.start()+ } catch (err) {+ await pluginWorkloadSdkServer.stop()+ pluginWorkloadSdkServer = null+ throw err+ }++ console.log('[Main] SDK-only mcp-host ready — waiting for WRC identity bootstrap')+ process.once('SIGTERM', () => shutdown('SIGTERM'))+ process.once('SIGINT', () => shutdown('SIGINT'))+}+/*** Main entry point.*/@@ -2751,9 +2830,13 @@ async function main(): Promise<void> {)process.exit(1)}- if (config.enableAuth && config.workflowEnabled && !config.wrcPublicKey) {+ if (+ config.enableAuth &&+ (config.runtimeKind === 'workflow' || config.runtimeKind === 'sdk-only') &&+ !config.wrcPublicKey+ ) {console.error(- '[Main] FATAL: enableAuth=true in workflow mode but WRC_PUBLIC_KEY_PEM is not set — refusing to start'+ `[Main] FATAL: enableAuth=true in ${config.runtimeKind} mode but WRC_PUBLIC_KEY_PEM is not set — refusing to start`)process.exit(1)}@@ -2805,7 +2888,7 @@ async function main(): Promise<void> {// Workflow approval: if workflow mode is active, all three approval env vars must be set.// Without them, steps that require approval cannot request gating from control-api.- if (config.workflowEnabled) {+ if (config.runtimeKind === 'workflow') {const missingApprovalVars: string[] = []if (!config.mcpHostRuntimeAccessToken) missingApprovalVars.push('MCP_HOST_RUNTIME_ACCESS_TOKEN')if (!config.mcpHostRuntimeRefreshToken)@@ -2822,129 +2905,132 @@ async function main(): Promise<void> {}}- // M-11: Workflow mode — skip standalone initialization entirely.- // The WRC will configure this Pod via POST /configure (apiKey, soul, model).- if (config.workflowEnabled) {- console.log(`[Main] Starting in WORKFLOW MODE (recipe: ${config.workflowRecipeName})`)-- const { WorkflowService } = await import('./workflow/workflowService')- const { McpClient } = await import('./mcp/client')-- rpcServer = new RPCServer(config.serverPort)-- // Inject a real HTTP MCP client factory so steps that declare mcpServers can- // actually connect to them. Without this, WorkflowService uses a default factory- // that always throws "No MCP client factory configured" (bug fix).- const mcpClientFactory = (server: { name: string; url: string; authToken?: string }) => {- const info = {- name: server.name,- contextRef: '',- transport: { type: 'streamableHttp' as const, url: server.url },- enabled: true,- status: { deployed: true, ready: true },- } as McpServerInfo- const client = new McpClient(info, server.authToken)- return {- connect: (options?: { timeoutMs?: number; signal?: AbortSignal }) =>- client.connect(options),- listTools: async (options?: { timeoutMs?: number; signal?: AbortSignal }) =>- (await client.listTools(options)).map(t => ({- name: t.name,- description: t.description,- inputSchema: t.inputSchema,- })),- callTool: async (- toolName: string,- args: Record<string, unknown>,- options?: { timeoutMs?: number; signal?: AbortSignal }- ) => {- const raw = await client.callTool(toolName, args, options)- return raw as { content: unknown; isError?: boolean }- },- disconnect: () => client.disconnect(),+ // M-11: Workflow mode — dispatch keeps the existing workflow startup+ // contract isolated from the stepless SDK-only runtime.+ await dispatchMcpHostRuntime(config.runtimeKind, {+ sdkOnly: startPluginWorkloadSdkOnlyMode,+ workflow: async () => {+ console.log(`[Main] Starting in WORKFLOW MODE (recipe: ${config.workflowRecipeName})`)++ const { WorkflowService } = await import('./workflow/workflowService')+ const { McpClient } = await import('./mcp/client')++ rpcServer = new RPCServer(config.serverPort)++ // Inject a real HTTP MCP client factory so steps that declare mcpServers can+ // actually connect to them. Without this, WorkflowService uses a default factory+ // that always throws "No MCP client factory configured" (bug fix).+ const mcpClientFactory = (server: { name: string; url: string; authToken?: string }) => {+ const info = {+ name: server.name,+ contextRef: '',+ transport: { type: 'streamableHttp' as const, url: server.url },+ enabled: true,+ status: { deployed: true, ready: true },+ } as McpServerInfo+ const client = new McpClient(info, server.authToken)+ return {+ connect: (options?: { timeoutMs?: number; signal?: AbortSignal }) =>+ client.connect(options),+ listTools: async (options?: { timeoutMs?: number; signal?: AbortSignal }) =>+ (await client.listTools(options)).map(t => ({+ name: t.name,+ description: t.description,+ inputSchema: t.inputSchema,+ })),+ callTool: async (+ toolName: string,+ args: Record<string, unknown>,+ options?: { timeoutMs?: number; signal?: AbortSignal }+ ) => {+ const raw = await client.callTool(toolName, args, options)+ return raw as { content: unknown; isError?: boolean }+ },+ disconnect: () => client.disconnect(),+ }}- }- // Build the shared runtime auth once so WorkflowService and any- // subsequent UsageReporter wiring share the refreshed access token.- if (!runtimeAuth) runtimeAuth = createMcpHostRuntimeAuth()- if (runtimeAuth) startRuntimeAuthProactiveRefresh(runtimeAuth)-- // Wire a UsageReporter for workflow mode so each LLM round-trip in- // executeStep ships an LlmUsageEvent (source_kind='workflow') to- // control-api. Without this the recipe's spend stays local to the- // step response and never lands in usage_events / the dashboard.- if (runtimeAuth && !usageReporter) {- const auth = runtimeAuth- usageReporter = new UsageReporter({- baseUrl: auth.baseUrl,- getAccessToken: () => auth.accessToken,- refreshOnUnauthorized: () => refreshWithRecovery(auth),- })- }-- // Plugin Workload SDK LLM binding: a push-style holder updated by- // WorkflowService.configure() — never a public getter, so the apiKey- // stays unreachable through the service's public API surface.- let pluginSdkLlmContext: {- provider: LlmProvider- defaultModel: string- } | null = null-- const workflowService = new WorkflowService(config.workflowRecipeName, {- mcpClientFactory,- runtimeAuth,- usageReporter,- onLlmConfigured: context => {- pluginSdkLlmContext = context- },- onPluginWorkloadSdkBootstrapConfigured: context => {- pluginSdkLlmContext = context- },- verifyPluginWorkloadSdkBootstrapV2: async (provider, model) => {- if (!pluginWorkloadSdkServer) return null- try {- return await pluginWorkloadSdkServer.verifyPromptBridgeBootstrapV2(provider, model)- } catch {- return null- }- },- })- rpcServer.setWorkflowService(workflowService)- wireWorkflowApprovalRuntimeRoutes(rpcServer, {- providerMessageAuthorization: handleProviderMessageAuthorization,- providerWorkflowApprovalDecision: handleProviderWorkflowApprovalDecision,- providerWorkflowApprovalResolve: handleProviderWorkflowApprovalResolve,- workflowApprovalNotificationClaim: handleWorkflowApprovalNotificationClaim,- workflowApprovalNotificationTerminal: handleWorkflowApprovalNotificationTerminal,- workflowApprovalMediumEnrollment: handleWorkflowApprovalMediumEnrollment,- telegramWorkflowApprovalVerification: handleTelegramWorkflowApprovalVerification,- })- await rpcServer.start()-- // Plugin Workload SDK: only recipe-bound mcp-hosts inside- // sandbox-recipes pass the triple activation gate; everyone else logs- // the structured reason and continues without the SDK. The LLM binding- // comes from WorkflowService (POST /configure delivers the API key).- pluginWorkloadSdkServer = maybeCreatePluginWorkloadSdkServer(config, runtimeAuth, {- getLlmContext: () => pluginSdkLlmContext,- usageReporter,- })- if (pluginWorkloadSdkServer) {- await pluginWorkloadSdkServer.start()- }+ // Build the shared runtime auth once so WorkflowService and any+ // subsequent UsageReporter wiring share the refreshed access token.+ if (!runtimeAuth) runtimeAuth = createMcpHostRuntimeAuth()+ if (runtimeAuth) startRuntimeAuthProactiveRefresh(runtimeAuth)++ // Wire a UsageReporter for workflow mode so each LLM round-trip in+ // executeStep ships an LlmUsageEvent (source_kind='workflow') to+ // control-api. Without this the recipe's spend stays local to the+ // step response and never lands in usage_events / the dashboard.+ if (runtimeAuth && !usageReporter) {+ const auth = runtimeAuth+ usageReporter = new UsageReporter({+ baseUrl: auth.baseUrl,+ getAccessToken: () => auth.accessToken,+ refreshOnUnauthorized: () => refreshWithRecovery(auth),+ })+ }- console.log('[Main] Workflow mcp-host ready — waiting for /configure from WRC')- process.once('SIGTERM', () => shutdown('SIGTERM'))- process.once('SIGINT', () => shutdown('SIGINT'))- return- }+ // Plugin Workload SDK LLM binding: a push-style holder updated by+ // WorkflowService.configure() — never a public getter, so the apiKey+ // stays unreachable through the service's public API surface.+ let pluginSdkLlmContext: {+ provider: LlmProvider+ defaultModel: string+ } | null = null++ const workflowService = new WorkflowService(config.workflowRecipeName, {+ mcpClientFactory,+ runtimeAuth,+ usageReporter,+ onLlmConfigured: context => {+ pluginSdkLlmContext = context+ },+ onPluginWorkloadSdkBootstrapConfigured: context => {+ pluginSdkLlmContext = context+ },+ verifyPluginWorkloadSdkBootstrapV2: async (provider, model) => {+ if (!pluginWorkloadSdkServer) return null+ try {+ return await pluginWorkloadSdkServer.verifyPromptBridgeBootstrapV2(provider, model)+ } catch {+ return null+ }+ },+ })+ rpcServer.setWorkflowService(workflowService)+ wireWorkflowApprovalRuntimeRoutes(rpcServer, {+ providerMessageAuthorization: handleProviderMessageAuthorization,+ providerWorkflowApprovalDecision: handleProviderWorkflowApprovalDecision,+ providerWorkflowApprovalResolve: handleProviderWorkflowApprovalResolve,+ workflowApprovalNotificationClaim: handleWorkflowApprovalNotificationClaim,+ workflowApprovalNotificationTerminal: handleWorkflowApprovalNotificationTerminal,+ workflowApprovalMediumEnrollment: handleWorkflowApprovalMediumEnrollment,+ telegramWorkflowApprovalVerification: handleTelegramWorkflowApprovalVerification,+ })+ await rpcServer.start()++ // Plugin Workload SDK: only recipe-bound mcp-hosts inside+ // sandbox-recipes pass the triple activation gate; everyone else logs+ // the structured reason and continues without the SDK. The LLM binding+ // comes from WorkflowService (POST /configure delivers the API key).+ pluginWorkloadSdkServer = maybeCreatePluginWorkloadSdkServer(config, runtimeAuth, {+ getLlmContext: () => pluginSdkLlmContext,+ usageReporter,+ })+ if (pluginWorkloadSdkServer) {+ await pluginWorkloadSdkServer.start()+ }- if (config.devMode) {- await startDevMode()- } else {- await startProductionMode()- }+ console.log('[Main] Workflow mcp-host ready — waiting for /configure from WRC')+ process.once('SIGTERM', () => shutdown('SIGTERM'))+ process.once('SIGINT', () => shutdown('SIGINT'))+ },+ standalone: async () => {+ if (config.devMode) {+ await startDevMode()+ } else {+ await startProductionMode()+ }+ },+ })}// Run main only when this module is the executable entry point. Keeping importsdiff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.tsnew file mode 100644index 000000000..8eb816f55--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.ts@@ -0,0 +1,55 @@+import { isRunnableLlmModelId } from '@clerum/llm-providers'+import { isLlmProvider } from '../llm/registryCore'+import type { LlmProvider } from '../llm/registryCore'+import type { ConfigureResponse, PluginWorkloadSdkBootstrapRequest } from '../workflow/types'+import type { PluginWorkloadSdkBootstrapProof } from './promptBridge/controlApiClient'++export interface PluginWorkloadSdkBootstrapIdentityDeps {+ onConfigured?: (context: { provider: LlmProvider; defaultModel: string }) => void+ verify?: (provider: string, model: string) => Promise<PluginWorkloadSdkBootstrapProof | null>+}++/**+ * Validate and publish the public provider/model bootstrap identity shared by+ * workflow and sdk-only hosts. Credentials are deliberately absent from this+ * contract; promptBridge resolves one credential ticket per provider attempt.+ */+export async function configurePluginWorkloadSdkBootstrapIdentity(+ req: PluginWorkloadSdkBootstrapRequest | undefined,+ deps: PluginWorkloadSdkBootstrapIdentityDeps+): Promise<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 (!isRunnableLlmModelId(model)) {+ return { configured: false, message: 'model is required and has an invalid format' }+ }+ const proof = deps.verify ? await deps.verify(req.provider, model) : null+ if (deps.verify && !proof) {+ return {+ configured: false,+ ready: false,+ contractVersion: 2,+ message: 'Plugin Workload SDK identity bootstrap contract is not ready',+ }+ }+ deps.onConfigured?.({ provider: req.provider, defaultModel: model })+ return {+ configured: true,+ ready: true,+ provider: req.provider,+ model,+ contractVersion: 2,+ ...(proof ? { policyReady: proof.policyReady, policyState: proof.policyState } : {}),+ ...(proof?.policyReason ? { policyReason: proof.policyReason } : {}),+ ...(proof?.policyRevision !== undefined ? { policyRevision: proof.policyRevision } : {}),+ ...(proof?.policyHash !== undefined ? { policyHash: proof.policyHash } : {}),+ ...(proof?.defaultTargetRef !== undefined ? { defaultTargetRef: proof.defaultTargetRef } : {}),+ ...(proof?.defaultProvider !== undefined ? { defaultProvider: proof.defaultProvider } : {}),+ ...(proof?.defaultModel !== undefined ? { defaultModel: proof.defaultModel } : {}),+ }+}diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.tsnew file mode 100644index 000000000..867adc2c1--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.test.ts@@ -0,0 +1,127 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { SignJWT, importPKCS8 } from 'jose'+import crypto from 'node:crypto'+import type http from 'node:http'+import type { AddressInfo } from 'node:net'+import { config } from '../config'+import { PluginWorkloadSdkBootstrapServer } from './bootstrapServer'++const originalEnableAuth = config.enableAuth+const originalWrcPublicKey = config.wrcPublicKey+const originalRecipe = process.env.CLERUM_WORKFLOW_RECIPE+const originalNamespace = process.env.CLERUM_WORKFLOW_NAMESPACE+let publicKeyPem: string+let privateKeyPem: string++beforeAll(() => {+ const pair = crypto.generateKeyPairSync('rsa', {+ modulusLength: 2048,+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+ })+ publicKeyPem = pair.publicKey+ privateKeyPem = pair.privateKey+})++async function signWorkflowToken(claims: Record<string, unknown>): Promise<string> {+ const key = await importPKCS8(privateKeyPem, 'RS256')+ return new SignJWT({+ sub: 'wrc',+ recipeName: 'sdk-recipe',+ recipeNamespace: 'sandbox-recipes',+ scopes: ['configure'],+ ...claims,+ })+ .setProtectedHeader({ alg: 'RS256' })+ .setIssuer('clerum-wrc')+ .setAudience('mcp-host')+ .setExpirationTime('5m')+ .sign(key)+}++describe('PluginWorkloadSdkBootstrapServer', () => {+ let server: PluginWorkloadSdkBootstrapServer | null = null++ beforeEach(() => {+ config.enableAuth = false+ })++ afterEach(async () => {+ await server?.stop()+ server = null+ config.enableAuth = originalEnableAuth+ config.wrcPublicKey = originalWrcPublicKey+ if (originalRecipe === undefined) delete process.env.CLERUM_WORKFLOW_RECIPE+ else process.env.CLERUM_WORKFLOW_RECIPE = originalRecipe+ if (originalNamespace === undefined) delete process.env.CLERUM_WORKFLOW_NAMESPACE+ else process.env.CLERUM_WORKFLOW_NAMESPACE = originalNamespace+ })++ async function start(configure = vi.fn().mockResolvedValue({ configured: true, ready: true })) {+ server = new PluginWorkloadSdkBootstrapServer({ port: 0, configure })+ await server.start()+ const listener = (server as unknown as { server: http.Server }).server+ const address = listener.address() as AddressInfo+ return { baseUrl: `http://127.0.0.1:${address.port}`, configure }+ }++ it('exposes readiness and projects bootstrap input to public identity only', async () => {+ const { baseUrl, configure } = await start()+ const health = await fetch(`${baseUrl}/v1/runtime/health`)+ expect(health.status).toBe(200)+ await expect(health.json()).resolves.toMatchObject({ mode: 'sdk-only', ready: true })++ const response = await fetch(`${baseUrl}/api/v1/workflow/plugin-workload-sdk/bootstrap`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ provider: 'openai',+ model: 'gpt-5.4-mini',+ apiKey: 'must-not-cross-the-boundary',+ }),+ })+ expect(response.status).toBe(200)+ expect(configure).toHaveBeenCalledWith({ provider: 'openai', model: 'gpt-5.4-mini' })+ })++ it('requires a configure-scoped WRC token bound to the Pod recipe', async () => {+ config.enableAuth = true+ config.wrcPublicKey = publicKeyPem+ process.env.CLERUM_WORKFLOW_RECIPE = 'sdk-recipe'+ process.env.CLERUM_WORKFLOW_NAMESPACE = 'sandbox-recipes'+ const { baseUrl, configure } = await start()+ const endpoint = `${baseUrl}/api/v1/workflow/plugin-workload-sdk/bootstrap`+ const request = (token?: string) =>+ fetch(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ },+ body: JSON.stringify({ provider: 'openai', model: 'gpt-5.4-mini' }),+ })++ expect((await request()).status).toBe(401)+ expect((await request(await signWorkflowToken({ scopes: ['execute'] }))).status).toBe(403)+ expect(+ (await request(await signWorkflowToken({ sub: 'coordinator', scopes: ['configure'] }))).status+ ).toBe(403)+ expect(+ (await request(await signWorkflowToken({ recipeName: 'different-recipe' }))).status+ ).toBe(403)+ expect((await request(await signWorkflowToken({}))).status).toBe(200)+ expect(configure).toHaveBeenCalledTimes(1)+ })++ it.each([+ '/api/v1/workflow/configure',+ '/api/v1/workflow/execute',+ '/api/v1/workflow/artifacts',+ '/v1/runtime/messages',+ '/v1/runtime/artifacts',+ ])('does not expose workflow or standalone route %s', async route => {+ const { baseUrl } = await start()+ const response = await fetch(`${baseUrl}${route}`, { method: 'POST' })+ expect(response.status).toBe(404)+ })+})diff --git a/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.tsnew file mode 100644index 000000000..f5d229f8c--- /dev/null+++ b/mcp-host/src/pluginWorkloadSdk/bootstrapServer.ts@@ -0,0 +1,118 @@+import express, { type NextFunction, type Request, type Response } from 'express'+import type http from 'node:http'+import type { ConfigureResponse, PluginWorkloadSdkBootstrapRequest } from '../workflow/types'+import {+ requireWorkflowAuth,+ validateWorkflowBinding,+ workflowClaims,+} from '../workflow/workflowAuth'++const CONTROL_RATE_LIMIT_WINDOW_MS = 60_000+const CONTROL_RATE_LIMIT_MAX = 60+const CONTROL_RATE_LIMIT_MAX_BUCKETS = 10_000++export type PluginWorkloadSdkBootstrapHandler = (+ request: PluginWorkloadSdkBootstrapRequest+) => Promise<ConfigureResponse>++export interface PluginWorkloadSdkBootstrapServerOptions {+ port: number+ configure: PluginWorkloadSdkBootstrapHandler+}++/**+ * Minimal control surface for an sdk-only mcp-host. It intentionally does not+ * construct RPCServer or WorkflowService, so workflow execution, approval,+ * artifacts, coordinator configuration and standalone chat routes are absent.+ */+export class PluginWorkloadSdkBootstrapServer {+ private readonly app = express()+ private readonly rateLimitBuckets = new Map<string, { windowStart: number; count: number }>()+ private server: http.Server | null = null++ constructor(private readonly opts: PluginWorkloadSdkBootstrapServerOptions) {+ this.app.disable('x-powered-by')+ this.app.use(express.json({ limit: '16kb' }))+ this.app.get('/v1/runtime/health', (_req, res) => {+ res.status(200).json({ status: 'healthy', mode: 'sdk-only', ready: true })+ })+ this.app.get('/v1/runtime/live', (_req, res) => {+ res.status(200).json({ status: 'alive', mode: 'sdk-only' })+ })+ this.app.post(+ '/api/v1/workflow/plugin-workload-sdk/bootstrap',+ requireWorkflowAuth('configure'),+ this.rateLimit,+ async (req, res) => {+ if (!validateWorkflowBinding(req, res, { expectedSub: 'wrc' })) return+ const raw = req.body as PluginWorkloadSdkBootstrapRequest+ // Identity-only projection: credential-shaped extras never cross the+ // handler boundary even if a caller includes them in the JSON object.+ const request: PluginWorkloadSdkBootstrapRequest = {+ provider: raw?.provider,+ model: raw?.model,+ }+ try {+ const result = await this.opts.configure(request)+ res.status(result.configured ? 200 : result.ready === false ? 503 : 400).json(result)+ } catch {+ res.status(503).json({+ configured: false,+ ready: false,+ contractVersion: 2,+ message: 'Plugin Workload SDK identity bootstrap contract is not ready',+ })+ }+ }+ )+ this.app.use((_req, res) => {+ res.status(404).json({ error: 'Not found' })+ })+ }++ private readonly rateLimit = (req: Request, res: Response, next: NextFunction): void => {+ const claims = workflowClaims(req)+ const key = claims+ ? `sdk-bootstrap:${claims.recipeNamespace}/${claims.recipeName}:${claims.sub}`+ : 'sdk-bootstrap:unauthenticated'+ const now = Date.now()+ const existing = this.rateLimitBuckets.get(key)+ const bucket =+ existing && now - existing.windowStart < CONTROL_RATE_LIMIT_WINDOW_MS+ ? existing+ : { windowStart: now, count: 0 }+ if (bucket.count >= CONTROL_RATE_LIMIT_MAX) {+ const retryAfterSeconds = Math.max(+ 1,+ Math.ceil((bucket.windowStart + 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+ this.rateLimitBuckets.set(key, bucket)+ if (this.rateLimitBuckets.size > CONTROL_RATE_LIMIT_MAX_BUCKETS) {+ const oldest = this.rateLimitBuckets.keys().next().value+ if (typeof oldest === 'string') this.rateLimitBuckets.delete(oldest)+ }+ next()+ }++ async start(): Promise<void> {+ if (this.server) throw new Error('Plugin Workload SDK bootstrap server already started')+ await new Promise<void>((resolve, reject) => {+ const server = this.app.listen(this.opts.port, '0.0.0.0', () => resolve())+ server.once('error', reject)+ this.server = server+ })+ console.log(`[PluginWorkloadSdk] SDK-only bootstrap server started on port ${this.opts.port}`)+ }++ async stop(): Promise<void> {+ const server = this.server+ if (!server) return+ this.server = null+ await new Promise<void>(resolve => server.close(() => resolve()))+ }+}diff --git a/mcp-host/src/runtimeDispatch.test.ts b/mcp-host/src/runtimeDispatch.test.tsnew file mode 100644index 000000000..ad17f67fe--- /dev/null+++ b/mcp-host/src/runtimeDispatch.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it, vi } from 'vitest'+import { dispatchMcpHostRuntime } from './runtimeDispatch'++describe('dispatchMcpHostRuntime', () => {+ it.each([+ ['standalone', 'standalone'],+ ['workflow', 'workflow'],+ ['sdk-only', 'sdkOnly'],+ ] as const)('dispatches %s to exactly its own startup branch', async (kind, expected) => {+ const starters = {+ standalone: vi.fn().mockResolvedValue(undefined),+ workflow: vi.fn().mockResolvedValue(undefined),+ sdkOnly: vi.fn().mockResolvedValue(undefined),+ }+ await dispatchMcpHostRuntime(kind, starters)+ expect(starters[expected]).toHaveBeenCalledTimes(1)+ for (const [name, starter] of Object.entries(starters)) {+ if (name !== expected) expect(starter).not.toHaveBeenCalled()+ }+ })+})diff --git a/mcp-host/src/runtimeDispatch.ts b/mcp-host/src/runtimeDispatch.tsnew file mode 100644index 000000000..44571c356--- /dev/null+++ b/mcp-host/src/runtimeDispatch.ts@@ -0,0 +1,29 @@+import type { McpHostRuntimeKind } from './config'++export interface McpHostRuntimeStarters {+ standalone: () => Promise<void>+ workflow: () => Promise<void>+ sdkOnly: () => Promise<void>+}++/** Exhaustive startup dispatch for the three disjoint mcp-host products. */+export async function dispatchMcpHostRuntime(+ kind: McpHostRuntimeKind,+ starters: McpHostRuntimeStarters+): Promise<void> {+ switch (kind) {+ case 'standalone':+ await starters.standalone()+ return+ case 'workflow':+ await starters.workflow()+ return+ case 'sdk-only':+ await starters.sdkOnly()+ return+ default: {+ const exhaustive: never = kind+ throw new Error(`Unhandled mcp-host runtime kind: ${String(exhaustive)}`)+ }+ }+}diff --git a/mcp-host/src/workflow/workflowAuth.ts b/mcp-host/src/workflow/workflowAuth.tsnew file mode 100644index 000000000..c4b51485a--- /dev/null+++ b/mcp-host/src/workflow/workflowAuth.ts@@ -0,0 +1,120 @@+import type { NextFunction, Request, Response } from 'express'+import { importSPKI, jwtVerify } from 'jose'+import { config } from '../config'++export interface WorkflowTokenClaims {+ sub: 'wrc' | 'coordinator'+ recipeName: string+ recipeNamespace?: string+ runId?: string+ artifactName?: string+ scopes: string[]+}++let cachedPublicKey: Awaited<ReturnType<typeof importSPKI>> | null = null+let cachedPem = ''++async function verifyWorkflowToken(token: string): Promise<WorkflowTokenClaims> {+ const publicKeyPem = config.wrcPublicKey+ if (!publicKeyPem) throw new Error('WRC public key not configured')++ if (!cachedPublicKey || cachedPem !== publicKeyPem) {+ cachedPublicKey = await importSPKI(publicKeyPem, 'RS256')+ cachedPem = publicKeyPem+ }+ const { payload } = await jwtVerify(token, cachedPublicKey, {+ algorithms: ['RS256'],+ issuer: 'clerum-wrc',+ audience: 'mcp-host',+ })++ if (+ typeof payload.sub !== 'string' ||+ !Array.isArray(payload['scopes']) ||+ typeof payload['recipeName'] !== 'string'+ ) {+ throw new Error('Invalid workflow token claims')+ }++ return {+ sub: payload.sub as 'wrc' | 'coordinator',+ recipeName: payload['recipeName'] as string,+ recipeNamespace:+ typeof payload['recipeNamespace'] === 'string'+ ? (payload['recipeNamespace'] as string)+ : undefined,+ runId: typeof payload['runId'] === 'string' ? (payload['runId'] as string) : undefined,+ artifactName:+ typeof payload['artifactName'] === 'string' ? (payload['artifactName'] as string) : undefined,+ scopes: payload['scopes'] as string[],+ }+}++export function requireWorkflowAuth(requiredScope: string) {+ return (req: Request, res: Response, next: NextFunction): void => {+ if (!config.enableAuth) {+ next()+ return+ }++ const header = req.headers.authorization+ if (!header?.startsWith('Bearer ')) {+ res.status(401).json({ error: 'Missing workflow auth token' })+ return+ }++ verifyWorkflowToken(header.slice(7))+ .then(claims => {+ if (!claims.scopes.includes(requiredScope)) {+ res.status(403).json({ error: `Missing scope: ${requiredScope}` })+ return+ }+ ;(req as Request & { workflowClaims: WorkflowTokenClaims }).workflowClaims = claims+ next()+ })+ .catch(() => {+ res.status(401).json({ error: 'Invalid workflow token' })+ })+ }+}++export function workflowClaims(req: Request): WorkflowTokenClaims | undefined {+ return (req as Request & { workflowClaims?: WorkflowTokenClaims }).workflowClaims+}++export function validateWorkflowBinding(+ req: Request,+ res: Response,+ options: { expectedSub?: WorkflowTokenClaims['sub'] } = {}+): WorkflowTokenClaims | null {+ if (!config.enableAuth) return workflowClaims(req) ?? ({} as WorkflowTokenClaims)++ const claims = workflowClaims(req)+ const expectedRecipe = process.env.CLERUM_WORKFLOW_RECIPE ?? ''+ const expectedNamespace = process.env.CLERUM_WORKFLOW_NAMESPACE ?? ''+ if (!claims) {+ res.status(401).json({ error: 'Missing workflow auth token' })+ return null+ }+ if (!expectedRecipe) {+ res.status(500).json({ error: 'Workflow recipe not configured' })+ return null+ }+ if (!expectedNamespace) {+ res.status(500).json({ error: 'Workflow namespace not configured' })+ return null+ }+ if (options.expectedSub && claims.sub !== options.expectedSub) {+ res.status(403).json({ error: `Endpoint requires sub: ${options.expectedSub}` })+ return null+ }+ if (claims.recipeName !== expectedRecipe) {+ res.status(403).json({ error: 'recipeName mismatch' })+ return null+ }+ if (claims.recipeNamespace !== expectedNamespace) {+ res.status(403).json({ error: 'recipeNamespace mismatch' })+ return null+ }+ return claims+}diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.tsindex 6c1d3c8b2..e9a62e848 100644--- a/mcp-host/src/workflow/workflowRouter.ts+++ b/mcp-host/src/workflow/workflowRouter.ts@@ -14,9 +14,7 @@*/import { NextFunction, Request, Response, Router } from 'express'import * as fs from 'fs'-import { importSPKI, jwtVerify } from 'jose'import * as path from 'path'-import { config } from '../config'import {ArtifactPathError,type OpenedArtifactFile,@@ -26,144 +24,9 @@ import {} from './artifactPaths'import { getOutputDir } from './internalTools'import { ConfigureRequest, ExecuteStepRequest, PluginWorkloadSdkBootstrapRequest } from './types'+import { requireWorkflowAuth, validateWorkflowBinding, workflowClaims } from './workflowAuth'import { WorkflowService } from './workflowService'-// ─── V1 fix: JWT auth middleware for workflow endpoints ──────────────────-// Workflow tokens are signed by WRC (iss: clerum-wrc, aud: mcp-host) using-// the WRC private key. This is separate from the general mcp-host auth tokens-// (iss: control-api) — different signer, different trust boundary.--interface WorkflowTokenClaims {- sub: 'wrc' | 'coordinator'- recipeName: string- recipeNamespace?: string- runId?: string- artifactName?: string- scopes: string[]-}--// SEC-04 fix: cache the imported SPKI key to avoid per-request PEM parsing.-// Cache is keyed to PEM value so key rotation (Secret update + Pod restart) is handled.-let cachedPublicKey: Awaited<ReturnType<typeof importSPKI>> | null = null-let cachedPem = ''--async function verifyWorkflowToken(token: string): Promise<WorkflowTokenClaims> {- const publicKeyPem = config.wrcPublicKey- if (!publicKeyPem) throw new Error('WRC public key not configured')-- if (!cachedPublicKey || cachedPem !== publicKeyPem) {- cachedPublicKey = await importSPKI(publicKeyPem, 'RS256')- cachedPem = publicKeyPem- }- const { payload } = await jwtVerify(token, cachedPublicKey, {- algorithms: ['RS256'],- issuer: 'clerum-wrc',- audience: 'mcp-host',- })-- if (- typeof payload.sub !== 'string' ||- !Array.isArray(payload['scopes']) ||- typeof payload['recipeName'] !== 'string'- ) {- throw new Error('Invalid workflow token claims')- }-- return {- sub: payload.sub as 'wrc' | 'coordinator',- recipeName: payload['recipeName'] as string,- recipeNamespace:- typeof payload['recipeNamespace'] === 'string'- ? (payload['recipeNamespace'] as string)- : undefined,- runId: typeof payload['runId'] === 'string' ? (payload['runId'] as string) : undefined,- artifactName:- typeof payload['artifactName'] === 'string' ? (payload['artifactName'] as string) : undefined,- scopes: payload['scopes'] as string[],- }-}--// Supported workflow scopes, all emitted exclusively by WRC (iss: clerum-wrc).-// The middleware itself is generic — any string is accepted — but this list-// documents the authoritative vocabulary and lets reviewers grep for callers.-//-// configure - POST /configure (sub: wrc, long-lived Secret)-// execute - POST /execute (sub: coordinator, per-step token)-// mode_read - GET /mode (sub: *, read-only)-// health:read - GET /runtime/* (sub: *, read-only)-// kill_switch:write - POST /kill-switch (sub: wrc)-// status_read - GET /status (sub: *)-// artifact_read - GET /artifacts/: (sub: wrc, 60s TTL)-// artifact_delete - DELETE /artifacts (sub: wrc, 60s TTL, cleanup)-function requireWorkflowAuth(requiredScope: string) {- return (req: Request, res: Response, next: NextFunction): void => {- if (!config.enableAuth) {- next()- return- }-- const header = req.headers.authorization- if (!header?.startsWith('Bearer ')) {- res.status(401).json({ error: 'Missing workflow auth token' })- return- }-- verifyWorkflowToken(header.slice(7))- .then(claims => {- if (!claims.scopes.includes(requiredScope)) {- res.status(403).json({ error: `Missing scope: ${requiredScope}` })- return- }- ;(req as Request & { workflowClaims: WorkflowTokenClaims }).workflowClaims = claims- next()- })- .catch(() => {- res.status(401).json({ error: 'Invalid workflow token' })- })- }-}--function workflowClaims(req: Request): WorkflowTokenClaims | undefined {- return (req as Request & { workflowClaims?: WorkflowTokenClaims }).workflowClaims-}--function validateWorkflowBinding(- req: Request,- res: Response,- options: { expectedSub?: WorkflowTokenClaims['sub'] } = {}-): WorkflowTokenClaims | null {- if (!config.enableAuth) return workflowClaims(req) ?? ({} as WorkflowTokenClaims)-- const claims = workflowClaims(req)- const expectedRecipe = process.env.CLERUM_WORKFLOW_RECIPE ?? ''- const expectedNamespace = process.env.CLERUM_WORKFLOW_NAMESPACE ?? ''- if (!claims) {- res.status(401).json({ error: 'Missing workflow auth token' })- return null- }- if (!expectedRecipe) {- res.status(500).json({ error: 'Workflow recipe not configured' })- return null- }- if (!expectedNamespace) {- res.status(500).json({ error: 'Workflow namespace not configured' })- return null- }- if (options.expectedSub && claims.sub !== options.expectedSub) {- res.status(403).json({ error: `Endpoint requires sub: ${options.expectedSub}` })- return null- }- if (claims.recipeName !== expectedRecipe) {- res.status(403).json({ error: 'recipeName mismatch' })- return null- }- if (claims.recipeNamespace !== expectedNamespace) {- res.status(403).json({ error: 'recipeNamespace mismatch' })- return null- }- return claims-}-const EXECUTE_HEARTBEAT_MS = 15_000const WORKFLOW_CONTROL_RATE_LIMIT_WINDOW_MS = 60_000const WORKFLOW_CONTROL_RATE_LIMIT_MAX = 60diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.tsindex 02dc963fd..647be87c1 100644--- a/mcp-host/src/workflow/workflowService.ts+++ b/mcp-host/src/workflow/workflowService.ts@@ -7,7 +7,6 @@* - 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'@@ -17,6 +16,7 @@ import { buildGfsReadTools, buildGfsWriteTools } from '../internalTools/gfs'import { createGfscClient, hasGfsRuntimeAccess } from '../internalTools/gfsClient'import { SingleTurnProvider, createLLMProvider } from '../llm'import { type LlmProvider, descriptorFor, isLlmProvider, primarySlot } from '../llm/registryCore'+import { configurePluginWorkloadSdkBootstrapIdentity } from '../pluginWorkloadSdk/bootstrapIdentity'import type { PluginWorkloadSdkBootstrapProof } from '../pluginWorkloadSdk/promptBridge/controlApiClient'import type { ApiKeys } from '../types'import { type LlmUsageEvent, type UsageReporter, newRequestId } from '../usage/usageReporter'@@ -366,47 +366,14 @@ export class WorkflowService {async configurePluginWorkloadSdkBootstrap(req?: PluginWorkloadSdkBootstrapRequest): Promise<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 (!isRunnableLlmModelId(model)) {- return { configured: false, message: 'model is required and has an invalid format' }- }- const proof = this.verifyPluginWorkloadSdkBootstrapV2- ? await this.verifyPluginWorkloadSdkBootstrapV2(req.provider, model)- : null- if (this.verifyPluginWorkloadSdkBootstrapV2 && !proof) {- return {- configured: false,- ready: false,- contractVersion: 2,- message: 'Plugin Workload SDK identity bootstrap contract is not ready',- }- }- this.onPluginWorkloadSdkBootstrapConfigured?.({- provider: req.provider as import('../types').ModelConfig['provider'],- defaultModel: model,- })- return {- configured: true,- ready: true,- provider: req.provider,- model,- contractVersion: 2,- ...(proof ? { policyReady: proof.policyReady, policyState: proof.policyState } : {}),- ...(proof?.policyReason ? { policyReason: proof.policyReason } : {}),- ...(proof?.policyRevision !== undefined ? { policyRevision: proof.policyRevision } : {}),- ...(proof?.policyHash !== undefined ? { policyHash: proof.policyHash } : {}),- ...(proof?.defaultTargetRef !== undefined- ? { defaultTargetRef: proof.defaultTargetRef }+ return configurePluginWorkloadSdkBootstrapIdentity(req, {+ ...(this.onPluginWorkloadSdkBootstrapConfigured+ ? { onConfigured: this.onPluginWorkloadSdkBootstrapConfigured }: {}),- ...(proof?.defaultProvider !== undefined ? { defaultProvider: proof.defaultProvider } : {}),- ...(proof?.defaultModel !== undefined ? { defaultModel: proof.defaultModel } : {}),- }+ ...(this.verifyPluginWorkloadSdkBootstrapV2+ ? { verify: this.verifyPluginWorkloadSdkBootstrapV2 }+ : {}),+ })}isReady(): boolean {diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 9b9f870de..616c3b6ea 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.262",+ "version": "0.1.263","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.262",+ "version": "0.1.263","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 96809a20c..44550fa70 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.262",+ "version": "0.1.263","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.tsindex 0145b1417..c44cdeae6 100644--- a/workflow-recipes/src/reconciler/reconciler.test.ts+++ b/workflow-recipes/src/reconciler/reconciler.test.ts@@ -259,6 +259,15 @@ describe('WorkflowRecipeReconciler', () => {const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({phase: 'active',message: 'Plugin Workload SDK mcp-host registered',+ pluginWorkloadSdkBootstrapProof: {+ ready: true,+ contractVersion: 2,+ podUid: 'sdk-pod-uid',+ provider: 'zai',+ model: 'glm-4.7',+ policyReady: true,+ verifiedAt: '2026-08-04T00:00:00.000Z',+ },})const workflowReconcile = vi.fn();(@@ -299,6 +308,44 @@ describe('WorkflowRecipeReconciler', () => {expect(workflowReconcile).not.toHaveBeenCalled()})+ it('never settles promptBridge active when the SDK adapter omits bootstrap proof', async () => {+ const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({+ phase: 'active',+ message: 'Plugin Workload SDK mcp-host registered',+ })+ ;(+ 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 bootstrap identity proof pending',+ requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,+ })+ })+it('keeps an SDK-only recipe deploying and requeues while the eager host boots', async () => {const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({phase: 'deploying',diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex d7c6801de..3bd2d3379 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -2362,6 +2362,14 @@ export class WorkflowRecipeReconciler {: undefinedsdkOnlyProviderUnavailable = sdkOnlyRuntime?.phase === 'provider_unavailable'const sdkOnlyPolicyPending = sdkOnlyRuntime?.phase === 'awaiting_policy'+ // Defense in depth: an active promptBridge recipe is impossible without+ // a fresh v2 proof tied to the eager Pod. Keep the recipe in a progress+ // phase if an adapter regression ever omits it; never publish+ // active+BootstrapNotReady as a settled state.+ const sdkOnlyBootstrapPending =+ sdkOnlyRuntime?.phase === 'active' &&+ recipe.spec.pluginWorkloadSdk?.promptBridge !== undefined &&+ sdkOnlyRuntime.pluginWorkloadSdkBootstrapProof?.ready !== trueif (sdkOnlyRuntime?.phase === 'failed') {return {phase: 'failed',@@ -2378,9 +2386,10 @@ export class WorkflowRecipeReconciler {workloadStatuses.every(ws => ws.ready) &&webhookHealthy &&sdkOnlyRuntime?.phase !== 'deploying' &&- sdkOnlyRuntime?.phase !== 'provider_unavailable'+ sdkOnlyRuntime?.phase !== 'provider_unavailable' &&+ !sdkOnlyBootstrapPendinglet finalPhase: RecipePhase- if (sdkOnlyRuntime?.phase === 'deploying') {+ if (sdkOnlyRuntime?.phase === 'deploying' || sdkOnlyBootstrapPending) {// 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.@@ -2403,8 +2412,10 @@ export class WorkflowRecipeReconciler {? sdkOnlyRuntime.message: sdkOnlyPolicyPending? sdkOnlyRuntime.message- : sdkOnlyRuntime?.phase === 'deploying'- ? sdkOnlyRuntime.message+ : sdkOnlyRuntime?.phase === 'deploying' || sdkOnlyBootstrapPending+ ? sdkOnlyBootstrapPending+ ? 'Plugin Workload SDK bootstrap identity proof pending'+ : sdkOnlyRuntime.message: !allReady && !webhookHealthy? (webhookOutcome.message ?? 'Webhook gateway not ready'): allReady@@ -2430,7 +2441,8 @@ export class WorkflowRecipeReconciler {deniedTeardownFailed ||sdkOnlyRuntime?.phase === 'deploying' ||sdkOnlyRuntime?.phase === 'provider_unavailable' ||- sdkOnlyPolicyPending+ sdkOnlyPolicyPending ||+ sdkOnlyBootstrapPending? TRANSIENT_REQUEUE_BASE_MS: undefined,requeueFixedInterval: sdkOnlyPolicyPending,diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.tsindex 8bc9b09d2..ef87dbd69 100644--- a/workflow-recipes/src/workflow/podFactory.ts+++ b/workflow-recipes/src/workflow/podFactory.ts@@ -568,6 +568,10 @@ export function buildMcpHostPod(options: McpHostPodOptions): k8s.V1Pod {const mountWorkflowOutput = options.mountWorkflowOutput+ const runtimeMode = options.pluginWorkloadSdkRuntimeMode ?? 'workflow'+ if (runtimeMode === 'sdk-only' && options.pluginWorkloadSdkEnabled !== true) {+ throw new Error('sdk-only mcp-host runtime requires pluginWorkloadSdkEnabled=true')+ }if (mountWorkflowOutput && !workflowOutputClaimName) {throw new Error('workflowOutputClaimName is required for workflow mcp-host pods')}@@ -622,7 +626,10 @@ export function buildMcpHostPod(capabilities: { drop: ['ALL'] },},env: [- { name: 'CLERUM_WORKFLOW_ENABLED', value: 'true' },+ {+ name: 'CLERUM_WORKFLOW_ENABLED',+ value: runtimeMode === 'workflow' ? 'true' : 'false',+ },{ name: 'CLERUM_HOST_NAME', value: `${config.sandboxNamespace}/${recipeName}` },{ name: 'CLERUM_WORKFLOW_RECIPE', value: recipeName },{ name: 'CLERUM_WORKFLOW_NAMESPACE', value: config.sandboxNamespace },@@ -714,7 +721,7 @@ export function buildMcpHostPod({ name: 'PLUGIN_WORKLOAD_SDK_ENABLED', value: 'true' },{name: 'PLUGIN_WORKLOAD_SDK_RUNTIME_MODE',- value: options.pluginWorkloadSdkRuntimeMode ?? 'workflow',+ value: runtimeMode,},{name: 'PLUGIN_WORKLOAD_SDK_WORKLOAD_TOKENS_DIR',diff --git a/workflow-recipes/tests/unit/workflow/podFactory.test.ts b/workflow-recipes/tests/unit/workflow/podFactory.test.tsindex 5ae47cef4..c94b8ffbc 100644--- a/workflow-recipes/tests/unit/workflow/podFactory.test.ts+++ b/workflow-recipes/tests/unit/workflow/podFactory.test.ts@@ -472,6 +472,43 @@ describe('Pod Factory', () => {expect(env!.value).toBe('true')})+ it('derives a non-workflow process contract for sdk-only eager hosts', () => {+ const sdkOnlyPod = buildMcpHostPod(+ 'sdk-only',+ agent,+ config,+ 'sdk-only',+ 'sandbox-recipes',+ undefined,+ undefined,+ undefined,+ {+ mountWorkflowOutput: false,+ pluginWorkloadSdkEnabled: true,+ pluginWorkloadSdkRuntimeMode: 'sdk-only',+ }+ )+ const env = sdkOnlyPod.spec!.containers![0].env!+ expect(env.find(e => e.name === 'CLERUM_WORKFLOW_ENABLED')?.value).toBe('false')+ expect(env.find(e => e.name === 'PLUGIN_WORKLOAD_SDK_RUNTIME_MODE')?.value).toBe('sdk-only')+ })++ it('rejects sdk-only mode when the SDK runtime is not enabled', () => {+ expect(() =>+ buildMcpHostPod(+ 'sdk-only',+ agent,+ config,+ 'sdk-only',+ 'sandbox-recipes',+ undefined,+ undefined,+ undefined,+ { mountWorkflowOutput: false, pluginWorkloadSdkRuntimeMode: 'sdk-only' }+ )+ ).toThrow(/sdk-only mcp-host runtime requires pluginWorkloadSdkEnabled=true/)+ })+it('binds workflow identity env used by mcp-host artifact JWT checks', () => {const env = pod.spec!.containers![0].env!expect(env.find(e => e.name === 'CLERUM_WORKFLOW_RECIPE')?.value).toBe('my-wf')