Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): wire llm-lane port decorator + prompt-shaping built-in (phase 2)
Andy Paviabb99a556da1f
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex a62cdc464..8519e148d 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.238",+ "version": "0.1.239","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.238",+ "version": "0.1.239","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 2b209bb31..2dcb39dec 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.238",+ "version": "0.1.239","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.tsindex a91d6d094..ddaaa086d 100644--- a/mcp-host/src/agent/taskExecutor.ts+++ b/mcp-host/src/agent/taskExecutor.ts@@ -9,6 +9,7 @@ import { snapshotTaskTokenBaseline } from '../budget/taskBrake'import type { TaskTokenBaseline } from '../budget/taskBrake'import { config as appConfig } from '../config'import { maybeWrapFailover } from '../core/adapters/failoverLlmPort'+import { maybeWrapHookedLlmPort } from '../core/adapters/hookedLlmPort'import { AdapterStaticContext, LlmPortAdapter } from '../core/adapters/llmPortAdapter'import { CompositeToolRegistry, McpToolRegistryAdapter } from '../core/adapters/toolRegistryAdapter'import { compactConversation } from '../core/conversation/compaction'@@ -1101,6 +1102,10 @@ export class TaskExecutor {// usage sink + a per-pair token counter) so `usage_events` records the pair// really served. No policy → returns `llmPort` unchanged (byte-identical).const effectiveLlmPort = this.wrapFailoverPort(llmPort, conversation)+ // LLM-lane guardrails (spec §7): wrap ABOVE failover so built-in request+ // shaping fires once per logical request, not per fallback attempt. Inert+ // (returns the port unchanged) when no built-ins are configured (§5).+ const hookedLlmPort = maybeWrapHookedLlmPort(effectiveLlmPort, this.deps.guardrailsConfig)const metadata: Record<string, unknown> = {}if (this.task.sourceMessage) {@@ -1120,7 +1125,7 @@ export class TaskExecutor {// out-of-band through `ReasoningPort`. Otherwise fall back to the legacy// single-string identity built by `buildSystemIdentity`.const reasoningFactory = new DefaultReasoningFactory(- effectiveLlmPort,+ hookedLlmPort,undefined,metadata,// F1.4 — wire the send-time context-window-breakdown capture. The sink is@@ -1138,7 +1143,7 @@ export class TaskExecutor {const contextManager = new PressureContextManager(this.contextMaxTokens(),this.deps.workspaceService,- effectiveLlmPort,+ hookedLlmPort,tokenCounter,{dryRun: appConfig.tokenizerDryrun,diff --git a/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.tsnew file mode 100644index 000000000..3e872a182--- /dev/null+++ b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts@@ -0,0 +1,63 @@+/**+ * HookedLlmPort tests (spec §7): main-lane shaping on completeWithTools, aux-lane+ * passthrough on complete, and inert wrapping when no built-ins are configured.+ */+import { describe, expect, it, vi } from 'vitest'+import type { LlmPort } from '../../interfaces'+import type { ToolCompletionRequest } from '../../types'+import { HookedLlmPort, maybeWrapHookedLlmPort } from '../hookedLlmPort'++function fakePort(): LlmPort & {+ lastToolReq?: ToolCompletionRequest+ complete: ReturnType<typeof vi.fn>+} {+ const p = {+ lastToolReq: undefined as ToolCompletionRequest | undefined,+ modelName: () => 'm',+ getTokenCounter: () => ({}) as never,+ complete: vi.fn(async () => ({ content: 'aux', usage: {}, finish_reason: 'stop' }) as never),+ completeWithTools: vi.fn(async (r: ToolCompletionRequest) => {+ p.lastToolReq = r+ return { content: 'main', tool_calls: null, usage: {}, finish_reason: 'stop' } as never+ }),+ }+ return p as LlmPort & { lastToolReq?: ToolCompletionRequest; complete: ReturnType<typeof vi.fn> }+}++describe('HookedLlmPort', () => {+ it('applies main-lane shaping on completeWithTools', async () => {+ const inner = fakePort()+ const hooked = new HookedLlmPort(inner, r => ({ ...r, temperature: 0.2 }))+ await hooked.completeWithTools({ messages: [], tools: [] })+ expect(inner.lastToolReq?.temperature).toBe(0.2)+ })++ it('passes complete (aux lane) through unshaped', async () => {+ const inner = fakePort()+ const hooked = new HookedLlmPort(inner, r => ({ ...r, temperature: 0.2 }))+ await hooked.complete({ messages: [] })+ expect(inner.complete).toHaveBeenCalledTimes(1)+ })++ it('delegates modelName', () => {+ const hooked = new HookedLlmPort(fakePort(), r => r)+ expect(hooked.modelName()).toBe('m')+ })+})++describe('maybeWrapHookedLlmPort', () => {+ it('returns the port unchanged when no built-ins (inert)', () => {+ const inner = fakePort()+ expect(maybeWrapHookedLlmPort(inner, undefined)).toBe(inner)+ expect(maybeWrapHookedLlmPort(inner, { builtins: [] })).toBe(inner)+ })++ it('wraps when built-ins are configured', () => {+ const inner = fakePort()+ const wrapped = maybeWrapHookedLlmPort(inner, {+ builtins: [{ type: 'prompt-shaping', config: { temperature: 0.1 } }],+ })+ expect(wrapped).not.toBe(inner)+ expect(wrapped).toBeInstanceOf(HookedLlmPort)+ })+})diff --git a/mcp-host/src/core/adapters/hookedLlmPort.ts b/mcp-host/src/core/adapters/hookedLlmPort.tsnew file mode 100644index 000000000..4ae26ca7e--- /dev/null+++ b/mcp-host/src/core/adapters/hookedLlmPort.ts@@ -0,0 +1,64 @@+/**+ * HookedLlmPort — the LLM-lane guardrail boundary (spec §7), an `LlmPort`+ * decorator wrapping the effective port **above failover** so contributors fire+ * once per logical request, not per fallback attempt.+ *+ * Phase 2 (increment 1): applies the first-party built-in request-shaping chain+ * (`prompt-shaping`) on the MAIN lane (`completeWithTools`). The aux/compaction+ * lane (`complete`) runs the REDUCED set — no guardrail/PII (spec §7.4) — which+ * in this increment is a passthrough. Moderation (concurrent with the call),+ * `on_error` recovery, and installed hooks are later increments / Phase 3.+ */+import type { GuardrailsConfig } from '../guardrails'+import { type RequestShaper, buildLlmBuiltinChain } from '../guardrails/llm/builtinChain'+import type { LlmPort } from '../interfaces'+import type { TokenCounter } from '../tokenizer/tokenCounter'+import type {+ CompletionRequest,+ CompletionResponse,+ ToolCompletionRequest,+ ToolCompletionResponse,+} from '../types'++export class HookedLlmPort implements LlmPort {+ constructor(+ private readonly inner: LlmPort,+ private readonly shapeMainLane: RequestShaper+ ) {}++ modelName(): string {+ return this.inner.modelName()+ }++ getTokenCounter(): TokenCounter {+ const counter = this.inner.getTokenCounter?.()+ if (!counter) {+ throw new Error('[HookedLlmPort] inner port has no token counter — wiring bug')+ }+ return counter+ }++ /** Aux/compaction lane (spec §7.4): reduced set. Increment 1 = passthrough. */+ complete(request: CompletionRequest): Promise<CompletionResponse> {+ return this.inner.complete(request)+ }++ /** Main lane (spec §7): apply the built-in `pre` request shaping, then dispatch. */+ completeWithTools(request: ToolCompletionRequest): Promise<ToolCompletionResponse> {+ return this.inner.completeWithTools(this.shapeMainLane(request))+ }+}++/**+ * Wrap the effective (post-failover) port with the LLM-lane guardrails when any+ * built-ins are configured; otherwise return it unchanged (no-config+ * compatibility, spec §5 — no extra decorator layer when unused).+ */+export function maybeWrapHookedLlmPort(+ port: LlmPort,+ config: GuardrailsConfig | undefined+): LlmPort {+ // No built-ins → no decorator layer (byte-identical to today).+ if (!config?.builtins || config.builtins.length === 0) return port+ return new HookedLlmPort(port, buildLlmBuiltinChain(config.builtins))+}diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.tsindex c71aaf858..0699d26ef 100644--- a/mcp-host/src/core/guardrails/index.ts+++ b/mcp-host/src/core/guardrails/index.ts@@ -23,4 +23,8 @@ export { resolveToolIdentity, resolveToolIdentityFromRegistry } from './tool/proexport type { ToolIdentity } from './tool/provenance'export { recordAndCheck } from './tool/doomLoop'export type { DoomLoopState } from './tool/doomLoop'+export { buildLlmBuiltinChain } from './llm/builtinChain'+export type { BuiltinItem, RequestShaper } from './llm/builtinChain'+export { applyPromptShaping } from './llm/builtins/promptShaping'+export type { PromptShapingConfig } from './llm/builtins/promptShaping'export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'diff --git a/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts b/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.tsnew file mode 100644index 000000000..37137266f--- /dev/null+++ b/mcp-host/src/core/guardrails/llm/__tests__/builtinChain.test.ts@@ -0,0 +1,48 @@+/**+ * LLM-lane built-in chain tests (spec §7.2): prompt-shaping param forcing + order.+ */+import { describe, expect, it } from 'vitest'+import type { ToolCompletionRequest } from '../../../types'+import { buildLlmBuiltinChain } from '../builtinChain'++const req = (): ToolCompletionRequest => ({ messages: [], tools: [] })++describe('buildLlmBuiltinChain', () => {+ it('identity shaper when no built-ins (no-config compatibility)', () => {+ const r = req()+ expect(buildLlmBuiltinChain(undefined)(r)).toEqual(r)+ expect(buildLlmBuiltinChain([])(r)).toEqual(r)+ })++ it('prompt-shaping forces temperature/max_tokens/tool_choice', () => {+ const shape = buildLlmBuiltinChain([+ { type: 'prompt-shaping', config: { temperature: 0.1, maxTokens: 500, toolChoice: 'auto' } },+ ])+ const out = shape(req())+ expect(out.temperature).toBe(0.1)+ expect(out.max_tokens).toBe(500)+ expect(out.tool_choice).toBe('auto')+ })++ it('applies built-ins in ascending order', () => {+ const shape = buildLlmBuiltinChain([+ { type: 'prompt-shaping', order: 20, config: { temperature: 0.9 } },+ { type: 'prompt-shaping', order: 10, config: { temperature: 0.1, maxTokens: 100 } },+ ])+ const out = shape(req())+ expect(out.temperature).toBe(0.9) // order 20 (later) wins for temperature+ expect(out.max_tokens).toBe(100) // only order 10 set it+ })++ it('does not mutate the input request', () => {+ const shape = buildLlmBuiltinChain([{ type: 'prompt-shaping', config: { temperature: 0.5 } }])+ const r = req()+ shape(r)+ expect(r.temperature).toBeUndefined()+ })++ it('skips unknown built-in types', () => {+ const r = req()+ expect(buildLlmBuiltinChain([{ type: 'token-trim' }])(r)).toEqual(r) // not yet implemented → no-op+ })+})diff --git a/mcp-host/src/core/guardrails/llm/builtinChain.ts b/mcp-host/src/core/guardrails/llm/builtinChain.tsnew file mode 100644index 000000000..0736251cf--- /dev/null+++ b/mcp-host/src/core/guardrails/llm/builtinChain.ts@@ -0,0 +1,54 @@+/**+ * LLM-lane built-in chain (spec §7.2/§7.3).+ *+ * First-party, in-process `pre` rewrite contributors selected + ordered by+ * `Host.spec.guardrails.builtins` (spec §5). Phase 2 (increment 1) ships+ * `prompt-shaping`; `token-trim` (reusing `core/extensions/prePrune.ts`) lands+ * in a later increment. Installed hooks (moderation/PII/`on_error`) are Phase 3.+ */+import type { ToolCompletionRequest } from '../../types'+import { type PromptShapingConfig, applyPromptShaping } from './builtins/promptShaping'++/** One entry of `guardrails.builtins[]` (spec §7.2). */+export interface BuiltinItem {+ type: 'prompt-shaping' | 'token-trim'+ order?: number+ failMode?: 'open' | 'closed'+ timeoutMs?: number+ config?: Record<string, unknown>+}++/** A pure request-shaping function (the composed built-in chain). */+export type RequestShaper = (request: ToolCompletionRequest) => ToolCompletionRequest++const IDENTITY: RequestShaper = r => r++function isBuiltinItem(v: unknown): v is BuiltinItem {+ return !!v && typeof v === 'object' && (v as BuiltinItem).type !== undefined+}++/**+ * Compose the configured built-ins into a single ordered request shaper. Returns+ * an identity shaper when none are configured (no-config compatibility, spec §5).+ * Unknown built-in types are skipped (they are validated at admission in prod).+ */+export function buildLlmBuiltinChain(builtins: unknown[] | undefined): RequestShaper {+ if (!builtins || builtins.length === 0) return IDENTITY++ const items = builtins+ .filter(isBuiltinItem)+ .slice()+ .sort((a, b) => (a.order ?? 100) - (b.order ?? 100))++ const shapers: RequestShaper[] = []+ for (const item of items) {+ if (item.type === 'prompt-shaping') {+ const cfg = (item.config ?? {}) as PromptShapingConfig+ shapers.push(req => applyPromptShaping(req, cfg))+ }+ // TODO(phase2): item.type === 'token-trim' → reuse prePrune (§7.2).+ }++ if (shapers.length === 0) return IDENTITY+ return request => shapers.reduce((req, shape) => shape(req), request)+}diff --git a/mcp-host/src/core/guardrails/llm/builtins/promptShaping.ts b/mcp-host/src/core/guardrails/llm/builtins/promptShaping.tsnew file mode 100644index 000000000..119918d39--- /dev/null+++ b/mcp-host/src/core/guardrails/llm/builtins/promptShaping.ts@@ -0,0 +1,34 @@+/**+ * `prompt-shaping` built-in (spec §7.2) — a first-party, in-process `pre` rewrite+ * contributor for the LLM lane.+ *+ * Phase 2 (increment 1): forces `temperature` / `max_tokens` / `tool_choice` on+ * the request. These are currently unset on the main reasoning lane, so this is+ * additive. System-prompt-part injection is deferred (it entangles with the+ * tiered `SystemPromptParts` cache — see `reasoning/port.ts:buildMessages`).+ */+import type { ToolCompletionRequest } from '../../../types'++export interface PromptShapingConfig {+ /** Force the sampling temperature. */+ temperature?: number+ /** Force the max output tokens. */+ maxTokens?: number+ /** Force tool-choice mode. */+ toolChoice?: 'auto' | 'none' | 'required'+ /** TODO(phase2): inject a system prompt part (needs SystemPromptParts handling). */+ systemPromptPart?: string+}++/** Apply prompt-shaping to a completion request, returning a new request. */+export function applyPromptShaping(+ request: ToolCompletionRequest,+ config: PromptShapingConfig+): ToolCompletionRequest {+ const shaped: ToolCompletionRequest = { ...request }+ if (config.temperature !== undefined) shaped.temperature = config.temperature+ if (config.maxTokens !== undefined) shaped.max_tokens = config.maxTokens+ if (config.toolChoice !== undefined) shaped.tool_choice = config.toolChoice+ // TODO(phase2): if config.systemPromptPart, inject it into systemPromptParts.+ return shaped+}