Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
perf(guardrails): run llm-lane moderation concurrently with the model call
Andy Paviaff221d3fdac9
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex ba135dd08..eb3509021 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.246",+ "version": "0.1.247","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.246",+ "version": "0.1.247","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 0c8c0791f..6c0b6046d 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.246",+ "version": "0.1.247","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.tsindex e17643847..08eb176d8 100644--- a/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts+++ b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts@@ -58,7 +58,7 @@ describe('installed hooks (end-to-end via HookedLlmPort)', () => {...over,})- it('a moderate deny returns a filtered response WITHOUT calling the model', async () => {+ it('a moderate deny returns a filtered response and aborts the in-flight call (§7.1)', async () => {const inner = fakePort()const moderateDeny: FetchLike = async url => ({status: url.endsWith('/v1/moderate') ? 422 : 200,@@ -74,7 +74,36 @@ describe('installed hooks (end-to-end via HookedLlmPort)', () => {const hooked = new HookedLlmPort(inner, r => r, hooks)const res = await hooked.completeWithTools({ messages: [], tools: [] })expect(res.finish_reason).toBe('content_filter')- expect(vi.mocked(inner.completeWithTools)).not.toHaveBeenCalled()+ // Concurrent: the call is launched, then the moderation deny aborts it.+ expect(vi.mocked(inner.completeWithTools)).toHaveBeenCalledTimes(1)+ expect(inner.lastToolReq?.signal?.aborted).toBe(true)+ })++ it('moderation runs concurrently with the call; a pass proceeds to the result', async () => {+ const inner = fakePort()+ const moderatePass: FetchLike = async () => ({ status: 200, text: async () => '{}' })+ const hooks = buildLlmLaneHooks(+ [dscr({ lifecyclePoints: ['moderate'], capabilities: ['may_deny'] })],+ { getAuthToken: () => '', fetchImpl: moderatePass }+ )+ const hooked = new HookedLlmPort(inner, r => r, hooks)+ const res = await hooked.completeWithTools({ messages: [], tools: [] })+ expect(res.content).toBe('main')+ expect(inner.lastToolReq?.signal?.aborted).toBe(false) // not aborted on the happy path+ })++ it("the caller's abort signal still cancels the call under concurrent moderation", async () => {+ const inner = fakePort()+ const moderatePass: FetchLike = async () => ({ status: 200, text: async () => '{}' })+ const hooks = buildLlmLaneHooks(+ [dscr({ lifecyclePoints: ['moderate'], capabilities: ['may_deny'] })],+ { getAuthToken: () => '', fetchImpl: moderatePass }+ )+ const hooked = new HookedLlmPort(inner, r => r, hooks)+ const outer = new AbortController()+ outer.abort() // caller already cancelled+ await hooked.completeWithTools({ messages: [], tools: [], signal: outer.signal })+ expect(inner.lastToolReq?.signal?.aborted).toBe(true) // linked through to the call})it('a pre_call rewrite reaches the inner port', async () => {diff --git a/mcp-host/src/core/adapters/hookedLlmPort.ts b/mcp-host/src/core/adapters/hookedLlmPort.tsindex f75978d70..3b8ab6d5f 100644--- a/mcp-host/src/core/adapters/hookedLlmPort.ts+++ b/mcp-host/src/core/adapters/hookedLlmPort.ts@@ -6,20 +6,21 @@* On the MAIN lane (`completeWithTools`):* 1. apply the first-party built-in request-shaping chain (`prompt-shaping`,* `token-trim`);- * 2. run installed `pre_call` hooks (each may rewrite the request or reject);- * 3. run installed `moderate` hooks;- * 4. aggregate (spec §3) — a `deny` returns a content-filtered response WITHOUT- * calling the model; otherwise dispatch the (possibly rewritten) request;- * 5. if the model call throws, run installed `on_error` hooks — a gated hook may+ * 2. run installed `pre_call` hooks (each may rewrite the request or reject) —+ * a `deny` returns a content-filtered response WITHOUT calling the model;+ * 3. dispatch the (possibly rewritten) request. When `moderate` hooks exist they+ * run CONCURRENTLY with the model call (spec §7.1) — a moderation `deny`+ * aborts the in-flight call via a linked `AbortSignal` (no tokens wasted) and+ * returns a filtered response; the happy path proceeds to `post_call`;+ * 4. if the model call throws, run installed `on_error` hooks — a gated hook may* `substitute` a safe text-only result (else the error surfaces);- * 6. run installed `post_call` hooks over the result — each may redact content or+ * 5. run installed `post_call` hooks over the result — each may redact content or* drop tool_calls (never add them, N5), chained in `order`.* The aux/compaction lane (`complete`) runs the REDUCED set — no guardrail/PII* (spec §7.4) — a passthrough here.** Response-capability enforcement (F4), system-prompt immutability (N4), and- * subtractive actions (N5) are enforced inside `RemoteLlmHook`. The- * concurrent-moderation latency optimization (spec §7.1) is a later increment.+ * subtractive actions (N5) are enforced inside `RemoteLlmHook`.*/import { aggregateDecision } from '../guardrails'import type { Contributor, GuardrailsConfig } from '../guardrails'@@ -75,46 +76,111 @@ export class HookedLlmPort implements LlmPort {return this.inner.complete(request)}- /** Main lane (spec §7): built-ins → installed pre_call/moderate → aggregate → dispatch. */+ /** Main lane (spec §7): built-ins → pre_call → dispatch (moderation concurrent with the call). */async completeWithTools(request: ToolCompletionRequest): Promise<ToolCompletionResponse> {let req = this.shapeMainLane(request)- const contributions: Array<Contributor<ToolCompletionRequest, ToolCompletionResponse>> = []+ // pre_call runs first — it shapes the request the model + moderation both see,+ // and a reject blocks the call outright (no tokens spent).+ const preContribs: Array<Contributor<ToolCompletionRequest, ToolCompletionResponse>> = []for (const hook of this.hooks.preCall) {const c = await hook.preCall(req)if (c) {- contributions.push(c)+ preContribs.push(c)if (c.rewrite) req = c.rewrite // already system-role-stripped + capability-gated (N4/F4)}}- for (const hook of this.hooks.moderate) {- const c = await hook.moderate(req)- if (c) contributions.push(c)- }+ if (aggregateDecision(preContribs) === 'deny') return filteredResponse()- if (aggregateDecision(contributions) === 'deny') {- return filteredResponse()- }+ return this.hooks.moderate.length === 0+ ? this.dispatch(req)+ : this.dispatchWithConcurrentModeration(req)+ }+ /** No moderation hooks: call → on_error → post_call. */+ private async dispatch(req: ToolCompletionRequest): Promise<ToolCompletionResponse> {let response: ToolCompletionResponsetry {response = await this.inner.completeWithTools(req)} catch (err) {- // on_error (spec §8.1): a gated hook may substitute a safe text-only result;- // first substitute wins. No hook recovers → the error surfaces unchanged.- for (const hook of this.hooks.onError) {- const c = await hook.onError(req, err)- if (c?.substitute) return c.substitute- }- throw err+ return this.recoverOrThrow(req, err)}+ return this.applyPostCall(req, response)+ }++ /**+ * §7.1 latency optimization: run the model call and all `moderate` hooks+ * concurrently over the same request. A moderation `deny` aborts the in-flight+ * call via a linked `AbortSignal` (no tokens wasted) and returns a filtered+ * response; otherwise the happy path (`call ok` AND all moderation pass)+ * proceeds to `post_call`. Wall-clock is `max(call, moderation)`, not their sum.+ */+ private async dispatchWithConcurrentModeration(+ req: ToolCompletionRequest+ ): Promise<ToolCompletionResponse> {+ const controller = new AbortController()+ const callReq = this.linkAbort(req, controller)++ // The model call is wrapped so it never rejects — if moderation denies first we+ // return without awaiting it, and a discarded resolved promise raises no+ // unhandled-rejection warning.+ const modelOutcome = this.inner.completeWithTools(callReq).then(+ response => ({ ok: true as const, response }),+ error => ({ ok: false as const, error })+ )+ const moderationVerdict = Promise.all(this.hooks.moderate.map(hook => hook.moderate(req))).then(+ cs => aggregateDecision(cs.filter((c): c is NonNullable<typeof c> => c != null))+ )++ if ((await moderationVerdict) === 'deny') {+ controller.abort() // cancel the in-flight call (§7.1)+ return filteredResponse()+ }++ const outcome = await modelOutcome+ if (!outcome.ok) return this.recoverOrThrow(req, outcome.error)+ return this.applyPostCall(req, outcome.response)+ }++ /** Link the caller's abort signal (task cancel) into ours so either can cancel the call. */+ private linkAbort(+ req: ToolCompletionRequest,+ controller: AbortController+ ): ToolCompletionRequest {+ const caller = req.signal+ if (caller) {+ if (caller.aborted) controller.abort()+ else caller.addEventListener('abort', () => controller.abort(), { once: true })+ }+ return { ...req, signal: controller.signal }+ }++ /**+ * on_error (spec §8.1): a gated hook may substitute a safe text-only result;+ * first substitute wins. No hook recovers → the error surfaces unchanged.+ */+ private async recoverOrThrow(+ req: ToolCompletionRequest,+ err: unknown+ ): Promise<ToolCompletionResponse> {+ for (const hook of this.hooks.onError) {+ const c = await hook.onError(req, err)+ if (c?.substitute) return c.substitute+ }+ throw err+ }- // post_call (spec §8.1): redact/subtract over the result, chained in `order`.+ /** post_call (spec §8.1): redact/subtract over the result, chained in `order`. */+ private async applyPostCall(+ req: ToolCompletionRequest,+ response: ToolCompletionResponse+ ): Promise<ToolCompletionResponse> {+ let out = responsefor (const hook of this.hooks.postCall) {- const c = await hook.postCall(req, response)- if (c?.substitute) response = c.substitute+ const c = await hook.postCall(req, out)+ if (c?.substitute) out = c.substitute}- return response+ return out}}