UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

639 lines (638 loc) • 25.6 kB
/** * HITL (Human-in-the-Loop) Manager * * Central orchestrator for all HITL confirmation workflows. * Manages user confirmation requests, timeouts, and argument modifications * for enterprise-grade AI safety. */ import { EventEmitter } from "events"; import { randomUUID } from "crypto"; import { HITLCancelledError, HITLTimeoutError, HITLConfigurationError, } from "./hitlErrors.js"; import { logger } from "../utils/logger.js"; import { suggestClosest } from "../utils/stringDistance.js"; // Default configuration constants const DEFAULT_TIMEOUT = 30000; // 30 seconds // Shared with NeuroLink's HITL init logs so they report the policy applied here export const DEFAULT_ALLOW_MODIFICATION = false; // Record<keyof HITLConfig, true> makes adding a HITLConfig key without listing it here a compile error const KNOWN_CONFIG_KEYS = new Set(Object.keys({ enabled: true, dangerousActions: true, timeout: true, confirmationMethod: true, allowArgumentModification: true, autoApproveOnTimeout: true, autoApproveExclusions: true, auditLogging: true, customRules: true, confirmBuiltinTools: true, confirmDirectToolCalls: true, })); /** The abort reason as text for `hitl:cancelled`, whatever the caller passed. */ export function describeAbortReason(signal) { const reason = signal.reason; if (typeof reason === "string" && reason.length > 0) { return reason; } if (reason instanceof Error && reason.message) { return reason.message; } return "Tool call was aborted"; } /** * HITLManager - Central orchestrator for Human-in-the-Loop safety mechanisms * * Features: * - Real-time user confirmation via events * - Configurable dangerous action detection * - Custom rule engine for complex scenarios * - Argument modification support * - Comprehensive audit logging * - Timeout handling with cleanup */ export class HITLManager extends EventEmitter { config; pendingConfirmations = new Map(); /** hitl:cancelled deliveries held back while that ID's request emit runs. */ requestsEmitting = new Map(); statistics = { totalRequests: 0, pendingRequests: 0, averageResponseTime: 0, approvedRequests: 0, rejectedRequests: 0, timedOutRequests: 0, }; constructor(config) { super(); this.config = this.validateConfig(config); this.setupEventHandlers(); } warnedUnknownKeys = new Set(); /** * Validate HITL configuration and apply defaults */ validateConfig(config) { // Warn only: throwing here would break callers that pass planned-but-unsupported keys today. // alwaysStderr, not logger.warn: warn is hidden unless NEUROLINK_DEBUG is set, and a typo'd key silently disables approval gates. for (const key of Object.keys(config)) { if (!KNOWN_CONFIG_KEYS.has(key) && !this.warnedUnknownKeys.has(key)) { this.warnedUnknownKeys.add(key); const [closest] = suggestClosest(key, [...KNOWN_CONFIG_KEYS], { limit: 1, }); const didYouMean = closest ? ` Did you mean "${closest}"?` : ""; logger.alwaysStderr(`[HITL] Unknown config key "${key}" is ignored and has no effect.${didYouMean} Supported keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. See docs/features/enterprise-hitl.md`); } } // Apply defaults for optional fields const configWithDefaults = { enabled: config.enabled, dangerousActions: config.dangerousActions, timeout: config.timeout ?? DEFAULT_TIMEOUT, // Default: 30 seconds confirmationMethod: config.confirmationMethod ?? "event", // Default: "event" allowArgumentModification: config.allowArgumentModification ?? DEFAULT_ALLOW_MODIFICATION, // Default: false autoApproveOnTimeout: config.autoApproveOnTimeout ?? false, // Default: false (safe) autoApproveExclusions: Array.isArray(config.autoApproveExclusions) ? [...config.autoApproveExclusions] : (config.autoApproveExclusions ?? []), auditLogging: config.auditLogging ?? false, // Default: false customRules: config.customRules ?? [], // Default: empty array confirmBuiltinTools: config.confirmBuiltinTools ?? true, // Default: true (built-in write/bash tools prompt) confirmDirectToolCalls: config.confirmDirectToolCalls ?? false, // Default: false (direct executeTool calls keep their existing behaviour) }; if (!configWithDefaults.enabled) { return configWithDefaults; // If disabled, don't validate other fields } if (!Array.isArray(configWithDefaults.dangerousActions)) { throw new HITLConfigurationError("dangerousActions must be an array of strings"); } if (!Array.isArray(configWithDefaults.autoApproveExclusions) || configWithDefaults.autoApproveExclusions.some((name) => typeof name !== "string" || name.length === 0)) { throw new HITLConfigurationError("autoApproveExclusions must be an array of non-empty tool names"); } if (typeof configWithDefaults.timeout !== "number" || configWithDefaults.timeout <= 0) { throw new HITLConfigurationError("timeout must be a positive number (milliseconds)"); } if (configWithDefaults.confirmationMethod !== "event") { throw new HITLConfigurationError("confirmationMethod must be 'event' (only supported method)"); } if (typeof configWithDefaults.allowArgumentModification !== "boolean") { throw new HITLConfigurationError("allowArgumentModification must be a boolean"); } return configWithDefaults; } /** * Check if a tool requires confirmation based on configuration */ requiresConfirmation(toolName, args) { if (!this.config.enabled) { return false; } // Check dangerous actions keywords const lowerToolName = toolName.toLowerCase(); for (const action of this.config.dangerousActions) { if (lowerToolName.includes(action.toLowerCase())) { return true; } } // Check custom rules if (this.config.customRules) { for (const rule of this.config.customRules) { if (rule.requiresConfirmation) { try { if (rule.condition(toolName, args)) { return true; } } catch (error) { // Log rule evaluation error but don't fail this.logAuditEvent("rule-evaluation-error", { ruleName: rule.name, toolName, error: error instanceof Error ? error.message : String(error), }); } } } } return false; } /** * Request confirmation for a tool execution. * * Aborting `context.signal` withdraws the request (see `cancelConfirmation`); * a signal that is already aborted raises no card at all. */ async requestConfirmation(toolName, arguments_, context) { const signal = context?.signal; if (signal?.aborted) { throw new HITLCancelledError(`Confirmation cancelled before it was requested for tool: ${toolName}`, undefined, describeAbortReason(signal)); } const confirmationId = this.generateConfirmationId(); const startTime = Date.now(); // Update statistics this.statistics.totalRequests++; this.statistics.pendingRequests++; return new Promise((resolve, reject) => { const onAbort = () => { if (signal) { this.cancelConfirmation(confirmationId, describeAbortReason(signal)); } }; // Every way the request settles detaches the listener, so a signal // that aborts after the answer cancels nothing. const detach = () => signal?.removeEventListener("abort", onAbort); // Set up timeout const timeoutHandle = setTimeout(() => { this.handleTimeout(confirmationId); }, this.config.timeout); // Store pending confirmation const request = { confirmationId, toolName, arguments: arguments_, timestamp: startTime, timeoutHandle, resolve: (result) => { detach(); resolve(result); }, reject: (error) => { detach(); reject(error); }, }; this.pendingConfirmations.set(confirmationId, request); // Attached before the card is emitted: a listener may answer, or the // caller may abort, synchronously inside the emit below. signal?.addEventListener("abort", onAbort, { once: true }); // Create confirmation request event const requestEvent = { type: "hitl:confirmation-request", payload: { confirmationId, toolName, serverId: context?.serverId, actionType: this.generateActionDescription(toolName, arguments_), arguments: arguments_, metadata: { timestamp: new Date(startTime).toISOString(), sessionId: context?.sessionId, userId: context?.userId, dangerousKeywords: this.getTriggeredKeywords(toolName, arguments_), }, timeoutMs: this.config.timeout ?? DEFAULT_TIMEOUT, allowModification: this.config.allowArgumentModification ?? DEFAULT_ALLOW_MODIFICATION, }, }; // Emit confirmation request event. An abort raised inside a listener // defers its hitl:cancelled until every request listener has run. this.requestsEmitting.set(confirmationId, []); try { this.emit("hitl:confirmation-request", requestEvent); } finally { const deferred = this.requestsEmitting.get(confirmationId) ?? []; this.requestsEmitting.delete(confirmationId); for (const deliver of deferred) { deliver(); } } // Log audit trail if enabled if (this.config.auditLogging) { this.logAuditEvent("confirmation-requested", { confirmationId, toolName, userId: context?.userId, sessionId: context?.sessionId, timestamp: startTime, arguments: arguments_, }); } }); } /** * Process user response to confirmation request */ processUserResponse(confirmationId, response) { const request = this.pendingConfirmations.get(confirmationId); if (!request) { logger.warn(`No pending confirmation found for ID: ${confirmationId}`); return; } // Clear timeout clearTimeout(request.timeoutHandle); // Remove from pending this.pendingConfirmations.delete(confirmationId); this.statistics.pendingRequests--; // Calculate response time const responseTime = response.responseTime || Date.now() - request.timestamp; // Update statistics if (response.approved) { this.statistics.approvedRequests++; } else { this.statistics.rejectedRequests++; } // Update average response time const totalResponses = this.statistics.approvedRequests + this.statistics.rejectedRequests; this.statistics.averageResponseTime = (this.statistics.averageResponseTime * (totalResponses - 1) + responseTime) / totalResponses; // Create result const result = { approved: response.approved, reason: response.reason, modifiedArguments: response.modifiedArguments, responseTime, }; // Log audit trail if enabled if (this.config.auditLogging) { this.logAuditEvent(response.approved ? "confirmation-approved" : "confirmation-rejected", { confirmationId, toolName: request.toolName, approved: response.approved, reason: response.reason, userId: response.userId, responseTime, arguments: request.arguments, }); } // Resolve the promise request.resolve(result); } /** * Handle confirmation timeout */ handleTimeout(confirmationId) { const request = this.pendingConfirmations.get(confirmationId); if (!request) { return; } // Remove from pending this.pendingConfirmations.delete(confirmationId); this.statistics.pendingRequests--; this.statistics.timedOutRequests++; // Calculate response time (timeout duration) const responseTime = Date.now() - request.timestamp; // Check if auto-approve on timeout is enabled const shouldAutoApprove = this.config.autoApproveOnTimeout === true && !this.config.autoApproveExclusions?.includes(request.toolName); // Log audit trail if enabled if (this.config.auditLogging) { this.logAuditEvent("confirmation-timeout", { confirmationId, toolName: request.toolName, timeout: this.config.timeout ?? DEFAULT_TIMEOUT, arguments: request.arguments, autoApproved: shouldAutoApprove, }); } // Create timeout event const timeoutEvent = { type: "hitl:timeout", payload: { confirmationId, toolName: request.toolName, timeout: this.config.timeout ?? DEFAULT_TIMEOUT, }, }; // Emit timeout event this.emit("hitl:timeout", timeoutEvent); if (shouldAutoApprove) { // Auto-approve the request this.statistics.approvedRequests++; // Update average response time const totalResponses = this.statistics.approvedRequests + this.statistics.rejectedRequests; this.statistics.averageResponseTime = (this.statistics.averageResponseTime * (totalResponses - 1) + responseTime) / totalResponses; // Log auto-approval if enabled if (this.config.auditLogging) { this.logAuditEvent("confirmation-auto-approved", { confirmationId, toolName: request.toolName, reason: "Auto-approved due to timeout", responseTime, arguments: request.arguments, }); } // Resolve with auto-approval const result = { approved: true, reason: "Auto-approved due to timeout", responseTime, }; request.resolve(result); } else { // Reject with timeout error (original behavior) request.reject(new HITLTimeoutError(`Confirmation timeout for tool: ${request.toolName}`, confirmationId, this.config.timeout ?? DEFAULT_TIMEOUT)); } } /** * Withdraw a pending confirmation because the call that asked was aborted. * * Clears the timer, forgets the entry (so a later answer for this ID runs * nothing), rejects the waiting call with `HITLCancelledError` and emits * `hitl:cancelled` so the approval UI can retire the card. * * @returns false when nothing was pending under this ID */ cancelConfirmation(confirmationId, reason = "Confirmation cancelled") { const request = this.pendingConfirmations.get(confirmationId); if (!request) { return false; } clearTimeout(request.timeoutHandle); this.pendingConfirmations.delete(confirmationId); this.statistics.pendingRequests--; if (this.config.auditLogging) { this.logAuditEvent("confirmation-cancelled", { confirmationId, toolName: request.toolName, reason, arguments: request.arguments, }); } // Reject before emitting: a throwing listener must not leave the call // waiting, and this often runs inside an AbortSignal listener, where a // throw would surface as an uncaught exception. request.reject(new HITLCancelledError(`Confirmation cancelled for tool: ${request.toolName}`, confirmationId, reason)); this.deliverCancelled(confirmationId, request.toolName, reason); return true; } /** * Emit `hitl:cancelled`, or hold it until the request emit for this ID has * finished so no listener sees the cancel before the card. */ deliverCancelled(confirmationId, toolName, reason) { const deliver = () => { const cancelledEvent = { type: "hitl:cancelled", payload: { confirmationId, toolName, reason }, }; try { this.emit("hitl:cancelled", cancelledEvent); } catch (error) { logger.warn("[HITL] A hitl:cancelled listener threw", { confirmationId, error: error instanceof Error ? error.message : String(error), }); } }; const held = this.requestsEmitting.get(confirmationId); if (held) { held.push(deliver); } else { deliver(); } } /** * Set up event handlers for processing responses */ setupEventHandlers() { this.on("hitl:confirmation-response", (event) => { if (event.payload?.confirmationId) { this.processUserResponse(event.payload.confirmationId, { approved: event.payload.approved, reason: event.payload.reason, modifiedArguments: event.payload.modifiedArguments, responseTime: event.payload.metadata?.responseTime, userId: event.payload.metadata?.userId, }); } }); } /** * Generate unique confirmation ID */ generateConfirmationId() { return `hitl-${Date.now()}-${randomUUID()}`; } /** * Generate human-readable action description */ generateActionDescription(toolName, args) { const lowerToolName = toolName.toLowerCase(); // Check for specific action types if (lowerToolName.includes("delete")) { return "Delete Operation"; } if (lowerToolName.includes("remove")) { return "Remove Operation"; } if (lowerToolName.includes("update")) { return "Update Operation"; } if (lowerToolName.includes("create")) { return "Create Operation"; } if (lowerToolName.includes("drop")) { return "Drop Operation"; } if (lowerToolName.includes("truncate")) { return "Truncate Operation"; } if (lowerToolName.includes("restart")) { return "Restart Operation"; } if (lowerToolName.includes("stop")) { return "Stop Operation"; } if (lowerToolName.includes("kill")) { return "Kill Operation"; } // Check custom rules for custom messages if (this.config.customRules) { for (const rule of this.config.customRules) { try { if (rule.condition(toolName, args) && rule.customMessage) { return rule.customMessage; } } catch { // Ignore rule evaluation errors } } } return `Execute ${toolName}`; } /** * Get keywords that triggered HITL */ getTriggeredKeywords(toolName, args) { const triggered = []; const lowerToolName = toolName.toLowerCase(); // Check dangerous actions for (const action of this.config.dangerousActions) { if (lowerToolName.includes(action.toLowerCase())) { triggered.push(action); } } // Check custom rules if (this.config.customRules) { for (const rule of this.config.customRules) { try { if (rule.requiresConfirmation && rule.condition(toolName, args)) { triggered.push(rule.name); } } catch { // Ignore rule evaluation errors } } } return triggered; } /** * Log audit events for compliance and debugging */ logAuditEvent(eventType, data) { const auditLog = { timestamp: new Date().toISOString(), eventType: eventType, toolName: data.toolName, userId: data.userId, sessionId: data.sessionId, arguments: data.arguments, reason: data.reason, responseTime: data.responseTime, ...data, }; logger.info(`[HITL Audit] ${eventType}:`, auditLog); // Emit audit event for external logging systems. Every caller logs before // it settles the waiting call, often inside a timer or an AbortSignal // listener, so a throwing listener must not reach it. try { this.emit("hitl:audit", auditLog); } catch (error) { logger.warn("[HITL] A hitl:audit listener threw", { eventType, error: error instanceof Error ? error.message : String(error), }); } } /** * Get current HITL usage statistics */ getStatistics() { return { ...this.statistics }; } /** * Get current configuration */ getConfig() { return { ...this.config, autoApproveExclusions: Array.isArray(this.config.autoApproveExclusions) ? [...this.config.autoApproveExclusions] : this.config.autoApproveExclusions, }; } /** * Update configuration (for dynamic reconfiguration) */ updateConfig(newConfig) { const updatedConfig = { ...this.config, ...newConfig }; this.config = this.validateConfig(updatedConfig); if (this.config.auditLogging) { this.logAuditEvent("configuration-updated", { oldConfig: this.config, newConfig: updatedConfig, }); } } /** * Clean up resources and reject pending confirmations */ cleanup() { const clearedConfirmations = this.pendingConfirmations.size; const pending = [...this.pendingConfirmations]; this.pendingConfirmations.clear(); this.statistics.pendingRequests = 0; for (const [confirmationId, request] of pending) { clearTimeout(request.timeoutHandle); request.reject(new Error(`HITL cleanup: confirmation ${confirmationId} cancelled`)); this.deliverCancelled(confirmationId, request.toolName, "HITL manager cleanup"); } if (this.config.auditLogging) { this.logAuditEvent("manager-cleanup", { clearedConfirmations }); } } /** * Check if manager is currently enabled */ isEnabled() { return this.config.enabled; } /** * Get count of pending confirmations */ getPendingCount() { return this.pendingConfirmations.size; } /** * Whether a specific confirmation is still awaiting a response on this manager. * * A pending entry holds the `resolve`/`reject` of the suspended tool call, so it * exists only in the memory of the manager that issued it. A manager constructed * after the confirmation was issued — a session rebuilt from persisted state, for * example — has an empty set, and `processUserResponse` for such an id logs a * warning and returns without resolving anything. * * Callers that report an outcome back to a user should check this before treating * a delivered `hitl:confirmation-response` as acted upon: the event being received * says a listener existed, not that anything was waiting for it. */ hasPendingConfirmation(confirmationId) { return this.pendingConfirmations.has(confirmationId); } }