/** * MAMA Tool Executor for MAMA Standalone * * Executes MAMA gateway tools (mama_search, mama_save, mama_update, mama_load_checkpoint, Read, discord_send). * NOT MCP - uses Claude Messages API tool definitions. * Supports both direct API integration and mock API for testing. * * Role-Based Permission Control: * - Each tool execution is checked against the current AgentContext's role * - Blocked tools return permission errors instead of executing * - Path-based tools (Read, Write) also check path permissions */ import type { GatewayToolName, GatewayToolInput, GatewayToolResult, GatewayToolExecutorOptions, AgentContext, BotPlatform, GatewayToolExecutionContext, BeginModelRunInput, ModelRunRecord } from './types.js'; import type { AgentProcessManager } from '../multi-agent/agent-process-manager.js'; import type { DelegationManager } from '../multi-agent/delegation-manager.js'; import type { AgentEventBus } from '../multi-agent/agent-event-bus.js'; import type { SQLiteDatabase } from '../sqlite.js'; import type { UICommandQueue } from '../api/ui-command-handler.js'; type GatewayExecutionContext = GatewayToolExecutionContext; type GatewayContextSnapshot = { agentId: string; source: string; channelId: string; }; /** * Discord gateway interface for sending messages */ export interface DiscordGatewayInterface { sendMessage(channelId: string, message: string): Promise; sendFile(channelId: string, filePath: string, caption?: string): Promise; sendImage(channelId: string, imagePath: string, caption?: string): Promise; } /** * Slack gateway interface for sending messages and files */ export interface SlackGatewayInterface { sendMessage(channelId: string, message: string): Promise; sendFile(channelId: string, filePath: string, caption?: string): Promise; sendImage(channelId: string, imagePath: string, caption?: string): Promise; } /** * Telegram gateway interface for sending messages and files */ export interface TelegramGatewayInterface { sendMessage(chatId: string, text: string): Promise; sendFile(chatId: string, filePath: string, caption?: string): Promise; sendImage(chatId: string, imagePath: string, caption?: string): Promise; sendSticker(chatId: string | number, emotion: string): Promise; } export declare class GatewayToolExecutor { private mamaApi; private readonly mamaDbPath?; private sessionStore?; private discordGateway; private slackGateway; private telegramGateway; private browserTool; private roleManager; private readonly executionContextStorage; private readonly envelopeEnforcer; private readonly envelopeIssuanceMode; private readonly metricsStore; private contextCompileService; private currentContext; private memoryAgentProcessManager; private agentProcessManager; private delegationManagerRef; private currentAgentId; private currentSource; private currentChannelId; private disallowedGatewayTools; private reportPublisher; private wikiPublisher; private obsidianVaultPath; setObsidianVaultPath(vaultPath: string): void; private agentEventBus; setAgentEventBus(bus: AgentEventBus): void; getAgentEventBus(): AgentEventBus | null; private sessionsDb; setSessionsDb(db: SQLiteDatabase): void; private rawStore; setRawStore(store: import('../connectors/framework/raw-store.js').RawStore): void; private delegationExecutor; private uiCommandQueue; setUICommandQueue(queue: UICommandQueue): void; private applyMultiAgentConfig; setApplyMultiAgentConfig(fn: ((config: Record) => Promise) | null): void; private restartMultiAgentAgent; setRestartMultiAgentAgent(fn: ((agentId: string) => Promise) | null): void; private validationService; setValidationService(svc: import('../validation/session-service.js').ValidationSessionService): void; setMemoryAgent(processManager: AgentProcessManager): void; setAgentProcessManager(pm: AgentProcessManager): void; setDelegationManager(dm: DelegationManager): void; /** Get AgentProcessManager (for cron/event triggers that need direct process access) */ getAgentProcessManager(): AgentProcessManager | null; private normalizeExecutionContext; private getExecutionState; private getFallbackExecutionContext; private mergeWithFallbackExecutionContext; private getActiveContext; private getActiveRouting; private getActiveDelegationRouting; withExecutionContext(executionContext: GatewayExecutionContext | undefined, fn: () => Promise): Promise; setCurrentAgentContext(agentId: string, source: string, channelId: string): void; getCurrentAgentRoutingContext(): GatewayContextSnapshot; restoreCurrentAgentRoutingContext(context: GatewayContextSnapshot): void; clearCurrentAgentContext(): void; setDisallowedGatewayTools(tools: string[]): void; private getPreferredViewerAgentTab; private syncViewerToAgentDetail; private resolveManagedAgentId; setReportPublisher(fn: (slots: Record) => void): void; setWikiPublisher(fn: (pages: Array<{ path: string; title: string; type: string; content: string; sourceIds: string[]; compiledAt: string; confidence: string; }>) => void): void; /** Check if a memory agent is available for routing memory writes. */ hasMemoryAgent(): boolean; /** Check if delegate tool support is available (multi-agent wired). */ hasDelegateSupport(): boolean; /** Retry delay (ms) for delegate backoff. Initialized from config in constructor. */ private _retryDelayMs; private createDelegationExecutor; private refreshDelegationExecutor; private getDelegationExecutor; constructor(options?: GatewayToolExecutorOptions); beginRuntimeModelRun(input: BeginModelRunInput): Promise; commitRuntimeModelRun(modelRunId: string, summary?: string): Promise; failRuntimeModelRun(modelRunId: string, errorSummary: string): Promise; /** * Set the current agent context for permission checks * @param context - AgentContext with role and permissions */ setAgentContext(context: AgentContext | null): void; /** * Get the current agent context */ getAgentContext(): AgentContext | null; setDiscordGateway(gateway: DiscordGatewayInterface): void; setSlackGateway(gateway: SlackGatewayInterface): void; setTelegramGateway(gateway: TelegramGatewayInterface): void; setContextCompileService(service: GatewayToolExecutorOptions['contextCompileService']): void; /** * Initialize the MAMA API by importing from mcp-server package * Called lazily on first tool execution if not provided in constructor */ private initializeMAMAApi; /** * Check if a tool is allowed for the current context * @param toolName - Name of the tool to check * @returns Object with allowed status and optional error message */ private checkToolPermission; /** * Check if a path is allowed for the current context * @param path - File path to check * @returns Object with allowed status and optional error message */ private checkPathPermission; private enforceEnvelopeForToolCall; private logEnvelopeActivity; /** * Execute a gateway tool with permission checks * * @param toolName - Name of the tool to execute * @param input - Tool input parameters * @returns Tool execution result * @throws AgentError on tool errors or permission denial */ execute(toolName: string, input: GatewayToolInput, executionContext?: GatewayExecutionContext): Promise; private beginTraceIfNeeded; private requireTraceApi; private appendToolTraceIfNeeded; private summarizeToolTraceOutput; private completeDirectModelRunIfNeeded; private failDirectModelRunIfNeeded; private computeScopeAuditFields; private resolveAuditMemoryScopes; private deriveMemoryScopesFromActiveContext; private applyEnvelopeScopedReadDefaults; private buildTrustedMemoryWriteOptions; private supportsTrustedIngest; private supportsTrustedSave; private isMemoryDecisionSaveInput; private logGatewayToolCall; private alarmScopeMismatch; private executeWithEnvelopeAndPermissions; /** * Execute read tool - Read file from filesystem * Checks path permissions based on current AgentContext */ private executeRead; /** * Execute Write tool - Write content to a file * Checks path permissions based on current AgentContext */ private executeWrite; /** * Execute Bash tool - Execute bash command */ private executeBash; /** * Execute discord_send tool - Send message/file to Discord channel * Supports images, documents, and any file type */ private executeDiscordSend; /** * Execute slack_send tool - Send message/file to Slack channel */ private executeSlackSend; /** * Execute telegram_send tool - Send message/file to Telegram chat */ private executeTelegramSend; /** * Navigate to a URL */ private executeBrowserNavigate; /** * Take a screenshot */ private executeBrowserScreenshot; /** * Click an element */ private executeBrowserClick; /** * Type text into an element */ private executeBrowserType; /** * Get page text content */ private executeBrowserGetText; /** * Scroll the page */ private executeBrowserScroll; /** * Wait for element */ private executeBrowserWaitFor; /** * Evaluate JavaScript in page */ private executeBrowserEvaluate; /** * Generate PDF of page */ private executeBrowserPdf; /** * Close the browser */ private executeBrowserClose; /** * Check if current context is from viewer (OS agent) * Returns error message if not allowed */ private checkViewerOnly; /** * Execute os_add_bot tool - Add a new bot to config * Viewer-only: requires systemControl permission */ private executeAddBot; /** * Execute os_set_permissions tool - Modify role permissions * Viewer-only: requires systemControl permission */ private executeSetPermissions; /** * Execute os_get_config tool - Get current configuration * Masks sensitive data for non-viewer sources */ private executeGetConfig; /** * Recursively mask sensitive data in config object */ private maskSensitiveData; /** * Execute os_set_model tool - Set model configuration for a role or globally * Viewer-only: requires systemControl permission * * Usage: * - Set role-specific model: { role: 'chat_bot', model: 'claude-3-haiku-20240307' } * - Set global model: { model: 'claude-sonnet-4-6' } */ private executeSetModel; /** * Callback to get bot status from running gateways * Set by the main application when gateways are initialized */ private botStatusCallback; /** * Callback to control bots * Set by the main application when gateways are initialized */ private botControlCallback; /** * Set the bot status callback (called by main app) */ setBotStatusCallback(callback: () => Map): void; /** * Set the bot control callback (called by main app) */ setBotControlCallback(callback: (platform: BotPlatform, action: 'start' | 'stop') => Promise<{ success: boolean; error?: string; }>): void; /** * Execute os_list_bots tool - List all configured bots and their status */ private executeListBots; /** * Execute os_restart_bot tool - Restart a bot * Viewer-only: requires systemControl permission */ private executeRestartBot; /** * Execute os_stop_bot tool - Stop a bot * Viewer-only: requires systemControl permission */ private executeStopBot; private parsePRUrl; private executePrReviewThreads; /** * Execute webchat_send tool — Send message/file to webchat viewer * Copies file to outbound directory and returns the path for viewer rendering * * Note: session_id removed - all files route to shared outbound dir */ private executeWebchatSend; /** * Execute Obsidian CLI command on the wiki vault. */ private executeObsidian; private resolveCodeActSandboxRole; private normalizeCodeActToolPatterns; private isKnownCodeActToolPattern; private matchesAnyCodeActToolPattern; private matchesCodeActToolPattern; private executeCodeAct; /** * Handle mama_add — auto-extract facts from conversation content with derived memory scopes. */ private handleMamaAdd; private handleMamaIngest; private handleMamaRecall; static getValidTools(): GatewayToolName[]; /** * Check if a tool name is valid */ static isValidTool(toolName: string): toolName is GatewayToolName; private handleContextCompile; } export {}; //# sourceMappingURL=gateway-tool-executor.d.ts.map