Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge remote-tracking branch 'origin/dev' into feat/678-desktop-upload-documents
Alfredo Lopez62e745664a20
diff --cc control-api/package-lock.jsonindex 33f2df8e4,7d6bad938..f70bce446--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-control-api",- "version": "0.1.713",- "version": "0.1.711",++ "version": "0.1.714","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.713",- "version": "0.1.711",++ "version": "0.1.714","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --cc control-api/package.jsonindex 0a60f5958,0882b95ab..d6b80060c--- a/control-api/package.json+++ b/control-api/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-control-api",- "version": "0.1.713",- "version": "0.1.711",++ "version": "0.1.714","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --cc mcp-host/package-lock.jsonindex 2e0a546d6,92694a93a..642e04a30--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-mcp-host",- "version": "0.1.504",- "version": "0.1.499",++ "version": "0.1.505","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.504",- "version": "0.1.499",++ "version": "0.1.505","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --cc mcp-host/package.jsonindex 3881d4e89,6c77eba38..2ba1fba6a--- a/mcp-host/package.json+++ b/mcp-host/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-mcp-host",- "version": "0.1.504",- "version": "0.1.499",++ "version": "0.1.505","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --cc mcp-host/src/agent/taskExecutor.tsindex e6f73fde3,27c9081fa..ac31c6456--- a/mcp-host/src/agent/taskExecutor.ts+++ b/mcp-host/src/agent/taskExecutor.ts@@@ -119,9 -117,14 +123,15 @@@ import { resolveCronTaskSessionKey, serimport { GovernedRunReporter, UsageReporter } from '../usage/usageReporter.js'import { resolveProviderWorkflowCallerContext } from '../workflow/providerWorkflowCallerContextClient'import type { Workspace } from '../workspace/service'+import { attachmentContextWindow } from './attachmentContextWindow'import type { CronScheduler } from './cronScheduler'import { referencedFilesForTurnContext } from './fileReferenceResolver'+ import {+ GFS_SYSTEM_CALLER_IDENTITY,+ gfsManagedWorkspaceExecution,+ gfsWorkspaceExecutionEnabled,+ } from './gfsExecutionCapability'+ import { hasLargeAvailableGfsReferences, prepareGfsFiles } from './gfsFilePreparation'import {type ProviderWorkflowAccessDenialReason,isProviderWorkflowChannel,@@@ -2123,8 -2130,41 +2200,36 @@@ export class TaskExecutorappConfig,this.deps.failover?.policy.fallbacks)+ const gfsCallerIdentity = this.task.sourceMessage?.sender ?? GFS_SYSTEM_CALLER_IDENTITY+ const gfsProcessingLeaseProvider =+ this.deps.gfsProcessingLeaseProvider ??+ (this.deps.gfsDownloadStore && gfsCallerIdentity+ ? this.deps.gfsDownloadStore.processingLeaseProvider(gfsCallerIdentity)+ : undefined)+ const gfsWorkspace = gfsManagedWorkspaceExecution({+ approvalEnabled: appConfig.enableApproval,+ source: this.task.source,+ callerIdentity: gfsCallerIdentity,+ store: this.deps.gfsDownloadStore,+ callerWorkspacePath: this.deps.gfsCallerWorkspacePath,+ processingLeaseProvider: gfsProcessingLeaseProvider,+ approvalConfig: this.deps.approvalConfig,+ retentionOwnerId: this.taskId,+ })+ const gfsDeliveryEligible = gfsWorkspace+ ? gfsWorkspaceExecutionEnabled({+ approvalEnabled: appConfig.enableApproval,+ source: this.task.source,+ callerIdentity: this.task.sourceMessage?.sender,+ store: gfsWorkspace.store,+ callerWorkspacePath: gfsWorkspace.callerWorkspacePath,+ processingLeaseProvider: gfsWorkspace.processingLeaseProvider,+ approvalConfig: this.deps.approvalConfig,+ retentionOwnerId: this.taskId,+ })+ : falseconst nativeRegistry = new NativeToolRegistry(- // The spillover threshold is a top-level setting; clerum__attachment_read- // states it in its description (#666).- {- ...appConfig.nativeTool,- toolSpilloverThresholdBytes: appConfig.toolSpilloverThresholdBytes,- },+ appConfig.nativeTool,this.conversation!.id,this.deps.cronScheduler ?? undefined,this.task.sourceMessage,diff --cc mcp-host/src/core/interfaces.tsindex 0600cac4a,f04b3dfdb..b43397bae--- a/mcp-host/src/core/interfaces.ts+++ b/mcp-host/src/core/interfaces.ts@@@ -124,19 -115,12 +124,25 @@@ export interface ToolsupportsProgressOutput?(): boolean/** Local implementation-owned bounded cleanup after execution is stopped. */timeoutCleanupMs?(): number+ /**+ * Optional. Return true when the tool's output is bounded by its own+ * contract (the caller chose the page, or the output is a blob already+ * spilled once), so the tool loop ships it inline instead of replacing it+ * with a spillover summary. Tools that do not opt in are spilled at the+ * configured threshold.+ */+ spilloverExempt?(): boolean+ /** Final budget/revocation fence, after result transforms and before publication. */+ finalizeResult?(+ result: ToolResult,+ context: ToolEmissionContext+ ): ToolResult | Promise<ToolResult>+ /**+ * True when the concrete producer owns abort/timeout settlement and callers+ * must await that promise instead of racing cancellation cleanup. Used by+ * physical-execution tools whose late effects must be fenced before release.+ */+ joinsAbortSettlement?(): boolean}// ─── Channel ────────────────────────────────────────────────diff --cc mcp-host/src/core/orchestration/__tests__/guardrailGate.test.tsindex 4c5f77021,45f292a12..71b280601--- a/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts+++ b/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts@@@ -194,6 -195,6 +195,30 @@@ describe('guardrail gate in executeToolexpect(toolResults[0].is_error).toBe(false)})++ it('finalizeResult fences the transformed result, after transformResult', async () => {++ const tool = new StubTool('do_thing')++ const finalized: string[] = []++ const fenced = Object.assign(tool, {++ finalizeResult: (result: { content: string }) => {++ finalized.push(result.content)++ return { ...result, content: `[fenced:${result.content}]` }++ },++ })++ const guardrail: ToolLaneGuardrail = {++ async decide(_id, input) {++ return { decision: 'allow', reasonCode: 'r', effectiveInput: input, source: 'host_rule' }++ },++ async transformResult(_id, _input, result) {++ return { content: `[redacted:${result.content}]`, isError: result.isError }++ },++ }++ const config = { ...makeConfig(fenced, guardrail), measureToolMessage: () => 1 }++ const { toolResults } = await executeToolCalls([call], config, 0)++ expect(tool.calls).toHaveLength(1)++ expect(finalized).toEqual(['[redacted:ok]'])++ expect(toolResults[0].content).toBe('[fenced:[redacted:ok]]')++ })++it('ask + matching one-shot approval → proceeds and clears pending', async () => {const tool = new StubTool('do_thing')const conversation: Partial<Conversation> = {diff --cc mcp-host/src/core/orchestration/toolCallPolicy.tsindex 000000000,e8e091139..743aba94emode 000000,100644..100644--- a/mcp-host/src/core/orchestration/toolCallPolicy.ts+++ b/mcp-host/src/core/orchestration/toolCallPolicy.ts@@@ -1,0 -1,208 +1,215 @@@+ import { randomUUID } from 'node:crypto'+ import { isDeepStrictEqual } from 'node:util'+ import {+ type ToolIdentity,+ recordAndCheck,+ recordDecision,+ resolveToolIdentityFromRegistry,+ } from '../guardrails'+ import type { PendingApproval, ToolCall, ToolResult } from '../types'+ import type { LoopConfig } from './loopConfig'+ import { executeSingleTool } from './toolUseLoopSingleTool'++ export type ToolCallAdmission =+ | { kind: 'result'; toolResult: ToolResult }+ | { kind: 'suspend'; approval: PendingApproval }+ | { kind: 'execute'; call: ToolCall; toolIdentity?: ToolIdentity }++ function guardrailSuspension(+ call: ToolCall,+ config: LoopConfig,+ reasonCode: string+ ): { type: 'suspend'; approval: PendingApproval } {+ const descriptor = config.toolRegistry.get(call.name)?.traceDescriptor?.(call.arguments) ?? {+ kind: 'internal_tool' as const,+ sourceRef: 'mcp-host' as const,+ }+ return {+ type: 'suspend',+ approval: {+ request_id: randomUUID(),+ authorization_scope: 'exact_invocation',+ tool_name: call.name,+ tool_kind: descriptor.kind,+ tool_source_ref: descriptor.sourceRef,+ parameters: call.arguments,+ description: `Guardrail requires approval (${reasonCode})`,+ tool_call_id: call.id,+ context_snapshot: [],+ },+ }+ }++ /**+ * Shared per-call admission: validation, doom-loop, tool-lane guardrails and+ * the live approval gate. Both model-generated calls and Host preparation use+ * this exact boundary; no caller may execute a tool directly after policy.+ */+ export async function admitToolCall(+ inputCall: ToolCall,+ config: LoopConfig,+ iteration: number+ ): Promise<ToolCallAdmission> {+ let call = inputCall+ let validation = config.toolOutputProcessor.beforeExecution(call.name, call.arguments)+ if (validation.is_valid) {+ validation =+ (await config.toolRegistry.get(call.name)?.validateParams?.(call.arguments)) ?? validation+ }+ if (!validation.is_valid) {+ config.events.emit({+ type: 'safety:input_blocked',+ data: { toolName: call.name, errors: validation.errors, iteration },+ timestamp: new Date(),+ })+ return {+ kind: 'result',+ toolResult: {+ tool_call_id: call.id,+ name: call.name,+ content: `Parameter validation failed: ${validation.errors.join(', ')}`,+ is_error: true,+ },+ }+ }++ let toolIdentity: ToolIdentity | undefined+ let gate: 'proceed' | 'skip' | { type: 'suspend'; approval: PendingApproval }+ if (config.guardrails) {+ toolIdentity = resolveToolIdentityFromRegistry(call.name, config.toolRegistry, call.arguments)+ const key = `${toolIdentity.provenance}:${toolIdentity.server ?? ''}:${toolIdentity.name}:${JSON.stringify(call.arguments)}`+ const doomLoop = recordAndCheck(config.conversation.guardrail_doom_loop ?? { count: 0 }, key)+ config.conversation.guardrail_doom_loop = doomLoop.state+ if (doomLoop.tripped) {+ recordDecision('tool', 'deny', 'current', 'denied', 'repeated_identical_call')+ config.events.emit({+ type: 'guardrail:decision',+ data: {+ toolName: call.name,+ decision: 'deny',+ reasonCode: 'repeated_identical_call',+ source: 'current',+ iteration,+ },+ timestamp: new Date(),+ })+ return {+ kind: 'result',+ toolResult: {+ tool_call_id: call.id,+ name: call.name,+ content: 'Blocked: repeated identical tool call (doom-loop guard).',+ is_error: true,+ },+ }+ }++ const decision = await config.guardrails.decide(toolIdentity, call.arguments)+ config.events.emit({+ type: 'guardrail:decision',+ data: {+ toolName: call.name,+ decision: decision.decision,+ reasonCode: decision.reasonCode,+ source: decision.source,+ iteration,+ },+ timestamp: new Date(),+ })+ const mode = config.executionMode ?? 'interactive'+ if (decision.decision === 'deny') {+ recordDecision('tool', 'deny', decision.source, 'denied', decision.reasonCode, mode)+ return {+ kind: 'result',+ toolResult: {+ tool_call_id: call.id,+ name: call.name,+ content: `Blocked by guardrail policy (${decision.reasonCode}).`,+ is_error: true,+ },+ }+ }+ if (decision.effectiveInput !== call.arguments) {+ call = { ...call, arguments: decision.effectiveInput }+ }+ if (decision.decision === 'ask') {+ const pending = config.conversation.pending_approval+ const exactInvocationMatches =+ pending?.authorization_scope !== 'turn_tools' &&+ pending?.tool_call_id === call.id &&+ isDeepStrictEqual(pending?.parameters, call.arguments)+ const pendingMatches =+ pending?.tool_name === call.name &&+ (pending.authorization_scope === 'turn_tools' || exactInvocationMatches)+ if (pending && pendingMatches) {+ config.conversation.pending_approval = undefined+ recordDecision('tool', 'ask', decision.source, 'executed', decision.reasonCode, mode)+ gate = 'proceed'+ } else if (mode === 'unattended') {+ recordDecision('tool', 'deny', decision.source, 'denied', 'approval_unavailable', mode)+ return {+ kind: 'result',+ toolResult: {+ tool_call_id: call.id,+ name: call.name,+ content:+ 'Blocked: approval required but no approver is available in an autonomous run.',+ is_error: true,+ },+ }+ } else {+ recordDecision('tool', 'ask', decision.source, 'ask', decision.reasonCode, mode)+ gate = guardrailSuspension(call, config, decision.reasonCode)+ }+ } else {+ recordDecision(+ 'tool',+ decision.decision,+ decision.source,+ 'executed',+ decision.reasonCode,+ mode+ )+ gate = config.loopController.beforeTool(call.name, call.arguments)+ }+ } else {+ gate = config.loopController.beforeTool(call.name, call.arguments)+ }++ if (gate === 'skip') {+ return {+ kind: 'result',+ toolResult: {+ tool_call_id: call.id,+ name: call.name,+ content: 'Tool execution skipped',+ is_error: false,+ },+ }+ }+ if (typeof gate === 'object' && gate.type === 'suspend')+ return { kind: 'suspend', approval: gate.approval }+ return { kind: 'execute', call, toolIdentity }+ }++ export async function executeAdmittedTool(+ admission: Extract<ToolCallAdmission, { kind: 'execute' }>,+ config: LoopConfig,+ iteration: number+ ): Promise<ToolResult> {- const toolResult = await executeSingleTool(admission.call, config, iteration)- if (!config.guardrails?.transformResult || !admission.toolIdentity) return toolResult- const view = await config.guardrails.transformResult(- admission.toolIdentity,- admission.call.arguments,- { content: toolResult.content, isError: toolResult.is_error }- )- return view.content === toolResult.content ? toolResult : { ...toolResult, content: view.content }++ const { guardrails } = config++ const { toolIdentity } = admission++ // The transform runs inside executeSingleTool so a tool's finalizeResult++ // fence measures and publishes the transformed content, not the raw output.++ const transformResult =++ guardrails?.transformResult && toolIdentity++ ? async (result: ToolResult): Promise<ToolResult> => {++ const view = await guardrails.transformResult!(toolIdentity, admission.call.arguments, {++ content: result.content,++ isError: result.is_error,++ })++ return view.content === result.content ? result : { ...result, content: view.content }++ }++ : undefined++ return executeSingleTool(admission.call, config, iteration, transformResult)+ }diff --cc mcp-host/src/server.tsindex 7d78be919,34039c21b..3f1259554--- a/mcp-host/src/server.ts+++ b/mcp-host/src/server.ts@@@ -10,8 -10,8 +10,9 @@@ import * as path from 'pathimport { register } from 'prom-client'import { readOpenedArtifactBuffer, redactArtifactForDelivery } from './artifacts/artifactBytes'import type { ArtifactSecretEntry } from './artifacts/artifactRedaction'+ import './internalTools/gfsDownloadMetrics'import type { RuntimeLifecycleGate } from './lifecycle/statelessHeartbeat'+import { logger } from './logger'import './mcp/catalogBootstrapMetrics'import './mcp/statusHeartbeatMetrics'import './observability/processMetrics'