/** * Agent Loop Engine for MAMA Standalone * * Main orchestrator that: * - Maintains conversation history * - Calls Claude API via ClaudeClient * - Parses tool_use blocks from responses * - Executes tools via MCPExecutor * - Sends tool_result back to Claude * - Loops until stop_reason is "end_turn" or max turns reached */ import type { OAuthManager } from '../auth/index.js'; import type { ContentBlock, ToolDefinition, AgentLoopOptions, AgentLoopResult, ClaudeClientOptions, GatewayToolExecutorOptions, AgentContext, GatewayToolExecutionContext } from './types.js'; /** * Load composed system prompt with persona layers + CLAUDE.md + optional context * Tries to load persona files from ~/.mama/ in order: * 1. SOUL.md (philosophical principles) * 2. IDENTITY.md (role and character) * 3. USER.md (user preferences) * 4. **Context Prompt** (if AgentContext provided - role awareness) * 5. CLAUDE.md (base instructions) * * If persona files are missing, logs warning and continues with CLAUDE.md alone. * * @param verbose - Enable verbose logging * @param context - Optional AgentContext for role-aware prompt injection */ /** * Load backend-specific AGENTS.md from ~/.mama/ * Maps backend to file: 'claude' → AGENTS.claude.md, 'codex-mcp' → AGENTS.codex.md */ export declare function loadBackendAgentsMd(backend?: string, verbose?: boolean): string; export declare function loadComposedSystemPrompt(verbose?: boolean, context?: AgentContext): string; export declare function getGatewayToolsPrompt(disallowed?: string[]): string; export type AgentToolExecutionContext = GatewayToolExecutionContext; export declare function buildAgentToolExecutionContext(options?: AgentLoopOptions): AgentToolExecutionContext | null; export declare class AgentLoop { private readonly agent; private readonly persistentCLI; private readonly mcpExecutor; private readonly maxTurns; private readonly model; private readonly onTurn?; private readonly onToolUse?; private readonly onTokenUsage?; private readonly onMetric?; private readonly laneManager; private readonly useLanes; private sessionKey; private readonly sessionPool; private readonly toolsConfig; private readonly isGatewayMode; private readonly useCodeAct; private readonly backend; private readonly defaultSystemPrompt; private readonly postToolHandler; private readonly stopContinuationHandler; private readonly preCompactHandler; private preCompactInjected; private currentStreamCallbacks?; private currentTier; private readonly disallowedTools?; constructor(_oauthManager: OAuthManager, options?: AgentLoopOptions, _clientOptions?: ClaudeClientOptions, executorOptions?: GatewayToolExecutorOptions); setContextCompileService(service: GatewayToolExecutorOptions['contextCompileService']): void; /** * Set session key for lane-based concurrency * Use format: "{source}:{channelId}:{userId}" */ setSessionKey(key: string): void; /** * Get current session key */ getSessionKey(): string; private resolveGlobalLaneForSession; private buildToolExecutionContext; /** * Set system prompt override (for per-message context injection) */ setSystemPrompt(prompt: string | undefined): void; /** * Set Discord gateway for discord_send tool */ setDiscordGateway(gateway: { sendMessage(channelId: string, message: string): Promise; sendFile(channelId: string, filePath: string, caption?: string): Promise; sendImage(channelId: string, imagePath: string, caption?: string): Promise; }): void; /** * Set Telegram gateway for telegram_send tool */ setTelegramGateway(gateway: { 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; }): void; /** * Set shared sessions DB for agent management and validation-aware tools. */ setSessionsDb(db: import('../sqlite.js').default): void; /** * Set UI command queue for viewer_state / viewer_navigate tools. */ setUICommandQueue(queue: import('../api/ui-command-handler.js').UICommandQueue): void; /** * Set validation service for agent_test / delegate validation flows. */ setValidationService(svc: import('../validation/session-service.js').ValidationSessionService): void; /** * Set raw store for connector-backed agent_test input gathering. */ setRawStore(store: import('../connectors/framework/raw-store.js').RawStore): void; /** * Set report publisher for report_publish tool (Dashboard Agent) */ setReportPublisher(fn: (slots: Record) => void): void; /** * Set wiki publisher for wiki_publish tool (Wiki Agent) */ setWikiPublisher(fn: (pages: Array<{ path: string; title: string; type: string; content: string; sourceIds: string[]; compiledAt: string; confidence: string; }>) => void): void; /** * Set AgentProcessManager for delegate tool (multi-agent delegation) */ setAgentProcessManager(pm: import('../multi-agent/agent-process-manager.js').AgentProcessManager): void; /** * Set DelegationManager for delegate tool (permission checks) */ setDelegationManager(dm: import('../multi-agent/delegation-manager.js').DelegationManager): void; /** * Set runtime multi-agent config applier for agent management tools. */ setApplyMultiAgentConfig(fn: ((config: Record) => Promise) | null): void; /** * Set per-agent runtime restarter for agent management tools. */ setRestartMultiAgentAgent(fn: ((agentId: string) => Promise) | null): void; /** * Set AgentEventBus for agent_notices tool */ setAgentEventBus(eventBus: import('../multi-agent/agent-event-bus.js').AgentEventBus): void; /** * Run the agent loop with a user prompt * * Uses lane-based concurrency when useLanes is enabled: * - Same session messages are processed in order * - Different sessions can run in parallel * - Global lane limits total concurrent API calls * * @param prompt - User prompt to process * @param options - Execution options (systemPrompt, disableAutoRecall, etc.) * @returns Agent loop result with final response and history * @throws AgentError on errors */ run(prompt: string, options?: AgentLoopOptions): Promise; /** * Run the agent loop with multimodal content blocks * * Uses lane-based concurrency when useLanes is enabled. * * @param content - Array of content blocks (text, images, documents) * @param options - Execution options (systemPrompt, disableAutoRecall, etc.) * @returns Agent loop result with final response and history * @throws AgentError on errors */ runWithContent(content: ContentBlock[], options?: AgentLoopOptions): Promise; /** * Internal implementation of runWithContent (without lane queueing) */ private runWithContentInternal; private shouldBeginModelRun; private withBackgroundTaskRegistry; private drainBackgroundTasks; private buildModelRunInput; /** * Execute tools from response content blocks */ private executeTools; /** * Search MAMA for contracts related to a tool operation. * Used as PreToolUse interceptor — searches for contract_* topics * related to the file being written/edited. * * Non-blocking: returns empty string if search fails or no contracts found. */ private searchContractsForTool; /** * Parse tool_call blocks from text response (Gateway Tools mode) * Format: ```tool_call\n{"name": "...", "input": {...}}\n``` */ private parseToolCallsFromText; /** * Parse ```js code blocks as code_act tool calls (Code-Act mode) */ private parseCodeActBlocks; /** * Execute Code-Act JS code in a sandboxed QuickJS environment */ private executeCodeAct; /** * Remove tool_call and code_act blocks from text (to avoid duplication in response) */ private removeToolCallBlocks; private extractTextFromContent; /** * Extract text response from the last assistant message */ private extractTextResponse; /** * Format only the last user message for persistent CLI * Persistent CLI maintains context automatically, so we only send the new message */ private formatLastMessageOnly; /** * Get the MAMA tool definitions */ static getToolDefinitions(): ToolDefinition[]; /** * Get the default system prompt (verbose logging) */ static getDefaultSystemPrompt(): string; /** * Stop and cleanup the AgentLoop resources */ private stopped; stop(): Promise; } //# sourceMappingURL=agent-loop.d.ts.map