/** * Master Orchestrator Agent * * This is the BRAIN - it orchestrates, remembers, and delegates. * It does NOT do the work itself. Claude Code CLI workers do the work. */ import type { MessageParam } from '@anthropic-ai/sdk/resources/messages'; import { LiaTask, LiaPlan } from './core/task-queue.js'; export type MessageSender = (message: string) => Promise; export interface WorkerStatus { id: string; task: string; status: 'running' | 'completed' | 'failed' | 'timeout'; progress: number; elapsed: number; estimated: number; } export type WorkerStatusCallback = (workers: WorkerStatus[]) => void; export type WorkerLogCallback = (workerId: string, line: string, stream: 'stdout' | 'stderr') => void; export interface LiaTodoItem { id: string; content: string; activeForm: string; status: 'pending' | 'in_progress' | 'completed'; workerId?: string; progress?: number; } export type TodoUpdateCallback = (todos: LiaTodoItem[]) => void; export interface WorkerAsset { path: string; name: string; type: 'new' | 'modified' | 'unchanged'; fileType: 'code' | 'image' | 'pdf' | 'text' | 'other'; preview?: string; diff?: Array<{ type: 'context' | 'add' | 'remove'; content: string; }>; } export interface GalleryWorker { id: string; task: string; status: 'running' | 'completed' | 'failed'; assets: WorkerAsset[]; } export type GalleryCallback = (workers: GalleryWorker[]) => void; export type InstanceMode = 'personal' | 'team'; export declare class MasterOrchestrator { private client; private model; private maxTokens; private toolMaxTokens; private memory; private contextGraph; private orgMemory?; private orgContextGraph?; private orgId?; private orgRole?; private instanceMode; private userOrgMemories; private userOrgContextGraphs; private scheduler; private indexer; private jobs; private jobCounter; private workerStatusCallback; private workerLogCallback; private workerStatusInterval; private attachmentContext; private lastUserMessage; private currentMessageId; private galleryCallback; private userId; private workspaceDir; private claudePath; private initialized; private currentFileScope; private forceTeamWorkingDir; private recentFileWrites; private recentWorkerActivity; private bashTool; private webTools; private workerTools; private calendarTools; private sharedState; private verboseMode; private taskQueue; private taskUpdateCallback?; private planUpdateCallback?; private currentTodos; private todoUpdateCallback?; constructor(options: { apiKey: string; userId: string; orgId?: string; orgRole?: 'owner' | 'member'; workspaceDir?: string; model?: string; maxTokens?: number; voyageApiKey?: string; instanceMode?: InstanceMode; userOrgIds?: string[]; }); /** * Initialize the orchestrator - indexes filesystem on first call */ initialize(): Promise; /** * Set callback for worker status updates (for UI progress bars) */ setWorkerStatusCallback(callback: WorkerStatusCallback | null): void; /** * Set callback for worker log streaming */ setWorkerLogCallback(callback: WorkerLogCallback | null): void; /** * Set callback for gallery updates (worker assets for UI gallery view) */ setGalleryCallback(callback: GalleryCallback | null): void; /** * Set callback for task queue updates (for real-time UI updates) */ setTaskUpdateCallback(callback: ((task: LiaTask) => void) | null): void; /** * Set callback for plan updates (for real-time UI updates) */ setPlanUpdateCallback(callback: ((plan: LiaPlan) => void) | null): void; /** * Set callback for visible todo list updates (displayed inline in chat) */ setTodoUpdateCallback(callback: TodoUpdateCallback | null): void; /** * Queue a message for async processing (non-blocking) * Returns immediately with task ID - use callbacks or getTaskQueueStatus for results */ queueMessage(message: string, options?: { priority?: 'urgent' | 'high' | 'normal' | 'low'; messageId?: string; }): LiaTask; /** * Process a task from the queue (called by LiaTaskQueue) */ private processQueuedTask; /** * Get task queue status (for UI) */ getTaskQueueStatus(): { isProcessing: boolean; currentTask: LiaTask | null; pendingCount: number; queuePreview: string[]; }; /** * Get pending tasks */ getPendingTasks(): LiaTask[]; /** * Get task by ID */ getTask(taskId: string): LiaTask | null; /** * Cancel a pending task */ cancelTask(taskId: string): boolean; /** * Get Lia's internal todo list formatted for context */ getTaskQueueContext(): string; /** * Get gallery workers with their assets */ getGalleryWorkers(): GalleryWorker[]; /** * Broadcast gallery update to callback */ private broadcastGalleryUpdate; /** * Get current status of all workers (from both delegateToWorker and spawn_worker) */ getWorkerStatus(): WorkerStatus[]; /** * Broadcast worker status to callback */ private broadcastWorkerStatus; /** * Estimate task duration based on content */ private estimateTaskDuration; /** * Find the claude binary path */ private findClaudeBinary; /** * Handle slash commands */ private handleSlashCommand; private extractAttachmentContext; private stripTodoSnapshot; private hasTodoMutation; private hasCalendarMutation; private hasFileMutation; private hasHumanChatMutation; private getUserTagHint; private getBreakdownTarget; private ensureBreakdownOriginalDone; private getLocalDateKey; private getLocalTimeZone; private getTodoCalSystemPrompt; private getToolChoice; private recordUsage; private withAttachments; private updateFileScope; private getTeamFilesDir; private getFileScopeOverrides; private rewriteFilesAlias; private resolveFilesWritePath; private toFilesVirtualPath; private finalizeResponse; private getFileScopeSystemNote; private recordWorkerActivity; private formatRelativeTime; private getRecentWorkerSummary; private isStatusInquiry; private buildStatusReply; /** * Check if verbose mode is enabled */ isVerbose(): boolean; /** * Process a user message */ processMessage(message: string, conversationHistory?: MessageParam[], sendMessage?: MessageSender): Promise; private tryHandleCalendarTodo; private extractTodoItems; private extractCalendarEvents; private parseCalendarEvent; private parseExplicitDateTimeEvent; private to24h; private nextOccurrence; private toDateKey; /** * Get relevant memory context for a message * Routes based on instanceMode: * - personal: search personal memories + all team memories * - team: search ONLY team memory (never personal - team Lia is isolated) */ private getMemoryContext; /** * Auto-remember important information from conversations * Routes based on instanceMode: * - personal: write to personal memory * - team: write to team memory */ private autoRemember; private autoCaptureContext; private normalizeEntityName; private isIgnoredEntity; /** * Run the agentic loop */ private runAgentLoop; /** * Get tool definitions for the orchestrator */ private getToolDefinitions; /** * Process tool calls */ private processToolCalls; private workerResultCallback; /** * Set callback for when workers complete (for async notification) */ setWorkerResultCallback(callback: ((workerId: string, result: string) => void) | null): void; setCurrentMessageId(messageId?: string): void; /** * Delegate task to Claude Code CLI worker - NON-BLOCKING * Returns immediately, sends results via callback when done */ private delegateToWorker; /** * Try to recover worker output from log file * Workers are instructed to write logs to /tmp/worker-{id}-log.txt */ private recoverWorkerLog; /** * Log worker failure to memory for learning */ private logWorkerFailure; /** * Extract memory and coordination contributions from worker output * Workers can contribute using: * - [MEMORY] type=X | content=Y * - [SHARE] key=X | value=Y * - [SIGNAL] name=X | data=Y * - [MESSAGE] to=X | content=Y */ private extractWorkerMemories; /** * Execute remember tool * Routes writes based on instanceMode: * - personal: write to personal memory only * - team: write to team memory only */ private executeRemember; /** * Execute search memory tool * Routes searches based on instanceMode: * - personal: search personal + all team memories * - team: search team memory only (never personal) */ private executeSearchMemory; /** * Execute schedule task tool */ private executeScheduleTask; /** * Execute list scheduled tool */ private executeListScheduled; /** * Execute memory stats tool */ private executeMemoryStats; /** * Open a URL in the user's default browser */ private executeOpenBrowser; /** * Start a persistent HTTP server */ private executeStartServer; /** * Stop a running server on a port */ private executeStopServer; /** * Create a plan with steps (Lia's internal planning) */ private executeLiaPlan; /** * Add a task to Lia's internal queue */ private executeLiaAddTask; /** * Get Lia's task queue status */ private executeLiaGetQueue; /** * Update visible todo list (displayed inline in chat) */ private executeLiaTodoWrite; /** * Format tool preview for user */ private formatToolPreview; private hasToolUse; private extractText; /** * Shutdown cleanly */ shutdown(): Promise; }