/** * 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, MAMAApiSetInput, AgentContext, GatewayToolExecutionContext, BeginModelRunInput, ModelRunRecord, PrincipalRepository } from './types.js'; import type { AgentProcessManager } from '../multi-agent/agent-process-manager.js'; import type { AgentEventBus } from '../multi-agent/agent-event-bus.js'; import type { SQLiteDatabase } from '../sqlite.js'; import { type WikiPublishAdapter } from '../wiki-artifacts/wiki-publish-adapter.js'; import type { WikiPagePublisher } from '../wiki-artifacts/types.js'; import { type PrivateConnectorPolicy } from '../connectors/private-connector-policy.js'; type PrivateAwareGatewayToolExecutorOptions = GatewayToolExecutorOptions & { privateConnectorPolicy?: PrivateConnectorPolicy; }; 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, idempotencyKey?: string): Promise; sendFile(chatId: string, filePath: string, caption?: string, idempotencyKey?: string): Promise; sendImage(chatId: string, imagePath: string, caption?: string, idempotencyKey?: string): Promise; sendSticker(chatId: string | number, emotion: string): Promise; sendMessageFromActiveTurn?(chatId: string, text: string, idempotencyKey?: string): Promise; sendFileFromActiveTurn?(chatId: string, filePath: string, caption?: string, idempotencyKey?: string): Promise; sendImageFromActiveTurn?(chatId: string, imagePath: string, caption?: string, idempotencyKey?: string): Promise; sendStickerFromActiveTurn?(chatId: string | number, emotion: string): Promise; } export declare class GatewayToolExecutor { private readonly driveTools; private readonly imageTranslationTools; private readonly driveDestinationCapabilities; private mamaApi; private readonly mamaDbPath?; private sessionStore?; private discordGateway; private slackGateway; private telegramGateway; private roleManager; private readonly privateConnectorPolicy; private readonly executionContextStorage; private readonly envelopeEnforcer; private readonly channelGrantProvider; private readonly envelopeIssuanceMode; private readonly metricsStore; private principalRepository; private contextCompileService; private temporalContextPacketLookup; private currentContext; private memoryAgentProcessManager; private agentProcessManager; private currentAgentId; private currentSource; private currentChannelId; private disallowedGatewayTools; private reportPublisher; private reportRequestHandler; private workOrderRequestHandler; private reportReader; private wikiPublisher; private wikiPublishAdapter; private obsidianVaultPath; private obsidianVaultName; setObsidianVaultPath(vaultPath: string, vaultName?: string): void; private taskLedger; setTaskLedger(ledger: import('../operator/task-ledger.js').TaskLedger): void; getTaskLedger(): import('../operator/task-ledger.js').TaskLedger | null; private agentEventBus; setAgentEventBus(bus: AgentEventBus): void; getAgentEventBus(): AgentEventBus | null; private sessionsDb; setSessionsDb(db: SQLiteDatabase): void; /** Accepted and discarded: the only reader was the delegation executor, which is gone. * The setter stays because its callers are live - delete both together when a second * reader appears or the callers do not. */ setRawStore(_store: import('../connectors/framework/raw-store.js').RawStore): void; /** Same as setRawStore: the only reader was the delegation executor. */ setValidationService(_svc: import('../validation/session-service.js').ValidationSessionService): void; setMemoryAgent(processManager: AgentProcessManager): void; setAgentProcessManager(pm: AgentProcessManager): 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; withExecutionContext(executionContext: GatewayExecutionContext | undefined, fn: () => Promise): Promise; private requireActiveTemporalAuthority; setCurrentAgentContext(agentId: string, source: string, channelId: string): void; getCurrentAgentRoutingContext(): GatewayContextSnapshot; restoreCurrentAgentRoutingContext(context: GatewayContextSnapshot): void; clearCurrentAgentContext(): void; setDisallowedGatewayTools(tools: string[]): void; setReportPublisher(fn: (slots: Record) => void): void; /** Forwarder hook for on-demand full reports (plan v6 S1-T3). */ setReportRequestHandler(fn: () => { accepted: boolean; reason?: string; }): void; /** Forwarder hook for owner-issued workorders (Stage-2 S2-T4; enqueue+ack only). */ setWorkOrderRequestHandler(fn: (kind: 'board' | 'wiki' | 'memory-curation', causeEventIds?: readonly string[]) => { accepted: boolean; reason?: string; }): void; /** Read seam for the owner board slots (plan v6 S1-T4 artifact hub). */ setReportReader(fn: () => Record): void; setWikiPublisher(fn: WikiPagePublisher): void; setWikiPublishAdapter(adapter: WikiPublishAdapter | null): void; setPrincipalRepository(repository: PrincipalRepository): void; /** Check if a memory agent is available for routing memory writes. */ hasMemoryAgent(): boolean; /** Check if delegate tool support is available (multi-agent wired). */ constructor(options?: PrivateAwareGatewayToolExecutorOptions); 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; /** Wire the shared MAMA API built at boot (initMamaCore) so the executor never * lazily constructs a second API/adapter stack against the same DB. */ setMamaApi(api: MAMAApiSetInput): 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; projectPrivateAgentContext(context: AgentContext): AgentContext; /** * 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 issueDriveDestinationCapability; 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; /** * External lifecycle decisions are only valid while the host-created model run that owns the * claimed board attempt is still running. Tool input cannot name either authority. */ private requireExternalLifecycleModelRun; private beginTraceIfNeeded; private requireTraceApi; private appendToolTraceIfNeeded; private extractFailureCode; private summarizeToolTraceOutput; private completeDirectModelRunIfNeeded; private failDirectModelRunIfNeeded; private computeScopeAuditFields; private resolveAuditMemoryScopes; private deriveMemoryScopesFromActiveContext; private resolveMamaRecallScopes; /** * The grant-mirror READ allowance for memory tools (see mirrorReadScopes): * computed lazily - only memory-scoped tools pay the connector-config read - * and against the LIVE grant, so a channel the owner removes stops being * readable on the next call, mid-envelope included. */ private readScopeMirrorFor; private applyEnvelopeScopedReadDefaults; private buildTrustedMemoryWriteOptions; 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; /** * 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 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; /** * schedule_upcoming (M8 P4): read the calendar connector's raw store and * return events in [now, now+days] plus a compact text digest. Lazy readonly * open (operator-handler pattern); prefers metadata JSON start when present. * v1 limits (documented in the tool description): no recurrence expansion, * no cancellation tracking. */ private scheduleDb; private executeScheduleUpcoming; /** * Execute Obsidian CLI command on the wiki vault. */ private executeObsidian; private executeCodeAct; /** * Answer what a stored claim rests on. * * The counterpart to recall, and the reason recall now returns an id at all: an agent * that can only read memories can assert them, while an agent that can resolve them can * say which ones a statement stands on - or that a statement stands on nothing. That * second answer is the one the original bad report could not produce. * * Scope is re-derived here rather than trusted from the caller, and the connector grant * is read off the active envelope, so this path can never show an event that the normal * raw read would refuse. */ private handleMamaProvenance; 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