openviber 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/task.ts","../src/core/message.ts","../src/core/provider.ts","../src/config.ts","../src/storage/adapters/local.ts","../src/storage/base.ts","../src/storage/adapters/supabase.ts","../src/storage/space.ts","../src/utils/id.ts","../src/data/adapters/local.ts","../src/data/adapters/supabase-server.ts","../src/data/factory.ts","../src/tools/base.ts","../src/tools/file.ts","../src/tools/search-config.ts","../src/tools/search.ts","../src/tools/web.ts","../src/tools/browser.ts","../src/tools/desktop.ts","../src/tools/index.ts","../src/core/tool.ts","../src/skills/registry.ts","../src/core/agent.ts","../src/core/plan.ts","../src/core/viber-agent.ts","../src/core/collaboration.ts","../src/core/space.ts","../src/index.ts","../src/data/manager.ts","../src/state/store.ts","../src/daemon/controller.ts","../src/daemon/runtime.ts","../src/daemon/terminal.ts"],"sourcesContent":["/**\n * Task - Individual execution units within a space\n */\n\nexport enum TaskStatus {\n PENDING = \"pending\",\n RUNNING = \"running\",\n COMPLETED = \"completed\",\n FAILED = \"failed\",\n BLOCKED = \"blocked\",\n CANCELLED = \"cancelled\",\n}\n\nexport interface TaskStep {\n id: string;\n description: string;\n status: TaskStatus;\n startedAt?: Date;\n completedAt?: Date;\n error?: string;\n}\n\nexport interface TaskDependency {\n taskId: string;\n type: \"required\" | \"optional\";\n}\n\nexport class Task {\n public id: string;\n public title: string;\n public description: string;\n public status: TaskStatus;\n public assignedTo?: string;\n public priority: \"low\" | \"medium\" | \"high\";\n public estimatedTime?: string;\n public actualTime?: string;\n public dependencies: TaskDependency[];\n public steps: TaskStep[];\n public tags: string[];\n public metadata: Record<string, any>;\n public createdAt: Date;\n public updatedAt: Date;\n public startedAt?: Date;\n public completedAt?: Date;\n public error?: string;\n\n constructor({\n id,\n title,\n description,\n status = TaskStatus.PENDING,\n assignedTo,\n priority = \"medium\",\n estimatedTime,\n dependencies = [],\n steps = [],\n tags = [],\n metadata = {},\n }: {\n id: string;\n title: string;\n description: string;\n status?: TaskStatus;\n assignedTo?: string;\n priority?: \"low\" | \"medium\" | \"high\";\n estimatedTime?: string;\n dependencies?: TaskDependency[];\n steps?: TaskStep[];\n tags?: string[];\n metadata?: Record<string, any>;\n }) {\n this.id = id;\n this.title = title;\n this.description = description;\n this.status = status;\n this.assignedTo = assignedTo;\n this.priority = priority;\n this.estimatedTime = estimatedTime;\n this.dependencies = dependencies;\n this.steps = steps;\n this.tags = tags;\n this.metadata = metadata;\n this.createdAt = new Date();\n this.updatedAt = new Date();\n }\n\n start(): void {\n if (this.status !== TaskStatus.PENDING) {\n throw new Error(`Cannot start task in ${this.status} status`);\n }\n this.status = TaskStatus.RUNNING;\n this.startedAt = new Date();\n this.updatedAt = new Date();\n }\n\n complete(): void {\n if (this.status !== TaskStatus.RUNNING) {\n throw new Error(`Cannot complete task in ${this.status} status`);\n }\n this.status = TaskStatus.COMPLETED;\n this.completedAt = new Date();\n this.updatedAt = new Date();\n if (this.startedAt) {\n this.actualTime = this.calculateDuration(\n this.startedAt,\n this.completedAt\n );\n }\n }\n\n fail(error: string): void {\n this.status = TaskStatus.FAILED;\n this.error = error;\n this.completedAt = new Date();\n this.updatedAt = new Date();\n }\n\n block(reason: string): void {\n this.status = TaskStatus.BLOCKED;\n this.error = reason;\n this.updatedAt = new Date();\n }\n\n cancel(): void {\n this.status = TaskStatus.CANCELLED;\n this.completedAt = new Date();\n this.updatedAt = new Date();\n }\n\n isActionable(context?: { getTaskStatus: (id: string) => TaskStatus | undefined }): boolean {\n return (\n this.status === TaskStatus.PENDING && !this.hasBlockingDependencies(context)\n );\n }\n\n hasBlockingDependencies(context?: { getTaskStatus: (id: string) => TaskStatus | undefined }): boolean {\n if (!context || !this.dependencies || this.dependencies.length === 0) {\n return false;\n }\n\n return this.dependencies.some((dep) => {\n // Only required dependencies block execution\n if (dep.type === \"optional\") return false;\n\n const status = context.getTaskStatus(dep.taskId);\n // Block if dependency is not completed (or cancelled/failed if strict, but let's say COMPLETED)\n // If status is undefined (task not found), we assume it's missing -> blocking\n return status !== TaskStatus.COMPLETED;\n });\n }\n\n private calculateDuration(start: Date, end: Date): string {\n const ms = end.getTime() - start.getTime();\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n\n if (hours > 0) {\n return `${hours}h ${minutes % 60}m`;\n } else if (minutes > 0) {\n return `${minutes}m ${seconds % 60}s`;\n } else {\n return `${seconds}s`;\n }\n }\n\n toJSON(): any {\n return {\n id: this.id,\n title: this.title,\n description: this.description,\n status: this.status,\n assignedTo: this.assignedTo,\n priority: this.priority,\n estimatedTime: this.estimatedTime,\n actualTime: this.actualTime,\n dependencies: this.dependencies,\n steps: this.steps,\n tags: this.tags,\n metadata: this.metadata,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n startedAt: this.startedAt?.toISOString(),\n completedAt: this.completedAt?.toISOString(),\n error: this.error,\n };\n }\n\n static fromJSON(data: any): Task {\n const task = new Task({\n id: data.id,\n title: data.title,\n description: data.description,\n status: data.status,\n assignedTo: data.assignedTo,\n priority: data.priority,\n estimatedTime: data.estimatedTime,\n dependencies: data.dependencies,\n steps: data.steps,\n tags: data.tags,\n metadata: data.metadata,\n });\n\n task.createdAt = new Date(data.createdAt);\n task.updatedAt = new Date(data.updatedAt);\n task.actualTime = data.actualTime;\n task.error = data.error;\n\n if (data.startedAt) {\n task.startedAt = new Date(data.startedAt);\n }\n if (data.completedAt) {\n task.completedAt = new Date(data.completedAt);\n }\n\n return task;\n }\n}\n","/**\n * Message types for Viber - Using AI SDK v6 types directly\n */\n\nimport type { ModelMessage } from 'ai';\n\n// Extend CoreMessage to include our metadata\nexport interface ViberMessage {\n role: 'system' | 'user' | 'assistant' | 'function' | 'data' | 'tool';\n content: any;\n id?: string; // Message ID (includes agent prefix for tracking)\n metadata?: {\n agentName?: string;\n timestamp?: number;\n [key: string]: any;\n };\n}\n\n// Use ViberMessage as our Message type\nexport type Message = ViberMessage;\n\n/**\n * Get text content from a message\n */\nexport function getTextContent(message: Message): string {\n if (!message || !message.content) {\n return '';\n }\n\n if (typeof message.content === 'string') {\n return message.content;\n }\n\n if (Array.isArray(message.content)) {\n return message.content\n .filter((part: any) => part && part.type === 'text')\n .map((part: any) => part.text || '')\n .join(' ');\n }\n\n return '';\n}\n\n/**\n * Queued message with metadata\n */\nexport interface QueuedMessage {\n id: string;\n content: string;\n status: 'queued' | 'processing' | 'completed' | 'error';\n timestamp: number;\n edited?: boolean;\n error?: string;\n metadata?: any;\n}\n\n/**\n * Queue state for UI\n */\nexport interface QueueState {\n current?: QueuedMessage;\n queue: QueuedMessage[];\n processing: boolean;\n}\n\n/**\n * Queue listener type\n */\nexport type QueueListener = (state: QueueState) => void;\n\n/**\n * Enhanced Message Queue with management capabilities\n */\nexport class MessageQueue {\n private queue: QueuedMessage[] = [];\n private current?: QueuedMessage;\n private processing = false;\n private listeners = new Set<QueueListener>();\n private nextId = 1;\n\n /**\n * Add message to queue\n */\n add(content: string, metadata?: any): string {\n const message: QueuedMessage = {\n id: `msg-${this.nextId++}`,\n content,\n status: 'queued',\n timestamp: Date.now(),\n metadata,\n };\n\n this.queue.push(message);\n this.notify();\n return message.id;\n }\n\n /**\n * Get next message from queue\n */\n next(): QueuedMessage | undefined {\n const message = this.queue.shift();\n if (message) {\n message.status = 'processing';\n this.current = message;\n this.processing = true;\n this.notify();\n }\n return message;\n }\n\n /**\n * Mark current message as complete\n */\n complete(messageId: string) {\n if (this.current?.id === messageId) {\n this.current.status = 'completed';\n this.current = undefined;\n this.processing = false;\n this.notify();\n }\n }\n\n /**\n * Mark current message as error\n */\n error(messageId: string, error: string) {\n if (this.current?.id === messageId) {\n this.current.status = 'error';\n this.current.error = error;\n this.current = undefined;\n this.processing = false;\n this.notify();\n }\n }\n\n /**\n * Remove message from queue\n */\n remove(messageId: string): boolean {\n const index = this.queue.findIndex(m => m.id === messageId);\n if (index > -1) {\n this.queue.splice(index, 1);\n this.notify();\n return true;\n }\n return false;\n }\n\n /**\n * Reorder queue\n */\n reorder(messageId: string, newIndex: number) {\n const currentIndex = this.queue.findIndex(m => m.id === messageId);\n if (currentIndex > -1 && newIndex >= 0 && newIndex < this.queue.length) {\n const [message] = this.queue.splice(currentIndex, 1);\n this.queue.splice(newIndex, 0, message);\n this.notify();\n }\n }\n\n /**\n * Edit queued message\n */\n edit(messageId: string, content: string) {\n const message = this.queue.find(m => m.id === messageId);\n if (message && message.status === 'queued') {\n message.content = content;\n message.edited = true;\n this.notify();\n }\n }\n\n /**\n * Clear all queued messages\n */\n clear() {\n this.queue = [];\n this.notify();\n }\n\n /**\n * Get queue state\n */\n getState(): QueueState {\n return {\n current: this.current,\n queue: [...this.queue],\n processing: this.processing,\n };\n }\n\n /**\n * Subscribe to queue changes\n */\n subscribe(listener: QueueListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Check if queue is empty\n */\n isEmpty(): boolean {\n return this.queue.length === 0;\n }\n\n /**\n * Check if processing\n */\n isProcessing(): boolean {\n return this.processing;\n }\n\n /**\n * Notify listeners\n */\n private notify() {\n const state = this.getState();\n this.listeners.forEach(listener => listener(state));\n }\n}\n\n/**\n * Conversation History management\n */\nexport class ConversationHistory {\n public messages: Message[] = [];\n\n add(message: Message): void {\n // Ensure message has an ID\n if (!message.id) {\n const agentName = message.metadata?.agentName || 'unknown';\n const prefix = agentName.toLowerCase().replace(/\\s+/g, '-');\n const randomId = Math.random().toString(36).substring(2, 10);\n message.id = `${prefix}_${randomId}`;\n }\n this.messages.push(message);\n }\n\n getMessages(): Message[] {\n return [...this.messages];\n }\n\n getLastN(n: number): Message[] {\n return this.messages.slice(-n);\n }\n\n clear(): void {\n this.messages = [];\n }\n\n toModelMessages(): ModelMessage[] {\n // Convert to AI SDK format, cleaning content appropriately\n return this.messages\n .map(msg => {\n // Skip tool messages - they can't be passed without their parent tool_calls\n if (msg.role === 'tool') {\n return null;\n }\n\n // Clean content to be AI SDK compatible\n let cleanContent: any = msg.content;\n\n // If content is an array, extract only text parts\n if (Array.isArray(msg.content)) {\n const textParts = msg.content.filter((part: any) => part.type === 'text');\n if (textParts.length > 0) {\n // Join all text parts into a single string\n cleanContent = textParts\n .map((part: any) => part.text || '')\n .filter((text: string) => text)\n .join('\\n');\n } else {\n // No text content, skip this message\n return null;\n }\n }\n\n // Skip messages with no content\n if (!cleanContent) {\n return null;\n }\n\n return {\n role: msg.role,\n content: cleanContent,\n };\n })\n .filter(msg => msg !== null) as ModelMessage[];\n }\n}","/**\n * AI Provider Management\n * Handles initialization and configuration of different AI providers\n *\n * Philosophy: Keep it simple - agents specify their provider and model explicitly.\n *\n * To add a new provider (e.g., Google, Mistral, Cohere):\n * 1. Install: `pnpm add @ai-sdk/google`\n * 2. Import: `import { createGoogleGenerativeAI } from \"@ai-sdk/google\";`\n * 3. Add case: `case \"google\": return createGoogleGenerativeAI({...})`\n * 4. Add environment variable handling\n */\n\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { deepseek } from \"@ai-sdk/deepseek\";\nimport { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\n\nexport type ModelProvider = string; // Allow any provider string for extensibility\n\nexport interface ModelConfig {\n provider: ModelProvider;\n modelName: string;\n apiKey?: string;\n baseURL?: string;\n // Viber-specific options\n spaceId?: string;\n userId?: string; // For usage tracking (e.g., Helicone)\n storageRoot?: string;\n teamConfig?: string;\n defaultGoal?: string;\n}\n\n/**\n * Get the appropriate AI provider instance\n */\nexport function getModelProvider(config: ModelConfig) {\n const {\n provider,\n apiKey,\n baseURL,\n spaceId,\n userId,\n storageRoot,\n teamConfig,\n defaultGoal,\n } = config;\n\n switch (provider) {\n case \"anthropic\":\n return createAnthropic({\n apiKey: apiKey || process.env.ANTHROPIC_API_KEY,\n baseURL: baseURL || process.env.ANTHROPIC_BASE_URL,\n });\n\n case \"openai\":\n return createOpenAI({\n apiKey: apiKey || process.env.OPENAI_API_KEY,\n baseURL: baseURL || process.env.OPENAI_BASE_URL,\n });\n\n case \"deepseek\":\n return deepseek;\n\n case \"openrouter\":\n // Use the official OpenRouter SDK (v2.0.2+ for AI SDK 6 compatibility)\n const openrouterConfig: any = {\n apiKey: apiKey || process.env.OPENROUTER_API_KEY,\n };\n\n // Use Helicone gateway for observability if configured\n if (process.env.HELICONE_API_KEY) {\n openrouterConfig.baseURL =\n baseURL || \"https://openrouter.helicone.ai/api/v1\";\n openrouterConfig.headers = {\n \"Helicone-Auth\": `Bearer ${process.env.HELICONE_API_KEY}`,\n \"Helicone-Property-User\": userId || \"anonymous\",\n \"Helicone-Property-Space\": spaceId || \"default\",\n };\n }\n\n return createOpenRouter(openrouterConfig);\n\n default:\n // For other providers, assume they follow the standard pattern\n // This allows users to add support for Google, Mistral, Cohere, etc.\n // by providing the appropriate imports and configuration\n throw new Error(\n `Provider '${provider}' is not configured. ` +\n `To use ${provider}, add the appropriate AI SDK provider import and configuration to core/provider.ts`,\n );\n }\n}\n\n/**\n * Check if a provider is properly configured\n */\nexport function isProviderConfigured(provider: string): boolean {\n switch (provider) {\n case \"anthropic\":\n return !!process.env.ANTHROPIC_API_KEY;\n case \"openai\":\n return !!process.env.OPENAI_API_KEY;\n case \"deepseek\":\n return !!process.env.DEEPSEEK_API_KEY;\n case \"openrouter\":\n return !!process.env.OPENROUTER_API_KEY;\n case \"google\":\n // Google provider needs to be imported and configured\n return false; // Not yet implemented\n case \"mistral\":\n return false; // Not yet implemented\n case \"cohere\":\n return false; // Not yet implemented\n default:\n return false;\n }\n}\n\n/**\n * Get list of configured providers\n */\nexport function getConfiguredProviders(): string[] {\n const providers = [\n \"anthropic\",\n \"openai\",\n \"deepseek\",\n \"openrouter\",\n \"google\",\n \"mistral\",\n \"cohere\",\n ];\n return providers.filter(isProviderConfigured);\n}\n\n/**\n * Parse model string to extract provider and model name\n * Examples: \"gpt-4o\" -> { provider: \"openai\", modelName: \"gpt-4o\" }\n */\nexport function parseModelString(model: string): ModelConfig {\n // Viber models are handled differently - not through this parser\n // if (model.startsWith(\"viber-\") || model === \"viber\") {\n // return { provider: \"viber\", modelName: model };\n // }\n\n // Anthropic models (direct access)\n if (model.startsWith(\"claude-\")) {\n return { provider: \"anthropic\", modelName: model };\n }\n\n // Deepseek models (direct access)\n if (model.startsWith(\"deepseek-\")) {\n return { provider: \"deepseek\", modelName: model };\n }\n\n // Models with \"/\" are OpenRouter format (e.g., \"deepseek/deepseek-chat\", \"openai/gpt-4o-mini\")\n // OpenRouter API expects upstream provider/model only — never prefix with \"openrouter/\"\n if (model.includes(\"/\")) {\n const modelName = model.startsWith(\"openrouter/\")\n ? model.slice(\"openrouter/\".length)\n : model;\n return { provider: \"openrouter\", modelName };\n }\n\n // Simple model names default to OpenAI (e.g., \"gpt-4o\", \"gpt-4o-mini\")\n return { provider: \"openai\", modelName: model };\n}\n\n/**\n * Get context limit for a model\n */\nexport function getModelContextLimit(modelName: string): number {\n const contextLimits: Record<string, number> = {\n // Viber (uses underlying model limits dynamically)\n viber: 100000,\n \"viber-default\": 100000,\n\n // Deepseek\n \"deepseek-chat\": 65536,\n \"deepseek-reasoner\": 65536,\n\n // OpenRouter models\n \"anthropic/claude-3.5-sonnet\": 150000,\n \"anthropic/claude-3.5-haiku\": 150000,\n \"openai/gpt-4o\": 100000,\n \"openai/o1-preview\": 100000,\n \"google/gemini-2.0-flash-exp:free\": 100000,\n \"meta-llama/llama-3.3-70b-instruct\": 32000,\n\n // Anthropic\n \"claude-3-5-sonnet-20240620\": 150000,\n \"claude-3-haiku-20240307\": 150000,\n \"claude-3-opus-20240229\": 150000,\n\n // OpenAI\n \"gpt-4o\": 100000,\n \"gpt-4o-mini\": 100000,\n \"gpt-4-turbo\": 100000,\n \"gpt-3.5-turbo\": 16000,\n };\n\n return contextLimits[modelName] || 50000; // Default to 50k\n}\n\n/**\n * Get completion token reservation for a model\n */\nexport function getCompletionTokens(modelName: string): number {\n if (modelName.startsWith(\"deepseek-reasoner\")) {\n return 32000; // Deepseek reasoner needs more tokens\n }\n if (modelName.startsWith(\"deepseek-\")) {\n return 8000;\n }\n return 4000; // Default for most models\n}\n","/**\n * OpenViber Configuration\n * \n * Runtime configuration for the openviber framework.\n * Applications should call configure() before using openviber.\n */\n\nimport type { SupabaseClient } from '@supabase/supabase-js';\nimport os from 'os';\nimport path from 'path';\n\nexport interface ViberConfig {\n /** Root directory for file storage */\n storageRoot: string;\n\n /** Supabase client factory for database operations */\n createSupabaseClient?: () => SupabaseClient | null;\n\n /** Supabase service role client factory for admin operations */\n createServiceRoleClient?: () => SupabaseClient | null;\n\n /** Defaults directory path */\n defaultsPath?: string;\n}\n\nlet config: ViberConfig | null = null;\n\n/**\n * Configure viber with application-specific settings\n */\nexport function configure(newConfig: ViberConfig): void {\n config = newConfig;\n}\n\n/**\n * Get current viber configuration\n */\nexport function getConfig(): ViberConfig {\n if (!config) {\n // Default configuration - use ~/.openviber for daemon mode\n return {\n storageRoot: path.join(os.homedir(), '.openviber'),\n defaultsPath: './defaults',\n };\n }\n return config;\n}\n\n/**\n * Get viber storage root path\n */\nexport function getViberRoot(): string {\n return getConfig().storageRoot;\n}\n\n/**\n * Get path relative to viber root\n */\nexport function getViberPath(...segments: string[]): string {\n const root = getViberRoot();\n return [root, ...segments].join('/');\n}\n\n/**\n * ViberPaths - Path utilities\n */\nexport const ViberPaths = {\n getRoot: getViberRoot,\n getPath: getViberPath,\n getDefaultsPath: () => getConfig().defaultsPath || './defaults',\n};\n\n/**\n * Get Supabase client\n */\nexport function getSupabaseClient(): SupabaseClient | null {\n const cfg = getConfig();\n if (cfg.createSupabaseClient) {\n return cfg.createSupabaseClient();\n }\n return null;\n}\n\n/**\n * Get Supabase service role client\n */\nexport function getSupabaseServiceRoleClient(): SupabaseClient | null {\n const cfg = getConfig();\n if (cfg.createServiceRoleClient) {\n return cfg.createServiceRoleClient();\n }\n return null;\n}\n","/**\n * Local filesystem adapter for storage\n */\n\nimport { promises as fs } from 'fs';\nimport path from 'path';\nimport type { StorageAdapter, ArtifactInfo } from '../base';\n\n/**\n * Local filesystem adapter\n */\nexport class LocalStorageAdapter implements StorageAdapter {\n async readFile(filepath: string): Promise<Buffer> {\n return fs.readFile(filepath);\n }\n\n async readTextFile(filepath: string): Promise<string> {\n return fs.readFile(filepath, 'utf8');\n }\n\n async writeFile(filepath: string, data: Buffer | string): Promise<void> {\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n await fs.writeFile(filepath, data, typeof data === 'string' ? 'utf8' : undefined);\n }\n\n async deleteFile(filepath: string): Promise<void> {\n await fs.unlink(filepath);\n }\n\n async exists(filepath: string): Promise<boolean> {\n try {\n await fs.access(filepath);\n return true;\n } catch {\n return false;\n }\n }\n\n async mkdir(dirpath: string): Promise<void> {\n await fs.mkdir(dirpath, { recursive: true });\n }\n\n async readdir(dirpath: string): Promise<string[]> {\n return fs.readdir(dirpath);\n }\n\n async stat(filepath: string): Promise<any> {\n return fs.stat(filepath);\n }\n\n // ==================== Artifact Operations ====================\n \n async saveArtifact(spaceId: string, artifact: ArtifactInfo, buffer: Buffer): Promise<ArtifactInfo> {\n // Determine base directory for this space\n const baseDir = path.join(process.cwd(), '.viber', 'spaces', spaceId);\n \n // Save file\n const filePath = path.join(baseDir, 'artifacts', artifact.storageKey);\n await this.writeFile(filePath, buffer);\n \n // Save metadata to artifacts.json\n const metadataPath = path.join(baseDir, 'artifacts.json');\n let artifacts: ArtifactInfo[] = [];\n \n try {\n const content = await fs.readFile(metadataPath, 'utf-8');\n artifacts = JSON.parse(content);\n } catch {\n // File doesn't exist yet\n }\n \n // Add or update artifact\n const index = artifacts.findIndex(a => a.id === artifact.id);\n const artifactInfo: ArtifactInfo = {\n ...artifact,\n createdAt: artifact.createdAt || new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n \n if (index >= 0) {\n artifacts[index] = artifactInfo;\n } else {\n artifacts.push(artifactInfo);\n }\n \n await fs.mkdir(path.dirname(metadataPath), { recursive: true });\n await fs.writeFile(metadataPath, JSON.stringify(artifacts, null, 2));\n \n return artifactInfo;\n }\n \n async getArtifact(spaceId: string, artifactId: string): Promise<{ info: ArtifactInfo; buffer: Buffer } | null> {\n const info = await this.getArtifactInfo(spaceId, artifactId);\n if (!info) return null;\n \n const baseDir = path.join(process.cwd(), '.viber', 'spaces', spaceId);\n const filePath = path.join(baseDir, 'artifacts', info.storageKey);\n const buffer = await fs.readFile(filePath);\n \n return { info, buffer };\n }\n \n async getArtifactInfo(spaceId: string, artifactId: string): Promise<ArtifactInfo | null> {\n const baseDir = path.join(process.cwd(), '.viber', 'spaces', spaceId);\n const metadataPath = path.join(baseDir, 'artifacts.json');\n \n try {\n const content = await fs.readFile(metadataPath, 'utf-8');\n const artifacts: ArtifactInfo[] = JSON.parse(content);\n return artifacts.find(a => a.id === artifactId) || null;\n } catch {\n return null;\n }\n }\n \n async listArtifacts(spaceId: string): Promise<ArtifactInfo[]> {\n const baseDir = path.join(process.cwd(), '.viber', 'spaces', spaceId);\n const metadataPath = path.join(baseDir, 'artifacts.json');\n \n try {\n const content = await fs.readFile(metadataPath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return [];\n }\n }\n \n async deleteArtifact(spaceId: string, artifactId: string): Promise<void> {\n const info = await this.getArtifactInfo(spaceId, artifactId);\n if (!info) throw new Error('Artifact not found');\n \n const baseDir = path.join(process.cwd(), '.viber', 'spaces', spaceId);\n \n // Delete file\n const filePath = path.join(baseDir, 'artifacts', info.storageKey);\n await fs.unlink(filePath);\n \n // Update metadata\n const metadataPath = path.join(baseDir, 'artifacts.json');\n const content = await fs.readFile(metadataPath, 'utf-8');\n const artifacts: ArtifactInfo[] = JSON.parse(content);\n const filtered = artifacts.filter(a => a.id !== artifactId);\n await fs.writeFile(metadataPath, JSON.stringify(filtered, null, 2));\n }\n}","/**\n * Base Storage - Abstract storage interface for all Viber storage needs\n */\n\nimport path from \"path\";\nimport { getViberRoot } from \"../config\";\nimport { LocalStorageAdapter } from \"./adapters/local\";\n\nexport interface ArtifactInfo {\n id: string;\n storageKey: string;\n originalName: string;\n mimeType: string;\n sizeBytes: number;\n category?: \"input\" | \"intermediate\" | \"output\";\n metadata?: Record<string, any>;\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport interface StorageAdapter {\n // Low-level file operations\n readFile(path: string): Promise<Buffer>;\n readTextFile(path: string): Promise<string>;\n writeFile(path: string, data: Buffer | string): Promise<void>;\n deleteFile(path: string): Promise<void>;\n exists(path: string): Promise<boolean>;\n mkdir(path: string): Promise<void>;\n readdir(path: string): Promise<string[]>;\n stat(path: string): Promise<any>;\n\n // High-level artifact operations (encapsulates file + metadata)\n saveArtifact(\n spaceId: string,\n artifact: ArtifactInfo,\n buffer: Buffer\n ): Promise<ArtifactInfo>;\n getArtifact(\n spaceId: string,\n artifactId: string\n ): Promise<{ info: ArtifactInfo; buffer: Buffer } | null>;\n getArtifactInfo(\n spaceId: string,\n artifactId: string\n ): Promise<ArtifactInfo | null>;\n listArtifacts(spaceId: string): Promise<ArtifactInfo[]>;\n deleteArtifact(spaceId: string, artifactId: string): Promise<void>;\n}\n\n/**\n * Base storage class with common operations\n */\nexport class BaseStorage {\n protected adapter: StorageAdapter;\n protected basePath: string;\n\n constructor(basePath?: string, adapter?: StorageAdapter) {\n this.basePath = basePath || getViberRoot();\n // If no adapter provided, create LocalStorageAdapter (server-only)\n if (adapter) {\n this.adapter = adapter;\n } else {\n this.adapter = new LocalStorageAdapter();\n }\n }\n\n /**\n * Get full path relative to base\n */\n protected getPath(...segments: string[]): string {\n return path.join(this.basePath, ...segments);\n }\n\n /**\n * Initialize storage (ensure directories exist)\n */\n async initialize(): Promise<void> {\n await this.adapter.mkdir(this.basePath);\n }\n\n /**\n * Read JSON file\n */\n async readJSON<T = any>(relativePath: string): Promise<T | null> {\n try {\n const fullPath = this.getPath(relativePath);\n const content = await this.adapter.readTextFile(fullPath);\n return JSON.parse(content) as T;\n } catch (error: any) {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Read YAML file\n */\n async readYaml<T = any>(relativePath: string): Promise<T | null> {\n try {\n const fullPath = this.getPath(relativePath);\n const content = await this.adapter.readTextFile(fullPath);\n const yaml = await import(\"yaml\");\n return yaml.parse(content) as T;\n } catch (error: any) {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Write JSON file\n */\n async writeJSON(relativePath: string, data: any): Promise<void> {\n const fullPath = this.getPath(relativePath);\n const content = JSON.stringify(data, null, 2);\n await this.adapter.writeFile(fullPath, content);\n }\n\n /**\n * Write YAML file\n */\n async writeYaml(relativePath: string, data: any): Promise<void> {\n const fullPath = this.getPath(relativePath);\n const yaml = await import(\"yaml\");\n const content = yaml.stringify(data);\n await this.adapter.writeFile(fullPath, content);\n }\n\n /**\n * Check if file exists\n */\n async exists(relativePath: string): Promise<boolean> {\n const fullPath = this.getPath(relativePath);\n return this.adapter.exists(fullPath);\n }\n\n /**\n * Read text file\n */\n async readTextFile(relativePath: string): Promise<string> {\n const fullPath = this.getPath(relativePath);\n return this.adapter.readTextFile(fullPath);\n }\n\n /**\n * Write file (text or binary)\n */\n async writeFile(relativePath: string, data: Buffer | string): Promise<void> {\n const fullPath = this.getPath(relativePath);\n await this.adapter.writeFile(fullPath, data);\n }\n\n /**\n * Delete file\n */\n async delete(relativePath: string): Promise<void> {\n const fullPath = this.getPath(relativePath);\n await this.adapter.deleteFile(fullPath);\n }\n\n /**\n * List files in directory\n */\n async list(relativePath: string = \"\"): Promise<string[]> {\n const fullPath = this.getPath(relativePath);\n try {\n return await this.adapter.readdir(fullPath);\n } catch {\n return [];\n }\n }\n\n /**\n * Create directory\n */\n async mkdir(relativePath: string): Promise<void> {\n const fullPath = this.getPath(relativePath);\n await this.adapter.mkdir(fullPath);\n }\n\n /**\n * Read binary file\n */\n async readFile(relativePath: string): Promise<Buffer> {\n const fullPath = this.getPath(relativePath);\n return this.adapter.readFile(fullPath);\n }\n\n /**\n * Copy file from one storage to another\n */\n async copyFileTo(\n relativePath: string,\n targetStorage: BaseStorage,\n targetPath: string\n ): Promise<void> {\n const fileData = await this.readFile(relativePath);\n await targetStorage.writeFile(targetPath, fileData);\n }\n\n /**\n * Get file statistics (size, timestamps, etc.)\n */\n async getArtifactFileStats(relativePath: string): Promise<any> {\n const fullPath = this.getPath(relativePath);\n return this.adapter.stat(fullPath);\n }\n}\n","import { StorageAdapter, ArtifactInfo } from \"../base\";\nimport { getSupabaseClient, getSupabaseServiceRoleClient } from \"../../config\";\nimport type { SupabaseClient } from \"@supabase/supabase-js\";\n\nexport interface SupabaseStorageConfig {\n defaultBucket: string;\n bucketMappings?: Record<string, string>; // pathPrefix -> bucketName\n}\n\nexport class SupabaseStorageAdapter implements StorageAdapter {\n private client: SupabaseClient | null = null;\n private config: SupabaseStorageConfig;\n\n constructor(private userId: string, config?: Partial<SupabaseStorageConfig>) {\n this.config = {\n defaultBucket: \"spaces\",\n ...config,\n };\n }\n\n private async getClient(): Promise<SupabaseClient> {\n if (!this.client) {\n const client = getSupabaseClient();\n if (!client) {\n throw new Error(\"Supabase client not configured\");\n }\n this.client = client;\n }\n return this.client;\n }\n\n private getServiceRoleClient(): SupabaseClient {\n const client = getSupabaseServiceRoleClient();\n if (!client) {\n throw new Error(\"Supabase service role client not configured\");\n }\n return client;\n }\n\n // Helper to normalize path for object storage\n // Removes leading slashes and ensures forward slashes\n private normalizePath(p: string): string {\n return p.replace(/^[\\/\\\\]+/, \"\").replace(/\\\\/g, \"/\");\n }\n\n // Determine which bucket to use based on path\n private getBucket(path: string): string {\n const normalized = this.normalizePath(path);\n if (this.config.bucketMappings) {\n for (const [prefix, bucket] of Object.entries(this.config.bucketMappings)) {\n if (normalized.startsWith(prefix) || path.startsWith(prefix)) {\n return bucket;\n }\n }\n }\n return this.config.defaultBucket;\n }\n\n async readFile(path: string): Promise<Buffer> {\n const client = await this.getClient();\n const normalizedPath = this.normalizePath(path);\n const bucket = this.getBucket(path);\n\n const { data, error } = await client.storage\n .from(bucket)\n .download(normalizedPath);\n\n if (error) {\n // Supabase Storage returns 400 for missing files sometimes\n if ((error as any).statusCode === '400' || (error as any).status === 400) {\n const enoentError = new Error('File not found');\n (enoentError as any).code = 'ENOENT';\n throw enoentError;\n }\n throw error;\n }\n const arrayBuffer = await data.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n async readTextFile(path: string): Promise<string> {\n const buffer = await this.readFile(path);\n return buffer.toString(\"utf-8\");\n }\n\n async writeFile(path: string, data: Buffer | string): Promise<void> {\n const client = await this.getClient();\n const normalizedPath = this.normalizePath(path);\n const bucket = this.getBucket(path);\n\n const { error } = await client.storage\n .from(bucket)\n .upload(normalizedPath, data, {\n upsert: true,\n });\n\n if (error) throw error;\n }\n\n async deleteFile(path: string): Promise<void> {\n const client = await this.getClient();\n const normalizedPath = this.normalizePath(path);\n const bucket = this.getBucket(path);\n\n const { error } = await client.storage.from(bucket).remove([normalizedPath]);\n if (error) throw error;\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n const client = await this.getClient();\n const normalizedPath = this.normalizePath(path);\n const bucket = this.getBucket(path);\n const dir = normalizedPath.split(\"/\").slice(0, -1).join(\"/\");\n const filename = normalizedPath.split(\"/\").pop();\n\n const { data } = await client.storage.from(bucket).list(dir, {\n search: filename,\n });\n\n return !!data && data.some(item => item.name === filename);\n } catch {\n return false;\n }\n }\n\n async mkdir(path: string): Promise<void> {\n // Supabase storage is object storage, directories are virtual.\n // No-op.\n }\n\n async readdir(path: string): Promise<string[]> {\n const client = await this.getClient();\n const normalizedPath = this.normalizePath(path);\n const bucket = this.getBucket(path);\n\n const { data, error } = await client.storage.from(bucket).list(normalizedPath);\n if (error) throw error;\n return data.map((item) => item.name);\n }\n\n async stat(path: string): Promise<any> {\n // Basic stat implementation\n return {\n isDirectory: () => false, // Hard to tell without listing, assume file for now\n size: 0,\n };\n }\n\n // ==================== Artifact Operations ====================\n\n async saveArtifact(spaceId: string, artifact: ArtifactInfo, buffer: Buffer): Promise<ArtifactInfo> {\n const client = await this.getClient();\n const serviceClient = this.getServiceRoleClient();\n\n // Save file to storage bucket\n const filePath = `${spaceId}/artifacts/${artifact.storageKey}`;\n const { error: storageError } = await client.storage\n .from(this.config.defaultBucket)\n .upload(filePath, buffer, { upsert: true });\n\n if (storageError) throw storageError;\n\n // Get current user for ownership\n const { data: { user } } = await client.auth.getUser();\n\n // Save metadata to database using service role client (bypasses RLS)\n const { data, error: dbError } = await serviceClient\n .from('artifacts')\n .insert({\n id: artifact.id,\n space_id: spaceId,\n user_id: user?.id || this.userId,\n storage_key: artifact.storageKey,\n original_name: artifact.originalName,\n mime_type: artifact.mimeType,\n size_bytes: artifact.sizeBytes,\n category: artifact.category || 'input',\n metadata: artifact.metadata || {},\n })\n .select()\n .single();\n\n if (dbError) {\n // Clean up uploaded file on metadata save failure\n await client.storage.from(this.config.defaultBucket).remove([filePath]);\n throw dbError;\n }\n\n // Return standardized artifact info\n return {\n id: data.id,\n storageKey: data.storage_key,\n originalName: data.original_name,\n mimeType: data.mime_type,\n sizeBytes: data.size_bytes,\n category: data.category,\n metadata: data.metadata,\n createdAt: data.created_at,\n updatedAt: data.updated_at,\n };\n }\n\n async getArtifact(spaceId: string, artifactId: string): Promise<{ info: ArtifactInfo; buffer: Buffer } | null> {\n const info = await this.getArtifactInfo(spaceId, artifactId);\n if (!info) return null;\n\n const filePath = `${spaceId}/artifacts/${info.storageKey}`;\n const buffer = await this.readFile(filePath);\n\n return { info, buffer };\n }\n\n async getArtifactInfo(spaceId: string, artifactId: string): Promise<ArtifactInfo | null> {\n const serviceClient = this.getServiceRoleClient();\n\n const { data, error } = await serviceClient\n .from('artifacts')\n .select('*')\n .eq('id', artifactId)\n .eq('space_id', spaceId)\n .single();\n\n if (error || !data) return null;\n\n return {\n id: data.id,\n storageKey: data.storage_key,\n originalName: data.original_name,\n mimeType: data.mime_type,\n sizeBytes: data.size_bytes,\n category: data.category,\n metadata: data.metadata,\n createdAt: data.created_at,\n updatedAt: data.updated_at,\n };\n }\n\n async listArtifacts(spaceId: string): Promise<ArtifactInfo[]> {\n const serviceClient = this.getServiceRoleClient();\n\n const { data, error } = await serviceClient\n .from('artifacts')\n .select('*')\n .eq('space_id', spaceId)\n .order('created_at', { ascending: false });\n\n if (error) throw error;\n\n return (data || []).map(row => ({\n id: row.id,\n storageKey: row.storage_key,\n originalName: row.original_name,\n mimeType: row.mime_type,\n sizeBytes: row.size_bytes,\n category: row.category,\n metadata: row.metadata,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }));\n }\n\n async deleteArtifact(spaceId: string, artifactId: string): Promise<void> {\n const client = await this.getClient();\n const serviceClient = this.getServiceRoleClient();\n\n // Get artifact info first to know the storage key\n const info = await this.getArtifactInfo(spaceId, artifactId);\n if (!info) throw new Error('Artifact not found');\n\n // Delete from storage\n const filePath = `${spaceId}/artifacts/${info.storageKey}`;\n await client.storage.from(this.config.defaultBucket).remove([filePath]);\n\n // Delete from database\n const { error } = await serviceClient\n .from('artifacts')\n .delete()\n .eq('id', artifactId)\n .eq('space_id', spaceId);\n\n if (error) throw error;\n }\n}\n","/**\n * Space Storage - Handles storage operations for spaces\n */\n\nimport path from \"path\";\nimport { BaseStorage, StorageAdapter, ArtifactInfo } from \"./base\";\nimport { getViberRoot, getSupabaseClient } from \"../config\";\n// LocalStorageAdapter is imported dynamically to avoid bundling Node.js fs module in client\n\nexport interface StorageOptions {\n rootPath: string;\n spaceId: string;\n adapter?: StorageAdapter;\n}\n\nexport class SpaceStorage extends BaseStorage {\n private spaceId: string;\n\n constructor(options: StorageOptions) {\n super(options.rootPath, options.adapter);\n this.spaceId = options.spaceId;\n }\n\n getSpacePath(): string {\n return this.basePath;\n }\n\n getFilePath(filename: string): string {\n return this.getPath(filename);\n }\n\n async saveFile(filename: string, data: any): Promise<void> {\n const content =\n typeof data === \"string\" ? data : JSON.stringify(data, null, 2);\n await this.writeFile(filename, content);\n }\n\n async saveFileBuffer(filename: string, data: Buffer): Promise<void> {\n await this.writeFile(filename, data);\n }\n\n /**\n * DEPRECATED: Use artifact operations below instead\n * Save an artifact file (low-level file operation only)\n */\n async saveArtifact(\n storageKey: string,\n buffer: Buffer,\n metadata: {\n mimeType: string;\n size: number;\n artifactType?: string;\n },\n originalFilename?: string\n ): Promise<void> {\n const artifactPath = `artifacts/${storageKey}`;\n await this.mkdir(\"artifacts\");\n await this.writeFile(artifactPath, buffer);\n }\n\n // ==================== High-Level Artifact Operations ====================\n\n /**\n * Save a complete artifact (both file AND metadata)\n */\n async saveCompleteArtifact(artifact: ArtifactInfo, buffer: Buffer): Promise<ArtifactInfo> {\n return this.adapter.saveArtifact(this.spaceId, artifact, buffer);\n }\n\n /**\n * Get a complete artifact (both file AND metadata)\n */\n async getCompleteArtifact(artifactId: string): Promise<{ info: ArtifactInfo; buffer: Buffer } | null> {\n return this.adapter.getArtifact(this.spaceId, artifactId);\n }\n\n /**\n * Get artifact metadata only (without loading the file)\n */\n async getArtifactInfo(artifactId: string): Promise<ArtifactInfo | null> {\n return this.adapter.getArtifactInfo(this.spaceId, artifactId);\n }\n\n /**\n * List all artifacts in this space\n */\n async listArtifacts(): Promise<ArtifactInfo[]> {\n return this.adapter.listArtifacts(this.spaceId);\n }\n\n /**\n * Delete an artifact (both file AND metadata)\n */\n async deleteCompleteArtifact(artifactId: string): Promise<void> {\n return this.adapter.deleteArtifact(this.spaceId, artifactId);\n }\n\n\n\n async listFiles(): Promise<string[]> {\n return this.list();\n }\n\n async createDirectory(dirname: string): Promise<void> {\n await this.mkdir(dirname);\n }\n\n async getMetadata(): Promise<any> {\n return this.readJSON(\"metadata.json\");\n }\n\n async saveMetadata(metadata: any): Promise<void> {\n await this.writeJSON(\"metadata.json\", metadata);\n }\n\n async getArtifact(\n filename: string\n ): Promise<{ content: Buffer; metadata?: any } | null> {\n try {\n const artifactPath = `artifacts/${filename}`;\n const content = await this.readFile(artifactPath);\n\n // Metadata is now stored in database, not in .xmeta files\n return { content, metadata: null };\n } catch (error: any) {\n // Check if error indicates file not found (adapter specific)\n // For now assume any error means not found or issue\n return null;\n }\n }\n\n async cleanup(): Promise<void> {\n // Optional: Clean up temporary files\n const files = await this.listFiles();\n for (const file of files) {\n if (file.startsWith(\"tmp_\") || file.endsWith(\".tmp\")) {\n await this.delete(file);\n }\n }\n }\n}\n\nexport class SpaceStorageFactory {\n // Get root path dynamically to ensure env vars are loaded\n private static getRootPath(): string {\n return getViberRoot();\n }\n\n private static rootPath: string | null = null;\n\n static setRootPath(rootPath: string): void {\n SpaceStorageFactory.rootPath = rootPath;\n }\n\n static async create(spaceId: string): Promise<SpaceStorage> {\n let adapter: StorageAdapter | undefined;\n let rootPath = \"\";\n\n // Check for explicit Supabase storage mode\n // Note: VIBEX_DATA_MODE controls metadata storage (database), not file storage\n // File storage requires explicit VIBEX_FILE_STORAGE=supabase to use Supabase Storage\n const fileStorageMode = process.env.VIBEX_FILE_STORAGE || 'local';\n\n // Try to use Supabase storage if explicitly enabled\n if (fileStorageMode === 'supabase') {\n try {\n const supabase = getSupabaseClient();\n if (!supabase) {\n throw new Error('Supabase client not configured');\n }\n const { data: { user } } = await supabase.auth.getUser();\n\n if (user) {\n // For Supabase, rootPath is the space prefix\n // We use spaceId for isolation (spaces are already user-isolated via RLS)\n rootPath = spaceId;\n\n const { SupabaseStorageAdapter } = await import(\"./adapters/supabase\");\n\n // Store everything in the 'spaces' bucket under [spaceId]/artifacts/\n // This keeps all space data together and leverages spaceId for isolation\n adapter = new SupabaseStorageAdapter(user.id, {\n defaultBucket: \"spaces\",\n bucketMappings: {},\n });\n\n console.log(`[SpaceStorage] Using Supabase storage for space ${spaceId} (artifacts only)`);\n }\n } catch (e) {\n console.warn(\"[SpaceStorage] Failed to initialize Supabase storage, falling back to local:\", e);\n }\n }\n\n // Use local storage (default for file storage)\n if (!adapter) {\n // Only use LocalStorageAdapter on server\n if (typeof window === 'undefined') {\n // Dynamic import to avoid bundling fs in client\n const { LocalStorageAdapter } = await import(\"./adapters/local\");\n adapter = new LocalStorageAdapter();\n const baseRoot = SpaceStorageFactory.rootPath || SpaceStorageFactory.getRootPath();\n rootPath = path.join(baseRoot, \"spaces\", spaceId);\n console.log(`[SpaceStorage] Using local file storage for space ${spaceId}`);\n } else {\n throw new Error('LocalStorageAdapter cannot be used in client code. Provide a client-compatible adapter.');\n }\n }\n\n const storage = new SpaceStorage({\n rootPath,\n spaceId,\n adapter\n });\n await storage.initialize();\n return storage;\n }\n\n static async list(): Promise<string[]> {\n // Listing spaces is tricky with mixed storage.\n // For now, we'll implement listing for the active storage mode.\n\n const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;\n\n if (supabaseUrl) {\n try {\n const supabase = getSupabaseClient();\n if (!supabase) {\n throw new Error('Supabase client not configured');\n }\n const { data: { user } } = await supabase.auth.getUser();\n\n if (user) {\n const { SupabaseStorageAdapter } = await import(\"./adapters/supabase\");\n const adapter = new SupabaseStorageAdapter(user.id);\n // List directories in user's folder\n // Supabase storage list returns files/folders in the prefix\n // We need to list folders under userId/\n // But Supabase list is flat-ish or simulates folders.\n // We can list root of userId/\n\n // Actually, SupabaseStorageAdapter.readdir takes a path.\n // If we pass empty string or just userId, it might work depending on implementation.\n // Our adapter implementation of readdir lists contents of a path.\n // So we can list content of `${user.id}`.\n\n // However, SupabaseStorageAdapter constructor takes userId, but it doesn't prefix it automatically \n // in readdir unless we change logic.\n // In create(), we pass `${user.id}/${spaceId}` as rootPath.\n // So the adapter itself is generic.\n\n // Let's create a temporary adapter just to list\n // But we need to list *spaces*, which are subfolders of user.id\n\n // We can use the adapter to list `${user.id}`\n // But wait, SupabaseStorageAdapter constructor takes userId but doesn't use it for prefixing \n // EXCEPT for maybe internal logic? \n // Actually in my implementation:\n // constructor(private userId: string) {}\n // But I didn't use `this.userId` in `readFile` etc!\n // I used `path` passed to methods.\n // AND `SpaceStorage` passes `rootPath` (which includes userId) + relativePath.\n\n // So `SupabaseStorageAdapter` is actually stateless regarding path prefix, \n // `userId` in constructor was unused in my previous implementation!\n // I should fix that or just ignore it if I pass full path.\n\n // If I pass `${user.id}` to readdir, it should list spaces.\n const files = await adapter.readdir(user.id);\n // Filter for what looks like space directories (or just return all)\n return files;\n }\n } catch (e) {\n console.warn(\"Failed to list Supabase spaces:\", e);\n }\n }\n\n // Fallback to local (server-only)\n if (typeof window === 'undefined') {\n try {\n // Dynamic import to avoid bundling fs in client\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const fs = require(\"fs\").promises;\n const rootPath = SpaceStorageFactory.rootPath || SpaceStorageFactory.getRootPath();\n const spacesPath = path.join(rootPath, \"spaces\");\n\n try {\n await fs.access(spacesPath);\n } catch {\n return [];\n }\n\n const entries = await fs.readdir(spacesPath);\n const spaces: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(spacesPath, entry);\n const stat = await fs.stat(entryPath);\n if (stat.isDirectory() && !entry.startsWith(\".\")) {\n spaces.push(entry);\n }\n }\n\n return spaces;\n } catch {\n return [];\n }\n }\n\n // If we reach here (browser environment with no Supabase), return empty\n return [];\n }\n\n static async exists(spaceId: string): Promise<boolean> {\n // Similar logic to create() to check existence\n const storage = await SpaceStorageFactory.create(spaceId);\n // Check if space.json exists as a proxy for space existence\n return storage.exists(\"space.json\");\n }\n\n static async delete(spaceId: string): Promise<void> {\n const storage = await SpaceStorageFactory.create(spaceId);\n // Recursive delete not easily supported in base interface\n // But for Supabase we can delete folder\n // For local we can use fs.rm\n\n // This is a bit hacky, ideally StorageAdapter has rmdir or similar\n // Or we just delete known files.\n\n // For now, let's try to delete metadata.json\n await storage.delete(\"metadata.json\");\n // And maybe artifacts...\n // A proper delete would require listing all files and deleting them.\n\n const files = await storage.list();\n for (const file of files) {\n await storage.delete(file);\n }\n\n // Also artifacts\n try {\n const artifacts = await storage.list(\"artifacts\");\n for (const file of artifacts) {\n await storage.delete(`artifacts/${file}`);\n }\n } catch { }\n }\n}\n\n","/**\n * ID Generator Utilities for Viber\n *\n * Simple, unique ID generation for documents and other entities.\n */\n\nimport { customAlphabet } from \"nanoid\";\n\n// Define safe character set for IDs (A-Za-z0-9_)\nconst ALPHABET_SAFE =\n \"abcdefghijklmnopqrstuvwxyz0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * Generate a short, unique ID that's URL-safe\n * Uses a custom alphabet to ensure compatibility\n *\n * @param length Length of the ID (default: 8)\n * @returns A short, unique ID string\n */\nexport function generateShortId(length: number = 8): string {\n // Create a custom nanoid generator\n const nanoid = customAlphabet(ALPHABET_SAFE, length);\n\n // Generate ID and ensure first character is a letter\n let id = nanoid();\n while (!/^[a-zA-Z]/.test(id)) {\n id = nanoid();\n }\n\n return id;\n}\n\n/**\n * Generate a space ID with optional topic prefix\n *\n * @param topic Optional topic to use as prefix\n * @returns A space ID like 'aB3x_9Kp' (always clean random ID)\n */\nexport function generateSpaceId(topic?: string): string {\n // Always generate a clean 8-char random ID to avoid URL encoding issues\n // with non-ASCII characters in topics\n return generateShortId(8);\n}\n\n/**\n * Validate a document ID\n * Checks that the ID starts with a letter and contains only letters, numbers, and underscores\n *\n * @param id ID string to validate\n * @returns Boolean indicating if the ID is valid\n */\nexport function validateId(id: string): boolean {\n if (!id || typeof id !== \"string\" || id.trim() === \"\") {\n return false;\n }\n\n // ID must start with a letter and contain only letters, numbers, and underscores\n const idPattern = /^[a-zA-Z][a-zA-Z0-9_]*$/;\n return idPattern.test(id);\n}\n","/**\n * LocalDataAdapter - File-based data storage using YAML/JSON files\n * Uses ~/.openviber/ directory for local agent mode\n */\n\nimport type { DataAdapter } from \"../adapter\";\nimport type {\n Agent,\n Tool,\n Space,\n Artifact,\n Conversation,\n Task,\n ModelProvider,\n Datasource,\n} from \"../types\";\nimport { SpaceStorageFactory } from \"../../storage/space\";\nimport { BaseStorage } from \"../../storage/base\";\nimport { getViberRoot } from \"../../config\";\nimport * as yaml from \"yaml\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\n// ESM-compatible __dirname\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport class LocalDataAdapter implements DataAdapter {\n // Helper to read and parse YAML file\n private async readYamlFile(storage: BaseStorage, path: string): Promise<any> {\n try {\n const content = await storage.readTextFile(path);\n return yaml.parse(content);\n } catch (error: any) {\n if (error.code === \"ENOENT\") return null;\n throw error;\n }\n }\n\n // ==================== Agents ====================\n\n async getAgents(): Promise<Agent[]> {\n const defaultsStorage = new BaseStorage(\n path.join(__dirname, \"..\", \"defaults\"),\n );\n const rootStorage = new BaseStorage(getViberRoot());\n const agents: Agent[] = [];\n\n // Load built-in agents from defaults/agents/\n try {\n const files = await defaultsStorage.list(\"agents\");\n for (const file of files.filter(\n (f) => f.endsWith(\".yaml\") || f.endsWith(\".yml\"),\n )) {\n const agent = await this.readYamlFile(\n defaultsStorage,\n `agents/${file}`,\n );\n if (agent) {\n agents.push({ ...agent, isCustom: false });\n }\n }\n } catch {\n // No built-in agents\n }\n\n // Load user agents from ~/.openviber/agents/\n try {\n const files = await rootStorage.list(\"agents\");\n for (const file of files.filter(\n (f) => f.endsWith(\".yaml\") || f.endsWith(\".yml\"),\n )) {\n 0;\n const agent = await this.readYamlFile(rootStorage, `agents/${file}`);\n if (agent) {\n agents.push({ ...agent, isCustom: true });\n }\n }\n } catch {\n // No user agents\n }\n\n return agents;\n }\n\n async getAgent(id: string): Promise<Agent | null> {\n const defaultsPath = path.join(__dirname, \"..\", \"defaults\");\n const defaultsStorage = new BaseStorage(defaultsPath);\n const rootStorage = new BaseStorage(getViberRoot());\n\n // Try built-in first\n for (const ext of [\"yaml\", \"yml\"]) {\n const agent = await this.readYamlFile(\n defaultsStorage,\n `agents/${id}.${ext}`,\n );\n if (agent) return { ...agent, id, isCustom: false };\n }\n\n // Try user agents\n for (const ext of [\"yaml\", \"yml\"]) {\n const agent = await this.readYamlFile(rootStorage, `agents/${id}.${ext}`);\n if (agent) return { ...agent, id, isCustom: true };\n }\n\n return null;\n }\n\n async saveAgent(agent: Agent): Promise<Agent> {\n const rootStorage = new BaseStorage(getViberRoot());\n const content = yaml.stringify(agent);\n await rootStorage.writeFile(`agents/${agent.id}.yaml`, content);\n return agent;\n }\n\n async deleteAgent(id: string): Promise<void> {\n const rootStorage = new BaseStorage(getViberRoot());\n try {\n await rootStorage.delete(`agents/${id}.yaml`);\n } catch {\n await rootStorage.delete(`agents/${id}.yml`);\n }\n }\n\n async cloneAgent(id: string): Promise<Agent> {\n const agent = await this.getAgent(id);\n if (!agent) throw new Error(`Agent ${id} not found`);\n\n const { generateShortId } = await import(\"../../utils/id\");\n const newId = `custom-${generateShortId(8)}`;\n const cloned = { ...agent, id: newId, isCustom: true };\n\n return await this.saveAgent(cloned);\n }\n\n // ==================== Tools ====================\n\n async getTools(): Promise<Tool[]> {\n const defaultsStorage = new BaseStorage(\n path.join(__dirname, \"..\", \"..\", \"defaults\"),\n );\n const tools: Tool[] = [];\n\n // Load built-in tools from defaults/tools/\n try {\n const files = await defaultsStorage.list(\"tools\");\n for (const file of files.filter(\n (f) => f.endsWith(\".yaml\") || f.endsWith(\".yml\"),\n )) {\n const tool = await this.readYamlFile(defaultsStorage, `tools/${file}`);\n if (tool) {\n tools.push(tool);\n }\n }\n } catch {\n // No tools\n }\n\n return tools;\n }\n\n async getTool(id: string): Promise<Tool | null> {\n const tools = await this.getTools();\n return tools.find((t) => t.id === id) || null;\n }\n\n async saveTool(tool: Tool): Promise<Tool> {\n const rootStorage = new BaseStorage(getViberRoot());\n await rootStorage.mkdir(\"tools\");\n const content = yaml.stringify(tool);\n await rootStorage.writeFile(`tools/${tool.id}.yaml`, content);\n return tool;\n }\n\n async deleteTool(id: string): Promise<void> {\n const rootStorage = new BaseStorage(getViberRoot());\n try {\n await rootStorage.delete(`tools/${id}.yaml`);\n } catch {\n await rootStorage.delete(`tools/${id}.yml`);\n }\n }\n\n async cloneTool(id: string): Promise<Tool> {\n const tool = await this.getTool(id);\n if (!tool) throw new Error(`Tool ${id} not found`);\n\n const { generateShortId } = await import(\"../../utils/id\");\n const newId = `custom-${generateShortId(8)}`;\n const cloned = { ...tool, id: newId };\n\n return await this.saveTool(cloned);\n }\n\n // ==================== Spaces ====================\n\n async getSpaces(): Promise<Space[]> {\n const spaceIds = await SpaceStorageFactory.list();\n const spaces: Space[] = [];\n\n for (const id of spaceIds) {\n const space = await this.getSpace(id);\n if (space) {\n spaces.push(space);\n }\n }\n\n return spaces;\n }\n\n async getSpace(id: string): Promise<Space | null> {\n try {\n const storage = await SpaceStorageFactory.create(id);\n const data = await storage.readJSON<any>(\"space.json\");\n\n if (!data) return null;\n\n return {\n id,\n name: data.name || id,\n description: data.description,\n config: data.config || {},\n createdAt: data.createdAt,\n updatedAt: data.updatedAt,\n };\n } catch (error) {\n return null;\n }\n }\n\n async saveSpace(space: Space): Promise<Space> {\n const storage = await SpaceStorageFactory.create(space.id);\n\n const data = {\n name: space.name,\n description: space.description,\n config: space.config || {},\n createdAt: space.createdAt || new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n await storage.writeJSON(\"space.json\", data);\n return space;\n }\n\n async deleteSpace(id: string): Promise<void> {\n // Space deletion needs to be handled carefully\n // For now, we just mark it as deleted or remove the directory\n throw new Error(\"Space deletion not implemented in local mode\");\n }\n\n // ==================== Artifacts ====================\n\n async getArtifacts(spaceId: string): Promise<Artifact[]> {\n const storage = await SpaceStorageFactory.create(spaceId);\n const files = await storage.list(\"artifacts\");\n const artifacts: Artifact[] = [];\n\n for (const file of files) {\n // Skip system files\n if (file.startsWith(\".\")) {\n continue;\n }\n\n // In local mode without DB, we can't easily get metadata\n // Just return basic file info\n try {\n const stats = await storage.getArtifactFileStats(`artifacts/${file}`);\n\n artifacts.push({\n id: file, // Storage key as ID\n spaceId,\n storageKey: file,\n originalName: file,\n mimeType: \"application/octet-stream\", // Unknown without metadata\n sizeBytes: stats.size,\n metadata: {},\n createdAt: stats.birthtime.toISOString(),\n updatedAt: stats.mtime.toISOString(),\n });\n } catch (error) {\n // Skip files we can't read\n continue;\n }\n }\n\n return artifacts;\n }\n\n async getArtifact(id: string): Promise<Artifact | null> {\n // In local mode, we need space context to find artifacts\n // This is a limitation of file-based storage\n throw new Error(\"getArtifact requires space context in local mode\");\n }\n\n async saveArtifact(artifact: Artifact): Promise<Artifact> {\n // Artifacts are saved through SpaceStorage.saveArtifact()\n // This method is mainly for metadata updates\n // In local mode without DB, we can't persist metadata separately easily\n // So this is effectively a no-op for metadata persistence in pure local mode\n return artifact;\n }\n\n async deleteArtifact(id: string): Promise<void> {\n // Requires space context\n throw new Error(\"deleteArtifact requires space context in local mode\");\n }\n\n // NEW: Artifact queries by ownership and category\n async getArtifactsBySpace(spaceId: string): Promise<Artifact[]> {\n const allArtifacts = await this.getArtifacts(spaceId);\n return allArtifacts.filter(\n (a) => a.spaceId === spaceId || (a.spaceId === spaceId && !a.taskId),\n );\n }\n\n async getArtifactsByTask(taskId: string): Promise<Artifact[]> {\n // In local mode, we need to iterate through spaces to find task artifacts\n // This is inefficient but necessary for file-based storage\n const spaceIds = await SpaceStorageFactory.list();\n const taskArtifacts: Artifact[] = [];\n\n for (const wsId of spaceIds) {\n const artifacts = await this.getArtifacts(wsId);\n taskArtifacts.push(...artifacts.filter((a) => a.taskId === taskId));\n }\n\n return taskArtifacts;\n }\n\n async getArtifactsByCategory(\n spaceOrTaskId: string,\n category: \"input\" | \"intermediate\" | \"output\",\n isTask = false,\n ): Promise<Artifact[]> {\n const artifacts = isTask\n ? await this.getArtifactsByTask(spaceOrTaskId)\n : await this.getArtifactsBySpace(spaceOrTaskId);\n\n return artifacts.filter((a) => a.category === category);\n }\n\n // ==================== Tasks (formerly Conversations) ====================\n\n async getTasks(spaceId: string): Promise<Task[]> {\n const conversations = await this.getConversations(spaceId);\n // Task extends Conversation, so we can cast\n return conversations as Task[];\n }\n\n async getTask(id: string): Promise<Task | null> {\n const conversation = await this.getConversation(id);\n return conversation as Task | null;\n }\n\n async saveTask(task: Task): Promise<Task> {\n const conversation = await this.saveConversation(task as Conversation);\n return conversation as Task;\n }\n\n async deleteTask(id: string): Promise<void> {\n await this.deleteConversation(id);\n }\n\n // ==================== Conversations (Legacy) ====================\n\n async getConversations(spaceId: string): Promise<Conversation[]> {\n const storage = await SpaceStorageFactory.create(spaceId);\n\n try {\n // In local mode, we might store conversations as individual files\n // or as part of space.json\n const files = await storage.list(\"conversations\");\n const conversations: Conversation[] = [];\n\n for (const file of files) {\n if (!file.endsWith(\".json\")) continue;\n\n try {\n const data = await storage.readJSON<Conversation>(\n `conversations/${file}`,\n );\n if (data) {\n conversations.push(data);\n }\n } catch (error) {\n continue;\n }\n }\n\n return conversations;\n } catch (error) {\n // Conversations directory doesn't exist yet\n return [];\n }\n }\n\n async getConversation(id: string): Promise<Conversation | null> {\n // Requires space context\n throw new Error(\"getConversation requires space context in local mode\");\n }\n\n async saveConversation(conversation: Conversation): Promise<Conversation> {\n if (!conversation.spaceId) {\n throw new Error(\"Conversation must have a spaceId\");\n }\n const storage = await SpaceStorageFactory.create(conversation.spaceId);\n await storage.mkdir(\"conversations\");\n await storage.writeJSON(\n `conversations/${conversation.id}.json`,\n conversation,\n );\n return conversation;\n }\n\n async deleteConversation(id: string): Promise<void> {\n // Requires space context\n throw new Error(\"deleteConversation requires space context in local mode\");\n }\n\n // ==================== Model Providers ====================\n\n async getModelProviders(): Promise<ModelProvider[]> {\n try {\n const storage = new BaseStorage(getViberRoot());\n const content = await storage.readTextFile(\"models.yaml\");\n const data = yaml.parse(content);\n return Object.entries(data || {}).map(([id, config]: [string, any]) => ({\n id,\n ...config,\n }));\n } catch (error: any) {\n if (error.code === \"ENOENT\") return [];\n throw error;\n }\n }\n\n async getModelProvider(id: string): Promise<ModelProvider | null> {\n const providers = await this.getModelProviders();\n return providers.find((p) => p.id === id) || null;\n }\n\n async saveModelProvider(provider: ModelProvider): Promise<ModelProvider> {\n const storage = new BaseStorage(getViberRoot());\n const providers = await this.getModelProviders();\n const existing = providers.find((p) => p.id === provider.id);\n\n let updated: ModelProvider[];\n if (existing) {\n updated = providers.map((p) => (p.id === provider.id ? provider : p));\n } else {\n updated = [...providers, provider];\n }\n\n // Convert array to object for YAML format\n const data = updated.reduce((acc, p) => ({ ...acc, [p.id]: p }), {});\n const content = yaml.stringify(data);\n await storage.writeFile(\"models.yaml\", content);\n return provider;\n }\n\n async deleteModelProvider(id: string): Promise<void> {\n const storage = new BaseStorage(getViberRoot());\n const providers = await this.getModelProviders();\n const filtered = providers.filter((p) => p.id !== id);\n const data = filtered.reduce((acc, p) => ({ ...acc, [p.id]: p }), {});\n const content = yaml.stringify(data);\n await storage.writeFile(\"models.yaml\", content);\n }\n\n // ==================== Datasources ====================\n\n async getDatasources(): Promise<Datasource[]> {\n try {\n const storage = new BaseStorage(getViberRoot());\n const content = await storage.readTextFile(\"datasources.yaml\");\n const data = yaml.parse(content);\n return Object.entries(data || {}).map(([id, config]: [string, any]) => ({\n id,\n ...config,\n }));\n } catch (error: any) {\n if (error.code === \"ENOENT\") return [];\n throw error;\n }\n }\n\n async getDatasource(id: string): Promise<Datasource | null> {\n const datasources = await this.getDatasources();\n return datasources.find((d) => d.id === id) || null;\n }\n\n async saveDatasource(datasource: Datasource): Promise<Datasource> {\n const storage = new BaseStorage(getViberRoot());\n const datasources = await this.getDatasources();\n const existing = datasources.find((d) => d.id === datasource.id);\n\n let updated: Datasource[];\n if (existing) {\n updated = datasources.map((d) =>\n d.id === datasource.id ? datasource : d,\n );\n } else {\n updated = [...datasources, datasource];\n }\n\n const data = updated.reduce((acc, d) => ({ ...acc, [d.id]: d }), {});\n const content = yaml.stringify(data);\n await storage.writeFile(\"datasources.yaml\", content);\n return datasource;\n }\n\n async deleteDatasource(id: string): Promise<void> {\n const storage = new BaseStorage(getViberRoot());\n const datasources = await this.getDatasources();\n const filtered = datasources.filter((d) => d.id !== id);\n const data = filtered.reduce((acc, d) => ({ ...acc, [d.id]: d }), {});\n const content = yaml.stringify(data);\n await storage.writeFile(\"datasources.yaml\", content);\n }\n}\n","/**\n * SupabaseDatabaseAdapter - Direct Supabase/PostgreSQL database access\n * SERVER-ONLY VERSION - Uses dynamic imports to avoid bundling in client\n * \n * This file should ONLY be imported from server-side code (API routes).\n * For client-side code, use DatabaseDataAdapter which calls API routes.\n */\n\nimport type { DataAdapter } from \"../adapter\";\nimport type {\n Agent,\n Tool,\n Space,\n Artifact,\n Conversation,\n Task,\n ModelProvider,\n Datasource,\n} from \"../types\";\nimport { getSupabaseServiceRoleClient } from \"../../config\";\n\n/**\n * Convert camelCase object keys to snake_case for database\n */\nfunction toSnakeCase(obj: any): any {\n if (obj === null || obj === undefined) return obj;\n if (Array.isArray(obj)) return obj.map(toSnakeCase);\n if (typeof obj !== \"object\") return obj;\n\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n const snakeKey = key.replace(\n /[A-Z]/g,\n (letter) => `_${letter.toLowerCase()}`\n );\n result[snakeKey] =\n typeof value === \"object\" && value !== null ? toSnakeCase(value) : value;\n }\n return result;\n}\n\n/**\n * Convert snake_case object keys to camelCase for TypeScript\n */\nfunction toCamelCase(obj: any): any {\n if (obj === null || obj === undefined) return obj;\n if (Array.isArray(obj)) return obj.map(toCamelCase);\n if (typeof obj !== \"object\") return obj;\n\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n const camelKey = key.replace(/_([a-z])/g, (_, letter) =>\n letter.toUpperCase()\n );\n result[camelKey] =\n typeof value === \"object\" && value !== null ? toCamelCase(value) : value;\n }\n return result;\n}\n\nexport class SupabaseDatabaseAdapter implements DataAdapter {\n private supabase: any;\n private supabasePromise: Promise<any> | null = null;\n\n constructor() {\n // Lazy load Supabase client to avoid bundling server code in client\n if (typeof window !== 'undefined') {\n throw new Error('SupabaseDatabaseAdapter can only be used on the server');\n }\n // Initialize Supabase client lazily\n this.supabasePromise = this.initSupabase();\n }\n\n private async initSupabase() {\n // Use config module for Supabase client\n const client = getSupabaseServiceRoleClient();\n if (!client) {\n throw new Error('Supabase service role client not configured. Call configure() first.');\n }\n return client;\n }\n\n private async getSupabase() {\n if (!this.supabase) {\n this.supabase = await this.supabasePromise;\n }\n return this.supabase;\n }\n\n // ==================== Agents ====================\n\n async getAgents(): Promise<Agent[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"agents\")\n .select(\"*\")\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch agents: ${error.message}`);\n\n // Transform database format to Agent type\n return (data || []).map((agent: any) => {\n const camelCased = toCamelCase(agent);\n return {\n ...camelCased,\n llm: {\n provider: camelCased.llmProvider,\n model: camelCased.llmModel,\n settings: camelCased.llmSettings,\n },\n // Remove the flat fields\n llmProvider: undefined,\n llmModel: undefined,\n llmSettings: undefined,\n };\n });\n }\n\n async getAgent(id: string): Promise<Agent | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"agents\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch agent: ${error.message}`);\n }\n\n // Transform database format to Agent type\n const camelCased = toCamelCase(data);\n\n return {\n ...camelCased,\n llm: {\n provider: camelCased.llmProvider,\n model: camelCased.llmModel,\n settings: camelCased.llmSettings,\n },\n // Remove the flat fields to avoid confusion\n llmProvider: undefined,\n llmModel: undefined,\n llmSettings: undefined,\n };\n }\n\n async saveAgent(agent: Agent): Promise<Agent> {\n const supabase = await this.getSupabase();\n // Get authenticated user to set user_id if not already set\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n // Transform Agent type to database format\n // Convert llm object to flat fields\n const { llm, ...restAgent } = agent;\n const flatAgent = {\n ...restAgent,\n llmProvider: llm?.provider,\n llmModel: llm?.model,\n llmSettings: llm?.settings,\n userId: agent.userId || user?.id,\n updatedAt: new Date().toISOString(),\n };\n\n const dbAgent = toSnakeCase(flatAgent);\n\n const { data, error } = await supabase\n .from(\"agents\")\n .upsert(dbAgent)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save agent: ${error.message}`);\n\n // Transform back to Agent type with llm object\n const camelCased = toCamelCase(data);\n return {\n ...camelCased,\n llm: {\n provider: camelCased.llmProvider,\n model: camelCased.llmModel,\n settings: camelCased.llmSettings,\n },\n llmProvider: undefined,\n llmModel: undefined,\n llmSettings: undefined,\n };\n }\n\n async deleteAgent(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"agents\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete agent: ${error.message}`);\n }\n\n async cloneAgent(id: string): Promise<Agent> {\n const original = await this.getAgent(id);\n if (!original) {\n throw new Error(`Agent ${id} not found`);\n }\n\n const cloned = {\n ...original,\n id: `${original.id}-copy-${Date.now()}`,\n name: `${original.name} (Copy)`,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n return this.saveAgent(cloned);\n }\n\n // ==================== Tools ====================\n\n async getTools(): Promise<Tool[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"tools\")\n .select(\"*\")\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch tools: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getTool(id: string): Promise<Tool | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"tools\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch tool: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveTool(tool: Tool): Promise<Tool> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const dbTool = toSnakeCase({\n ...tool,\n userId: tool.userId || user?.id,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"tools\")\n .upsert(dbTool)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save tool: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteTool(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"tools\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete tool: ${error.message}`);\n }\n\n async cloneTool(id: string): Promise<Tool> {\n const original = await this.getTool(id);\n if (!original) {\n throw new Error(`Tool ${id} not found`);\n }\n\n const cloned = {\n ...original,\n id: `${original.id}-copy-${Date.now()}`,\n name: `${original.name} (Copy)`,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n return this.saveTool(cloned);\n }\n\n // ==================== Spaces ====================\n\n async getSpaces(): Promise<Space[]> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const { data, error } = await supabase\n .from(\"spaces\")\n .select(\"*\")\n .eq(\"user_id\", user?.id || \"\")\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch spaces: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getSpace(id: string): Promise<Space | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"spaces\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch space: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveSpace(space: Space): Promise<Space> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const dbSpace = toSnakeCase({\n ...space,\n userId: space.userId || user?.id,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"spaces\")\n .upsert(dbSpace)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save space: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteSpace(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"spaces\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete space: ${error.message}`);\n }\n\n // ==================== Artifacts ====================\n\n async getArtifacts(spaceId: string): Promise<Artifact[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"artifacts\")\n .select(\"*\")\n .eq(\"space_id\", spaceId)\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch artifacts: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getArtifact(id: string): Promise<Artifact | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"artifacts\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch artifact: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveArtifact(artifact: Artifact): Promise<Artifact> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const dbArtifact = toSnakeCase({\n ...artifact,\n userId: artifact.userId || user?.id,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"artifacts\")\n .upsert(dbArtifact)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save artifact: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteArtifact(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"artifacts\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete artifact: ${error.message}`);\n }\n\n // Artifact queries\n async getArtifactsBySpace(spaceId: string): Promise<Artifact[]> {\n return this.getArtifacts(spaceId);\n }\n\n async getArtifactsByTask(taskId: string): Promise<Artifact[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"artifacts\")\n .select(\"*\")\n .eq(\"task_id\", taskId)\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch artifacts: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getArtifactsByCategory(\n spaceOrTaskId: string,\n category: 'input' | 'intermediate' | 'output',\n isTask?: boolean\n ): Promise<Artifact[]> {\n const supabase = await this.getSupabase();\n let query = supabase\n .from(\"artifacts\")\n .select(\"*\")\n .eq(\"category\", category);\n\n if (isTask) {\n query = query.eq(\"task_id\", spaceOrTaskId);\n } else {\n query = query.eq(\"space_id\", spaceOrTaskId);\n }\n\n const { data, error } = await query.order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch artifacts: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n // ==================== Tasks/Conversations ====================\n\n async getTasks(spaceId: string): Promise<Task[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"tasks\")\n .select(\"*\")\n .eq(\"space_id\", spaceId)\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch tasks: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getTask(id: string): Promise<Task | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"tasks\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch task: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveTask(task: Task): Promise<Task> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const dbTask = toSnakeCase({\n ...task,\n userId: task.userId || user?.id,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"tasks\")\n .upsert(dbTask)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save task: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteTask(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"tasks\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete task: ${error.message}`);\n }\n\n // Legacy conversation methods\n async getConversations(spaceId: string): Promise<Conversation[]> {\n return this.getTasks(spaceId) as Promise<Conversation[]>;\n }\n\n async getConversation(id: string, spaceId?: string): Promise<Conversation | null> {\n const supabase = await this.getSupabase();\n let query = supabase.from(\"tasks\").select(\"*\").eq(\"id\", id);\n\n if (spaceId) {\n query = query.eq(\"space_id\", spaceId);\n }\n\n const { data, error } = await query.single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null; // Not found\n throw new Error(`Failed to fetch conversation: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveConversation(conversation: Conversation): Promise<Conversation> {\n const supabase = await this.getSupabase();\n const {\n data: { user },\n } = await supabase.auth.getUser();\n\n const dbConversation = toSnakeCase({\n ...conversation,\n userId: conversation.userId || user?.id,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"tasks\")\n .upsert(dbConversation)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save conversation: ${error.message}`);\n return toCamelCase(data);\n }\n\n async deleteConversation(id: string, spaceId?: string): Promise<void> {\n const supabase = await this.getSupabase();\n let query = supabase.from(\"tasks\").delete().eq(\"id\", id);\n\n if (spaceId) {\n query = query.eq(\"space_id\", spaceId);\n }\n\n const { error } = await query;\n\n if (error)\n throw new Error(`Failed to delete conversation: ${error.message}`);\n }\n\n // ==================== Model Providers ====================\n\n async getModelProviders(): Promise<ModelProvider[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"model_providers\")\n .select(\"*\")\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch model providers: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getModelProvider(id: string): Promise<ModelProvider | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"model_providers\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null;\n throw new Error(`Failed to fetch model provider: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveModelProvider(provider: ModelProvider): Promise<ModelProvider> {\n const supabase = await this.getSupabase();\n const dbProvider = toSnakeCase({\n ...provider,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"model_providers\")\n .upsert(dbProvider)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save model provider: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteModelProvider(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"model_providers\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete model provider: ${error.message}`);\n }\n\n // ==================== Datasources ====================\n\n async getDatasources(): Promise<Datasource[]> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"datasources\")\n .select(\"*\")\n .order(\"created_at\", { ascending: false });\n\n if (error) throw new Error(`Failed to fetch datasources: ${error.message}`);\n\n return (data || []).map(toCamelCase);\n }\n\n async getDatasource(id: string): Promise<Datasource | null> {\n const supabase = await this.getSupabase();\n const { data, error } = await supabase\n .from(\"datasources\")\n .select(\"*\")\n .eq(\"id\", id)\n .single();\n\n if (error) {\n if (error.code === \"PGRST116\") return null;\n throw new Error(`Failed to fetch datasource: ${error.message}`);\n }\n\n return toCamelCase(data);\n }\n\n async saveDatasource(datasource: Datasource): Promise<Datasource> {\n const supabase = await this.getSupabase();\n const dbDatasource = toSnakeCase({\n ...datasource,\n updatedAt: new Date().toISOString(),\n });\n\n const { data, error } = await supabase\n .from(\"datasources\")\n .upsert(dbDatasource)\n .select()\n .single();\n\n if (error) throw new Error(`Failed to save datasource: ${error.message}`);\n\n return toCamelCase(data);\n }\n\n async deleteDatasource(id: string): Promise<void> {\n const supabase = await this.getSupabase();\n const { error } = await supabase.from(\"datasources\").delete().eq(\"id\", id);\n\n if (error) throw new Error(`Failed to delete datasource: ${error.message}`);\n }\n}\n\n","/**\n * DataAdapterFactory - Creates appropriate data adapter based on configuration\n * Internal to Viber - external code should use ViberDataManager\n */\n\nimport type { DataAdapter } from \"./adapter\";\nimport { LocalDataAdapter } from \"./adapters/local\";\n// SupabaseDatabaseAdapter is NOT imported here - it's imported dynamically in getServerDataAdapter()\n// to avoid bundling server code (next/headers) in client bundle\n\nexport type DataMode = \"local\" | \"database\" | \"auto\";\n\nexport class DataAdapterFactory {\n private static instance: DataAdapter | null = null;\n\n /**\n * Create or get singleton data adapter instance\n */\n static create(mode?: DataMode): DataAdapter {\n if (this.instance) {\n return this.instance;\n }\n\n const dataMode = mode || this.detectMode();\n\n if (dataMode === \"database\") {\n // For client-side database mode, we should ideally not be creating an adapter here\n // but rather using server actions. However, for legacy compatibility or\n // if this is called on the server, we might need to handle it.\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"Client-side direct database access is not supported. Use server actions.\"\n );\n }\n console.log(\"[ViberDataAdapter] Using database mode (API-based)\");\n // We can't synchronously return SupabaseDatabaseAdapter here because of dynamic import requirements for server-only code.\n // This method is synchronous. If we are on the server, we should use getServerDataAdapter instead.\n // For now, we'll throw an error to enforce using the async/server-specific path.\n throw new Error(\n \"Synchronous creation of database adapter is not supported. Use getServerDataAdapter().\"\n );\n } else {\n console.log(\"[ViberDataAdapter] Using local mode (file-based)\");\n this.instance = new LocalDataAdapter();\n }\n\n return this.instance;\n }\n\n /**\n * Auto-detect which mode to use based on environment\n */\n private static detectMode(): DataMode {\n // Check explicit environment variable\n const explicitMode = process.env.VIBEX_DATA_MODE as DataMode | undefined;\n if (explicitMode === \"local\" || explicitMode === \"database\") {\n return explicitMode;\n }\n\n // Use database mode only if Supabase is explicitly configured\n if (\n process.env.NEXT_PUBLIC_SUPABASE_URL &&\n process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY\n ) {\n return \"database\";\n }\n\n // Default to local mode for standalone/daemon use\n return \"local\";\n }\n\n /**\n * Reset singleton instance (useful for testing)\n */\n static reset(): void {\n this.instance = null;\n }\n\n /**\n * Get current mode\n */\n static getCurrentMode(): DataMode {\n return this.detectMode();\n }\n}\n\n/**\n * Get data adapter for client-side and general use\n * Internal to Viber - use ViberDataManager instead\n */\nexport function getDataAdapter(): DataAdapter {\n return DataAdapterFactory.create();\n}\n\n/**\n * Get data adapter for server-side API routes\n * Uses direct Supabase access in database mode (not API calls)\n *\n * NOTE: This function uses server-only imports and should only be called\n * from server-side code (API routes, server components, server actions).\n */\nlet serverAdapterInstance: DataAdapter | null = null;\n\nexport function getServerDataAdapter(): DataAdapter {\n // Return cached instance if available\n if (serverAdapterInstance) {\n return serverAdapterInstance;\n }\n\n // Check we're on the server\n if (typeof window !== \"undefined\") {\n throw new Error(\"getServerDataAdapter() can only be called on the server\");\n }\n\n const mode = DataAdapterFactory.getCurrentMode();\n\n if (mode === \"database\") {\n // Dynamic require to avoid bundling server code in client bundle\n // Use server-only version that doesn't import next/headers at module level\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { SupabaseDatabaseAdapter } = require(\"./adapters/supabase-server\");\n // API routes use direct Supabase access to avoid circular dependencies\n console.log(\n \"[ViberDataAdapter] Server: Using Supabase database mode (direct access)\"\n );\n serverAdapterInstance = new SupabaseDatabaseAdapter();\n } else {\n // Local mode uses file system\n console.log(\"[ViberDataAdapter] Server: Using local mode (file-based)\");\n serverAdapterInstance = new LocalDataAdapter();\n }\n\n return serverAdapterInstance!;\n}\n","/**\n * Base classes and decorators for custom tools\n * Provides decorator-based tool extraction for multi-tool providers\n */\n\nimport { z } from \"zod\";\nimport * as path from \"path\";\nimport { promises as fs } from \"fs\";\nimport \"reflect-metadata\";\nimport { CoreTool } from \"../core/tool\";\nimport { getViberRoot } from \"../config\";\n\nconst TOOLS_METADATA_KEY = Symbol(\"tools\");\n\n/**\n * Option definition for select fields\n * Contains semantic information about options (NOT UI concerns like icons)\n */\nexport interface OptionDefinition {\n value: string; // The actual value stored\n label: string; // Human-readable label\n description?: string; // Semantic description of what this option does\n}\n\n/**\n * Base configuration item - shared properties for all field types\n */\ninterface BaseConfigItem {\n name: string; // Human-readable field name\n description?: string; // What this field does/controls\n required?: boolean; // Whether this field is required\n defaultValue?: any; // Default value for the field\n}\n\n/**\n * String field configuration\n * Supports environment variable integration\n */\nexport interface StringConfigItem extends BaseConfigItem {\n type: \"string\";\n envVar?: string; // Environment variable name if applicable\n}\n\n/**\n * Number field configuration\n * Supports min/max validation\n */\nexport interface NumberConfigItem extends BaseConfigItem {\n type: \"number\";\n min?: number; // Minimum value\n max?: number; // Maximum value\n}\n\n/**\n * Boolean field configuration\n */\nexport interface BooleanConfigItem extends BaseConfigItem {\n type: \"boolean\";\n}\n\n/**\n * Select field configuration\n * Supports simple string options or rich option definitions\n */\nexport interface SelectConfigItem extends BaseConfigItem {\n type: \"select\";\n options: string[] | OptionDefinition[]; // Available choices\n}\n\n/**\n * Array field configuration\n */\nexport interface ArrayConfigItem extends BaseConfigItem {\n type: \"array\";\n itemType?: \"string\" | \"number\"; // Type of array items\n}\n\n/**\n * Configuration item - discriminated union of all field types\n * Each type has its own specific properties, ensuring type safety\n */\nexport type ConfigItem =\n | StringConfigItem\n | NumberConfigItem\n | BooleanConfigItem\n | SelectConfigItem\n | ArrayConfigItem;\n\n/**\n * Tool configuration schema using ConfigItem\n */\nexport interface ConfigSchema {\n [key: string]: ConfigItem;\n}\n\n/**\n * Tool function decorator - marks a method as a tool with schema and description\n */\nexport function ToolFunction<T extends z.ZodSchema>(config: {\n name?: string; // Optional, defaults to method name\n description: string;\n input: T; // Input schema\n}) {\n return function (\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor\n ) {\n // Store tool metadata\n const tools = Reflect.getMetadata(TOOLS_METADATA_KEY, target) || [];\n tools.push({\n methodName: propertyKey,\n toolName: config.name || propertyKey,\n description: config.description,\n inputSchema: config.input,\n });\n Reflect.defineMetadata(TOOLS_METADATA_KEY, tools, target);\n\n // Wrap the original method to validate input\n const originalMethod = descriptor.value;\n descriptor.value = async function (input: z.infer<T>) {\n // Validate input\n const validated = config.input.parse(input);\n // Call original method\n return originalMethod.call(this, validated);\n };\n\n return descriptor;\n };\n}\n\n// Shorter alias\nexport { ToolFunction as Function };\n\n/**\n * Configuration schema for tools\n */\nexport interface ToolConfig {\n [key: string]: any;\n}\n\n/**\n * Tool metadata\n */\nexport interface ToolMetadata {\n id: string;\n name: string;\n description: string;\n category: string;\n requiresApiKey?: boolean;\n apiKeyName?: string;\n}\n\n/**\n * Base class for tools - a single class can provide multiple related tool methods\n *\n * Provides standardized space-aware file operations that automatically handle\n * Viber space storage structure (.viber/{spaceId}/artifacts/).\n *\n * Example usage in a custom tool:\n * ```typescript\n * class MyTool extends Tool {\n * @ToolFunction({\n * description: 'Process a file in the space',\n * input: z.object({ fileName: z.string() })\n * })\n * async processFile(input: { fileName: string }) {\n * // Check if file exists in space artifacts\n * if (await this.artifactFileExists(input.fileName)) {\n * // Read file content\n * const content = await this.readArtifactFile(input.fileName);\n *\n * // Process content...\n * const processed = content.toUpperCase();\n *\n * // Write back to artifacts\n * await this.writeArtifactFile('processed_' + input.fileName, processed);\n *\n * return { success: true };\n * }\n * throw new Error('File not found in space artifacts');\n * }\n * }\n * ```\n */\nexport abstract class Tool {\n protected spaceId?: string;\n\n /**\n * Get tool metadata\n */\n abstract getMetadata(): ToolMetadata;\n\n /**\n * Get configuration schema for this tool\n * Returns null if no configuration needed\n */\n getConfigSchema(): ConfigSchema | null {\n return null;\n }\n\n /**\n * Validate configuration\n */\n validateConfig(config: any): boolean {\n const schema = this.getConfigSchema();\n if (!schema) return true;\n\n // Basic validation based on ConfigSchema\n for (const [key, item] of Object.entries(schema)) {\n const value = config[key];\n\n // Check required fields\n if (\n item.required &&\n (value === undefined || value === null || value === \"\")\n ) {\n return false;\n }\n\n // Type validation\n if (value !== undefined && value !== null) {\n switch (item.type) {\n case \"number\": {\n if (typeof value !== \"number\") return false;\n // TypeScript knows item is NumberConfigItem here\n if (item.min !== undefined && value < item.min) return false;\n if (item.max !== undefined && value > item.max) return false;\n break;\n }\n case \"boolean\":\n if (typeof value !== \"boolean\") return false;\n break;\n case \"select\": {\n // TypeScript knows item is SelectConfigItem here\n // Handle both string[] and OptionDefinition[]\n const validValues = item.options.map((opt) =>\n typeof opt === \"string\" ? opt : opt.value\n );\n if (!validValues.includes(value)) return false;\n break;\n }\n case \"array\":\n if (!Array.isArray(value)) return false;\n break;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Get current configuration\n */\n getConfig(): ToolConfig | null {\n return null;\n }\n\n /**\n * Set configuration\n */\n setConfig(config: ToolConfig): void {\n // Override in subclasses if needed\n // The config parameter is intentionally unused in the base class\n void config;\n }\n\n /**\n * Set space context for this tool instance\n * Called by the tool system when spaceId is available\n */\n setSpaceId(spaceId?: string): void {\n this.spaceId = spaceId;\n }\n\n /**\n * Get the current space ID\n */\n getSpaceId(): string | undefined {\n return this.spaceId;\n }\n\n /**\n * Get space-aware storage path\n * Utility method for tools that need to work with space-specific storage\n */\n protected async getSpacePathAsync(subPath: string = \"\"): Promise<string> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n // Use the storage module properly\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n const basePath = storage.getSpacePath();\n return subPath ? path.join(basePath, subPath) : basePath;\n }\n\n private static getRootPath(): string {\n return getViberRoot();\n }\n\n protected getSpacePath(subPath: string = \"\"): string {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n // Use the exact same root path logic as SpaceStorageFactory\n const rootPath = Tool.getRootPath();\n const basePath = path.join(rootPath, \"spaces\", this.spaceId);\n return subPath ? path.join(basePath, subPath) : basePath;\n }\n\n /**\n * Get space artifacts directory path\n * Utility method for tools that work with space artifacts\n */\n protected getSpaceArtifactsPath(fileName: string = \"\"): string {\n const artifactsPath = this.getSpacePath(\"artifacts\");\n return fileName ? path.join(artifactsPath, fileName) : artifactsPath;\n }\n\n /**\n * Resolve file path within space artifacts directory\n * Handles both relative and absolute paths, with security checks\n */\n protected resolveArtifactPath(filePath: string): string {\n if (path.isAbsolute(filePath)) {\n // For absolute paths, check if they're within the space artifacts directory\n const artifactsPath = this.getSpaceArtifactsPath();\n const resolved = path.resolve(filePath);\n if (!resolved.startsWith(artifactsPath)) {\n throw new Error(\n \"Absolute paths outside space artifacts directory are not allowed\"\n );\n }\n return resolved;\n }\n // For relative paths, resolve within artifacts directory\n return this.getSpaceArtifactsPath(filePath);\n }\n\n /**\n * Read file from space artifacts directory\n */\n protected async readArtifactFile(\n filePath: string,\n encoding: BufferEncoding = \"utf8\"\n ): Promise<string> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize path - remove \"artifacts/\" prefix if present since storage methods handle it\n const normalizedPath = filePath.startsWith(\"artifacts/\")\n ? filePath.substring(10)\n : filePath;\n const artifactPath = `artifacts/${normalizedPath}`;\n\n const buffer = await storage.readFile(artifactPath);\n return buffer.toString(encoding);\n }\n\n /**\n * Write file to space artifacts directory\n */\n protected async writeArtifactFile(\n filePath: string,\n content: string,\n encoding: BufferEncoding = \"utf8\"\n ): Promise<void> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize path - remove \"artifacts/\" prefix if present\n const normalizedPath = filePath.startsWith(\"artifacts/\")\n ? filePath.substring(10)\n : filePath;\n const artifactPath = `artifacts/${normalizedPath}`;\n\n const buffer = Buffer.from(content, encoding);\n await storage.writeFile(artifactPath, buffer);\n }\n\n /**\n * Check if file exists in space artifacts directory\n */\n protected async artifactFileExists(filename: string): Promise<boolean> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n try {\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Try to get the artifact by filename - simple and direct\n const artifact = await storage.getArtifact(filename);\n return artifact !== null;\n } catch {\n return false;\n }\n }\n\n /**\n * Get file stats from space artifacts directory\n * Note: This method still uses fs.stat for local storage compatibility\n * For Supabase storage, size info is available through artifact metadata\n */\n protected async getArtifactFileStats(filePath: string) {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n // For local storage, we can still use fs.stat on the resolved path\n // This is acceptable since getArtifactFileStats is primarily used for\n // file metadata that's already available through other means in Supabase\n const fullPath = this.resolveArtifactPath(filePath);\n return await fs.stat(fullPath);\n }\n\n /**\n * List files in space artifacts directory\n */\n protected async listArtifactFiles(\n dirPath: string = \"\",\n recursive: boolean = false\n ): Promise<string[]> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize directory path\n const normalizedPath = dirPath.startsWith(\"artifacts/\")\n ? dirPath.substring(10)\n : dirPath;\n const searchPath = normalizedPath ? `artifacts/${normalizedPath}` : \"artifacts\";\n\n // Get list of files from storage\n const allFiles = await storage.list(searchPath);\n\n if (!recursive) {\n // Filter to only direct children (no subdirectories)\n return allFiles.filter((file) => !file.includes(\"/\"));\n }\n\n return allFiles;\n }\n\n /**\n * Delete file from space artifacts directory\n */\n protected async deleteArtifactFile(filePath: string): Promise<void> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize path\n const normalizedPath = filePath.startsWith(\"artifacts/\")\n ? filePath.substring(10)\n : filePath;\n const artifactPath = `artifacts/${normalizedPath}`;\n\n await storage.delete(artifactPath);\n }\n\n /**\n * Copy file within space artifacts directory\n */\n protected async copyArtifactFile(\n sourcePath: string,\n destPath: string\n ): Promise<void> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize paths\n const normalizedSource = sourcePath.startsWith(\"artifacts/\")\n ? sourcePath.substring(10)\n : sourcePath;\n const normalizedDest = destPath.startsWith(\"artifacts/\")\n ? destPath.substring(10)\n : destPath;\n\n const sourceArtifactPath = `artifacts/${normalizedSource}`;\n const destArtifactPath = `artifacts/${normalizedDest}`;\n\n // Read source file and write to destination\n const content = await storage.readFile(sourceArtifactPath);\n await storage.writeFile(destArtifactPath, content);\n }\n\n /**\n * Move file within space artifacts directory\n */\n protected async moveArtifactFile(\n sourcePath: string,\n destPath: string\n ): Promise<void> {\n if (!this.spaceId) {\n throw new Error(\n \"Space ID not set. This tool requires space context.\"\n );\n }\n\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const storage = await SpaceStorageFactory.create(this.spaceId);\n\n // Normalize paths\n const normalizedSource = sourcePath.startsWith(\"artifacts/\")\n ? sourcePath.substring(10)\n : sourcePath;\n const normalizedDest = destPath.startsWith(\"artifacts/\")\n ? destPath.substring(10)\n : destPath;\n\n const sourceArtifactPath = `artifacts/${normalizedSource}`;\n const destArtifactPath = `artifacts/${normalizedDest}`;\n\n // Read, write, then delete source\n const content = await storage.readFile(sourceArtifactPath);\n await storage.writeFile(destArtifactPath, content);\n await storage.delete(sourceArtifactPath);\n }\n\n /**\n * Check if tool is available/properly configured\n */\n isAvailable(): boolean {\n return true;\n }\n\n /**\n * Automatically extract all decorated methods as tools\n */\n getTools(): Record<string, CoreTool> {\n const tools: Record<string, CoreTool> = {};\n\n // Get all decorated tool methods\n const toolMetadata = Reflect.getMetadata(TOOLS_METADATA_KEY, this) || [];\n\n for (const {\n methodName,\n toolName,\n description,\n inputSchema,\n } of toolMetadata) {\n // Create CoreTool entry - tool names should already be in snake_case\n tools[toolName] = {\n description,\n inputSchema: inputSchema || z.any(),\n execute: (this as any)[methodName].bind(this),\n };\n }\n\n return tools;\n }\n\n /**\n * Get list of tool names provided by this class\n */\n getToolNames(): string[] {\n const toolMetadata = Reflect.getMetadata(TOOLS_METADATA_KEY, this) || [];\n return toolMetadata.map((t: any) => t.toolName);\n }\n\n /**\n * Get detailed information about all tool functions\n * Returns the same structure as getTools() but without execute functions\n */\n getToolDetails(): Array<{\n name: string;\n description: string;\n parameters: any;\n }> {\n const tools = this.getTools();\n return Object.entries(tools).map(([name, tool]) => ({\n name,\n description: tool.description,\n parameters: tool.inputSchema?._def || tool.inputSchema || {},\n }));\n }\n}\n","/**\n * FileTool using unified decorator for cleaner code\n */\n\nimport { z } from \"zod\";\nimport { promises as fs } from \"fs\";\nimport * as path from \"path\";\nimport {\n Tool,\n ToolFunction,\n ToolMetadata,\n ToolConfig,\n ConfigSchema,\n} from \"./base\";\n\nexport class FileTool extends Tool {\n private config: ToolConfig = {\n basePath: process.cwd(),\n allowAbsolutePaths: true,\n maxFileSize: 10 * 1024 * 1024, // 10MB\n allowedExtensions: null, // null means all extensions allowed\n excludedPaths: [\".git\", \"node_modules\", \".env\"],\n };\n\n getMetadata(): ToolMetadata {\n return {\n id: \"file\",\n name: \"File System Tools\",\n description:\n \"Read, write, manage and manipulate files and directories in the local file system\",\n category: \"file\",\n };\n }\n\n getConfigSchema(): ConfigSchema {\n return {\n basePath: {\n name: \"Base Path\",\n type: \"string\",\n description: \"Base directory for file operations\",\n defaultValue: process.cwd(),\n required: false,\n },\n allowAbsolutePaths: {\n name: \"Allow Absolute Paths\",\n type: \"boolean\",\n description:\n \"Allow operations on absolute paths outside the base directory\",\n defaultValue: false,\n required: false,\n },\n maxFileSize: {\n name: \"Max File Size\",\n type: \"number\",\n description: \"Maximum file size in bytes\",\n defaultValue: 10485760, // 10MB\n required: false,\n },\n allowedExtensions: {\n name: \"Allowed Extensions\",\n type: \"array\",\n description:\n \"List of allowed file extensions (leave empty to allow all)\",\n defaultValue: null,\n required: false,\n },\n excludedPaths: {\n name: \"Excluded Paths\",\n type: \"array\",\n description: \"Directories and paths to exclude from operations\",\n defaultValue: [\".git\", \"node_modules\", \".env\"],\n required: false,\n },\n };\n }\n\n getConfig(): ToolConfig {\n return this.config;\n }\n\n setConfig(config: ToolConfig): void {\n this.config = { ...this.config, ...config };\n }\n\n private getBasePath(): string {\n // If we have a space ID, use the space's artifacts directory\n if (this.spaceId) {\n return this.getSpaceArtifactsPath();\n }\n return this.config.basePath || process.cwd();\n }\n\n private resolvePath(filePath: string): string {\n // If we have space context, use artifact-aware path resolution\n if (this.spaceId) {\n return this.resolveArtifactPath(filePath);\n }\n\n // Fallback to original logic for non-space context\n if (path.isAbsolute(filePath)) {\n if (!this.config.allowAbsolutePaths) {\n throw new Error(\n \"Absolute paths are not allowed. Please use relative paths or enable allowAbsolutePaths in configuration.\"\n );\n }\n return filePath;\n }\n return path.join(this.getBasePath(), filePath);\n }\n\n @ToolFunction({\n description:\n \"Create a new file or overwrite an existing file with the specified content. Creates parent directories if they don't exist.\",\n input: z.object({\n path: z\n .string()\n .describe(\n \"The file path to create or overwrite (relative or absolute)\"\n ),\n content: z.string().describe(\"The content to write to the file\"),\n encoding: z\n .enum([\"utf8\", \"base64\"])\n .optional()\n .default(\"utf8\")\n .describe(\n \"The encoding format for the file content (utf8 for text, base64 for binary)\"\n ),\n }),\n })\n async create_file(input: {\n path: string;\n content: string;\n encoding?: \"utf8\" | \"base64\";\n }) {\n // Use base class method for space context\n if (this.spaceId) {\n await this.writeArtifactFile(input.path, input.content, input.encoding || \"utf8\");\n return {\n success: true,\n path: input.path,\n size: Buffer.byteLength(input.content, input.encoding || \"utf8\"),\n };\n }\n\n // Fallback to fs for non-space operations\n const fullPath = this.resolvePath(input.path);\n\n // Ensure directory exists\n const dir = path.dirname(fullPath);\n await fs.mkdir(dir, { recursive: true });\n\n // Write file\n await fs.writeFile(fullPath, input.content, input.encoding || \"utf8\");\n\n return {\n success: true,\n path: fullPath,\n size: Buffer.byteLength(input.content, input.encoding || \"utf8\"),\n };\n }\n\n @ToolFunction({\n description:\n \"Read the contents of a file from the file system. Returns the file content along with metadata like size and modification time.\",\n input: z.object({\n path: z.string().describe(\"The file path to read (relative or absolute)\"),\n encoding: z\n .enum([\"utf8\", \"base64\"])\n .optional()\n .default(\"utf8\")\n .describe(\n \"The encoding to use when reading the file (utf8 for text files, base64 for binary files)\"\n ),\n }),\n })\n async read_file(input: { path: string; encoding?: \"utf8\" | \"base64\" }) {\n // Use base class method for space context\n if (this.spaceId) {\n const content = await this.readArtifactFile(input.path, input.encoding || \"utf8\");\n const stats = await this.getArtifactFileStats(input.path);\n return {\n content,\n path: input.path,\n size: stats.size,\n modified: stats.mtime.toISOString(),\n };\n }\n\n // Fallback to fs for non-space operations\n const fullPath = this.resolvePath(input.path);\n\n const content = await fs.readFile(fullPath, input.encoding || \"utf8\");\n const stats = await fs.stat(fullPath);\n\n return {\n content,\n path: fullPath,\n size: stats.size,\n modified: stats.mtime.toISOString(),\n };\n }\n\n @ToolFunction({\n description:\n \"Delete a file from the file system. This operation is irreversible. The file must exist or an error will be thrown.\",\n input: z.object({\n path: z\n .string()\n .describe(\"The file path to delete (relative or absolute)\"),\n }),\n })\n async delete_file(input: { path: string }) {\n // Use base class method for space context\n if (this.spaceId) {\n await this.deleteArtifactFile(input.path);\n return {\n success: true,\n path: input.path,\n };\n }\n\n // Fallback to fs for non-space operations\n const fullPath = this.resolvePath(input.path);\n\n await fs.unlink(fullPath);\n\n return {\n success: true,\n path: fullPath,\n };\n }\n\n @ToolFunction({\n description:\n \"List all files in a directory with optional recursive traversal and pattern filtering. Returns an array of file paths.\",\n input: z.object({\n directory: z\n .string()\n .describe(\n \"The directory path to list files from (relative or absolute)\"\n ),\n recursive: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to recursively list files in subdirectories\"),\n pattern: z\n .string()\n .optional()\n .describe(\n \"Optional pattern to filter files (simple string matching, not full glob)\"\n ),\n }),\n })\n async list_files(input: {\n directory: string;\n recursive?: boolean;\n pattern?: string;\n }) {\n // Use base class method for space context\n if (this.spaceId) {\n let files = await this.listArtifactFiles(input.directory, input.recursive || false);\n\n // Apply pattern filter if provided\n if (input.pattern) {\n files = files.filter((file) => file.includes(input.pattern!));\n }\n\n return {\n directory: input.directory,\n files,\n count: files.length,\n };\n }\n\n // Fallback to fs for non-space operations\n const fullPath = this.resolvePath(input.directory);\n\n const files: string[] = [];\n\n async function walk(dir: string) {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dir, entry.name);\n\n if (entry.isDirectory() && input.recursive) {\n await walk(entryPath);\n } else if (entry.isFile()) {\n // Apply pattern filter if provided\n if (!input.pattern || entryPath.includes(input.pattern)) {\n files.push(entryPath);\n }\n }\n }\n }\n\n await walk(fullPath);\n\n return {\n directory: fullPath,\n files,\n count: files.length,\n };\n }\n\n @ToolFunction({\n description:\n \"Move or rename a file from one location to another. Creates parent directories if needed. The source file will no longer exist after this operation.\",\n input: z.object({\n source: z\n .string()\n .describe(\"The source file path to move from (relative or absolute)\"),\n destination: z\n .string()\n .describe(\n \"The destination file path to move to (relative or absolute)\"\n ),\n }),\n })\n async move_file(input: { source: string; destination: string }) {\n // Use base class method for space context\n if (this.spaceId) {\n await this.moveArtifactFile(input.source, input.destination);\n return {\n success: true,\n source: input.source,\n destination: input.destination,\n };\n }\n\n // Fallback to fs for non-space operations\n const sourcePath = this.resolvePath(input.source);\n const destPath = this.resolvePath(input.destination);\n\n // Ensure destination directory exists\n const destDir = path.dirname(destPath);\n await fs.mkdir(destDir, { recursive: true });\n\n await fs.rename(sourcePath, destPath);\n\n return {\n success: true,\n source: sourcePath,\n destination: destPath,\n };\n }\n\n @ToolFunction({\n description:\n \"Copy a file from one location to another. Creates parent directories if needed. The source file remains unchanged.\",\n input: z.object({\n source: z\n .string()\n .describe(\"The source file path to copy from (relative or absolute)\"),\n destination: z\n .string()\n .describe(\n \"The destination file path to copy to (relative or absolute)\"\n ),\n }),\n })\n async copy_file(input: { source: string; destination: string }) {\n // Use base class method for space context\n if (this.spaceId) {\n await this.copyArtifactFile(input.source, input.destination);\n return {\n success: true,\n source: input.source,\n destination: input.destination,\n };\n }\n\n // Fallback to fs for non-space operations\n const sourcePath = this.resolvePath(input.source);\n const destPath = this.resolvePath(input.destination);\n\n // Ensure destination directory exists\n const destDir = path.dirname(destPath);\n await fs.mkdir(destDir, { recursive: true });\n\n await fs.copyFile(sourcePath, destPath);\n\n return {\n success: true,\n source: sourcePath,\n destination: destPath,\n };\n }\n\n @ToolFunction({\n description:\n \"Check if a file or directory exists at the specified path. Returns existence status and file metadata if it exists.\",\n input: z.object({\n path: z\n .string()\n .describe(\"The file or directory path to check (relative or absolute)\"),\n }),\n })\n async file_exists(input: { path: string }) {\n const fullPath = this.resolvePath(input.path);\n\n try {\n // Use base class method for space-aware file existence check when in space context\n if (this.spaceId) {\n const exists = await this.artifactFileExists(input.path);\n if (exists) {\n const stats = await this.getArtifactFileStats(input.path);\n return {\n exists: true,\n path: fullPath,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n size: stats.size,\n };\n } else {\n return {\n exists: false,\n path: fullPath,\n };\n }\n }\n\n // Fallback for non-space context\n await fs.access(fullPath);\n const stats = await fs.stat(fullPath);\n\n return {\n exists: true,\n path: fullPath,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n size: stats.size,\n };\n } catch {\n return {\n exists: false,\n path: fullPath,\n };\n }\n }\n}\n","/**\n * Simplified Search Tool Configuration\n * Focuses on Tavily and Serper as primary providers\n */\n\nimport { z } from 'zod';\n\nexport type SearchProvider = 'tavily' | 'serper';\n\nexport const SearchConfigSchema = z.object({\n tavilyApiKey: z.string().optional(),\n serperApiKey: z.string().optional(),\n defaultProvider: z.enum(['tavily', 'serper', 'auto']).default('auto'),\n enableFallback: z.boolean().default(true),\n});\n\nexport type SearchConfig = z.infer<typeof SearchConfigSchema>;\n\n// Provider metadata\nexport const SEARCH_PROVIDERS = {\n tavily: {\n name: 'Tavily',\n endpoint: 'https://api.tavily.com/search',\n envVar: 'TAVILY_API_KEY',\n priority: 1, // Higher priority\n },\n serper: {\n name: 'Serper', \n endpoint: 'https://google.serper.dev/search',\n envVar: 'SERPER_API_KEY',\n priority: 2,\n },\n} as const;\n\n/**\n * Simplified Search Configuration Manager\n */\nexport class SearchConfigManager {\n private config: SearchConfig;\n \n constructor(config?: Partial<SearchConfig>) {\n this.config = SearchConfigSchema.parse(config || {});\n }\n\n getApiKey(provider: SearchProvider): string | null {\n // First check config, then fall back to env vars\n if (provider === 'tavily' && this.config.tavilyApiKey) {\n return this.config.tavilyApiKey;\n }\n if (provider === 'serper' && this.config.serperApiKey) {\n return this.config.serperApiKey;\n }\n \n // Fall back to environment variable\n return process.env[SEARCH_PROVIDERS[provider].envVar] || null;\n }\n\n isProviderAvailable(provider: SearchProvider): boolean {\n return !!this.getApiKey(provider);\n }\n\n getAvailableProviders(): SearchProvider[] {\n return (Object.keys(SEARCH_PROVIDERS) as SearchProvider[])\n .filter(p => this.isProviderAvailable(p))\n .sort((a, b) => SEARCH_PROVIDERS[a].priority - SEARCH_PROVIDERS[b].priority);\n }\n\n selectProvider(): SearchProvider | null {\n if (this.config.defaultProvider !== 'auto') {\n const provider = this.config.defaultProvider;\n if (this.isProviderAvailable(provider)) {\n return provider;\n }\n }\n \n const available = this.getAvailableProviders();\n return available[0] || null;\n }\n\n getFallbackProvider(excludeProvider: SearchProvider): SearchProvider | null {\n if (!this.config.enableFallback) return null;\n \n const available = this.getAvailableProviders();\n return available.find(p => p !== excludeProvider) || null;\n }\n\n isSearchAvailable(): boolean {\n return this.getAvailableProviders().length > 0;\n }\n\n getStatus() {\n const providers = (Object.keys(SEARCH_PROVIDERS) as SearchProvider[]).map(id => ({\n id,\n name: SEARCH_PROVIDERS[id].name,\n configured: !!this.getApiKey(id),\n available: this.isProviderAvailable(id),\n }));\n\n return {\n available: this.isSearchAvailable(),\n providers,\n defaultProvider: this.config.defaultProvider,\n selectedProvider: this.selectProvider(),\n };\n }\n}","/**\n * Simplified SearchTool - Focuses on essential search functionality\n */\n\nimport { z } from 'zod';\nimport { Tool, ToolFunction, ToolMetadata, ToolConfig, ConfigSchema } from './base';\nimport { SearchConfigManager, SearchProvider, SEARCH_PROVIDERS } from './search-config';\n\n// Search result interfaces\nexport interface SearchResult {\n title: string;\n url: string;\n snippet: string;\n content?: string;\n score?: number;\n publishedDate?: string;\n}\n\nexport interface SearchResponse {\n provider: string;\n query: string;\n results: SearchResult[];\n totalResults?: number;\n}\n\n/**\n * Simplified SearchTool\n */\nexport class SearchTool extends Tool {\n private configManager: SearchConfigManager;\n private config: any = {};\n\n constructor() {\n super();\n this.configManager = new SearchConfigManager();\n }\n\n getMetadata(): ToolMetadata {\n const status = this.configManager.getStatus();\n const availableProviders = status.providers\n .filter(p => p.available)\n .map(p => p.name)\n .join(' and ');\n \n return {\n id: 'search',\n name: 'Web Search',\n description: availableProviders \n ? `Search the web for current information using ${availableProviders}`\n : 'Web search functionality (requires TAVILY_API_KEY or SERPER_API_KEY)',\n category: 'search',\n };\n }\n\n getConfigSchema(): ConfigSchema {\n return {\n defaultProvider: {\n name: '默认搜索提供商',\n type: 'select',\n description: '选择默认使用的搜索引擎提供商',\n options: [\n { value: 'auto', label: '自动选择', description: '根据可用性自动选择最佳搜索引擎' },\n { value: 'tavily', label: 'Tavily', description: '专为 AI 优化的搜索引擎,提供高质量结构化结果' },\n { value: 'serper', label: 'Serper', description: 'Google 搜索 API,提供全面的搜索结果' },\n ],\n defaultValue: 'auto',\n required: false,\n },\n enableFallback: {\n name: '启用备用提供商',\n type: 'boolean',\n description: '当主提供商失败时自动切换到备用提供商',\n defaultValue: true,\n required: false,\n },\n tavilyApiKey: {\n name: 'Tavily API 密钥',\n type: 'string',\n description: '用于 Tavily 网络搜索服务的 API 密钥。可以在此直接设置,或通过环境变量 TAVILY_API_KEY 提供',\n envVar: 'TAVILY_API_KEY',\n required: false,\n },\n serperApiKey: {\n name: 'Serper API 密钥',\n type: 'string',\n description: '用于 Serper (Google 搜索) 服务的 API 密钥。可以在此直接设置,或通过环境变量 SERPER_API_KEY 提供',\n envVar: 'SERPER_API_KEY',\n required: false,\n },\n defaultLanguage: {\n name: '默认语言',\n type: 'select',\n description: '搜索结果的默认语言偏好',\n options: [\n { value: 'auto', label: '自动检测' },\n { value: 'zh-CN', label: '简体中文' },\n { value: 'zh-TW', label: '繁体中文' },\n { value: 'en', label: 'English' },\n { value: 'ja', label: '日本語' },\n { value: 'ko', label: '한국어' },\n ],\n defaultValue: 'auto',\n required: false,\n },\n defaultCountry: {\n name: '默认地区',\n type: 'select',\n description: '搜索结果的默认地区偏好',\n options: [\n { value: 'auto', label: '自动选择' },\n { value: 'CN', label: '中国大陆' },\n { value: 'TW', label: '中国台湾省' },\n { value: 'HK', label: '中国香港' },\n { value: 'US', label: '美国' },\n { value: 'JP', label: '日本' },\n { value: 'KR', label: '韩国' },\n ],\n defaultValue: 'auto',\n required: false,\n },\n defaultSearchType: {\n name: '默认搜索类型',\n type: 'select',\n description: '默认的搜索类型',\n options: [\n { value: 'general', label: '常规搜索' },\n { value: 'news', label: '新闻搜索' },\n ],\n defaultValue: 'general',\n required: false,\n },\n defaultNewsDays: {\n name: '新闻时间范围',\n type: 'number',\n description: '新闻搜索的默认时间范围(天数)',\n defaultValue: 7,\n required: false,\n },\n includeDomains: {\n name: '优先域名',\n type: 'array',\n description: '优先显示这些域名的搜索结果(例如:[\"baidu.com\", \"zhihu.com\"])',\n defaultValue: [],\n required: false,\n },\n excludeDomains: {\n name: '排除域名',\n type: 'array',\n description: '从搜索结果中排除这些域名',\n defaultValue: [],\n required: false,\n },\n };\n }\n\n getConfig(): ToolConfig {\n return {\n ...this.config,\n ...this.configManager.getStatus(),\n };\n }\n\n setConfig(config: ToolConfig): void {\n this.config = config;\n\n // Update config manager with new settings\n this.configManager = new SearchConfigManager({\n tavilyApiKey: config.tavilyApiKey,\n serperApiKey: config.serperApiKey,\n defaultProvider: config.defaultProvider,\n enableFallback: config.enableFallback,\n });\n }\n\n isAvailable(): boolean {\n return this.configManager.isSearchAvailable();\n }\n\n @ToolFunction({\n description: 'Search the web for information using configured search providers (Tavily or Serper). Returns relevant web pages with titles, URLs, and snippets. For news queries, automatically prioritizes recent articles and news sources. Supports multiple languages and locales.',\n input: z.object({\n query: z.string().min(1).describe('The search query or keywords to search for'),\n maxResults: z.number().min(1).max(20).optional().default(10).describe('Maximum number of search results to return (1-20, default: 10)'),\n searchType: z.enum(['general', 'news']).optional().default('general').describe('Type of search: \"general\" for all web results, \"news\" for recent news articles only'),\n days: z.number().min(1).max(365).optional().describe('For news searches, limit results to articles from the last N days (default: 7 for news, unlimited for general)'),\n language: z.string().optional().describe('Language code for results (e.g., \"en\" for English, \"zh\" for Chinese, \"zh-CN\" for Simplified Chinese, \"zh-TW\" for Traditional Chinese, \"ja\" for Japanese, \"ko\" for Korean). Defaults to auto-detect from query.'),\n country: z.string().optional().describe('Country code for localized results (e.g., \"US\", \"CN\", \"JP\", \"KR\", \"TW\", \"HK\"). Helps prioritize region-specific sources.'),\n includeDomains: z.array(z.string()).optional().describe('List of domains to prioritize in results (e.g., [\"baidu.com\", \"zhihu.com\"] for Chinese sources)'),\n excludeDomains: z.array(z.string()).optional().describe('List of domains to exclude from results'),\n })\n } as any)\n async search_web(input: {\n query: string;\n maxResults?: number;\n searchType?: 'general' | 'news';\n days?: number;\n language?: string;\n country?: string;\n includeDomains?: string[];\n excludeDomains?: string[];\n }): Promise<SearchResponse> {\n const provider = this.configManager.selectProvider();\n\n if (!provider) {\n throw new Error('No search provider available. Please configure TAVILY_API_KEY or SERPER_API_KEY.');\n }\n\n // Apply config defaults for missing parameters\n const effectiveInput = {\n ...input,\n searchType: input.searchType || (this.config.defaultSearchType as 'general' | 'news') || 'general',\n days: input.days || (input.searchType === 'news' || this.config.defaultSearchType === 'news' ? (this.config.defaultNewsDays || 7) : undefined),\n language: input.language || (this.config.defaultLanguage !== 'auto' ? this.config.defaultLanguage : undefined),\n country: input.country || (this.config.defaultCountry !== 'auto' ? this.config.defaultCountry : undefined),\n includeDomains: input.includeDomains || this.config.includeDomains || [],\n excludeDomains: input.excludeDomains || this.config.excludeDomains || [],\n };\n\n try {\n return await this.searchWithProvider(provider, effectiveInput);\n } catch (error) {\n // Try fallback if available\n const fallback = this.configManager.getFallbackProvider(provider);\n if (fallback) {\n console.warn(`Primary search provider ${provider} failed, trying fallback provider ${fallback}...`);\n return await this.searchWithProvider(fallback, effectiveInput);\n }\n throw error;\n }\n }\n\n private async searchWithProvider(\n provider: SearchProvider,\n input: {\n query: string;\n maxResults?: number;\n searchType?: 'general' | 'news';\n days?: number;\n language?: string;\n country?: string;\n includeDomains?: string[];\n excludeDomains?: string[];\n }\n ): Promise<SearchResponse> {\n const apiKey = this.configManager.getApiKey(provider);\n if (!apiKey) {\n throw new Error(`${provider} API key is not configured`);\n }\n\n const endpoint = SEARCH_PROVIDERS[provider].endpoint;\n\n switch (provider) {\n case 'tavily':\n return await this.searchWithTavily(endpoint, apiKey, input);\n case 'serper':\n return await this.searchWithSerper(endpoint, apiKey, input);\n default:\n throw new Error(`Search provider ${provider} is not implemented`);\n }\n }\n\n private async searchWithTavily(\n endpoint: string,\n apiKey: string,\n input: {\n query: string;\n maxResults?: number;\n searchType?: 'general' | 'news';\n days?: number;\n language?: string;\n country?: string;\n includeDomains?: string[];\n excludeDomains?: string[];\n }\n ): Promise<SearchResponse> {\n const isNews = input.searchType === 'news';\n const days = input.days || (isNews ? 7 : undefined);\n\n const requestBody: any = {\n query: input.query,\n search_depth: 'advanced',\n max_results: input.maxResults || 10,\n include_raw_content: false,\n include_answer: false,\n };\n\n // Add news-specific parameters\n if (isNews) {\n requestBody.topic = 'news';\n }\n\n // Add language/locale parameters\n // Tavily doesn't have direct language parameter, but we can influence results via include_domains\n const defaultNewsDomains = isNews ? [\n 'reuters.com', 'apnews.com', 'bbc.com', 'cnn.com',\n 'theguardian.com', 'nytimes.com', 'washingtonpost.com',\n ] : [];\n\n // Add language-specific domains\n const languageBasedDomains: string[] = [];\n if (input.language?.startsWith('zh') || input.country === 'CN' || input.country === 'TW' || input.country === 'HK') {\n languageBasedDomains.push(\n 'sina.com.cn', '163.com', 'qq.com', 'sohu.com', 'ifeng.com',\n 'people.com.cn', 'xinhuanet.com', 'chinanews.com', 'thepaper.cn',\n 'caixin.com', 'guancha.cn', 'huanqiu.com', 'chinadaily.com.cn'\n );\n } else if (input.language === 'ja' || input.country === 'JP') {\n languageBasedDomains.push(\n 'nhk.or.jp', 'asahi.com', 'nikkei.com', 'yomiuri.co.jp',\n 'mainichi.jp', 'sankei.com', 'jiji.com'\n );\n } else if (input.language === 'ko' || input.country === 'KR') {\n languageBasedDomains.push(\n 'chosun.com', 'donga.com', 'joins.com', 'hani.co.kr',\n 'khan.co.kr', 'yna.co.kr'\n );\n }\n\n // Combine all domain preferences\n const allIncludeDomains = [\n ...(input.includeDomains || []),\n ...languageBasedDomains,\n ...(languageBasedDomains.length === 0 ? defaultNewsDomains : []),\n ];\n\n if (allIncludeDomains.length > 0) {\n requestBody.include_domains = allIncludeDomains;\n }\n\n // Add exclude domains if specified\n if (input.excludeDomains && input.excludeDomains.length > 0) {\n requestBody.exclude_domains = input.excludeDomains;\n }\n\n // Add time filter if specified\n if (days) {\n requestBody.days = days;\n }\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'api-key': apiKey,\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n throw new Error(`Tavily search failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n return {\n provider: 'tavily',\n query: input.query,\n results: data.results.map((r: any) => {\n // Extract domain from URL for favicon\n let domain = '';\n let favicon = '';\n try {\n const urlObj = new URL(r.url);\n domain = urlObj.hostname.replace('www.', '');\n // Use Google's favicon service\n favicon = `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;\n } catch {\n // Invalid URL, skip favicon\n }\n\n return {\n title: r.title,\n url: r.url,\n snippet: r.content,\n description: r.content, // Use content as description for consistency\n content: r.content, // Map to content field\n score: r.score,\n publishedDate: r.published_date,\n domain,\n favicon,\n };\n }),\n totalResults: data.results.length,\n };\n }\n\n private async searchWithSerper(\n endpoint: string,\n apiKey: string,\n input: {\n query: string;\n maxResults?: number;\n searchType?: 'general' | 'news';\n days?: number;\n language?: string;\n country?: string;\n includeDomains?: string[];\n excludeDomains?: string[];\n }\n ): Promise<SearchResponse> {\n const isNews = input.searchType === 'news';\n const days = input.days || (isNews ? 7 : undefined);\n\n // Use news endpoint for news searches\n const searchEndpoint = isNews ? 'https://google.serper.dev/news' : endpoint;\n\n const requestBody: any = {\n q: input.query,\n num: input.maxResults || 10,\n };\n\n // Add language parameter (Serper native support)\n // Serper uses hl (host language) parameter\n if (input.language) {\n // Convert language codes to Serper format\n let langCode = input.language;\n if (langCode === 'zh') langCode = 'zh-CN'; // Default Chinese to Simplified\n requestBody.hl = langCode;\n }\n\n // Add country/location parameter (Serper native support)\n // Serper uses gl (geolocation) parameter\n if (input.country) {\n requestBody.gl = input.country.toLowerCase();\n }\n\n // Add domain filters\n if (input.includeDomains && input.includeDomains.length > 0) {\n // Serper doesn't have include_domains, but we can modify the query\n const siteFilters = input.includeDomains.map(d => `site:${d}`).join(' OR ');\n requestBody.q = `${input.query} (${siteFilters})`;\n }\n\n if (input.excludeDomains && input.excludeDomains.length > 0) {\n // Add exclude site filters to query\n const excludeFilters = input.excludeDomains.map(d => `-site:${d}`).join(' ');\n requestBody.q = `${requestBody.q} ${excludeFilters}`;\n }\n\n // Add time range for news\n if (isNews && days) {\n // Serper uses tbs parameter for time filtering\n // qdr:d = past day, qdr:w = past week, qdr:m = past month, qdr:y = past year\n if (days <= 1) {\n requestBody.tbs = 'qdr:d';\n } else if (days <= 7) {\n requestBody.tbs = 'qdr:w';\n } else if (days <= 30) {\n requestBody.tbs = 'qdr:m';\n } else {\n requestBody.tbs = 'qdr:y';\n }\n }\n\n const response = await fetch(searchEndpoint, {\n method: 'POST',\n headers: {\n 'X-API-KEY': apiKey,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n });\n\n if (!response.ok) {\n throw new Error(`Serper search failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // News results are in data.news array, regular results in data.organic\n const resultsArray = isNews ? (data.news || []) : (data.organic || []);\n\n return {\n provider: 'serper',\n query: input.query,\n results: resultsArray.map((r: any) => {\n // Extract domain from URL for favicon\n let domain = '';\n let favicon = '';\n try {\n const urlObj = new URL(r.link);\n domain = urlObj.hostname.replace('www.', '');\n // Use Google's favicon service\n favicon = `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;\n } catch {\n // Invalid URL, skip favicon\n }\n\n return {\n title: r.title,\n url: r.link,\n snippet: r.snippet,\n description: r.snippet, // Use snippet as description for consistency\n content: r.snippet, // Also map to content for fallback\n publishedDate: r.date,\n domain,\n favicon,\n };\n }),\n totalResults: data.searchInformation?.totalResults,\n };\n }\n}","/**\n * WebTool - Simplified version using external services (Firecrawl/Jina)\n */\n\nimport { z } from 'zod';\nimport { Tool, ToolFunction, ToolMetadata, ToolConfig, ConfigSchema } from './base';\n\nexport class WebTool extends Tool {\n private config: ToolConfig = {\n jinaApiKey: null,\n firecrawlApiKey: null,\n defaultProvider: 'firecrawl', // firecrawl or jina\n timeout: 30000,\n maxContentLength: 100000,\n followRedirects: true,\n userAgent: 'Mozilla/5.0 (compatible; ViberBot/1.0)',\n enableJavaScript: false, // for providers that support it\n };\n\n getMetadata(): ToolMetadata {\n const jinaApiKey = this.getJinaApiKey();\n const firecrawlApiKey = this.getFirecrawlApiKey();\n\n let availableProviders: string[] = [];\n if (jinaApiKey) availableProviders.push('Jina');\n if (firecrawlApiKey) availableProviders.push('Firecrawl');\n\n return {\n id: 'web',\n name: 'Web Tools',\n description: availableProviders.length > 0\n ? `Extract web content, check URL availability, and crawl websites (Providers: ${availableProviders.join(', ')})`\n : 'Web content extraction, URL checking, and website crawling (requires API configuration)',\n category: 'web',\n };\n }\n\n getConfigSchema(): ConfigSchema {\n return {\n jinaApiKey: {\n name: 'Jina API Key',\n type: 'string',\n description: 'Jina API key for advanced content extraction',\n envVar: 'JINA_API_KEY',\n required: false,\n },\n firecrawlApiKey: {\n name: 'Firecrawl API Key',\n type: 'string',\n description: 'Firecrawl API key for JavaScript rendering',\n envVar: 'FIRECRAWL_API_KEY',\n required: false,\n },\n defaultProvider: {\n name: 'Default Provider',\n type: 'select',\n description: 'Default content extraction provider',\n options: ['firecrawl', 'jina'],\n defaultValue: 'firecrawl',\n required: false,\n },\n timeout: {\n name: 'Request Timeout',\n type: 'number',\n description: 'Request timeout in milliseconds',\n defaultValue: 30000,\n min: 1000,\n max: 120000,\n required: false,\n },\n maxContentLength: {\n name: 'Max Content Length',\n type: 'number',\n description: 'Maximum content length to extract (in characters)',\n defaultValue: 500000,\n required: false,\n },\n userAgent: {\n name: 'User Agent',\n type: 'string',\n description: 'Custom user agent string for HTTP requests',\n required: false,\n },\n enableJavaScript: {\n name: 'Enable JavaScript',\n type: 'boolean',\n description: 'Enable JavaScript rendering for dynamic content (requires compatible provider)',\n defaultValue: false,\n required: false,\n },\n };\n }\n\n getConfig(): ToolConfig {\n return this.config;\n }\n\n setConfig(config: ToolConfig): void {\n this.config = { ...this.config, ...config };\n }\n\n isAvailable(): boolean {\n // Tool is available if at least one provider is configured\n return !!(this.getJinaApiKey() || this.getFirecrawlApiKey());\n }\n\n private getJinaApiKey(): string | null {\n return this.config.jinaApiKey || process.env.JINA_API_KEY || null;\n }\n\n private getFirecrawlApiKey(): string | null {\n return this.config.firecrawlApiKey || process.env.FIRECRAWL_API_KEY || null;\n }\n\n private get providers() {\n return {\n jina: {\n apiKey: this.getJinaApiKey(),\n endpoint: 'https://r.jina.ai',\n },\n firecrawl: {\n apiKey: this.getFirecrawlApiKey(),\n endpoint: 'https://api.firecrawl.dev/v0',\n },\n };\n }\n\n @ToolFunction({\n description: 'Extract and parse web page content into structured formats (markdown, text, HTML). Supports JavaScript-rendered pages and can capture metadata, links, and images. Uses Firecrawl or Jina services for reliable extraction.',\n input: z.object({\n url: z.string().url().describe('The URL to extract content from'),\n provider: z.enum(['jina', 'firecrawl']).optional().describe('Extraction provider to use (auto-selects if not specified)'),\n format: z.enum(['markdown', 'text', 'html', 'all']).optional().default('markdown').describe('Output format for the extracted content'),\n includeMetadata: z.boolean().optional().default(true).describe('Include page metadata (title, description, author, etc.)'),\n includeLinks: z.boolean().optional().default(false).describe('Extract and include all links found on the page'),\n includeImages: z.boolean().optional().default(false).describe('Extract and include all images found on the page'),\n waitForSelector: z.string().optional().describe('CSS selector to wait for before extraction (for dynamic content)'),\n screenshot: z.boolean().optional().default(false).describe('Capture a screenshot of the page (Firecrawl only)'),\n maxLength: z.number().optional().describe('Maximum content length in characters (truncates if exceeded)'),\n timeout: z.number().optional().default(30000).describe('Maximum time to wait for page load in milliseconds'),\n })\n })\n async fetch_webpage(input: {\n url: string;\n provider?: 'jina' | 'firecrawl';\n format?: 'markdown' | 'text' | 'html' | 'all';\n includeMetadata?: boolean;\n includeLinks?: boolean;\n includeImages?: boolean;\n waitForSelector?: string;\n screenshot?: boolean;\n maxLength?: number;\n timeout?: number;\n }) {\n // Auto-select provider if not specified\n const provider = input.provider || this.selectProvider();\n\n if (!provider) {\n throw new Error('No web extraction provider configured. Please configure Firecrawl or Jina API key.');\n }\n\n switch (provider) {\n case 'jina':\n return await this.extractWithJina(input);\n case 'firecrawl':\n return await this.extractWithFirecrawl(input);\n default:\n throw new Error(`Unknown provider: ${provider}`);\n }\n }\n\n @ToolFunction({\n description: 'Crawl a website to extract content from multiple pages. Follows links up to a specified depth and returns structured content from all discovered pages. Useful for documentation sites, blogs, or comprehensive site analysis.',\n input: z.object({\n url: z.string().url().describe('The starting URL for the crawl'),\n maxPages: z.number().min(1).max(100).optional().default(10).describe('Maximum number of pages to crawl (1-100)'),\n maxDepth: z.number().min(1).max(5).optional().default(2).describe('Maximum depth to follow links from the starting page (1-5)'),\n includePattern: z.string().optional().describe('Regex pattern - only crawl URLs matching this pattern'),\n excludePattern: z.string().optional().describe('Regex pattern - skip URLs matching this pattern'),\n format: z.enum(['markdown', 'text', 'html']).optional().default('markdown').describe('Output format for extracted content'),\n })\n })\n async crawl_website(input: {\n url: string;\n maxPages?: number;\n maxDepth?: number;\n includePattern?: string;\n excludePattern?: string;\n format?: 'markdown' | 'text' | 'html';\n }) {\n if (!this.providers.firecrawl.apiKey) {\n throw new Error('Web crawling requires Firecrawl API key to be configured');\n }\n\n // Start crawl job\n const startResponse = await fetch(`${this.providers.firecrawl.endpoint}/crawl`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.providers.firecrawl.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n url: input.url,\n crawlerOptions: {\n maxPages: input.maxPages || 10,\n maxDepth: input.maxDepth || 2,\n includes: input.includePattern ? [input.includePattern] : undefined,\n excludes: input.excludePattern ? [input.excludePattern] : undefined,\n },\n pageOptions: {\n onlyMainContent: true,\n },\n }),\n });\n\n if (!startResponse.ok) {\n const error = await startResponse.text();\n throw new Error(`Failed to start crawl: ${error}`);\n }\n\n const { jobId } = await startResponse.json();\n\n // Poll for results\n let attempts = 0;\n const maxAttempts = 60; // 5 minutes with 5 second intervals\n\n while (attempts < maxAttempts) {\n await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds\n\n const statusResponse = await fetch(`${this.providers.firecrawl.endpoint}/crawl/status/${jobId}`, {\n headers: {\n 'Authorization': `Bearer ${this.providers.firecrawl.apiKey}`,\n },\n });\n\n if (!statusResponse.ok) {\n throw new Error('Failed to check crawl status');\n }\n\n const status = await statusResponse.json();\n\n if (status.status === 'completed') {\n return {\n url: input.url,\n pages: status.data,\n totalPages: status.total,\n provider: 'firecrawl',\n crawledAt: new Date().toISOString(),\n };\n } else if (status.status === 'failed') {\n throw new Error(`Crawl failed: ${status.error}`);\n }\n\n attempts++;\n }\n\n throw new Error('Crawl timed out after 5 minutes');\n }\n\n @ToolFunction({\n description: 'Check if a URL is accessible and retrieve basic information about the resource. Returns HTTP status, content type, size, and last modified date without downloading the full content.',\n input: z.object({\n url: z.string().url().describe('The URL to check for accessibility'),\n timeout: z.number().optional().default(5000).describe('Maximum time to wait for response in milliseconds'),\n })\n })\n async check_url(input: { url: string; timeout?: number }) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), input.timeout || 5000);\n\n try {\n const response = await fetch(input.url, {\n method: 'HEAD',\n headers: {\n 'User-Agent': this.config.userAgent || 'Mozilla/5.0 (compatible; ViberBot/1.0)',\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n return {\n url: input.url,\n accessible: response.ok,\n statusCode: response.status,\n statusText: response.statusText,\n contentType: response.headers.get('content-type'),\n contentLength: response.headers.get('content-length'),\n lastModified: response.headers.get('last-modified'),\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n return {\n url: input.url,\n accessible: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n private selectProvider(): string | null {\n if (this.providers.firecrawl.apiKey) return 'firecrawl';\n if (this.providers.jina.apiKey) return 'jina';\n return null;\n }\n\n private async extractWithJina(input: any) {\n const provider = this.providers.jina;\n\n if (!provider.apiKey) {\n throw new Error('Jina API key not configured');\n }\n\n // Jina uses URL-based API\n const jinaUrl = `${provider.endpoint}/${input.url}`;\n\n const headers: Record<string, string> = {\n 'Accept': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n };\n\n // Add format preferences\n if (input.format === 'markdown') {\n headers['X-Return-Format'] = 'markdown';\n } else if (input.format === 'text') {\n headers['X-Return-Format'] = 'text';\n }\n\n const response = await fetch(jinaUrl, {\n headers,\n signal: AbortSignal.timeout(input.timeout || 30000),\n });\n\n if (!response.ok) {\n throw new Error(`Jina extraction failed: ${response.statusText}`);\n }\n\n const contentType = response.headers.get('content-type');\n let result: any;\n\n if (contentType?.includes('application/json')) {\n result = await response.json();\n } else {\n const text = await response.text();\n result = {\n content: text,\n format: input.format || 'markdown',\n };\n }\n\n // Apply max length if specified\n let content = result.content || result.text || result.markdown;\n if (input.maxLength && content && content.length > input.maxLength) {\n content = content.substring(0, input.maxLength) + '...';\n }\n\n return {\n url: input.url,\n title: result.title,\n content,\n markdown: result.markdown,\n text: result.text,\n html: result.html,\n metadata: result.metadata ? {\n description: result.metadata.description,\n author: result.metadata.author,\n publishedDate: result.metadata.publishedDate,\n keywords: result.metadata.keywords,\n language: result.metadata.language,\n image: result.metadata.ogImage || result.metadata.image,\n } : undefined,\n links: input.includeLinks ? result.links : undefined,\n images: input.includeImages ? result.images : undefined,\n provider: 'jina',\n extractedAt: new Date().toISOString(),\n };\n }\n\n private async extractWithFirecrawl(input: any) {\n const provider = this.providers.firecrawl;\n if (!provider.apiKey) {\n throw new Error('Firecrawl API key not configured');\n }\n\n const response = await fetch(`${provider.endpoint}/scrape`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${provider.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n url: input.url,\n pageOptions: {\n onlyMainContent: true,\n includeHtml: input.format === 'html' || input.format === 'all',\n screenshot: input.screenshot,\n waitFor: input.waitForSelector ? parseInt(input.waitForSelector) : undefined,\n },\n timeout: input.timeout,\n }),\n signal: AbortSignal.timeout(input.timeout || 30000),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Firecrawl extraction failed: ${error}`);\n }\n\n const data = await response.json();\n\n if (!data.success) {\n throw new Error(`Firecrawl extraction failed: ${data.error}`);\n }\n\n const result = data.data;\n\n // Apply max length if specified\n let content = result.markdown || result.content;\n if (input.maxLength && content && content.length > input.maxLength) {\n content = content.substring(0, input.maxLength) + '...';\n }\n\n return {\n url: input.url,\n title: result.metadata?.title,\n content,\n markdown: result.markdown,\n text: result.content,\n html: result.html,\n metadata: {\n description: result.metadata?.description,\n author: result.metadata?.author,\n publishedDate: result.metadata?.publishedTime,\n modifiedDate: result.metadata?.modifiedTime,\n keywords: result.metadata?.keywords?.split(',').map((k: string) => k.trim()),\n language: result.metadata?.language,\n image: result.metadata?.ogImage,\n favicon: result.metadata?.favicon,\n },\n links: input.includeLinks ? result.links : undefined,\n images: input.includeImages ? result.images : undefined,\n screenshot: input.screenshot ? result.screenshot : undefined,\n provider: 'firecrawl',\n extractedAt: new Date().toISOString(),\n };\n }\n}","import { z } from \"zod\";\nimport WebSocket from \"ws\";\nimport { Tool, ToolFunction, ToolMetadata, ToolConfig, ConfigSchema } from \"./base\";\n\n// --- BrowserCDP Implementation ---\n\nexport interface CDPTarget {\n id: string;\n type: string;\n title: string;\n url: string;\n webSocketDebuggerUrl?: string;\n}\n\nexport interface BrowserCDPConfig {\n host?: string;\n port?: number;\n}\n\nexport class BrowserCDP {\n private host: string;\n private port: number;\n private messageId = 0;\n\n constructor(config: BrowserCDPConfig = {}) {\n this.host = config.host || \"localhost\";\n this.port = config.port || 9222;\n }\n\n /**\n * List all available targets (pages, iframes, etc.)\n */\n async listTargets(): Promise<CDPTarget[]> {\n const res = await fetch(`http://${this.host}:${this.port}/json`);\n if (!res.ok) {\n throw new Error(`CDP not available at ${this.host}:${this.port}`);\n }\n return await res.json();\n }\n\n /**\n * Find a target by predicate\n */\n async findTarget(predicate: (t: CDPTarget) => boolean): Promise<CDPTarget | undefined> {\n const targets = await this.listTargets();\n return targets.find(predicate);\n }\n\n /**\n * Execute (evaluate) JavaScript in a specific target\n */\n async evaluate<T = any>(\n target: CDPTarget | string,\n expression: string,\n awaitPromise = false\n ): Promise<T> {\n const wsUrl = typeof target === \"string\" ? target : target.webSocketDebuggerUrl;\n if (!wsUrl) throw new Error(\"Target has no WebSocket URL\");\n\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n const id = ++this.messageId;\n\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error(\"CDP evaluation timeout\"));\n }, 10000);\n\n ws.on(\"open\", () => {\n ws.send(JSON.stringify({\n id,\n method: \"Runtime.evaluate\",\n params: {\n expression,\n returnByValue: true,\n awaitPromise\n }\n }));\n });\n\n ws.on(\"message\", (data: string) => {\n try {\n const msg = JSON.parse(data);\n if (msg.id === id) {\n clearTimeout(timeout);\n ws.close();\n\n if (msg.error) {\n reject(new Error(msg.error.message));\n } else if (msg.result?.exceptionDetails) {\n reject(new Error(`Runtime exception: ${msg.result.exceptionDetails.text}`));\n } else {\n resolve(msg.result?.result?.value);\n }\n }\n } catch (err) {\n clearTimeout(timeout);\n ws.close();\n reject(err);\n }\n });\n\n ws.on(\"error\", (err) => {\n clearTimeout(timeout);\n reject(err);\n });\n });\n }\n /**\n * Check if text exists in the page body\n */\n async hasText(target: CDPTarget | string, text: string): Promise<boolean> {\n return this.evaluate<boolean>(target, `document.body.innerText.includes(\"${text}\")`);\n }\n\n /**\n * Click an element containing specific text\n */\n async clickOnText(target: CDPTarget | string, text: string, tag: string = \"button\"): Promise<boolean> {\n return this.evaluate<boolean>(target, `\n (function() {\n // Helper to find element by text\n const elements = Array.from(document.querySelectorAll(\"${tag}\"));\n const el = elements.find(e => e.textContent.includes(\"${text}\"));\n if (el) {\n el.click();\n return true;\n }\n return false;\n })()\n `);\n }\n\n /**\n * Get a simplified DOM snapshot (useful for LLM context)\n */\n async getDomSnapshot(target: CDPTarget | string): Promise<string> {\n return this.evaluate<string>(target, `\n (function() {\n // Simple DOM serializer to text\n return document.body.innerText;\n })()\n `);\n }\n}\n\n// --- BrowserTool Wrapper ---\n\nexport class BrowserTool extends Tool {\n private cdp: BrowserCDP | null = null;\n\n getMetadata(): ToolMetadata {\n return {\n id: \"browser\",\n name: \"Browser Automation\",\n description: \"Control a web browser using Chrome DevTools Protocol (CDP)\",\n category: \"browser\",\n };\n }\n\n isAvailable(): boolean {\n return true; // Or check if Chrome is running?\n }\n\n private async getCdp(): Promise<BrowserCDP> {\n if (!this.cdp) {\n this.cdp = new BrowserCDP();\n }\n return this.cdp;\n }\n\n @ToolFunction({\n description: \"Launch or connect to a browser instance\",\n input: z.object({\n headless: z.boolean().optional().default(false),\n })\n })\n async launch_browser(input: { headless?: boolean }) {\n // This might be a no-op if we assume connecting to existing\n return { success: true, message: \"Browser connection managed by CDP\" };\n }\n\n @ToolFunction({\n description: \"List all open browser pages/targets\",\n input: z.object({})\n })\n async list_targets() {\n const cdp = await this.getCdp();\n return await cdp.listTargets();\n }\n\n @ToolFunction({\n description: \"Find a browser page that contains specific text\",\n input: z.object({\n text: z.string().describe(\"Text to search for\"),\n })\n })\n async find_page_with_text(input: { text: string }) {\n const cdp = await this.getCdp();\n const targets = await cdp.listTargets();\n const pages = targets.filter((t: CDPTarget) => t.type === 'page');\n\n for (const page of pages) {\n const hasIt = await cdp.hasText(page, input.text);\n if (hasIt) return { found: true, targetId: page.id, title: page.title, url: page.url };\n }\n return { found: false };\n }\n\n @ToolFunction({\n description: \"Click on an element containing specific text\",\n input: z.object({\n text: z.string().describe(\"Text of the element to click\"),\n targetId: z.string().optional().describe(\"Specific page ID to target (optional)\"),\n })\n })\n async click_element(input: { text: string, targetId?: string }) {\n const cdp = await this.getCdp();\n let page: CDPTarget | undefined; // Initialize page as CDPTarget or undefined\n\n if (input.targetId) {\n // If targetId is provided, we need to find the full CDPTarget object\n // as the evaluate method requires webSocketDebuggerUrl\n const targets = await cdp.listTargets();\n page = targets.find((t: CDPTarget) => t.id === input.targetId);\n } else {\n const targets = await cdp.listTargets();\n page = targets.find((t: CDPTarget) => t.type === 'page' && !t.url.startsWith('chrome'));\n }\n\n if (!page) throw new Error(\"No active page found or targetId not found\");\n\n await cdp.clickOnText(page, input.text);\n return { success: true, message: `Clicked element with text \"${input.text}\"` };\n }\n}\n","import { z } from \"zod\";\nimport { Tool, ToolFunction, ToolMetadata, ToolConfig, ConfigSchema } from \"./base\";\nimport { exec } from \"child_process\";\nimport { promisify } from \"util\";\n\n// --- AppleScript Helper ---\n\nconst execAsync = promisify(exec);\n\nasync function runAppleScript(script: string): Promise<string> {\n const command = `osascript -e '${script}'`;\n try {\n const { stdout } = await execAsync(command);\n return stdout.trim();\n } catch (error: any) {\n throw new Error(`AppleScript failed: ${error.message}`);\n }\n}\n\n// --- DesktopTool Wrapper ---\n\nexport class DesktopTool extends Tool {\n getMetadata(): ToolMetadata {\n return {\n id: \"desktop\",\n name: \"Desktop Automation\",\n description: \"Control desktop applications using AppleScript\",\n category: \"system\",\n };\n }\n\n isAvailable(): boolean {\n return process.platform === \"darwin\";\n }\n\n @ToolFunction({\n description: \"Open an application by name\",\n input: z.object({\n appName: z.string().describe(\"Name of the application\"),\n })\n })\n async open_app(input: { appName: string }) {\n await runAppleScript(`tell application \"${input.appName}\" to activate`);\n return { success: true, message: `Opened/Activated ${input.appName}` };\n }\n\n @ToolFunction({\n description: \"Bring an application to the front\",\n input: z.object({\n appName: z.string().describe(\"Name of the application\"),\n })\n })\n async activate_app(input: { appName: string }) {\n await runAppleScript(`tell application \"${input.appName}\" to activate`);\n return { success: true, message: `Activated ${input.appName}` };\n }\n\n @ToolFunction({\n description: \"Type text into the currently focused window\",\n input: z.object({\n text: z.string().describe(\"Text to type\"),\n })\n })\n async type_text(input: { text: string }) {\n const safeText = input.text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n await runAppleScript(`tell application \"System Events\" to keystroke \"${safeText}\"`);\n return { success: true, message: `Typed \"${input.text}\"` };\n }\n}\n","/**\n * Tools Registry\n *\n * Dynamic tool discovery and management system.\n * Tools are discovered from tool classes using decorators.\n */\n\nimport { CoreTool } from \"../core/tool\";\nimport { Tool } from \"./base\";\n\n// Import all tools\nimport { FileTool } from \"./file\";\nimport { SearchTool } from \"./search\";\nimport { WebTool } from \"./web\";\nimport { BrowserTool } from \"./browser\";\nimport { DesktopTool } from \"./desktop\";\n\nexport interface ToolInfo {\n id: string;\n name: string;\n description: string;\n category: string;\n icon?: string; // Icon name (Lucide icon name, Icons component key, or URL)\n tags?: string[]; // Tags for categorization and filtering\n features?: string[]; // List of features the tool provides\n tools: string[]; // Keep for backward compatibility\n functions?: any[]; // New field for function names/objects\n functionDetails?: Array<{\n name: string;\n description: string;\n parameters: any;\n }>; // Detailed function info\n configSchema?: any; // Configuration schema for the tool\n enabled?: boolean;\n}\n\n// Tool instances (created on demand)\nconst toolInstances = new Map<string, Tool>();\n\n// Available tool classes\nconst toolClasses = new Map<string, new () => Tool>([\n [\"file\", FileTool],\n [\"search\", SearchTool],\n [\"web\", WebTool],\n [\"browser\", BrowserTool],\n [\"desktop\", DesktopTool],\n]);\n\n/**\n * Load tool configuration through DataAdapter\n */\nasync function loadToolConfig(toolId: string): Promise<any> {\n try {\n const { getServerDataAdapter } = await import(\"../data/factory\");\n const adapter = getServerDataAdapter();\n\n // Get tool from adapter\n const tool = await adapter.getTool(toolId);\n return tool?.config || {};\n } catch (error) {\n console.error(`[loadToolConfig] Error loading config for ${toolId}:`, error);\n return {};\n }\n}\n\n/**\n * Get or create a tool instance\n */\nexport function getToolInstance(toolId: string): Tool | null {\n if (!toolInstances.has(toolId)) {\n const ToolClass = toolClasses.get(toolId);\n if (!ToolClass) return null;\n\n try {\n const instance = new ToolClass();\n\n // Load configuration from file if available\n // This is async but we handle it synchronously for now\n // In production, configuration should be loaded at startup\n loadToolConfig(toolId)\n .then((config) => {\n if (Object.keys(config).length > 0) {\n instance.setConfig(config);\n }\n })\n .catch((error) => {\n console.error(`[getToolInstance] Error loading config for ${toolId}:`, error);\n });\n\n // Check if tool is available\n if (!instance.isAvailable()) {\n console.warn(`[getToolInstance] Tool ${toolId} is not available`);\n return null;\n }\n\n toolInstances.set(toolId, instance);\n } catch (error) {\n console.warn(`[Tools] Failed to initialize tool ${toolId}:`, error);\n return null;\n }\n }\n return toolInstances.get(toolId) || null;\n}\n\n// Static function details for server-side rendering\nconst staticFunctionDetails = {\n file: [\n {\n name: \"createFile\",\n description:\n \"Create a new file or overwrite an existing file with the specified content. Creates parent directories if they don't exist.\",\n parameters: {},\n },\n {\n name: \"readFile\",\n description:\n \"Read the contents of a file from the file system. Returns the file content along with metadata like size and modification time.\",\n parameters: {},\n },\n {\n name: \"deleteFile\",\n description:\n \"Delete a file from the file system. This operation is irreversible. The file must exist or an error will be thrown.\",\n parameters: {},\n },\n {\n name: \"listFiles\",\n description:\n \"List all files in a directory with optional recursive traversal and pattern filtering. Returns an array of file paths.\",\n parameters: {},\n },\n {\n name: \"moveFile\",\n description:\n \"Move or rename a file from one location to another. Creates parent directories if needed. The source file will no longer exist after this operation.\",\n parameters: {},\n },\n {\n name: \"copyFile\",\n description:\n \"Copy a file from one location to another. Creates parent directories if needed. The source file remains unchanged.\",\n parameters: {},\n },\n {\n name: \"fileExists\",\n description:\n \"Check if a file or directory exists at the specified path. Returns existence status and file metadata if it exists.\",\n parameters: {},\n },\n ],\n search: [\n {\n name: \"search\",\n description:\n \"Search the web for information using configured search providers (Tavily or Serper). Returns relevant web pages with titles, URLs, and snippets.\",\n parameters: {},\n },\n ],\n web: [\n {\n name: \"fetchWebpage\",\n description:\n \"Extract and parse web page content into structured formats (markdown, text, HTML). Supports JavaScript-rendered pages and can capture metadata, links, and images. Uses Firecrawl or Jina services for reliable extraction.\",\n parameters: {},\n },\n {\n name: \"crawlWebsite\",\n description:\n \"Crawl a website to extract content from multiple pages. Follows links up to a specified depth and returns structured content from all discovered pages. Useful for documentation sites, blogs, or comprehensive site analysis.\",\n parameters: {},\n },\n {\n name: \"checkUrl\",\n description:\n \"Check if a URL is accessible and retrieve basic information about the resource. Returns HTTP status, content type, size, and last modified date without downloading the full content.\",\n parameters: {},\n },\n ],\n};\n\n/**\n * Get all tools info\n */\nexport function getToolProviders(): ToolInfo[] {\n // Check if we're in a server environment\n if (typeof window === \"undefined\") {\n // In server/edge runtime, some tools might not work due to Node.js dependencies\n // Return tool metadata without instantiation\n const tools: ToolInfo[] = [\n {\n id: \"file\",\n name: \"File System Tools\",\n description:\n \"Read, write, manage and manipulate files and directories in the local file system\",\n category: \"file\",\n icon: \"FolderOpen\",\n tags: [\"Files\", \"Storage\", \"Local\", \"System\", \"IO\"],\n tools: [\n \"createFile\",\n \"readFile\",\n \"deleteFile\",\n \"listFiles\",\n \"moveFile\",\n \"copyFile\",\n \"fileExists\",\n ],\n functions: [\n \"createFile\",\n \"readFile\",\n \"deleteFile\",\n \"listFiles\",\n \"moveFile\",\n \"copyFile\",\n \"fileExists\",\n ],\n functionDetails: staticFunctionDetails.file,\n configSchema: {\n basePath: {\n name: \"Base Path\",\n type: \"string\",\n description: \"Base directory for file operations\",\n defaultValue: process.cwd(),\n required: false,\n },\n allowAbsolutePaths: {\n name: \"Allow Absolute Paths\",\n type: \"boolean\",\n description:\n \"Allow operations on absolute paths outside the base directory\",\n defaultValue: false,\n required: false,\n },\n maxFileSize: {\n name: \"Max File Size\",\n type: \"number\",\n description: \"Maximum file size in bytes\",\n defaultValue: 10485760,\n required: false,\n },\n },\n enabled: true,\n },\n {\n id: \"search\",\n name: \"Web Search\",\n description:\n \"Search the web for current information using configured search providers\",\n category: \"search\",\n icon: \"Search\",\n tags: [\"Search\", \"Web\", \"Research\", \"Internet\", \"Information\"],\n tools: [\"search\"],\n functions: [\"search\"],\n functionDetails: staticFunctionDetails.search,\n configSchema: {\n defaultProvider: {\n name: \"默认搜索提供商\",\n type: \"select\",\n description: \"选择默认使用的搜索引擎提供商\",\n options: [\n { value: \"auto\", label: \"自动选择\", description: \"根据可用性自动选择最佳搜索引擎\" },\n { value: \"tavily\", label: \"Tavily\", description: \"专为 AI 优化的搜索引擎,提供高质量结构化结果\" },\n { value: \"serper\", label: \"Serper\", description: \"Google 搜索 API,提供全面的搜索结果\" },\n ],\n defaultValue: \"auto\",\n required: false,\n },\n enableFallback: {\n name: \"启用备用提供商\",\n type: \"boolean\",\n description: \"当主提供商失败时自动切换到备用提供商\",\n defaultValue: true,\n required: false,\n },\n tavilyApiKey: {\n name: \"Tavily API 密钥\",\n type: \"string\",\n description: \"用于 Tavily 网络搜索服务的 API 密钥。可以在此直接设置,或通过环境变量 TAVILY_API_KEY 提供\",\n envVar: \"TAVILY_API_KEY\",\n required: false,\n },\n serperApiKey: {\n name: \"Serper API 密钥\",\n type: \"string\",\n description: \"用于 Serper (Google 搜索) 服务的 API 密钥。可以在此直接设置,或通过环境变量 SERPER_API_KEY 提供\",\n envVar: \"SERPER_API_KEY\",\n required: false,\n },\n defaultLanguage: {\n name: \"默认语言\",\n type: \"select\",\n description: \"搜索结果的默认语言偏好\",\n options: [\n { value: \"auto\", label: \"自动检测\" },\n { value: \"zh-CN\", label: \"简体中文\" },\n { value: \"zh-TW\", label: \"繁体中文\" },\n { value: \"en\", label: \"English\" },\n { value: \"ja\", label: \"日本語\" },\n { value: \"ko\", label: \"한국어\" },\n ],\n defaultValue: \"auto\",\n required: false,\n },\n defaultCountry: {\n name: \"默认地区\",\n type: \"select\",\n description: \"搜索结果的默认地区偏好\",\n options: [\n { value: \"auto\", label: \"自动选择\" },\n { value: \"CN\", label: \"中国大陆\" },\n { value: \"TW\", label: \"中国台湾省\" },\n { value: \"HK\", label: \"中国香港\" },\n { value: \"US\", label: \"美国\" },\n { value: \"JP\", label: \"日本\" },\n { value: \"KR\", label: \"韩国\" },\n ],\n defaultValue: \"auto\",\n required: false,\n },\n defaultSearchType: {\n name: \"默认搜索类型\",\n type: \"select\",\n description: \"默认的搜索类型\",\n options: [\n { value: \"general\", label: \"常规搜索\" },\n { value: \"news\", label: \"新闻搜索\" },\n ],\n defaultValue: \"general\",\n required: false,\n },\n defaultNewsDays: {\n name: \"新闻时间范围\",\n type: \"number\",\n description: \"新闻搜索的默认时间范围(天数)\",\n defaultValue: 7,\n required: false,\n },\n includeDomains: {\n name: \"优先域名\",\n type: \"array\",\n description: \"优先显示这些域名的搜索结果(例如:[\\\"baidu.com\\\", \\\"zhihu.com\\\"])\",\n defaultValue: [],\n required: false,\n },\n excludeDomains: {\n name: \"排除域名\",\n type: \"array\",\n description: \"从搜索结果中排除这些域名\",\n defaultValue: [],\n required: false,\n },\n },\n enabled: true,\n },\n {\n id: \"web\",\n name: \"Web Tools\",\n description:\n \"Extract web content, check URL availability, and crawl websites\",\n category: \"web\",\n icon: \"Globe\",\n tags: [\"Web\", \"Extraction\", \"Crawling\", \"Content\", \"Scraping\"],\n tools: [\"fetchWebpage\", \"crawlWebsite\", \"checkUrl\"],\n functions: [\"fetchWebpage\", \"crawlWebsite\", \"checkUrl\"],\n functionDetails: staticFunctionDetails.web,\n configSchema: {\n firecrawlApiKey: {\n name: \"Firecrawl API Key\",\n type: \"password\",\n description: \"API key for Firecrawl web extraction service\",\n envVar: \"FIRECRAWL_API_KEY\",\n required: false,\n },\n jinaApiKey: {\n name: \"Jina API Key\",\n type: \"password\",\n description: \"API key for Jina web extraction service\",\n envVar: \"JINA_API_KEY\",\n required: false,\n },\n defaultProvider: {\n name: \"Default Provider\",\n type: \"select\",\n description: \"Preferred web extraction provider\",\n options: [\"firecrawl\", \"jina\"],\n defaultValue: \"firecrawl\",\n required: false,\n },\n },\n enabled: true,\n },\n ];\n return tools;\n }\n\n // Original client-side code\n const tools: ToolInfo[] = [];\n\n for (const [id, ToolClass] of toolClasses) {\n try {\n const instance = new ToolClass();\n const metadata = instance.getMetadata();\n\n // Only include if available\n if (instance.isAvailable()) {\n // Add tags based on tool ID\n const tags =\n id === \"file\"\n ? [\"Files\", \"Storage\", \"Local\", \"System\", \"IO\"]\n : id === \"search\"\n ? [\"Search\", \"Web\", \"Research\", \"Internet\", \"Information\"]\n : id === \"web\"\n ? [\"Web\", \"Extraction\", \"Crawling\", \"Content\", \"Scraping\"]\n : [];\n\n tools.push({\n ...metadata,\n tags,\n tools: instance.getToolNames(),\n functions: instance.getToolNames(),\n functionDetails: instance.getToolDetails(),\n configSchema: instance.getConfigSchema(),\n enabled: true,\n });\n }\n } catch (error) {\n console.warn(`[Tools] Failed to get metadata for tool ${id}:`, error);\n }\n }\n\n return tools;\n}\n\n/**\n * Get a specific tool info\n */\nexport function getToolProvider(toolId: string): ToolInfo | null {\n const ToolClass = toolClasses.get(toolId);\n if (!ToolClass) return null;\n\n try {\n const instance = new ToolClass();\n const metadata = instance.getMetadata();\n\n // Add tags based on tool ID\n const tags =\n toolId === \"file\"\n ? [\"Files\", \"Storage\", \"Local\", \"System\", \"IO\"]\n : toolId === \"search\"\n ? [\"Search\", \"Web\", \"Research\", \"Internet\", \"Information\"]\n : toolId === \"web\"\n ? [\"Web\", \"Extraction\", \"Crawling\", \"Content\", \"Scraping\"]\n : [];\n\n return {\n ...metadata,\n tags,\n tools: instance.getToolNames(),\n functions: instance.getToolNames(),\n functionDetails: instance.getToolDetails(),\n configSchema: instance.getConfigSchema(),\n enabled: instance.isAvailable(),\n };\n } catch (error) {\n console.warn(`[Tools] Failed to get metadata for tool ${toolId}:`, error);\n return null;\n }\n}\n\n/**\n * Enable or disable a tool\n */\nexport function setProviderEnabled(\n _toolId: string,\n _enabled: boolean\n): boolean {\n // For now, this is controlled by availability (API keys, etc)\n // In the future we might store enable/disable state separately\n console.warn(`[Tools] setProviderEnabled is not fully implemented yet`);\n return true;\n}\n\n/**\n * Build a tool map for specific tool IDs\n * This is the ONLY function that core/tool.ts imports\n */\nexport function buildToolMap(\n toolIds: string[],\n context?: { spaceId?: string }\n): Record<string, CoreTool> {\n const tools: Record<string, CoreTool> = {};\n\n for (const toolId of toolIds) {\n // Check if this is a tool class ID (e.g., 'file', 'web', 'search')\n if (toolClasses.has(toolId)) {\n // Get all functions from this tool class\n const tool = getToolInstance(toolId);\n if (tool) {\n // Set space context for space-aware tools\n if (context?.spaceId) {\n tool.setSpaceId(context.spaceId);\n }\n const toolFunctions = tool.getTools();\n // Add all functions from this tool class\n Object.assign(tools, toolFunctions);\n continue;\n }\n }\n\n // Otherwise, try to find it as a specific function\n let found = false;\n\n\n\n for (const [id] of toolClasses) {\n const tool = getToolInstance(id);\n if (!tool) continue;\n\n // Set space context for space-aware tools\n if (context?.spaceId) {\n tool.setSpaceId(context.spaceId);\n }\n\n // Get all tool functions from this class\n const toolFunctions = tool.getTools();\n\n // Check if this tool has the requested function\n if (toolId in toolFunctions) {\n tools[toolId] = toolFunctions[toolId];\n found = true;\n break; // Found the tool, no need to check other classes\n }\n }\n\n if (!found) {\n console.warn(`[Tools] Tool not found: ${toolId}`);\n }\n }\n\n return tools;\n}\n\n/**\n * Get all available tool IDs\n * Useful for discovery/listing\n */\nexport function getAllToolIds(): string[] {\n const ids: string[] = [];\n\n for (const [toolId] of toolClasses) {\n const tool = getToolInstance(toolId);\n if (!tool) continue;\n\n const toolFunctions = tool.getTools();\n ids.push(...Object.keys(toolFunctions));\n }\n\n return ids;\n}\n\n/**\n * Get all available tool IDs for a specific tool\n */\nexport function getProviderToolIds(toolId: string): string[] {\n const tool = getToolInstance(toolId);\n if (!tool) return [];\n\n const toolFunctions = tool.getTools();\n return Object.keys(toolFunctions);\n}\n\n/**\n * Check if a tool ID is available\n */\nexport function isToolAvailable(toolId: string): boolean {\n for (const [id] of toolClasses) {\n const tool = getToolInstance(id);\n if (!tool) continue;\n\n const toolFunctions = tool.getTools();\n if (toolId in toolFunctions) {\n return true;\n }\n }\n\n return false;\n}\n\n// Export for backward compatibility\nexport function getAvailableTools(): string[] {\n return getAllToolIds();\n}\n\n// Backward compatibility exports (to be removed eventually)\nexport type ToolProviderInfo = ToolInfo;\n\n// Export registry functions for static access (no instantiation)\n","/**\n * Tool System for Viber\n *\n * Coordinates between custom tools and MCP tools.\n * Knows nothing about specific tool implementations.\n */\n\nimport { z } from \"zod\";\n\n// Core tool interface that AI SDK expects\nexport interface CoreTool {\n description: string;\n inputSchema: z.ZodSchema | any;\n execute: (args: any, context?: any) => Promise<any>;\n}\n\n// Cache for MCP clients\nconst mcpClients = new Map<string, any>();\n\n/**\n * Build a tool map for streamText from an array of tool IDs\n * Delegates to appropriate providers without knowing their internals\n */\nexport async function buildToolMap(\n toolIds: string[],\n context?: { spaceId?: string }\n): Promise<Record<string, CoreTool>> {\n const tools: Record<string, CoreTool> = {};\n\n // Load MCP server configurations to determine tool types\n const { getServerDataAdapter } = await import(\"../data/factory\");\n const adapter = getServerDataAdapter();\n const mcpServers = await adapter.getTools();\n const mcpServerIds = new Set(mcpServers.map((s: any) => s.id));\n\n // Separate custom tools and MCP tools\n const customToolIds: string[] = [];\n const mcpToolIds: string[] = [];\n\n for (const id of toolIds) {\n // Check if it's an MCP server ID\n if (mcpServerIds.has(id)) {\n mcpToolIds.push(id);\n } else {\n customToolIds.push(id);\n }\n }\n\n // Load custom tools if needed\n if (customToolIds.length > 0) {\n const { buildToolMap: buildCustomToolMap } = await import(\"../tools\");\n const customTools = buildCustomToolMap(customToolIds, context);\n Object.assign(tools, customTools);\n }\n\n // Load MCP tools if needed\n if (mcpToolIds.length > 0) {\n const mcpTools = await loadMcpTools(mcpToolIds);\n Object.assign(tools, mcpTools);\n }\n\n return tools;\n}\n\n/**\n * Load MCP tools by ID\n * This is the only part that knows about MCP specifics\n */\nasync function loadMcpTools(ids: string[]): Promise<Record<string, CoreTool>> {\n const tools: Record<string, CoreTool> = {};\n\n // Group by server for efficient loading\n const serverGroups = new Map<string, string[]>();\n for (const id of ids) {\n // Handle both mcp:serverId format and direct serverId format\n let serverId = id;\n if (id.startsWith(\"mcp:\")) {\n const parts = id.split(\":\");\n serverId = parts[1] || id;\n }\n\n if (!serverGroups.has(serverId)) {\n serverGroups.set(serverId, []);\n }\n serverGroups.get(serverId)!.push(id);\n }\n\n // Load each server's tools\n for (const [serverId, toolIds] of serverGroups) {\n try {\n let mcpClient = mcpClients.get(serverId);\n\n if (!mcpClient) {\n // MCP client creation disabled - would require external mcp library\n // TODO: Implement MCP client when library is available\n console.warn(`[Tools] MCP client creation not implemented for: ${serverId}`);\n continue;\n }\n\n // Extract requested tools\n if (mcpClient && typeof mcpClient === \"object\") {\n // Get all tools from the MCP client\n const mcpTools = await mcpClient.tools();\n\n // Return all tools from this server\n for (const [toolName, tool] of Object.entries(mcpTools)) {\n if (isValidTool(tool)) {\n tools[toolName] = tool as CoreTool;\n }\n }\n }\n } catch (error) {\n console.error(`[Tools] Failed to load MCP server ${serverId}:`, error);\n }\n }\n\n return tools;\n}\n\n/**\n * Check if an object is a valid tool\n */\nexport function isValidTool(obj: any): boolean {\n return !!(\n obj &&\n typeof obj === \"object\" &&\n typeof obj.execute === \"function\" &&\n typeof obj.description === \"string\"\n );\n}\n\n/**\n * Clear MCP cache (useful for testing)\n */\nexport function clearToolCache(): void {\n mcpClients.clear();\n}\n","import * as fs from \"fs/promises\";\nimport * as fsSync from \"fs\";\nimport * as path from \"path\";\nimport * as yaml from \"yaml\";\nimport { Skill, SkillModule } from \"./types\";\nimport { CoreTool } from \"../core/tool\";\n\nexport class SkillRegistry {\n private skills: Map<string, Skill> = new Map();\n private loadedTools: Map<string, Record<string, CoreTool>> = new Map();\n\n constructor(private skillsRoot: string) { }\n\n /**\n * Scan for skills in the skills directory\n */\n async loadAll(): Promise<void> {\n try {\n const entries = await fs.readdir(this.skillsRoot, { withFileTypes: true });\n const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);\n\n for (const dirName of dirs) {\n await this.loadSkill(dirName);\n }\n } catch (error) {\n console.warn(`[SkillRegistry] Failed to scan skills at ${this.skillsRoot}:`, error);\n }\n }\n\n /**\n * Load a specific skill by directory name\n */\n async loadSkill(dirName: string): Promise<Skill | undefined> {\n const skillDir = path.join(this.skillsRoot, dirName);\n const skillMdPath = path.join(skillDir, \"SKILL.md\");\n\n try {\n // Check if SKILL.md exists\n try {\n await fs.access(skillMdPath);\n } catch {\n return undefined; // Not a skill\n }\n\n // Read SKILL.md\n const content = await fs.readFile(skillMdPath, \"utf8\");\n\n // Parse frontmatter\n // Simple parse: split by ---\n const parts = content.split(/^---$/m);\n if (parts.length < 3) {\n console.warn(`[SkillRegistry] Invalid SKILL.md format in ${dirName}`);\n return undefined;\n }\n\n const frontmatter = parts[1];\n const instructions = parts.slice(2).join(\"---\").trim();\n\n const metadata = yaml.parse(frontmatter);\n const id = metadata.name || dirName;\n\n const skill: Skill = {\n id,\n metadata: {\n name: id,\n description: metadata.description || \"\",\n ...metadata\n },\n instructions,\n dir: skillDir,\n };\n\n this.skills.set(id, skill);\n return skill;\n\n } catch (error) {\n console.error(`[SkillRegistry] Failed to load skill ${dirName}:`, error);\n return undefined;\n }\n }\n\n /**\n * Get tools for a specific skill (lazy load module)\n */\n async getTools(skillId: string, config?: any): Promise<Record<string, CoreTool>> {\n const skill = this.skills.get(skillId);\n if (!skill) {\n throw new Error(`Skill ${skillId} not found`);\n }\n\n if (this.loadedTools.has(skillId)) {\n return this.loadedTools.get(skillId)!;\n }\n\n // Import index.ts\n const idxPath = path.join(skill.dir, \"index.ts\"); // or .js\n try {\n // Dynamic import\n // Note: In strict ESM/TS environments we might need full path or file URL\n const modulePath = path.resolve(idxPath);\n const mod = await import(modulePath) as SkillModule;\n\n let tools: Record<string, CoreTool> = {};\n\n if (mod.getTools) {\n tools = await mod.getTools(config);\n } else if (mod.tools) {\n tools = mod.tools;\n }\n\n this.loadedTools.set(skillId, tools);\n return tools;\n } catch (error) {\n console.error(`[SkillRegistry] Failed to load tools for ${skillId}:`, error);\n return {};\n }\n }\n\n /**\n * Pre-register tools for a skill (used for bundled builds where dynamic import of .ts fails)\n */\n preRegisterTools(skillId: string, tools: Record<string, CoreTool>): void {\n this.loadedTools.set(skillId, tools);\n }\n\n getSkill(id: string): Skill | undefined {\n return this.skills.get(id);\n }\n\n getAllSkills(): Skill[] {\n return Array.from(this.skills.values());\n }\n}\n\nimport { fileURLToPath } from \"url\";\nimport { getViberRoot } from \"../config\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Try multiple paths for skill discovery:\n// 1. process.cwd() + src/skills (CLI run from project root) - Most common case\n// 2. Relative to this file (works in dev mode with tsx)\n// 3. Viber storage root (for daemon mode)\nfunction getDefaultSkillsPath(): string {\n // Option 1: Check process.cwd() + src/skills (CLI run from project root)\n const cwdPath = path.resolve(process.cwd(), \"src/skills\");\n try {\n fsSync.accessSync(cwdPath);\n console.log(`[SkillRegistry] Using skills path (cwd): ${cwdPath}`);\n return cwdPath;\n } catch {\n // Option 2: Relative to this file (skills/registry.ts -> skills)\n const relativePath = path.resolve(__dirname, \".\");\n try {\n fsSync.accessSync(relativePath);\n console.log(`[SkillRegistry] Using skills path (relative): ${relativePath}`);\n return relativePath;\n } catch {\n // Fallback to Viber storage root (for daemon mode)\n const viberPath = path.join(getViberRoot(), \"skills\");\n console.log(`[SkillRegistry] Using skills path (viber root): ${viberPath}`);\n return viberPath;\n }\n }\n}\n\nexport const defaultRegistry = new SkillRegistry(getDefaultSkillsPath());\n\n","/**\n * Agent - Config-driven agent implementation\n *\n * Agents are defined entirely by configuration, not code.\n * Each agent is instantiated from a config object that defines\n * its role, tools, and LLM settings.\n */\n\nimport { generateText, streamText } from \"ai\";\nimport type { LanguageModel, ModelMessage } from \"ai\";\nimport { getViberPath } from \"../config\";\nimport { AgentConfig } from \"./config\";\nimport { ConversationHistory, ViberMessage } from \"./message\";\nimport { getModelProvider } from \"./provider\";\nimport { buildToolMap } from \"./tool\";\nimport { generateShortId } from \"../utils/id\";\n\nexport interface AgentContext {\n spaceId: string;\n taskId?: string;\n conversationHistory: ConversationHistory;\n metadata?: Record<string, any>;\n}\n\nexport interface AgentResponse {\n text: string;\n toolCalls?: any[];\n reasoning?: string;\n metadata?: Record<string, any>;\n}\n\n/**\n * Config-driven Agent implementation\n * No subclasses needed - behavior is entirely config-driven\n */\nimport { defaultRegistry } from \"../skills/registry\";\n\n/**\n * Config-driven Agent implementation\n * No subclasses needed - behavior is entirely config-driven\n */\nexport class Agent {\n public id: string;\n public name: string;\n public description: string;\n public config: AgentConfig;\n\n // LLM configuration\n public provider: string;\n public model: string;\n public temperature?: number;\n public maxTokens?: number;\n public topP?: number;\n public frequencyPenalty?: number;\n public presencePenalty?: number;\n public systemPrompt?: string;\n\n // Agent configuration\n public tools: string[];\n public skills: string[];\n public personality?: string;\n\n // Skill state\n private skillInstructions: string = \"\";\n private loadedSkillTools: Record<string, any> = {};\n private skillsLoaded: boolean = false;\n\n constructor(config: AgentConfig) {\n this.config = config;\n this.id = config.id || config.name;\n this.name = config.name;\n this.description = config.description;\n\n // LLM settings\n if (config.llm) {\n this.provider = config.llm.provider;\n this.model = config.llm.model;\n this.temperature = config.llm.settings?.temperature;\n this.maxTokens = config.llm.settings?.maxTokens;\n this.topP = config.llm.settings?.topP;\n this.frequencyPenalty = config.llm.settings?.frequencyPenalty;\n this.presencePenalty = config.llm.settings?.presencePenalty;\n this.systemPrompt = config.systemPrompt;\n } else {\n this.provider = config.provider!;\n this.model = config.model!;\n this.temperature = config.temperature;\n this.maxTokens = config.maxTokens;\n this.topP = config.topP;\n this.frequencyPenalty = config.frequencyPenalty;\n this.presencePenalty = config.presencePenalty;\n this.systemPrompt = config.systemPrompt;\n }\n\n if (this.provider === \"viber\" || this.provider?.startsWith(\"viber-\")) {\n throw new Error(\n `Invalid provider '${this.provider}' for agent '${this.name}'. Viber is not an AI provider.`,\n );\n }\n\n this.tools = config.tools || [];\n this.skills = config.skills || [];\n this.personality = config.personality;\n }\n\n /**\n * Ensure skills are loaded from registry\n */\n private async ensureSkillsLoaded(): Promise<void> {\n if (this.skillsLoaded) return;\n\n if (this.skills && this.skills.length > 0) {\n const instructionParts: string[] = [];\n\n for (const skillId of this.skills) {\n // Load skill metadata and instructions\n const skill = await defaultRegistry.loadSkill(skillId);\n if (skill) {\n instructionParts.push(`\\n### Skill: ${skill.metadata.name}`);\n instructionParts.push(skill.metadata.description);\n if (skill.instructions) {\n instructionParts.push(skill.instructions);\n }\n\n // Load tools\n const tools = await defaultRegistry.getTools(skillId);\n Object.assign(this.loadedSkillTools, tools);\n } else {\n console.warn(`[Agent] Skill '${skillId}' not found`);\n }\n }\n\n this.skillInstructions = instructionParts.join(\"\\n\\n\");\n }\n\n this.skillsLoaded = true;\n }\n\n /**\n * Get the system prompt for this agent\n */\n protected getSystemPrompt(context?: AgentContext): string {\n const segments: string[] = [];\n\n // Base identity\n segments.push(`You are ${this.name}.`);\n segments.push(this.description);\n\n // Personality\n if (this.personality) {\n segments.push(`\\nPersonality: ${this.personality}`);\n }\n\n // Skill Instructions\n if (this.skillInstructions) {\n segments.push(\"\\n=== ENABLED SKILLS ===\");\n segments.push(this.skillInstructions);\n segments.push(\"======================\\n\");\n }\n\n // Tool usage instructions\n if (\n (this.tools && this.tools.length > 0) ||\n Object.keys(this.loadedSkillTools).length > 0\n ) {\n segments.push(\"\\nIMPORTANT - TOOL USAGE:\");\n segments.push(\"You have tools available. To use a tool, you MUST:\");\n segments.push(\"1. Use the tool calling mechanism provided by the system\");\n segments.push(\n \"2. NEVER output tool calls as JSON, code blocks, or plain text\",\n );\n segments.push(\n \"When you need to call a tool, simply invoke it directly without any formatting.\",\n );\n if (Object.keys(this.loadedSkillTools).length > 0) {\n segments.push(\n \"When the user asks to use a skill by name (e.g. cursor-agent, tmux), one of your tools is for that—use each tool's description to decide when to call it.\",\n );\n }\n }\n\n // Custom system prompt\n if (this.systemPrompt) {\n segments.push(`\\n${this.systemPrompt}`);\n }\n\n // Context information\n if (context) {\n segments.push(\"\\nCurrent Context:\");\n segments.push(`- Space ID: ${context.spaceId}`);\n if (context.taskId) segments.push(`- Task ID: ${context.taskId}`);\n\n if (context.metadata) {\n // Add metadata fields\n for (const [key, value] of Object.entries(context.metadata)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n segments.push(`- ${key}: ${value}`);\n }\n }\n }\n }\n\n // Add current date and time context\n const now = new Date();\n segments.push(\"\\nDate/Time Information:\");\n segments.push(`- Same rules as before...`);\n // Truncating mainly to save space, assuming logic remains similar to original but with skills\n\n return segments.join(\"\\n\");\n }\n\n /**\n * Get the model provider for this agent\n */\n public getModel(context?: {\n spaceId?: string;\n userId?: string;\n }): LanguageModel {\n const modelProvider = getModelProvider({\n provider: this.provider as any,\n modelName: this.model,\n spaceId: context?.spaceId,\n userId: context?.userId,\n });\n\n // OpenRouter API expects upstream provider/model only (e.g. \"deepseek/deepseek-chat\"), not \"openrouter/...\"\n const modelForApi =\n this.provider === \"openrouter\" && this.model.startsWith(\"openrouter/\")\n ? this.model.slice(\"openrouter/\".length)\n : this.model;\n\n return (modelProvider as any)(modelForApi) as LanguageModel;\n }\n\n /**\n * Get tools available to this agent\n */\n protected async getTools(context?: { spaceId?: string }): Promise<any> {\n const tools = { ...this.loadedSkillTools };\n\n // Only load config tools if configured\n if (this.tools && this.tools.length > 0) {\n try {\n const customTools = await buildToolMap(this.tools, context);\n Object.assign(tools, customTools);\n } catch (error) {\n console.error(`Failed to load tools for agent ${this.name}:`, error);\n }\n }\n\n return Object.keys(tools).length > 0 ? tools : undefined;\n }\n\n /**\n * Prepare debug info without actually calling streamText\n */\n async prepareDebugInfo(options: {\n messages: ViberMessage[];\n system?: string;\n spaceId?: string;\n metadata?: Record<string, any>;\n }): Promise<{\n systemPrompt: string;\n tools: any;\n model: any;\n agentInfo: any;\n messages: any[];\n }> {\n await this.ensureSkillsLoaded();\n\n const { messages: viberMessages, system, spaceId, metadata } = options;\n\n // Extract metadata from messages for context enrichment\n let enrichedMetadata = metadata || {};\n\n // Find the last user message to extract any document context or other metadata\n const lastUserMsg = viberMessages.filter((m) => m.role === \"user\").pop();\n if (lastUserMsg?.metadata) {\n enrichedMetadata = { ...lastUserMsg.metadata, ...metadata };\n }\n\n // Build context for system prompt generation using ViberMessages\n const context: AgentContext = {\n spaceId: spaceId || \"default\",\n conversationHistory: new ConversationHistory(),\n metadata: enrichedMetadata,\n };\n\n // Use agent-specific prompt and append any extra system context\n const basePrompt = this.getSystemPrompt(context);\n const systemPrompt = system ? `${basePrompt}\\n\\n${system}` : basePrompt;\n const tools = await this.getTools({ spaceId });\n\n // Convert messages for display\n const modelMessages: any[] = viberMessages\n .filter((m) => m.role !== \"tool\")\n .map((m) => ({\n role: m.role,\n content:\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? (m.content as Array<{ type: string; text?: string }>)\n .filter((p) => p.type === \"text\" && p.text)\n .map((p) => p.text as string)\n .join(\"\\n\")\n : \"\",\n }))\n .filter((m) => m.content);\n\n return {\n systemPrompt,\n tools: Object.entries(tools || {}).map(([id, tool]) => ({\n id,\n name: (tool as any).name || id,\n description: (tool as any).description,\n functions: Object.keys((tool as any).functions || {}),\n })),\n model: {\n provider:\n this.config.llm?.provider || this.config.provider || \"unknown\",\n model: this.config.llm?.model || this.config.model || \"unknown\",\n settings: {\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n topP: this.topP,\n frequencyPenalty: this.frequencyPenalty,\n presencePenalty: this.presencePenalty,\n },\n },\n agentInfo: {\n id: this.id,\n name: this.name,\n description: this.description,\n personality: this.personality,\n },\n messages: modelMessages,\n };\n }\n\n /**\n * Stream text - works with ViberMessage[] internally\n * Converts to ModelMessage[] only when calling AI SDK\n */\n async streamText(options: {\n messages: ViberMessage[];\n system?: string;\n spaceId?: string;\n metadata?: Record<string, any>;\n [key: string]: any; // Allow all other AI SDK options to pass through\n }): Promise<any> {\n await this.ensureSkillsLoaded();\n\n // Extract context-specific options\n const {\n messages: viberMessages,\n system,\n spaceId,\n metadata,\n ...aiSdkOptions\n } = options;\n\n // Extract metadata from messages for context enrichment\n let enrichedMetadata = metadata || {};\n\n // Find the last user message to extract any document context or other metadata\n const lastUserMsg = viberMessages.filter((m) => m.role === \"user\").pop();\n if (lastUserMsg?.metadata) {\n enrichedMetadata = { ...lastUserMsg.metadata, ...metadata };\n }\n\n // Build context for system prompt generation using ViberMessages\n const context: AgentContext = {\n spaceId: spaceId || \"default\",\n conversationHistory: new ConversationHistory(),\n metadata: enrichedMetadata,\n };\n\n // Use agent-specific prompt and append any extra system context\n const basePrompt = this.getSystemPrompt(context);\n const systemPrompt = system ? `${basePrompt}\\n\\n${system}` : basePrompt;\n\n const model = this.getModel({ spaceId, userId: enrichedMetadata.userId });\n const tools = await this.getTools({ spaceId });\n\n // Generate a message ID that includes the agent name\n const agentPrefix = this.name.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Convert ViberMessage[] to ModelMessage[] ONLY here, right before AI SDK call\n const modelMessages: ModelMessage[] = viberMessages\n .filter((m) => m.role !== \"tool\") // Skip tool messages\n .map((m) => ({\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? (m.content as Array<{ type: string; text?: string }>)\n .filter((p) => p.type === \"text\" && p.text)\n .map((p) => p.text as string)\n .join(\"\\n\")\n : \"\",\n }))\n .filter((m) => m.content); // Remove empty messages\n\n // Pass through to AI SDK's streamText with agent defaults\n const result = streamText({\n model,\n system: systemPrompt,\n messages: modelMessages,\n tools,\n toolChoice: \"auto\", // Explicitly set tool choice mode\n maxSteps: 5, // Allow up to 5 tool call steps\n temperature: this.temperature,\n maxOutputTokens: this.maxTokens,\n topP: this.topP,\n frequencyPenalty: this.frequencyPenalty,\n presencePenalty: this.presencePenalty,\n maxRetries: 3,\n // Add callback to monitor tool calls\n onStepFinish: ({ text, toolCalls, toolResults, finishReason }) => {\n // ... logging logic ...\n },\n // Override with any provided options\n ...aiSdkOptions,\n // Use experimental_generateMessageId to include agent name in message ID\n // @ts-ignore - experimental feature may not be in types yet\n experimental_generateMessageId: () => {\n return `${agentPrefix}_${generateShortId()}`;\n },\n });\n\n // Attach agent metadata to the result for immediate access\n (result as any).agentMetadata = {\n name: this.name,\n };\n\n return result;\n }\n\n /**\n * Generate text - works with ViberMessage[] internally\n * Converts to ModelMessage[] only when calling AI SDK\n */\n async generateText(options: {\n messages: ViberMessage[];\n system?: string;\n spaceId?: string;\n metadata?: Record<string, any>;\n [key: string]: any;\n }): Promise<any> {\n await this.ensureSkillsLoaded();\n\n const {\n messages: viberMessages,\n system,\n spaceId,\n metadata,\n ...aiSdkOptions\n } = options;\n\n // Extract metadata from messages for context enrichment\n let enrichedMetadata = metadata || {};\n\n // Find the last user message to extract any document context or other metadata\n const lastUserMsg = viberMessages.filter((m) => m.role === \"user\").pop();\n if (lastUserMsg?.metadata) {\n enrichedMetadata = { ...lastUserMsg.metadata, ...metadata };\n }\n\n // Build context for system prompt generation\n const context: AgentContext = {\n spaceId: spaceId || \"default\",\n conversationHistory: new ConversationHistory(),\n metadata: enrichedMetadata,\n };\n\n // Use agent-specific prompt and append any extra system context\n const basePrompt = this.getSystemPrompt(context);\n const systemPrompt = system ? `${basePrompt}\\n\\n${system}` : basePrompt;\n\n const model = this.getModel({ spaceId, userId: enrichedMetadata.userId });\n const tools = await this.getTools({ spaceId });\n\n // Convert ViberMessage[] to ModelMessage[] ONLY here, right before AI SDK call\n const modelMessages: ModelMessage[] = viberMessages\n .filter((m) => m.role !== \"tool\") // Skip tool messages\n .map((m) => ({\n role: m.role as \"system\" | \"user\" | \"assistant\",\n content:\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? (m.content as Array<{ type: string; text?: string }>)\n .filter((p) => p.type === \"text\" && p.text)\n .map((p) => p.text as string)\n .join(\"\\n\")\n : \"\",\n }))\n .filter((m) => m.content);\n\n // Pass through to AI SDK's generateText with proper options\n return generateText({\n model,\n system: systemPrompt,\n messages: modelMessages,\n tools,\n temperature: this.temperature,\n maxRetries: 3,\n ...aiSdkOptions,\n // Add model-specific options if they exist\n ...(this.maxTokens && { maxSteps: 5 }), // generateText uses maxSteps not maxTokens\n ...(this.topP && { topP: this.topP }),\n ...(this.frequencyPenalty && { frequencyPenalty: this.frequencyPenalty }),\n ...(this.presencePenalty && { presencePenalty: this.presencePenalty }),\n });\n }\n\n /**\n * Get agent summary\n */\n getSummary(): Record<string, any> {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n tools: this.tools,\n llmModel: `${this.provider}/${this.model}`,\n };\n }\n}\n","/**\n * Plan - Manages the execution plan for a space\n */\n\nimport { Task, TaskStatus } from \"./task\";\n\nexport interface PlanSummary {\n totalTasks: number;\n completedTasks: number;\n runningTasks: number;\n pendingTasks: number;\n failedTasks: number;\n blockedTasks: number;\n progressPercentage: number;\n}\n\nexport class Plan {\n public tasks: Task[];\n public goal: string;\n public createdAt: Date;\n public updatedAt: Date;\n\n constructor({ tasks = [], goal }: { tasks?: Task[]; goal: string }) {\n this.tasks = tasks;\n this.goal = goal;\n this.createdAt = new Date();\n this.updatedAt = new Date();\n }\n\n addTask(task: Task): void {\n this.tasks.push(task);\n this.updatedAt = new Date();\n }\n\n removeTask(taskId: string): boolean {\n const index = this.tasks.findIndex((t) => t.id === taskId);\n if (index >= 0) {\n this.tasks.splice(index, 1);\n this.updatedAt = new Date();\n return true;\n }\n return false;\n }\n\n getTaskById(taskId: string): Task | undefined {\n return this.tasks.find((t) => t.id === taskId);\n }\n\n updateTaskStatus(taskId: string, status: TaskStatus): boolean {\n const task = this.getTaskById(taskId);\n if (task) {\n task.status = status;\n task.updatedAt = new Date();\n this.updatedAt = new Date();\n return true;\n }\n return false;\n }\n\n getNextActionableTask(): Task | undefined {\n return this.tasks.find((task) =>\n task.isActionable({\n getTaskStatus: (id) => this.getTaskById(id)?.status,\n })\n );\n }\n\n getAllActionableTasks(maxTasks?: number): Task[] {\n const actionableTasks = this.tasks.filter((task) =>\n task.isActionable({\n getTaskStatus: (id) => this.getTaskById(id)?.status,\n })\n );\n return maxTasks ? actionableTasks.slice(0, maxTasks) : actionableTasks;\n }\n\n getTasksByStatus(status: TaskStatus): Task[] {\n return this.tasks.filter((task) => task.status === status);\n }\n\n getTasksByAssignee(assignee: string): Task[] {\n return this.tasks.filter((task) => task.assignedTo === assignee);\n }\n\n isComplete(): boolean {\n return this.tasks.every(\n (task) =>\n task.status === TaskStatus.COMPLETED ||\n task.status === TaskStatus.CANCELLED\n );\n }\n\n hasFailedTasks(): boolean {\n return this.tasks.some((task) => task.status === TaskStatus.FAILED);\n }\n\n hasBlockedTasks(): boolean {\n return this.tasks.some((task) => task.status === TaskStatus.BLOCKED);\n }\n\n getProgressSummary(): PlanSummary {\n const summary: PlanSummary = {\n totalTasks: this.tasks.length,\n completedTasks: 0,\n runningTasks: 0,\n pendingTasks: 0,\n failedTasks: 0,\n blockedTasks: 0,\n progressPercentage: 0,\n };\n\n for (const task of this.tasks) {\n switch (task.status) {\n case TaskStatus.COMPLETED:\n summary.completedTasks++;\n break;\n case TaskStatus.RUNNING:\n summary.runningTasks++;\n break;\n case TaskStatus.PENDING:\n summary.pendingTasks++;\n break;\n case TaskStatus.FAILED:\n summary.failedTasks++;\n break;\n case TaskStatus.BLOCKED:\n summary.blockedTasks++;\n break;\n }\n }\n\n if (summary.totalTasks > 0) {\n summary.progressPercentage =\n (summary.completedTasks / summary.totalTasks) * 100;\n }\n\n return summary;\n }\n\n reorderTasks(fromIndex: number, toIndex: number): void {\n if (\n fromIndex < 0 ||\n fromIndex >= this.tasks.length ||\n toIndex < 0 ||\n toIndex >= this.tasks.length\n ) {\n throw new Error(\"Invalid task indices\");\n }\n\n const [task] = this.tasks.splice(fromIndex, 1);\n this.tasks.splice(toIndex, 0, task);\n this.updatedAt = new Date();\n }\n\n toJSON(): any {\n return {\n tasks: this.tasks.map((task) => task.toJSON()),\n goal: this.goal,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n\n static fromJSON(data: any): Plan {\n const plan = new Plan({\n goal: data.goal,\n tasks: data.tasks.map((taskData: any) => Task.fromJSON(taskData)),\n });\n\n plan.createdAt = new Date(data.createdAt);\n plan.updatedAt = new Date(data.updatedAt);\n\n return plan;\n }\n}\n","/**\n * ViberAgent - The space's conversational representative\n *\n * X is the interface between users and their spaces. Each space has an X agent\n * that acts as its representative. When you need to interact with a space, you\n * talk to X. ViberAgent merges TaskExecutor and Orchestrator functionality into a\n * single, user-friendly interface.\n */\n\nimport { Agent, AgentContext, AgentResponse } from \"./agent\";\nimport { AgentConfig } from \"./config\";\nimport { Space } from \"./space\";\nimport { getServerDataAdapter } from \"../data/factory\";\nimport { Plan } from \"./plan\";\nimport { Task, TaskStatus } from \"./task\";\nimport { generateText, Output } from \"ai\";\nimport { z } from \"zod\";\nimport type { ParallelTask } from \"./collaboration\";\n\nexport interface ViberOptions {\n model?: string; // AI model to use\n storageRoot?: string; // Storage location\n defaultGoal?: string; // Default goal for new spaces\n spaceId?: string; // Explicit space ID\n singleAgentId?: string; // If set, route directly to this agent ID\n}\n\nexport interface ViberStreamOptions {\n messages?: any[]; // Message history\n tools?: any; // Tools available\n artifactId?: string; // Artifact context\n [key: string]: any; // Additional options\n}\n\nexport interface ViberAgentResponse extends AgentResponse {\n plan?: Plan;\n taskResults?: any[];\n artifacts?: any[];\n preservedSteps?: string[];\n regeneratedSteps?: string[];\n planChanges?: Record<string, any>;\n}\n\nexport class ViberAgent extends Agent {\n private space: Space;\n public readonly spaceId: string;\n private abortController?: AbortController;\n private singleAgentId?: string; // If set, bypass planning\n\n constructor(config: AgentConfig, space: Space, options?: ViberOptions) {\n // Enhance the config for ViberAgent\n const xConfig: AgentConfig = {\n ...config,\n name: \"X\",\n description: `I am X, the conversational representative for this space. I manage all aspects of the space and coordinate with other agents to achieve our goals.`,\n };\n\n super(xConfig);\n this.space = space;\n this.spaceId = space.spaceId;\n this.singleAgentId = options?.singleAgentId;\n }\n\n /**\n * Getter for space (needed for external access)\n */\n getSpace(): Space {\n return this.space;\n }\n\n /**\n * Override getSystemPrompt to include plan and artifacts context\n */\n public getSystemPrompt(context?: AgentContext): string {\n const basePrompt = super.getSystemPrompt(context);\n return basePrompt + this.getPlanContext() + this.getArtifactsContext();\n }\n\n /**\n * Generate text - uses new AI SDK-style signature\n */\n async generateText(options: {\n messages: any[];\n system?: string;\n [key: string]: any;\n }): Promise<any> {\n // Add space context to options\n return super.generateText({\n ...options,\n spaceId: this.space.spaceId,\n metadata: {\n spaceName: this.space.name,\n spaceGoal: this.space.goal,\n ...options.metadata,\n },\n });\n }\n\n /**\n * ViberAgent streamText - Orchestration Layer\n * Responsibilities: History management, agent delegation, persistence\n */\n async streamText(options: {\n messages: any[];\n system?: string;\n spaceId?: string;\n metadata?: Record<string, any>;\n [key: string]: any;\n }): Promise<any> {\n const {\n messages,\n system: systemMessage,\n spaceId,\n metadata = {},\n ...restOptions\n } = options;\n\n console.log(\"[ViberAgent] Orchestration layer: starting streamText\");\n\n const mode = metadata?.mode;\n if (!mode || mode !== \"agent\") {\n throw new Error(\"ViberAgent only supports 'agent' mode\");\n }\n\n // PHASE 1: History Management\n await this.updateSpaceHistory(messages, metadata);\n\n // PHASE 2: Agent Delegation\n const streamResult = await this.handleAgentMode(\n messages,\n systemMessage,\n spaceId,\n metadata,\n restOptions,\n );\n\n // PHASE 3: Message Persistence\n if (spaceId) {\n this.handleMessagePersistence(streamResult, messages, spaceId, metadata);\n }\n\n return streamResult;\n }\n\n /**\n * Agent Mode Handler - Direct delegation with performance optimization\n * Supports both single agent and parallel execution\n */\n private async handleAgentMode(\n messages: any[],\n systemMessage: string | undefined,\n spaceId: string | undefined,\n metadata: Record<string, any>,\n restOptions: any,\n ): Promise<any> {\n // Check if parallel execution is requested\n const parallelAgents = metadata.parallelAgents as string[] | undefined;\n if (parallelAgents && parallelAgents.length > 1) {\n return this.handleParallelExecution(\n parallelAgents,\n messages,\n systemMessage,\n spaceId,\n metadata,\n restOptions,\n );\n }\n\n // Single agent execution (existing logic)\n const targetAgent = metadata.requestedAgent;\n if (!targetAgent) {\n throw new Error(\"Agent mode requires requestedAgent in metadata\");\n }\n\n console.log(\n `[ViberAgent] Agent mode: direct delegation to '${targetAgent}'`,\n );\n\n // Get or load target agent\n let agent = this.space.getAgent(targetAgent);\n if (!agent) {\n // Load agent on demand\n console.log(`[ViberAgent] Loading agent '${targetAgent}' on demand`);\n const dataAdapter = getServerDataAdapter();\n const agentConfig = await dataAdapter.getAgent(targetAgent);\n if (!agentConfig) {\n throw new Error(`Agent '${targetAgent}' not found`);\n }\n agent = new Agent(agentConfig as AgentConfig);\n this.space.registerAgent(targetAgent, agent);\n }\n\n // Use full conversation history so the LLM has context (e.g. user \"1\" after assistant's numbered list)\n const taskId = metadata?.taskId || metadata?.conversationId || \"default\";\n const task = this.space.getOrCreateTask(taskId);\n const fullHistory = task.history.getMessages();\n const messagesForAgent =\n fullHistory.length > 0\n ? this.optimizeContextForAgent(fullHistory)\n : this.optimizeContextForAgent(messages);\n console.log(\n `[ViberAgent] Agent mode: using ${messagesForAgent.length} messages from history`,\n );\n\n // Direct delegation - no orchestration overhead\n return await agent.streamText({\n messages: messagesForAgent,\n system: systemMessage,\n spaceId,\n metadata: {\n ...metadata,\n delegationType: \"direct\",\n userId: this.space.userId, // Pass space owner ID for tracking\n },\n ...restOptions,\n });\n }\n\n /**\n * Handle parallel execution of multiple agents\n */\n private async handleParallelExecution(\n agentIds: string[],\n messages: any[],\n systemMessage: string | undefined,\n spaceId: string | undefined,\n metadata: Record<string, any>,\n restOptions: any,\n ): Promise<any> {\n console.log(`[ViberAgent] Parallel execution: ${agentIds.length} agents`);\n\n // Ensure all agents are loaded\n const dataAdapter = getServerDataAdapter();\n for (const agentId of agentIds) {\n if (!this.space.getAgent(agentId)) {\n const agentConfig = await dataAdapter.getAgent(agentId);\n if (!agentConfig) {\n throw new Error(`Agent '${agentId}' not found`);\n }\n const agent = new Agent(agentConfig as AgentConfig);\n this.space.registerAgent(agentId, agent);\n }\n }\n\n // Use parallel execution engine\n if (!this.space.parallelEngine) {\n throw new Error(\"Parallel execution engine not initialized\");\n }\n\n // ParallelTask type is imported at top of file\n const tasks = agentIds.map((agentId, index) => ({\n id: `parallel-${agentId}-${Date.now()}-${index}`,\n agentId,\n messages: this.optimizeContextForAgent(messages),\n system: systemMessage,\n metadata: {\n ...metadata,\n delegationType: \"parallel\",\n userId: this.space.userId,\n parallelIndex: index,\n },\n priority: agentIds.length - index, // First agent gets highest priority\n }));\n\n const results = await this.space.parallelEngine.executeParallel(tasks);\n\n // Aggregate results\n return {\n text: results.map((r) => `[${r.agentId}]: ${r.result.text}`).join(\"\\n\\n\"),\n toolCalls: results.flatMap((r) => r.result.toolCalls || []),\n metadata: {\n ...metadata,\n parallelResults: results,\n agentCount: agentIds.length,\n },\n };\n }\n\n /**\n * Update space history with new messages\n * Now supports per-task history\n */\n private async updateSpaceHistory(\n messages: any[],\n metadata?: Record<string, any>,\n ): Promise<void> {\n // Get taskId from metadata, or use \"default\" for legacy support\n const taskId = metadata?.taskId || metadata?.conversationId || \"default\";\n const task = this.space.getOrCreateTask(taskId);\n\n const existingMessages = task.history.getMessages();\n // When client sends only the new message(s), messages.length <= existingMessages.length:\n // append incoming messages. When client sends full thread, take only the new tail.\n const newMessages =\n messages.length > existingMessages.length\n ? messages.slice(existingMessages.length)\n : messages;\n\n if (newMessages.length > 0) {\n for (const msg of newMessages) {\n const formattedMsg = {\n ...msg,\n content:\n typeof msg.content === \"string\"\n ? msg.content\n : Array.isArray(msg.content)\n ? msg.content\n : [{ type: \"text\", text: msg.content }],\n };\n task.history.add(formattedMsg);\n }\n console.log(\n `[ViberAgent] Updated task ${taskId} history with ${newMessages.length} new messages`,\n );\n }\n }\n\n /**\n * Optimize message context for single-agent performance\n */\n private optimizeContextForAgent(messages: any[]): any[] {\n // For agent mode, use recent messages only to minimize token usage\n return messages.slice(-4); // Last 4 messages (2 exchanges)\n }\n\n /**\n * Extract user prompt from messages for orchestration\n */\n private extractPromptFromMessages(messages: any[]): string {\n const lastMessage = messages[messages.length - 1];\n if (lastMessage?.role === \"user\") {\n const content = lastMessage.content;\n if (typeof content === \"string\") {\n return content;\n } else if (Array.isArray(content)) {\n return content\n .filter((part) => part.type === \"text\" && part.text)\n .map((part) => part.text)\n .join(\" \");\n }\n }\n return \"\";\n }\n\n /**\n * Handle message persistence after streaming completes\n */\n private handleMessagePersistence(\n streamResult: any,\n messages: any[],\n spaceId: string,\n metadata: any,\n ) {\n (async () => {\n try {\n let finalText = \"\";\n const toolInvocations: any[] = [];\n\n for await (const part of streamResult.fullStream) {\n switch (part.type) {\n case \"text-delta\":\n if (part.text) {\n finalText += part.text;\n }\n break;\n case \"tool-call\":\n toolInvocations.push({\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n args: part.args,\n });\n break;\n case \"tool-result\":\n const toolCall = toolInvocations.find(\n (t) => t.toolCallId === part.toolCallId,\n );\n if (toolCall) {\n toolCall.result = part.result;\n }\n break;\n case \"finish\":\n break;\n case \"error\":\n console.error(\"[ViberAgent] Stream error:\", part.error);\n return;\n }\n }\n\n // Build assistant message in AI SDK v5 format\n const assistantMessage = {\n role: \"assistant\" as const,\n content: [{ type: \"text\" as const, text: finalText }],\n id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n metadata: {\n agentName: this.singleAgentId || \"team\",\n spaceId,\n timestamp: Date.now(),\n ...metadata,\n },\n ...(toolInvocations.length > 0 && { toolInvocations }),\n };\n\n // Add assistant message to task history so next turn in same run has full context\n const taskId =\n metadata?.taskId || metadata?.conversationId || \"default\";\n const task = this.space.getOrCreateTask(taskId);\n task.history.add(assistantMessage);\n // Chat history is persisted at Viber Board level, not by the viber agent\n } catch (error) {\n console.error(\"[ViberAgent] Failed to persist messages:\", error);\n }\n })();\n }\n\n /**\n * Save space to storage\n */\n private async saveSpace(): Promise<void> {\n try {\n // NOTE: In database mode, space data is persisted through the data adapter (spaces table)\n // Storage is ONLY used for artifacts, not config files\n // This legacy file-based persistence is disabled to avoid conflicts\n\n // Legacy code disabled - space data now in database:\n // const { SpaceStorageFactory } = await import(\"../storage/space\");\n // const storage = await SpaceStorageFactory.create(this.spaceId);\n // await storage.saveFile(\"space.json\", { ... });\n\n // Space persistence is now handled by the API layer using SupabaseDatabaseAdapter\n // which writes to the spaces table, not storage buckets\n\n console.log(\"[ViberAgent] Space persistence handled by database adapter\");\n } catch (error) {\n console.error(\"[ViberAgent] Error saving space:\", error);\n // Don't throw - saving is best effort\n }\n }\n\n /**\n * Stop current operation\n */\n stop() {\n this.space.messageQueue.clear();\n if (this.abortController) {\n this.abortController.abort();\n }\n }\n\n /**\n * Add message to queue (soft interrupt)\n */\n addMessage(message: string, metadata?: any) {\n return this.space.messageQueue.add(message, metadata);\n }\n\n /**\n * Enrich context with space information\n */\n private enrichContext(context?: Partial<AgentContext>): AgentContext {\n return {\n spaceId: this.space.spaceId,\n conversationHistory: this.space.history,\n metadata: {\n spaceName: this.space.name,\n spaceGoal: this.space.goal,\n ...context?.metadata,\n },\n ...context,\n };\n }\n\n /**\n * Create or update the space plan\n */\n async createPlan(goal?: string): Promise<Plan> {\n const planGoal = goal || this.space.goal;\n\n // Generate plan using LLM\n const planSchema = z.object({\n tasks: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n assignedTo: z.string().optional(),\n priority: z.enum([\"low\", \"medium\", \"high\"]).default(\"medium\"),\n estimatedTime: z.string().optional(),\n dependencies: z\n .array(\n z.object({\n taskId: z.string(),\n type: z.enum([\"required\", \"optional\"]),\n }),\n )\n .default([]),\n tags: z.array(z.string()).default([]),\n }),\n ),\n });\n\n const result = await generateText({\n model: this.getModel(),\n system:\n this.getSystemPrompt() +\n \"\\n\\nCreate a detailed plan to achieve the goal.\",\n prompt: `Goal: ${planGoal}\\n\\nAvailable agents: ${Array.from(\n this.space.agents.keys(),\n ).join(\", \")}`,\n output: Output.object({ schema: planSchema }),\n });\n\n // Create Plan with Tasks - cast result.output to inferred schema type\n const planData = result.output as z.infer<typeof planSchema>;\n const tasks = planData.tasks.map(\n (taskData: z.infer<typeof planSchema>[\"tasks\"][number]) =>\n new Task({\n ...taskData,\n status: TaskStatus.PENDING,\n }),\n );\n\n const plan = new Plan({\n goal: planGoal,\n tasks,\n });\n\n await this.space.createPlan(plan);\n return plan;\n }\n\n /**\n * Adapt the plan based on new information or user feedback\n */\n async adaptPlan(feedback: string): Promise<Plan> {\n if (!this.space.plan) {\n // No existing plan, create a new one with the feedback\n return this.createPlan(feedback);\n }\n\n const currentPlan = this.space.plan;\n const progress = currentPlan.getProgressSummary();\n\n // Schema for plan adaptation\n const adaptSchema = z.object({\n preserveTasks: z\n .array(z.string())\n .describe(\"IDs of tasks to keep unchanged\"),\n modifyTasks: z\n .array(\n z.object({\n id: z.string(),\n changes: z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n assignedTo: z.string().optional(),\n }),\n }),\n )\n .describe(\"Tasks to modify\"),\n removeTasks: z.array(z.string()).describe(\"IDs of tasks to remove\"),\n addTasks: z\n .array(\n z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n assignedTo: z.string().optional(),\n priority: z.enum([\"low\", \"medium\", \"high\"]).default(\"medium\"),\n dependencies: z\n .array(\n z.object({\n taskId: z.string(),\n type: z.enum([\"required\", \"optional\"]),\n }),\n )\n .default([]),\n tags: z.array(z.string()).default([]),\n }),\n )\n .describe(\"New tasks to add\"),\n reasoning: z.string().describe(\"Explanation of the plan changes\"),\n });\n\n const prompt = `\nCurrent Plan Progress:\n- Total tasks: ${progress.totalTasks}\n- Completed: ${progress.completedTasks}\n- In Progress: ${progress.runningTasks}\n- Pending: ${progress.pendingTasks}\n\nCurrent Tasks:\n${currentPlan.tasks\n .map((t) => `- [${t.id}] ${t.title} (${t.status})`)\n .join(\"\\n\")}\n\nUser Feedback: ${feedback}\n\nAnalyze the current plan and adapt it based on the user's feedback.\nKeep completed tasks unless explicitly asked to redo them.\nPreserve tasks that are still relevant.\nModify, remove, or add tasks as needed to better achieve the goal.\n`;\n\n const result = await generateText({\n model: this.getModel(),\n system:\n this.getSystemPrompt() +\n \"\\n\\nAdapt the existing plan based on user feedback.\",\n prompt,\n output: Output.object({ schema: adaptSchema }),\n });\n\n // Apply adaptations - cast result.output to inferred schema type\n const adaptData = result.output as z.infer<typeof adaptSchema>;\n const adaptedTasks: Task[] = [];\n\n // Keep preserved tasks\n for (const taskId of adaptData.preserveTasks) {\n const task = currentPlan.tasks.find((t) => t.id === taskId);\n if (task) {\n adaptedTasks.push(task);\n }\n }\n\n // Modify tasks\n for (const modification of adaptData.modifyTasks) {\n const task = currentPlan.tasks.find((t) => t.id === modification.id);\n if (task) {\n // Apply changes\n if (modification.changes.title) task.title = modification.changes.title;\n if (modification.changes.description)\n task.description = modification.changes.description;\n if (modification.changes.priority)\n task.priority = modification.changes.priority;\n if (modification.changes.assignedTo)\n task.assignedTo = modification.changes.assignedTo;\n adaptedTasks.push(task);\n }\n }\n\n // Add new tasks\n for (const newTaskData of adaptData.addTasks) {\n const newTask = new Task({\n ...newTaskData,\n status: TaskStatus.PENDING,\n });\n adaptedTasks.push(newTask);\n }\n\n // Create adapted plan\n const adaptedPlan = new Plan({\n goal: currentPlan.goal,\n tasks: adaptedTasks,\n });\n\n // Update space with adapted plan\n await this.space.createPlan(adaptedPlan);\n\n // Log the reasoning\n console.log(\"[Plan Adaptation]\", adaptData.reasoning);\n\n return adaptedPlan;\n }\n\n /**\n * Get plan context for system prompt\n */\n private getPlanContext(): string {\n if (!this.space.plan) {\n return \"\\n\\nNo active plan for this space yet.\";\n }\n\n const summary = this.space.plan.getProgressSummary();\n return `\n\nCurrent Plan Status:\n- Total tasks: ${summary.totalTasks}\n- Completed: ${summary.completedTasks}\n- Running: ${summary.runningTasks}\n- Pending: ${summary.pendingTasks}\n- Failed: ${summary.failedTasks}\n- Progress: ${summary.progressPercentage.toFixed(1)}%\n`;\n }\n\n /**\n * Get artifacts context for system prompt\n */\n private getArtifactsContext(): string {\n if (!this.space.artifacts || this.space.artifacts.length === 0) {\n return \"\";\n }\n\n const artifactsList = this.space.artifacts\n .map((a) => `- ${a.title || a.path} (${a.artifactType || \"document\"})`)\n .join(\"\\n\");\n\n return `\n\nAvailable Artifacts:\n${artifactsList}\n\nThese artifacts are pre-loaded in the space and can be referenced in your responses.\n`;\n }\n\n /**\n * Get ViberAgent summary\n */\n getSummary(): Record<string, any> {\n const base = super.getSummary();\n return {\n ...base,\n spaceId: this.space.spaceId,\n spaceName: this.space.name,\n spaceGoal: this.space.goal,\n planStatus: this.space.plan?.getProgressSummary(),\n };\n }\n\n /**\n * Static factory to start a new space\n */\n static async start(\n goal: string,\n options: ViberOptions = {},\n ): Promise<ViberAgent> {\n const { spaceId, model, singleAgentId } = options;\n\n // Use provided spaceId or generate one\n const id =\n spaceId ||\n `proj_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n // Start space (this creates ViberAgent internally)\n const { startSpace } = await import(\"./space\");\n const space = await startSpace({\n spaceId: id,\n goal,\n name: goal.slice(0, 50),\n model,\n });\n\n if (!space.viberAgent) {\n throw new Error(\"Failed to initialize ViberAgent\");\n }\n\n // Set singleAgentId if provided\n if (singleAgentId) {\n (space.viberAgent as any).singleAgentId = singleAgentId;\n }\n\n return space.viberAgent;\n }\n\n /**\n * Static factory to resume an existing space\n */\n static async resume(\n spaceId: string,\n options: ViberOptions = {},\n ): Promise<ViberAgent> {\n const { model } = options;\n\n // Load existing space\n const { SpaceStorageFactory } = await import(\"../storage/space\");\n const { startSpace } = await import(\"./space\");\n\n // Check if space exists\n const exists = await SpaceStorageFactory.exists(spaceId);\n if (!exists) {\n throw new Error(`Space ${spaceId} not found`);\n }\n\n // Load space data\n const storage = await SpaceStorageFactory.create(spaceId);\n const spaceData = await storage.readJSON<any>(\"space.json\");\n\n if (!spaceData) {\n throw new Error(`Failed to load space ${spaceId}`);\n }\n\n // Recreate space with saved state\n const space = await startSpace({\n spaceId,\n goal: spaceData.goal,\n name: spaceData.name,\n model: model || spaceData.model,\n });\n\n if (!space.viberAgent) {\n throw new Error(\"Failed to initialize ViberAgent\");\n }\n\n // Set singleAgentId if provided\n const agentId = options.singleAgentId || spaceData.singleAgentId;\n if (agentId) {\n (space.viberAgent as any).singleAgentId = agentId;\n }\n\n // Restore conversation messages if exists (e.g. CLI resume from local storage)\n const messages = await storage.readJSON<any[]>(\"messages.json\");\n if (messages && Array.isArray(messages)) {\n space.history.clear();\n for (const msg of messages) {\n const normalizedMsg = { ...msg };\n if (typeof msg.content === \"string\") {\n normalizedMsg.content = [{ type: \"text\", text: msg.content }];\n }\n space.history.add(normalizedMsg);\n }\n }\n\n return space.viberAgent;\n }\n}\n","/**\n * Collaboration Module - Multi-Agent Collaboration Engine\n *\n * Provides:\n * - Parallel agent execution\n * - Agent-to-agent communication\n * - Shared context management\n * - Collaborative planning\n */\n\nimport { Agent } from \"./agent\";\nimport { Space } from \"./space\";\nimport type { AgentResponse } from \"./agent\";\n\nexport interface AgentMessage {\n from: string; // Agent ID\n to: string; // Agent ID or 'broadcast'\n content: string;\n metadata?: Record<string, any>;\n timestamp: Date;\n}\n\nexport interface SharedContext {\n spaceId: string;\n data: Record<string, any>;\n updatedAt: Date;\n updatedBy: string; // Agent ID\n}\n\nexport interface ParallelTask {\n id: string;\n agentId: string;\n messages: any[];\n system?: string;\n metadata?: Record<string, any>;\n priority?: number; // Higher = more important\n}\n\nexport interface ParallelExecutionResult {\n taskId: string;\n agentId: string;\n result: AgentResponse;\n error?: Error;\n duration: number;\n}\n\n/**\n * Agent Collaboration Manager\n * Handles agent-to-agent communication and shared context\n */\nexport class AgentCollaborationManager {\n private space: Space;\n private messageQueue: Map<string, AgentMessage[]>; // Agent ID -> messages\n private sharedContext: SharedContext;\n private listeners: Map<string, Set<(message: AgentMessage) => void>>;\n\n constructor(space: Space) {\n this.space = space;\n this.messageQueue = new Map();\n this.sharedContext = {\n spaceId: space.spaceId,\n data: {},\n updatedAt: new Date(),\n updatedBy: \"system\",\n };\n this.listeners = new Map();\n }\n\n /**\n * Send a message from one agent to another\n */\n sendMessage(\n from: string,\n to: string,\n content: string,\n metadata?: Record<string, any>\n ): void {\n const message: AgentMessage = {\n from,\n to,\n content,\n metadata,\n timestamp: new Date(),\n };\n\n if (to === \"broadcast\") {\n // Broadcast to all agents\n for (const agentId of this.space.agents.keys()) {\n if (agentId !== from) {\n this.queueMessage(agentId, message);\n }\n }\n } else {\n // Send to specific agent\n this.queueMessage(to, message);\n }\n\n // Notify listeners\n this.notifyListeners(to, message);\n if (to !== \"broadcast\") {\n this.notifyListeners(\"broadcast\", message);\n }\n }\n\n /**\n * Queue a message for an agent\n */\n private queueMessage(agentId: string, message: AgentMessage): void {\n if (!this.messageQueue.has(agentId)) {\n this.messageQueue.set(agentId, []);\n }\n this.messageQueue.get(agentId)!.push(message);\n }\n\n /**\n * Get pending messages for an agent\n */\n getMessages(agentId: string): AgentMessage[] {\n const messages = this.messageQueue.get(agentId) || [];\n this.messageQueue.set(agentId, []); // Clear after reading\n return messages;\n }\n\n /**\n * Subscribe to messages for an agent\n */\n subscribe(\n agentId: string,\n callback: (message: AgentMessage) => void\n ): () => void {\n if (!this.listeners.has(agentId)) {\n this.listeners.set(agentId, new Set());\n }\n this.listeners.get(agentId)!.add(callback);\n\n return () => {\n const callbacks = this.listeners.get(agentId);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.listeners.delete(agentId);\n }\n }\n };\n }\n\n /**\n * Notify listeners of a new message\n */\n private notifyListeners(agentId: string, message: AgentMessage): void {\n const callbacks = this.listeners.get(agentId);\n if (callbacks) {\n callbacks.forEach((cb) => {\n try {\n cb(message);\n } catch (error) {\n console.error(`[AgentCollaborationManager] Listener error:`, error);\n }\n });\n }\n }\n\n /**\n * Update shared context\n */\n updateContext(agentId: string, updates: Record<string, any>): void {\n this.sharedContext.data = {\n ...this.sharedContext.data,\n ...updates,\n };\n this.sharedContext.updatedAt = new Date();\n this.sharedContext.updatedBy = agentId;\n }\n\n /**\n * Get shared context\n */\n getContext(): SharedContext {\n return { ...this.sharedContext };\n }\n\n /**\n * Get a specific value from shared context\n */\n getContextValue(key: string): any {\n return this.sharedContext.data[key];\n }\n}\n\n/**\n * Parallel Execution Engine\n * Executes multiple agent tasks in parallel\n */\nexport class ParallelExecutionEngine {\n private space: Space;\n private maxConcurrency: number;\n private activeTasks: Map<string, Promise<ParallelExecutionResult>>;\n\n constructor(space: Space, maxConcurrency: number = 3) {\n this.space = space;\n this.maxConcurrency = maxConcurrency;\n this.activeTasks = new Map();\n }\n\n /**\n * Execute multiple tasks in parallel\n */\n async executeParallel(\n tasks: ParallelTask[]\n ): Promise<ParallelExecutionResult[]> {\n // Sort by priority (higher first)\n const sortedTasks = [...tasks].sort(\n (a, b) => (b.priority || 0) - (a.priority || 0)\n );\n\n // Execute in batches\n const results: ParallelExecutionResult[] = [];\n const executing: Promise<ParallelExecutionResult>[] = [];\n\n for (const task of sortedTasks) {\n // Wait if we've reached max concurrency\n if (executing.length >= this.maxConcurrency) {\n const completed = await Promise.race(executing);\n const index = executing.findIndex(\n (p) => p === Promise.resolve(completed)\n );\n if (index >= 0) {\n executing.splice(index, 1);\n }\n results.push(completed);\n }\n\n // Start execution\n const promise = this.executeTask(task);\n executing.push(promise);\n this.activeTasks.set(task.id, promise);\n }\n\n // Wait for remaining tasks\n const remaining = await Promise.allSettled(executing);\n for (const result of remaining) {\n if (result.status === \"fulfilled\") {\n results.push(result.value);\n } else {\n // Handle rejected promises\n console.error(\"[ParallelExecutionEngine] Task failed:\", result.reason);\n }\n }\n\n this.activeTasks.clear();\n return results;\n }\n\n /**\n * Execute a single task\n */\n private async executeTask(\n task: ParallelTask\n ): Promise<ParallelExecutionResult> {\n const startTime = Date.now();\n\n try {\n const agent = this.space.getAgent(task.agentId);\n if (!agent) {\n throw new Error(`Agent ${task.agentId} not found`);\n }\n\n // Execute agent\n const result = await agent.generateText({\n messages: task.messages,\n system: task.system,\n spaceId: this.space.spaceId,\n metadata: {\n ...task.metadata,\n parallelTaskId: task.id,\n },\n });\n\n const duration = Date.now() - startTime;\n\n return {\n taskId: task.id,\n agentId: task.agentId,\n result: {\n text: result.text || \"\",\n toolCalls: result.toolCalls,\n reasoning: result.reasoning,\n metadata: result.metadata,\n },\n duration,\n };\n } catch (error) {\n const duration = Date.now() - startTime;\n return {\n taskId: task.id,\n agentId: task.agentId,\n result: {\n text: \"\",\n metadata: { error: String(error) },\n },\n error: error instanceof Error ? error : new Error(String(error)),\n duration,\n };\n }\n }\n\n /**\n * Cancel a running task\n */\n cancelTask(taskId: string): void {\n const task = this.activeTasks.get(taskId);\n if (task) {\n // Note: We can't actually cancel a running promise, but we can mark it\n // The actual cancellation would need to be handled at the agent level\n this.activeTasks.delete(taskId);\n }\n }\n\n /**\n * Get active task count\n */\n getActiveTaskCount(): number {\n return this.activeTasks.size;\n }\n}\n\n/**\n * Collaborative Planner\n * Helps agents plan together\n */\nexport class CollaborativePlanner {\n private space: Space;\n private collaborationManager: AgentCollaborationManager;\n\n constructor(space: Space, collaborationManager: AgentCollaborationManager) {\n this.space = space;\n this.collaborationManager = collaborationManager;\n }\n\n /**\n * Create a collaborative plan with multiple agents\n */\n async createCollaborativePlan(\n goal: string,\n agentIds: string[]\n ): Promise<{ plan: any; agentAssignments: Map<string, string[]> }> {\n // Get shared context\n const context = this.collaborationManager.getContext();\n\n // Create planning tasks for each agent\n const planningTasks: ParallelTask[] = agentIds.map((agentId, index) => ({\n id: `plan-${agentId}-${Date.now()}`,\n agentId,\n messages: [\n {\n role: \"user\",\n content:\n `We need to create a collaborative plan for: ${goal}\\n\\n` +\n `Shared context: ${JSON.stringify(context.data, null, 2)}\\n\\n` +\n `You are one of ${agentIds.length} agents working together. ` +\n `Propose your part of the plan and identify dependencies on other agents.`,\n },\n ],\n priority: agentIds.length - index, // First agent gets highest priority\n metadata: {\n planningSession: true,\n goal,\n otherAgents: agentIds.filter((id) => id !== agentId),\n },\n }));\n\n // Execute planning in parallel\n const executionEngine = new ParallelExecutionEngine(this.space);\n const results = await executionEngine.executeParallel(planningTasks);\n\n // Aggregate plans\n const agentPlans = new Map<string, any>();\n for (const result of results) {\n if (!result.error) {\n agentPlans.set(result.agentId, result.result);\n }\n }\n\n // Create unified plan\n const plan = this.mergePlans(agentPlans, goal);\n const agentAssignments = this.assignTasks(plan, agentIds);\n\n return { plan, agentAssignments };\n }\n\n /**\n * Merge multiple agent plans into one\n */\n private mergePlans(agentPlans: Map<string, any>, goal: string): any {\n // Simple merge strategy - in a real implementation, this would be more sophisticated\n const tasks: any[] = [];\n let taskId = 1;\n\n for (const [agentId, plan] of agentPlans.entries()) {\n if (plan.text) {\n // Extract tasks from plan text (simplified)\n const lines = plan.text\n .split(\"\\n\")\n .filter(\n (line: string) =>\n line.trim().startsWith(\"-\") || line.trim().match(/^\\d+\\./)\n );\n\n for (const line of lines) {\n tasks.push({\n id: `task-${taskId++}`,\n description: line.replace(/^[-•\\d.]+\\s*/, \"\").trim(),\n assignedAgent: agentId,\n status: \"pending\",\n });\n }\n }\n }\n\n return {\n goal,\n tasks,\n createdAt: new Date().toISOString(),\n };\n }\n\n /**\n * Assign tasks to agents\n */\n private assignTasks(plan: any, agentIds: string[]): Map<string, string[]> {\n const assignments = new Map<string, string[]>();\n\n for (const agentId of agentIds) {\n assignments.set(agentId, []);\n }\n\n for (const task of plan.tasks) {\n const agentId = task.assignedAgent || agentIds[0];\n const tasks = assignments.get(agentId) || [];\n tasks.push(task.id);\n assignments.set(agentId, tasks);\n }\n\n return assignments;\n }\n}\n","/**\n * Space - The top-level container for Viber work (formerly Space)\n *\n * A Space represents a project context that contains multiple tasks.\n * Each space is managed by an XAgent that serves as its orchestrator.\n *\n * Key concepts:\n * - Space: Project container with shared configuration\n * - Task: Individual conversation threads within a space\n * - Each task has its own conversation history and artifacts\n */\n\nimport { Plan } from \"./plan\";\nimport { Task, TaskStatus } from \"./task\";\nimport { ViberAgent, ViberOptions } from \"./viber-agent\";\nimport { SpaceStorage, SpaceStorageFactory } from \"../storage/space\";\nimport { SpaceConfig, AgentConfig } from \"./config\";\nimport { Agent } from \"./agent\";\nimport { MessageQueue, ConversationHistory } from \"./message\";\nimport type { SpaceModel, SpaceState } from \"../types\";\nimport {\n AgentCollaborationManager,\n ParallelExecutionEngine,\n CollaborativePlanner,\n} from \"./collaboration\";\n\n// Re-export for convenience\nexport type { SpaceModel, SpaceState };\n\n// Task within a space\nexport interface SpaceTask {\n id: string;\n spaceId: string;\n title: string;\n history: ConversationHistory;\n artifactIds: string[];\n status: \"active\" | \"completed\" | \"archived\";\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport class Space {\n public spaceId: string;\n public userId?: string; // User ID of space owner\n public config: SpaceConfig;\n public history: ConversationHistory; // Legacy: primary task history\n public tasks: Map<string, SpaceTask>; // NEW: Multiple tasks\n public messageQueue: MessageQueue;\n public agents: Map<string, Agent>;\n public storage: SpaceStorage;\n public goal: string;\n public name: string;\n public viberAgent?: ViberAgent;\n public createdAt: Date;\n public updatedAt: Date;\n public plan?: Plan;\n public artifacts?: any[];\n public collaborationManager?: AgentCollaborationManager;\n public parallelEngine?: ParallelExecutionEngine;\n public collaborativePlanner?: CollaborativePlanner;\n\n constructor({\n spaceId,\n userId,\n config,\n history,\n messageQueue,\n agents,\n storage,\n goal,\n name,\n viberAgent,\n }: {\n spaceId: string;\n userId?: string;\n config: SpaceConfig;\n history: ConversationHistory;\n messageQueue: MessageQueue;\n agents: Map<string, Agent>;\n storage: SpaceStorage;\n goal: string;\n name?: string;\n viberAgent?: ViberAgent;\n }) {\n this.spaceId = spaceId;\n this.userId = userId;\n this.config = config;\n this.history = history; // Legacy: default task history\n this.tasks = new Map(); // NEW: Task storage\n this.messageQueue = messageQueue;\n this.agents = agents;\n this.storage = storage;\n this.goal = goal;\n this.name = name || `Space ${spaceId}`;\n this.viberAgent = viberAgent;\n this.createdAt = new Date();\n this.updatedAt = new Date();\n\n // Initialize collaboration components\n this.collaborationManager = new AgentCollaborationManager(this);\n this.parallelEngine = new ParallelExecutionEngine(this);\n this.collaborativePlanner = new CollaborativePlanner(\n this,\n this.collaborationManager,\n );\n }\n\n /**\n * Get or create a task within this space\n */\n getOrCreateTask(taskId: string, title?: string): SpaceTask {\n if (!this.tasks.has(taskId)) {\n const task: SpaceTask = {\n id: taskId,\n spaceId: this.spaceId,\n title: title || `Task ${taskId}`,\n history: new ConversationHistory(),\n artifactIds: [],\n status: \"active\",\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n this.tasks.set(taskId, task);\n console.log(`[Space] Created task ${taskId} in space ${this.spaceId}`);\n }\n return this.tasks.get(taskId)!;\n }\n\n /**\n * Get task by ID\n */\n getTask(taskId: string): SpaceTask | undefined {\n return this.tasks.get(taskId);\n }\n\n /**\n * Get all tasks in this space\n */\n getAllTasks(): SpaceTask[] {\n return Array.from(this.tasks.values());\n }\n\n /**\n * Update space task status (for conversation tasks, not Plan tasks)\n */\n updateSpaceTaskStatus(\n taskId: string,\n status: \"active\" | \"completed\" | \"archived\",\n ): boolean {\n const task = this.tasks.get(taskId);\n if (task) {\n task.status = status;\n task.updatedAt = new Date();\n return true;\n }\n return false;\n }\n\n getAgent(name: string): Agent | undefined {\n return this.agents.get(name);\n }\n\n registerAgent(name: string, agent: Agent): void {\n this.agents.set(name, agent);\n console.log(`[Space] Registered agent: ${name} - ${agent.description}`);\n }\n\n complete(): void {\n console.log(`Space ${this.spaceId} completed`);\n }\n\n getContext(): Record<string, any> {\n const context: Record<string, any> = {\n spaceId: this.spaceId,\n goal: this.goal,\n storagePath: this.storage.getSpacePath(),\n agents: Array.from(this.agents.keys()),\n historyLength: this.history.messages.length,\n createdAt: this.createdAt.toISOString(),\n };\n\n if (this.plan) {\n context.plan = {\n goal: this.goal,\n totalTasks: this.plan.tasks.length,\n progress: this.plan.getProgressSummary(),\n };\n }\n\n return context;\n }\n\n async createPlan(plan: Plan): Promise<void> {\n this.plan = plan;\n await this.persistState();\n console.log(\n `Created plan for space ${this.spaceId} with ${plan.tasks.length} tasks`,\n );\n }\n\n async updatePlan(plan: Plan): Promise<void> {\n this.plan = plan;\n this.updatedAt = new Date();\n await this.persistState();\n console.log(`Updated plan for space ${this.spaceId}`);\n }\n\n async setName(name: string): Promise<void> {\n this.name = name;\n this.updatedAt = new Date();\n await this.persistState();\n console.log(`Updated space ${this.spaceId} name to: ${name}`);\n }\n\n async getNextTask(): Promise<Task | undefined> {\n if (!this.plan) {\n return undefined;\n }\n return this.plan.getNextActionableTask();\n }\n\n async getParallelTasks(maxTasks: number = 3): Promise<Task[]> {\n if (!this.plan) {\n return [];\n }\n return this.plan.getAllActionableTasks(maxTasks);\n }\n\n async updateTaskStatus(taskId: string, status: TaskStatus): Promise<boolean> {\n if (!this.plan) {\n return false;\n }\n\n const success = this.plan.updateTaskStatus(taskId, status);\n if (success) {\n this.updatedAt = new Date();\n await this.persistState();\n console.log(`Updated task ${taskId} status to ${status}`);\n }\n\n return success;\n }\n\n async assignTask(taskId: string, agentName: string): Promise<boolean> {\n if (!this.plan) {\n return false;\n }\n\n const task = this.plan.getTaskById(taskId);\n if (!task) {\n return false;\n }\n\n if (!this.agents.has(agentName)) {\n console.error(`Agent '${agentName}' not found in space team`);\n return false;\n }\n\n task.assignedTo = agentName;\n this.updatedAt = new Date();\n await this.persistState();\n console.log(`Assigned task ${taskId} to agent ${agentName}`);\n return true;\n }\n\n isPlanComplete(): boolean {\n if (!this.plan) {\n return false;\n }\n return this.plan.isComplete();\n }\n\n hasFailedTasks(): boolean {\n if (!this.plan) {\n return false;\n }\n return this.plan.hasFailedTasks();\n }\n\n async persistState(): Promise<void> {\n // NOTE: In database mode, space data is persisted through the data adapter (spaces table)\n // Storage is ONLY used for artifacts, not config files\n // This legacy file-based persistence is disabled to avoid conflicts\n // Space persistence is now handled by the API layer using SupabaseDatabaseAdapter\n console.log(\"[Space] State persistence handled by database adapter\");\n }\n\n async loadState(): Promise<boolean> {\n try {\n // NOTE: In database mode, space data is loaded from the database, not storage\n // This method is kept for backward compatibility but returns false\n console.log(\"[Space] State loading handled by database adapter\");\n return false;\n\n // Legacy code disabled:\n // const spaceData = await this.storage.readFile(\"space.json\");\n // if (spaceData) {\n // const data = JSON.parse(spaceData.toString(\"utf-8\")) as SpaceModel;\n // this.createdAt = new Date(data.createdAt || this.createdAt.toISOString());\n // this.updatedAt = new Date(data.updatedAt || this.updatedAt.toISOString());\n // this.name = data.name || this.name;\n // if (data.plan) {\n // this.plan = Plan.fromJSON(data.plan);\n // }\n // // Load artifacts...\n // return true;\n // }\n } catch (error) {\n console.error(\"Failed to load space state:\", error);\n }\n return false;\n }\n\n async loadPlan(): Promise<Plan | undefined> {\n if (await this.loadState()) {\n return this.plan;\n }\n return undefined;\n }\n\n getState(): SpaceState {\n const state: SpaceState = {\n spaceId: this.spaceId,\n name: this.name,\n goal: this.goal,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n teamSize: this.agents.size,\n };\n\n if (this.plan) {\n const taskStats = {\n total: this.plan.tasks.length,\n completed: this.plan.tasks.filter(\n (t) => t.status === TaskStatus.COMPLETED,\n ).length,\n running: this.plan.tasks.filter((t) => t.status === TaskStatus.RUNNING)\n .length,\n pending: this.plan.tasks.filter((t) => t.status === TaskStatus.PENDING)\n .length,\n failed: this.plan.tasks.filter((t) => t.status === TaskStatus.FAILED)\n .length,\n };\n state.tasks = taskStats;\n state.progressPercentage =\n taskStats.total > 0 ? (taskStats.completed / taskStats.total) * 100 : 0;\n }\n\n return state;\n }\n}\n\n/**\n * Start a new space\n */\nexport async function startSpace({\n goal,\n spaceId,\n userId,\n spaceRoot,\n name,\n model,\n}: {\n goal: string;\n spaceId?: string;\n userId?: string;\n spaceRoot?: string;\n name?: string;\n model?: string;\n}): Promise<Space> {\n const id = spaceId || `proj_${Date.now().toString(36)}`;\n\n // Create minimal space config\n const spaceConfig: SpaceConfig = {\n name: name || goal.slice(0, 50),\n autoSave: true,\n checkpointInterval: 300,\n };\n\n console.log(`[Space] Creating space - agents will be loaded on demand`);\n\n // Create storage\n const storage = await SpaceStorageFactory.create(id);\n\n // Create agents map - empty initially, agents loaded on demand\n const agents = new Map<string, Agent>();\n\n console.log(`[Space] Space initialized (agents loaded on demand)`);\n\n // Create message queue and history\n const messageQueue = new MessageQueue();\n const history = new ConversationHistory();\n\n // Create the space\n const space = new Space({\n spaceId: id,\n userId,\n config: spaceConfig,\n history,\n messageQueue,\n agents,\n storage,\n goal,\n name: name || spaceConfig.name,\n });\n\n // Create ViberAgent for the space (includes tmux + cursor-agent so Viber Board can verify skills)\n const viberAgentConfig: AgentConfig = {\n name: \"Viber\",\n description: \"I manage this space and coordinate all work.\",\n provider: \"openrouter\",\n model: model || \"deepseek/deepseek-chat\",\n temperature: 0.7,\n promptFile: \"\", // ViberAgent doesn't use prompt files\n skills: [\"tmux\", \"cursor-agent\"],\n };\n\n const viberAgent = new ViberAgent(viberAgentConfig, space, {\n model,\n spaceId: id,\n });\n space.viberAgent = viberAgent;\n\n // MCP tools are now loaded on-demand by agents, not pre-loaded\n // This avoids the need for a central tool registry\n\n // Save initial state\n await space.persistState();\n\n return space;\n}\n","/**\n * Viber Framework - Main Entry Point\n *\n * Complete data management and multi-agent collaboration engine\n */\n\n// Core\nexport * from \"./core/space\";\nexport * from \"./core/viber-agent\";\nexport * from \"./core/agent\";\nexport * from \"./core/collaboration\";\n// Export config types but avoid ModelConfig duplicate\nexport type {\n SpaceConfig,\n SpaceState,\n SpaceModel,\n AgentConfig,\n} from \"./core/config\";\nexport * from \"./core/message\";\nexport * from \"./core/plan\";\nexport * from \"./core/task\";\n// Export provider but avoid ModelConfig duplicate (it's in types)\nexport { getModelProvider, parseModelString } from \"./core/provider\";\nexport type { ModelProvider } from \"./core/provider\";\nexport * from \"./core/tool\";\n\n// AI SDK Core - re-export from AI SDK v6\nexport { streamText, generateText, Output, ToolLoopAgent, stepCountIs } from \"ai\";\n\n// Data Management\nexport * from \"./data/manager\";\n\n// State Management \nexport * from \"./state/store\";\n\n// Storage\nexport * from \"./storage/space\";\nexport * from \"./storage/base\";\n\n// Types\nexport * from \"./types\";\n\n// Daemon\nexport * from \"./daemon\";\n","/**\n * ViberDataManager - Unified Data Access Layer\n *\n * This is the single source of truth for all Viber data operations.\n * It unifies DataAdapter (metadata) and SpaceStorage (files) into one interface.\n *\n * Key features:\n * - Unified query interface for spaces, artifacts, tasks, agents, tools\n * - Automatic caching\n * - Real-time subscriptions (when supported)\n * - Optimistic updates\n */\n\nimport type { DataAdapter } from \"./adapter\";\nimport type { Space as DataSpace, Artifact, Task, Agent, Tool } from \"./types\";\nimport { getDataAdapter, getServerDataAdapter } from \"./factory\";\nimport { SpaceStorage, SpaceStorageFactory } from \"../storage/space\";\nimport type { Space } from \"../core/space\";\nimport type { SpaceStorage as SpaceStorageType } from \"../storage/space\";\n\nexport interface SpaceFilters {\n userId?: string;\n name?: string;\n createdAfter?: Date;\n createdBefore?: Date;\n}\n\nexport interface ArtifactFilters {\n spaceId?: string;\n taskId?: string;\n category?: \"input\" | \"intermediate\" | \"output\";\n mimeType?: string;\n}\n\nexport interface TaskFilters {\n spaceId: string;\n status?: \"active\" | \"completed\" | \"archived\";\n createdAfter?: Date;\n}\n\nexport type Unsubscribe = () => void;\nexport type SubscriptionCallback<T> = (data: T) => void;\n\n/**\n * ViberDataManager - Central data access layer\n */\nexport class ViberDataManager {\n private dataAdapter: DataAdapter;\n private cache: Map<string, { data: any; timestamp: number }>;\n private subscriptions: Map<string, Set<SubscriptionCallback<any>>>;\n private cacheTTL: number = 5 * 60 * 1000; // 5 minutes default\n\n constructor(dataAdapter?: DataAdapter) {\n // If no adapter provided, try to get one from factory\n // Note: This will fail for database mode on client side, which is intended\n // as client side should use server actions, not ViberDataManager directly\n this.dataAdapter = dataAdapter || getDataAdapter();\n this.cache = new Map();\n this.subscriptions = new Map();\n }\n\n /**\n * Create a server-side instance (uses direct database access)\n * Uses dynamic import to avoid bundling server code in client\n *\n * NOTE: This should only be called from server-side code (API routes, server components)\n */\n static async createServer(): Promise<ViberDataManager> {\n // Dynamic import to avoid bundling server code in client bundle\n const { getServerDataAdapter } = await import(\"./factory\");\n return new ViberDataManager(getServerDataAdapter());\n }\n\n /**\n * Create a server-side instance synchronously (for use in server contexts)\n * This uses require() to avoid bundling in client code\n */\n static createServerSync(): ViberDataManager {\n if (typeof window !== \"undefined\") {\n throw new Error(\"createServerSync() can only be called on the server\");\n }\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { getServerDataAdapter } = require(\"./factory\");\n return new ViberDataManager(getServerDataAdapter());\n }\n\n /**\n * Create a client-side instance (uses API calls)\n * @deprecated Client-side direct usage is deprecated. Use server actions instead.\n */\n static createClient(): ViberDataManager {\n // Return a dummy instance or throw error?\n // For now, we'll throw to catch usage\n throw new Error(\n \"ViberDataManager.createClient() is deprecated. Use server actions.\"\n );\n }\n\n // ==================== Cache Management ====================\n\n private getCacheKey(prefix: string, id?: string): string {\n return id ? `${prefix}:${id}` : prefix;\n }\n\n private getCached<T>(key: string): T | null {\n const cached = this.cache.get(key);\n if (!cached) return null;\n\n const age = Date.now() - cached.timestamp;\n if (age > this.cacheTTL) {\n this.cache.delete(key);\n return null;\n }\n\n return cached.data as T;\n }\n\n private setCache<T>(key: string, data: T): void {\n this.cache.set(key, { data, timestamp: Date.now() });\n }\n\n private invalidateCache(pattern: string): void {\n for (const key of this.cache.keys()) {\n if (key.startsWith(pattern)) {\n this.cache.delete(key);\n }\n }\n }\n\n private notifySubscribers<T>(key: string, data: T): void {\n const callbacks = this.subscriptions.get(key);\n if (callbacks) {\n callbacks.forEach((cb) => {\n try {\n cb(data);\n } catch (error) {\n console.error(\n `[ViberDataManager] Subscription callback error:`,\n error\n );\n }\n });\n }\n }\n\n // ==================== Space Operations ====================\n\n /**\n * Get a single space by ID\n */\n async getSpace(spaceId: string): Promise<DataSpace | null> {\n const cacheKey = this.getCacheKey(\"space\", spaceId);\n const cached = this.getCached<DataSpace>(cacheKey);\n if (cached) return cached;\n\n const space = await this.dataAdapter.getSpace(spaceId);\n if (space) {\n this.setCache(cacheKey, space);\n }\n return space;\n }\n\n /**\n * List all spaces with optional filters\n */\n async listSpaces(filters?: SpaceFilters): Promise<DataSpace[]> {\n const cacheKey = `spaces:${JSON.stringify(filters || {})}`;\n const cached = this.getCached<DataSpace[]>(cacheKey);\n if (cached) return cached;\n\n let spaces = await this.dataAdapter.getSpaces();\n\n // Apply filters\n if (filters) {\n if (filters.userId) {\n spaces = spaces.filter((s) => s.userId === filters.userId);\n }\n if (filters.name) {\n const nameLower = filters.name.toLowerCase();\n spaces = spaces.filter((s) =>\n s.name?.toLowerCase().includes(nameLower)\n );\n }\n if (filters.createdAfter) {\n spaces = spaces.filter((s) => {\n if (!s.createdAt) return false;\n return new Date(s.createdAt) >= filters.createdAfter!;\n });\n }\n if (filters.createdBefore) {\n spaces = spaces.filter((s) => {\n if (!s.createdAt) return false;\n return new Date(s.createdAt) <= filters.createdBefore!;\n });\n }\n }\n\n this.setCache(cacheKey, spaces);\n return spaces;\n }\n\n /**\n * Create a new space\n */\n async createSpace(space: Partial<DataSpace>): Promise<DataSpace> {\n const newSpace = await this.dataAdapter.saveSpace({\n id: space.id || `space-${Date.now()}`,\n name: space.name || \"New Space\",\n description: space.description,\n userId: space.userId,\n config: space.config,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n } as DataSpace);\n\n // Invalidate caches\n this.invalidateCache(\"spaces:\");\n this.invalidateCache(\"space:\");\n\n // Notify subscribers\n this.notifySubscribers(\"spaces\", newSpace);\n this.notifySubscribers(`space:${newSpace.id}`, newSpace);\n\n return newSpace;\n }\n\n /**\n * Update a space\n */\n async updateSpace(\n spaceId: string,\n updates: Partial<DataSpace>\n ): Promise<DataSpace> {\n const existing = await this.getSpace(spaceId);\n if (!existing) {\n throw new Error(`Space ${spaceId} not found`);\n }\n\n const updated = await this.dataAdapter.saveSpace({\n ...existing,\n ...updates,\n updatedAt: new Date().toISOString(),\n });\n\n // Update cache\n this.setCache(this.getCacheKey(\"space\", spaceId), updated);\n this.invalidateCache(\"spaces:\");\n\n // Notify subscribers\n this.notifySubscribers(`space:${spaceId}`, updated);\n this.notifySubscribers(\"spaces\", updated);\n\n return updated;\n }\n\n /**\n * Delete a space\n */\n async deleteSpace(spaceId: string): Promise<void> {\n await this.dataAdapter.deleteSpace(spaceId);\n\n // Invalidate caches\n this.invalidateCache(\"space:\");\n this.invalidateCache(\"spaces:\");\n this.invalidateCache(`artifacts:space:${spaceId}`);\n\n // Notify subscribers\n this.notifySubscribers(`space:${spaceId}`, null);\n this.notifySubscribers(\"spaces\", null);\n }\n\n /**\n * Subscribe to space changes\n */\n subscribeToSpace(\n spaceId: string,\n callback: SubscriptionCallback<DataSpace | null>\n ): Unsubscribe {\n const key = `space:${spaceId}`;\n if (!this.subscriptions.has(key)) {\n this.subscriptions.set(key, new Set());\n }\n this.subscriptions.get(key)!.add(callback);\n\n // Send current value immediately\n this.getSpace(spaceId).then((space) => callback(space));\n\n return () => {\n const callbacks = this.subscriptions.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscriptions.delete(key);\n }\n }\n };\n }\n\n /**\n * Subscribe to all spaces\n */\n subscribeToSpaces(callback: SubscriptionCallback<DataSpace[]>): Unsubscribe {\n const key = \"spaces\";\n if (!this.subscriptions.has(key)) {\n this.subscriptions.set(key, new Set());\n }\n this.subscriptions.get(key)!.add(callback);\n\n // Send current value immediately\n this.listSpaces().then((spaces) => callback(spaces));\n\n return () => {\n const callbacks = this.subscriptions.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscriptions.delete(key);\n }\n }\n };\n }\n\n // ==================== Artifact Operations ====================\n\n /**\n * Get artifacts for a space\n */\n async getArtifacts(\n spaceId: string,\n filters?: ArtifactFilters\n ): Promise<Artifact[]> {\n const cacheKey = `artifacts:space:${spaceId}:${JSON.stringify(\n filters || {}\n )}`;\n const cached = this.getCached<Artifact[]>(cacheKey);\n if (cached) return cached;\n\n let artifacts = await this.dataAdapter.getArtifacts(spaceId);\n\n // Apply filters\n if (filters) {\n if (filters.taskId) {\n artifacts = artifacts.filter((a) => a.taskId === filters.taskId);\n }\n if (filters.category) {\n artifacts = artifacts.filter((a) => a.category === filters.category);\n }\n if (filters.mimeType) {\n artifacts = artifacts.filter((a) => a.mimeType === filters.mimeType);\n }\n }\n\n this.setCache(cacheKey, artifacts);\n return artifacts;\n }\n\n /**\n * Get a single artifact by ID\n */\n async getArtifact(artifactId: string): Promise<Artifact | null> {\n const cacheKey = this.getCacheKey(\"artifact\", artifactId);\n const cached = this.getCached<Artifact>(cacheKey);\n if (cached) return cached;\n\n const artifact = await this.dataAdapter.getArtifact(artifactId);\n if (artifact) {\n this.setCache(cacheKey, artifact);\n }\n return artifact;\n }\n\n /**\n * Create an artifact (metadata only - file upload handled separately)\n */\n async createArtifact(\n spaceId: string,\n artifact: Partial<Artifact>\n ): Promise<Artifact> {\n const newArtifact = await this.dataAdapter.saveArtifact({\n id: artifact.id || `artifact-${Date.now()}`,\n spaceId,\n userId: artifact.userId,\n taskId: artifact.taskId,\n category: artifact.category || \"intermediate\",\n storageKey: artifact.storageKey || \"\",\n originalName: artifact.originalName || \"untitled\",\n mimeType: artifact.mimeType || \"application/octet-stream\",\n sizeBytes: artifact.sizeBytes || 0,\n metadata: artifact.metadata,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n } as Artifact);\n\n // Invalidate caches\n this.invalidateCache(`artifacts:space:${spaceId}`);\n this.setCache(this.getCacheKey(\"artifact\", newArtifact.id), newArtifact);\n\n // Notify subscribers\n this.notifySubscribers(`artifacts:space:${spaceId}`, newArtifact);\n this.notifySubscribers(`artifact:${newArtifact.id}`, newArtifact);\n\n return newArtifact;\n }\n\n /**\n * Update an artifact\n */\n async updateArtifact(\n artifactId: string,\n updates: Partial<Artifact>\n ): Promise<Artifact> {\n const existing = await this.getArtifact(artifactId);\n if (!existing) {\n throw new Error(`Artifact ${artifactId} not found`);\n }\n\n const updated = await this.dataAdapter.saveArtifact({\n ...existing,\n ...updates,\n updatedAt: new Date().toISOString(),\n });\n\n // Update cache\n this.setCache(this.getCacheKey(\"artifact\", artifactId), updated);\n if (existing.spaceId) {\n this.invalidateCache(`artifacts:space:${existing.spaceId}`);\n }\n\n // Notify subscribers\n this.notifySubscribers(`artifact:${artifactId}`, updated);\n if (existing.spaceId) {\n this.notifySubscribers(`artifacts:space:${existing.spaceId}`, updated);\n }\n\n return updated;\n }\n\n /**\n * Delete an artifact\n */\n async deleteArtifact(artifactId: string, spaceId: string): Promise<void> {\n await this.dataAdapter.deleteArtifact(artifactId);\n\n // Invalidate caches\n this.invalidateCache(`artifact:${artifactId}`);\n this.invalidateCache(`artifacts:space:${spaceId}`);\n\n // Notify subscribers\n this.notifySubscribers(`artifact:${artifactId}`, null);\n this.notifySubscribers(`artifacts:space:${spaceId}`, null);\n }\n\n /**\n * Subscribe to artifacts for a space\n */\n subscribeToArtifacts(\n spaceId: string,\n callback: SubscriptionCallback<Artifact[]>\n ): Unsubscribe {\n const key = `artifacts:space:${spaceId}`;\n if (!this.subscriptions.has(key)) {\n this.subscriptions.set(key, new Set());\n }\n this.subscriptions.get(key)!.add(callback);\n\n // Send current value immediately\n this.getArtifacts(spaceId).then((artifacts) => callback(artifacts));\n\n return () => {\n const callbacks = this.subscriptions.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscriptions.delete(key);\n }\n }\n };\n }\n\n // ==================== Task Operations ====================\n\n /**\n * Get tasks for a space\n */\n async getTasks(spaceId: string, filters?: TaskFilters): Promise<Task[]> {\n const cacheKey = `tasks:space:${spaceId}:${JSON.stringify(filters || {})}`;\n const cached = this.getCached<Task[]>(cacheKey);\n if (cached) return cached;\n\n let tasks = await this.dataAdapter.getTasks(spaceId);\n\n // Apply filters\n if (filters) {\n if (filters.status) {\n tasks = tasks.filter((t) => t.metadata?.status === filters.status);\n }\n if (filters.createdAfter) {\n tasks = tasks.filter((t) => {\n if (!t.createdAt) return false;\n return new Date(t.createdAt) >= filters.createdAfter!;\n });\n }\n }\n\n this.setCache(cacheKey, tasks);\n return tasks;\n }\n\n /**\n * Get a single task by ID\n */\n async getTask(taskId: string): Promise<Task | null> {\n const cacheKey = this.getCacheKey(\"task\", taskId);\n const cached = this.getCached<Task>(cacheKey);\n if (cached) return cached;\n\n const task = await this.dataAdapter.getTask(taskId);\n if (task) {\n this.setCache(cacheKey, task);\n }\n return task;\n }\n\n /**\n * Create a new task\n */\n async createTask(spaceId: string, task: Partial<Task>): Promise<Task> {\n const newTask = await this.dataAdapter.saveTask({\n id: task.id || `task-${Date.now()}`,\n spaceId,\n userId: task.userId,\n title: task.title,\n model: task.model,\n mode: task.mode || \"chat\",\n systemMessage: task.systemMessage,\n messages: task.messages || [],\n supervision: task.supervision,\n metadata: task.metadata,\n context: task.context,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n } as Task);\n\n // Invalidate caches\n this.invalidateCache(`tasks:space:${spaceId}`);\n this.setCache(this.getCacheKey(\"task\", newTask.id), newTask);\n\n // Notify subscribers\n this.notifySubscribers(`tasks:space:${spaceId}`, newTask);\n this.notifySubscribers(`task:${newTask.id}`, newTask);\n\n return newTask;\n }\n\n /**\n * Update a task\n */\n async updateTask(taskId: string, updates: Partial<Task>): Promise<Task> {\n const existing = await this.getTask(taskId);\n if (!existing) {\n throw new Error(`Task ${taskId} not found`);\n }\n\n const updated = await this.dataAdapter.saveTask({\n ...existing,\n ...updates,\n updatedAt: new Date().toISOString(),\n });\n\n // Update cache\n this.setCache(this.getCacheKey(\"task\", taskId), updated);\n this.invalidateCache(`tasks:space:${existing.spaceId}`);\n\n // Notify subscribers\n this.notifySubscribers(`task:${taskId}`, updated);\n this.notifySubscribers(`tasks:space:${existing.spaceId}`, updated);\n\n return updated;\n }\n\n /**\n * Delete a task\n */\n async deleteTask(taskId: string, spaceId: string): Promise<void> {\n await this.dataAdapter.deleteTask(taskId);\n\n // Invalidate caches\n this.invalidateCache(`task:${taskId}`);\n this.invalidateCache(`tasks:space:${spaceId}`);\n\n // Notify subscribers\n this.notifySubscribers(`task:${taskId}`, null);\n this.notifySubscribers(`tasks:space:${spaceId}`, null);\n }\n\n /**\n * Subscribe to tasks for a space\n */\n subscribeToTasks(\n spaceId: string,\n callback: SubscriptionCallback<Task[]>\n ): Unsubscribe {\n const key = `tasks:space:${spaceId}`;\n if (!this.subscriptions.has(key)) {\n this.subscriptions.set(key, new Set());\n }\n this.subscriptions.get(key)!.add(callback);\n\n // Send current value immediately\n this.getTasks(spaceId).then((tasks) => callback(tasks));\n\n return () => {\n const callbacks = this.subscriptions.get(key);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.subscriptions.delete(key);\n }\n }\n };\n }\n\n // ==================== Agent Operations ====================\n\n /**\n * Get all agents\n */\n async getAgents(): Promise<Agent[]> {\n const cacheKey = \"agents\";\n const cached = this.getCached<Agent[]>(cacheKey);\n if (cached) return cached;\n\n const agents = await this.dataAdapter.getAgents();\n this.setCache(cacheKey, agents);\n return agents;\n }\n\n /**\n * Get a single agent by ID\n */\n async getAgent(agentId: string): Promise<Agent | null> {\n const cacheKey = this.getCacheKey(\"agent\", agentId);\n const cached = this.getCached<Agent>(cacheKey);\n if (cached) return cached;\n\n const agent = await this.dataAdapter.getAgent(agentId);\n if (agent) {\n this.setCache(cacheKey, agent);\n }\n return agent;\n }\n\n // ==================== Tool Operations ====================\n\n /**\n * Get all tools\n */\n async getTools(): Promise<Tool[]> {\n const cacheKey = \"tools\";\n const cached = this.getCached<Tool[]>(cacheKey);\n if (cached) return cached;\n\n const tools = await this.dataAdapter.getTools();\n this.setCache(cacheKey, tools);\n return tools;\n }\n\n /**\n * Get a single tool by ID\n */\n async getTool(toolId: string): Promise<Tool | null> {\n const cacheKey = this.getCacheKey(\"tool\", toolId);\n const cached = this.getCached<Tool>(cacheKey);\n if (cached) return cached;\n\n const tool = await this.dataAdapter.getTool(toolId);\n if (tool) {\n this.setCache(cacheKey, tool);\n }\n return tool;\n }\n\n // ==================== Storage Operations ====================\n\n /**\n * Get SpaceStorage instance for a space\n */\n async getSpaceStorage(spaceId: string): Promise<SpaceStorageType> {\n return await SpaceStorageFactory.create(spaceId);\n }\n\n /**\n * Upload an artifact file\n */\n async uploadArtifactFile(\n spaceId: string,\n artifactId: string,\n file: File | Blob,\n filename: string\n ): Promise<string> {\n const storage = await this.getSpaceStorage(spaceId);\n const storageKey = `artifacts/${artifactId}/${filename}`;\n\n if (file instanceof Blob) {\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n await storage.saveFileBuffer(storageKey, buffer);\n } else {\n await storage.saveFile(storageKey, file);\n }\n\n return storageKey;\n }\n\n /**\n * Download an artifact file\n */\n async downloadArtifactFile(\n spaceId: string,\n storageKey: string\n ): Promise<Blob> {\n const storage = await this.getSpaceStorage(spaceId);\n const buffer = await storage.readFile(storageKey);\n // Convert Buffer to Uint8Array for Blob (handles both ArrayBuffer and SharedArrayBuffer)\n const uint8Array = new Uint8Array(buffer);\n return new Blob([uint8Array]);\n }\n\n /**\n * Delete an artifact file\n */\n async deleteArtifactFile(spaceId: string, storageKey: string): Promise<void> {\n const storage = await this.getSpaceStorage(spaceId);\n await storage.delete(storageKey);\n }\n}\n\n// Export singleton instance getters\nlet clientInstance: ViberDataManager | null = null;\nlet serverInstance: ViberDataManager | null = null;\n\nexport function getViberDataManager(): ViberDataManager {\n if (typeof window === \"undefined\") {\n // Server-side\n if (!serverInstance) {\n serverInstance = ViberDataManager.createServerSync();\n }\n return serverInstance;\n } else {\n // Client-side - throw error to enforce server actions usage\n throw new Error(\n \"getViberDataManager() cannot be called on the client. Use server actions.\"\n );\n }\n}\n\n/**\n * Get server-side ViberDataManager (for API routes and server components)\n * This uses direct database access, not API calls\n *\n * NOTE: This function can only be called from server-side code\n */\nexport function getViberDataManagerServer(): ViberDataManager {\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"getViberDataManagerServer() can only be called on the server\"\n );\n }\n if (!serverInstance) {\n serverInstance = ViberDataManager.createServerSync();\n }\n return serverInstance;\n}\n","/**\n * Viber Unified State Store\n *\n * Single source of truth for all Viber state using Zustand.\n * Provides reactive state management with automatic synchronization.\n */\n\nimport { create } from \"zustand\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport type { Space, Artifact, Task, Agent, Tool } from \"../data/types\";\nimport { getViberDataManager } from \"../data/manager\";\n\ninterface ViberState {\n // Spaces\n spaces: Map<string, Space>;\n currentSpaceId: string | null;\n\n // Artifacts (indexed by spaceId)\n artifacts: Map<string, Artifact[]>;\n\n // Tasks (indexed by spaceId)\n tasks: Map<string, Task[]>;\n\n // Agents and Tools (global)\n agents: Agent[];\n tools: Tool[];\n\n // Loading states\n loading: {\n spaces: boolean;\n artifacts: Record<string, boolean>;\n tasks: Record<string, boolean>;\n agents: boolean;\n tools: boolean;\n };\n\n // Error states\n errors: {\n spaces: Error | null;\n artifacts: Record<string, Error | null>;\n tasks: Record<string, Error | null>;\n agents: Error | null;\n tools: Error | null;\n };\n\n // Actions\n setSpaces: (spaces: Space[]) => void;\n setSpace: (space: Space) => void;\n removeSpace: (spaceId: string) => void;\n setCurrentSpaceId: (spaceId: string | null) => void;\n\n setArtifacts: (spaceId: string, artifacts: Artifact[]) => void;\n addArtifact: (spaceId: string, artifact: Artifact) => void;\n updateArtifact: (\n spaceId: string,\n artifactId: string,\n updates: Partial<Artifact>\n ) => void;\n removeArtifact: (spaceId: string, artifactId: string) => void;\n\n setTasks: (spaceId: string, tasks: Task[]) => void;\n addTask: (spaceId: string, task: Task) => void;\n updateTask: (spaceId: string, taskId: string, updates: Partial<Task>) => void;\n removeTask: (spaceId: string, taskId: string) => void;\n\n setAgents: (agents: Agent[]) => void;\n setTools: (tools: Tool[]) => void;\n\n setLoading: (key: string, value: boolean) => void;\n setError: (key: string, error: Error | null) => void;\n\n // Sync actions (sync with ViberDataManager)\n syncSpaces: () => Promise<void>;\n syncArtifacts: (spaceId: string) => Promise<void>;\n syncTasks: (spaceId: string) => Promise<void>;\n syncAgents: () => Promise<void>;\n syncTools: () => Promise<void>;\n}\n\nexport const useViberStore = create<ViberState>()(\n subscribeWithSelector((set, get) => ({\n // Initial state\n spaces: new Map(),\n currentSpaceId: null,\n artifacts: new Map(),\n tasks: new Map(),\n agents: [],\n tools: [],\n\n loading: {\n spaces: false,\n artifacts: {},\n tasks: {},\n agents: false,\n tools: false,\n },\n\n errors: {\n spaces: null,\n artifacts: {},\n tasks: {},\n agents: null,\n tools: null,\n },\n\n // Space actions\n setSpaces: (spaces) => {\n const spacesMap = new Map<string, Space>();\n spaces.forEach((space) => {\n spacesMap.set(space.id, space);\n });\n set({ spaces: spacesMap });\n },\n\n setSpace: (space) => {\n set((state) => {\n const newSpaces = new Map(state.spaces);\n newSpaces.set(space.id, space);\n return { spaces: newSpaces };\n });\n },\n\n removeSpace: (spaceId) => {\n set((state) => {\n const newSpaces = new Map(state.spaces);\n newSpaces.delete(spaceId);\n const newArtifacts = new Map(state.artifacts);\n newArtifacts.delete(spaceId);\n const newTasks = new Map(state.tasks);\n newTasks.delete(spaceId);\n return {\n spaces: newSpaces,\n artifacts: newArtifacts,\n tasks: newTasks,\n currentSpaceId:\n state.currentSpaceId === spaceId ? null : state.currentSpaceId,\n };\n });\n },\n\n setCurrentSpaceId: (spaceId) => {\n set({ currentSpaceId: spaceId });\n },\n\n // Artifact actions\n setArtifacts: (spaceId, artifacts) => {\n set((state) => {\n const newArtifacts = new Map(state.artifacts);\n newArtifacts.set(spaceId, artifacts);\n return { artifacts: newArtifacts };\n });\n },\n\n addArtifact: (spaceId, artifact) => {\n set((state) => {\n const newArtifacts = new Map(state.artifacts);\n const existing = newArtifacts.get(spaceId) || [];\n newArtifacts.set(spaceId, [...existing, artifact]);\n return { artifacts: newArtifacts };\n });\n },\n\n updateArtifact: (spaceId, artifactId, updates) => {\n set((state) => {\n const newArtifacts = new Map(state.artifacts);\n const existing = newArtifacts.get(spaceId) || [];\n const updated = existing.map((a) =>\n a.id === artifactId ? { ...a, ...updates } : a\n );\n newArtifacts.set(spaceId, updated);\n return { artifacts: newArtifacts };\n });\n },\n\n removeArtifact: (spaceId, artifactId) => {\n set((state) => {\n const newArtifacts = new Map(state.artifacts);\n const existing = newArtifacts.get(spaceId) || [];\n const filtered = existing.filter((a) => a.id !== artifactId);\n newArtifacts.set(spaceId, filtered);\n return { artifacts: newArtifacts };\n });\n },\n\n // Task actions\n setTasks: (spaceId, tasks) => {\n set((state) => {\n const newTasks = new Map(state.tasks);\n newTasks.set(spaceId, tasks);\n return { tasks: newTasks };\n });\n },\n\n addTask: (spaceId, task) => {\n set((state) => {\n const newTasks = new Map(state.tasks);\n const existing = newTasks.get(spaceId) || [];\n newTasks.set(spaceId, [...existing, task]);\n return { tasks: newTasks };\n });\n },\n\n updateTask: (spaceId, taskId, updates) => {\n set((state) => {\n const newTasks = new Map(state.tasks);\n const existing = newTasks.get(spaceId) || [];\n const updated = existing.map((t) =>\n t.id === taskId ? { ...t, ...updates } : t\n );\n newTasks.set(spaceId, updated);\n return { tasks: newTasks };\n });\n },\n\n removeTask: (spaceId, taskId) => {\n set((state) => {\n const newTasks = new Map(state.tasks);\n const existing = newTasks.get(spaceId) || [];\n const filtered = existing.filter((t) => t.id !== taskId);\n newTasks.set(spaceId, filtered);\n return { tasks: newTasks };\n });\n },\n\n // Agent and Tool actions\n setAgents: (agents) => {\n set({ agents });\n },\n\n setTools: (tools) => {\n set({ tools });\n },\n\n // Loading and error actions\n setLoading: (key, value) => {\n set((state) => {\n const [category, subKey] = key.split(\":\");\n if (subKey) {\n // Nested key like \"artifacts:spaceId\"\n return {\n loading: {\n ...state.loading,\n [category]: {\n ...((state.loading[\n category as keyof typeof state.loading\n ] as Record<string, boolean>) || {}),\n [subKey]: value,\n },\n },\n };\n } else {\n // Top-level key\n return {\n loading: {\n ...state.loading,\n [key]: value,\n },\n };\n }\n });\n },\n\n setError: (key, error) => {\n set((state) => {\n const [category, subKey] = key.split(\":\");\n if (subKey) {\n // Nested key like \"artifacts:spaceId\"\n return {\n errors: {\n ...state.errors,\n [category]: {\n ...((state.errors[\n category as keyof typeof state.errors\n ] as Record<string, Error | null>) || {}),\n [subKey]: error,\n },\n },\n };\n } else {\n // Top-level key\n return {\n errors: {\n ...state.errors,\n [key]: error,\n },\n };\n }\n });\n },\n\n // Sync actions\n syncSpaces: async () => {\n const manager = getViberDataManager();\n set({ loading: { ...get().loading, spaces: true } });\n try {\n const spaces = await manager.listSpaces();\n get().setSpaces(spaces);\n set({\n loading: { ...get().loading, spaces: false },\n errors: { ...get().errors, spaces: null },\n });\n } catch (error) {\n set({\n loading: { ...get().loading, spaces: false },\n errors: {\n ...get().errors,\n spaces: error instanceof Error ? error : new Error(String(error)),\n },\n });\n }\n },\n\n syncArtifacts: async (spaceId) => {\n const manager = getViberDataManager();\n set((state) => ({\n loading: {\n ...state.loading,\n artifacts: { ...state.loading.artifacts, [spaceId]: true },\n },\n }));\n try {\n const artifacts = await manager.getArtifacts(spaceId);\n get().setArtifacts(spaceId, artifacts);\n set((state) => ({\n loading: {\n ...state.loading,\n artifacts: { ...state.loading.artifacts, [spaceId]: false },\n },\n errors: {\n ...state.errors,\n artifacts: { ...state.errors.artifacts, [spaceId]: null },\n },\n }));\n } catch (error) {\n set((state) => ({\n loading: {\n ...state.loading,\n artifacts: { ...state.loading.artifacts, [spaceId]: false },\n },\n errors: {\n ...state.errors,\n artifacts: {\n ...state.errors.artifacts,\n [spaceId]:\n error instanceof Error ? error : new Error(String(error)),\n },\n },\n }));\n }\n },\n\n syncTasks: async (spaceId) => {\n const manager = getViberDataManager();\n set((state) => ({\n loading: {\n ...state.loading,\n tasks: { ...state.loading.tasks, [spaceId]: true },\n },\n }));\n try {\n const tasks = await manager.getTasks(spaceId);\n get().setTasks(spaceId, tasks);\n set((state) => ({\n loading: {\n ...state.loading,\n tasks: { ...state.loading.tasks, [spaceId]: false },\n },\n errors: {\n ...state.errors,\n tasks: { ...state.errors.tasks, [spaceId]: null },\n },\n }));\n } catch (error) {\n set((state) => ({\n loading: {\n ...state.loading,\n tasks: { ...state.loading.tasks, [spaceId]: false },\n },\n errors: {\n ...state.errors,\n tasks: {\n ...state.errors.tasks,\n [spaceId]:\n error instanceof Error ? error : new Error(String(error)),\n },\n },\n }));\n }\n },\n\n syncAgents: async () => {\n const manager = getViberDataManager();\n set({ loading: { ...get().loading, agents: true } });\n try {\n const agents = await manager.getAgents();\n get().setAgents(agents);\n set({\n loading: { ...get().loading, agents: false },\n errors: { ...get().errors, agents: null },\n });\n } catch (error) {\n set({\n loading: { ...get().loading, agents: false },\n errors: {\n ...get().errors,\n agents: error instanceof Error ? error : new Error(String(error)),\n },\n });\n }\n },\n\n syncTools: async () => {\n const manager = getViberDataManager();\n set({ loading: { ...get().loading, tools: true } });\n try {\n const tools = await manager.getTools();\n get().setTools(tools);\n set({\n loading: { ...get().loading, tools: false },\n errors: { ...get().errors, tools: null },\n });\n } catch (error) {\n set({\n loading: { ...get().loading, tools: false },\n errors: {\n ...get().errors,\n tools: error instanceof Error ? error : new Error(String(error)),\n },\n });\n }\n },\n }))\n);\n\n// Selector hooks for optimized re-renders\nexport const useViberSpaces = () =>\n useViberStore((state) => Array.from(state.spaces.values()));\nexport const useViberCurrentSpace = () => {\n const currentSpaceId = useViberStore((state) => state.currentSpaceId);\n const spaces = useViberStore((state) => state.spaces);\n return currentSpaceId ? spaces.get(currentSpaceId) || null : null;\n};\nexport const useViberArtifacts = (spaceId: string | null | undefined) =>\n useViberStore((state) => (spaceId ? state.artifacts.get(spaceId) || [] : []));\nexport const useViberTasks = (spaceId: string | null | undefined) =>\n useViberStore((state) => (spaceId ? state.tasks.get(spaceId) || [] : []));\n","/**\n * ViberController - Daemon controller for outbound connection to command center\n *\n * A Viber is a local agent daemon that connects OUTBOUND to a central command center\n * (Supen). This eliminates the need for public IPs or port forwarding.\n *\n * Features:\n * - Persistent WebSocket connection to command center\n * - Auto-reconnection on disconnect\n * - Heartbeat/health monitoring\n * - Task execution and event streaming\n */\n\nimport { EventEmitter } from \"events\";\nimport WebSocket from \"ws\";\nimport type { ViberOptions } from \"../core/viber-agent\";\nimport { runTask } from \"./runtime\";\nimport { TerminalManager } from \"./terminal\";\n\n// ==================== Types ====================\n\nexport interface ViberControllerConfig {\n /** WebSocket URL to connect to (e.g., wss://supen.app/vibers/ws) */\n serverUrl: string;\n /** Authentication token */\n token: string;\n /** Unique identifier for this viber */\n viberId: string;\n /** Human-readable name for this viber */\n viberName?: string;\n /** Milliseconds between reconnection attempts */\n reconnectInterval?: number;\n /** Milliseconds between heartbeat messages */\n heartbeatInterval?: number;\n /** Enable desktop control tools */\n enableDesktop?: boolean;\n}\n\nexport interface ViberSkillInfo {\n id: string;\n name: string;\n description: string;\n}\n\nexport interface ViberInfo {\n id: string;\n name: string;\n version: string;\n platform: string;\n capabilities: string[];\n runningTasks: string[];\n /** Skills available on this viber (from SKILL.md) */\n skills?: ViberSkillInfo[];\n}\n\nexport interface ViberStatus {\n platform: string;\n uptime: number;\n memory: NodeJS.MemoryUsage;\n runningTasks: number;\n}\n\n// Server -> Viber messages (messages = full chat history from Viber Board for context)\nexport type ControllerServerMessage =\n | {\n type: \"task:submit\";\n taskId: string;\n goal: string;\n options?: ViberOptions;\n messages?: { role: string; content: string }[];\n }\n | { type: \"task:stop\"; taskId: string }\n | { type: \"task:message\"; taskId: string; message: string }\n | { type: \"ping\" }\n | { type: \"config:update\"; config: Partial<ViberControllerConfig> }\n // Terminal streaming messages\n | { type: \"terminal:list\" }\n | { type: \"terminal:attach\"; target: string }\n | { type: \"terminal:detach\"; target: string }\n | { type: \"terminal:input\"; target: string; keys: string }\n | { type: \"terminal:resize\"; target: string; cols: number; rows: number };\n\n// Viber -> Server messages\nexport type ControllerClientMessage =\n | { type: \"connected\"; viber: ViberInfo }\n | { type: \"task:started\"; taskId: string; spaceId: string }\n | { type: \"task:progress\"; taskId: string; event: any }\n | { type: \"task:completed\"; taskId: string; result: any }\n | { type: \"task:error\"; taskId: string; error: string }\n | { type: \"heartbeat\"; status: ViberStatus }\n | { type: \"pong\" }\n // Terminal streaming messages\n | { type: \"terminal:list\"; sessions: any[]; panes: any[] }\n | { type: \"terminal:attached\"; target: string; ok: boolean; error?: string }\n | { type: \"terminal:detached\"; target: string }\n | { type: \"terminal:output\"; target: string; data: string }\n | { type: \"terminal:resized\"; target: string; ok: boolean };\n\n// ==================== Controller ====================\n\nexport class ViberController extends EventEmitter {\n private ws: WebSocket | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private heartbeatTimer: NodeJS.Timeout | null = null;\n /** taskId -> AbortController for stop (daemon = thin runtime, no Space/agent instance) */\n private runningTasks: Map<string, AbortController> = new Map();\n private isConnected = false;\n private shouldReconnect = true;\n /** Terminal manager for streaming tmux panes */\n private terminalManager = new TerminalManager();\n\n constructor(private config: ViberControllerConfig) {\n super();\n }\n\n /**\n * Start the viber daemon\n */\n async start(): Promise<void> {\n console.log(`[Viber] Starting viber: ${this.config.viberId}`);\n console.log(`[Viber] Connecting to: ${this.config.serverUrl}`);\n this.shouldReconnect = true;\n await this.connect();\n }\n\n /**\n * Stop the viber daemon\n */\n async stop(): Promise<void> {\n console.log(\"[Viber] Stopping viber...\");\n this.shouldReconnect = false;\n\n for (const [taskId, controller] of this.runningTasks) {\n controller.abort();\n this.runningTasks.delete(taskId);\n }\n\n // Detach all terminal streams\n this.terminalManager.detachAll();\n\n // Clear timers\n this.stopHeartbeat();\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n // Close connection\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n\n this.emit(\"stopped\");\n }\n\n /**\n * Get current connection status\n */\n getStatus(): { connected: boolean; runningTasks: number } {\n return {\n connected: this.isConnected,\n runningTasks: this.runningTasks.size,\n };\n }\n\n // ==================== Connection Management ====================\n\n private async connect(): Promise<void> {\n try {\n this.ws = new WebSocket(this.config.serverUrl, {\n headers: {\n Authorization: `Bearer ${this.config.token}`,\n \"X-Viber-Id\": this.config.viberId,\n \"X-Viber-Version\": \"1.0.0\",\n },\n });\n\n this.ws.on(\"open\", () => {\n void this.onConnected();\n });\n this.ws.on(\"message\", (data) => this.onMessage(data));\n this.ws.on(\"close\", () => this.onDisconnected());\n this.ws.on(\"error\", (err) => this.onError(err));\n } catch (error) {\n console.error(\"[Viber] Connection failed:\", error);\n this.scheduleReconnect();\n }\n }\n\n private async onConnected(): Promise<void> {\n console.log(\"[Viber] Connected to command center\");\n this.isConnected = true;\n\n const capabilities = [\"file\", \"search\", \"web\"];\n if (this.config.enableDesktop) {\n capabilities.push(\"desktop\");\n }\n\n let skills: { id: string; name: string; description: string }[] = [];\n try {\n const { defaultRegistry } = await import(\"../skills/registry\");\n await defaultRegistry.loadAll();\n const all = defaultRegistry.getAllSkills();\n skills = all.map((s) => ({\n id: s.id,\n name: s.metadata.name || s.id,\n description: s.metadata.description || \"\",\n }));\n } catch (err) {\n console.warn(\"[Viber] Could not load skills for capabilities:\", err);\n }\n\n this.send({\n type: \"connected\",\n viber: {\n id: this.config.viberId,\n name: this.config.viberName || this.config.viberId,\n version: \"1.0.0\",\n platform: process.platform,\n capabilities,\n runningTasks: Array.from(this.runningTasks.keys()),\n skills: skills.length > 0 ? skills : undefined,\n },\n });\n\n this.startHeartbeat();\n this.emit(\"connected\");\n }\n\n private onDisconnected(): void {\n console.log(\"[Viber] Disconnected from command center\");\n this.isConnected = false;\n this.stopHeartbeat();\n\n if (this.shouldReconnect) {\n this.scheduleReconnect();\n }\n\n this.emit(\"disconnected\");\n }\n\n private onError(error: Error): void {\n console.error(\"[Viber] WebSocket error:\", error.message);\n this.emit(\"error\", error);\n }\n\n private async onMessage(data: WebSocket.Data): Promise<void> {\n try {\n const message = JSON.parse(data.toString()) as ControllerServerMessage;\n\n switch (message.type) {\n case \"task:submit\":\n await this.handleTaskSubmit(message);\n break;\n\n case \"task:stop\":\n await this.handleTaskStop(message.taskId);\n break;\n\n case \"task:message\":\n await this.handleTaskMessage(message.taskId, message.message);\n break;\n\n case \"ping\":\n this.send({ type: \"pong\" });\n break;\n\n case \"config:update\":\n Object.assign(this.config, message.config);\n this.emit(\"config:update\", message.config);\n break;\n\n // Terminal streaming\n case \"terminal:list\":\n this.handleTerminalList();\n break;\n\n case \"terminal:attach\":\n await this.handleTerminalAttach(message.target);\n break;\n\n case \"terminal:detach\":\n this.handleTerminalDetach(message.target);\n break;\n\n case \"terminal:input\":\n this.handleTerminalInput(message.target, message.keys);\n break;\n\n case \"terminal:resize\":\n this.handleTerminalResize(message.target, message.cols, message.rows);\n break;\n }\n } catch (error) {\n console.error(\"[Viber] Failed to process message:\", error);\n }\n }\n\n // ==================== Task Handling ====================\n\n private async handleTaskSubmit(message: {\n taskId: string;\n goal: string;\n options?: ViberOptions;\n messages?: { role: string; content: string }[];\n }): Promise<void> {\n const { taskId, goal, options, messages } = message;\n\n console.log(`[Viber] Received task: ${taskId}`);\n console.log(`[Viber] Goal: ${goal}`);\n\n const controller = new AbortController();\n this.runningTasks.set(taskId, controller);\n\n this.send({\n type: \"task:started\",\n taskId,\n spaceId: taskId,\n });\n\n try {\n const { streamResult, agent } = await runTask(\n goal,\n {\n taskId,\n model: options?.model,\n singleAgentId: options?.singleAgentId || \"default\",\n signal: controller.signal,\n },\n messages\n );\n\n // Consume stream to completion; do not send intermediate chunks to Viber Board by default.\n const finalText = await streamResult.text;\n\n this.send({\n type: \"task:completed\",\n taskId,\n result: {\n spaceId: taskId,\n text: finalText,\n summary: agent.getSummary(),\n },\n });\n } catch (error: any) {\n if (error?.name === \"AbortError\") {\n console.log(`[Viber] Task ${taskId} stopped`);\n } else {\n console.error(`[Viber] Task ${taskId} execution error:`, error);\n this.send({\n type: \"task:error\",\n taskId,\n error: error.message,\n });\n }\n } finally {\n this.runningTasks.delete(taskId);\n }\n }\n\n private async handleTaskStop(taskId: string): Promise<void> {\n const controller = this.runningTasks.get(taskId);\n if (controller) {\n controller.abort();\n this.runningTasks.delete(taskId);\n console.log(`[Viber] Task stopped: ${taskId}`);\n }\n }\n\n private async handleTaskMessage(\n _taskId: string,\n _message: string\n ): Promise<void> {\n // Daemon is thin: no in-memory conversation. Viber Board sends full messages on next task submit.\n }\n\n // ==================== Terminal Streaming ====================\n\n private handleTerminalList(): void {\n const { sessions, panes } = this.terminalManager.list();\n this.send({ type: \"terminal:list\", sessions, panes });\n }\n\n private async handleTerminalAttach(target: string): Promise<void> {\n console.log(`[Viber] Attaching to terminal: ${target}`);\n const ok = await this.terminalManager.attach(\n target,\n (data) => {\n this.send({ type: \"terminal:output\", target, data });\n },\n () => {\n this.send({ type: \"terminal:detached\", target });\n }\n );\n this.send({ type: \"terminal:attached\", target, ok });\n }\n\n private handleTerminalDetach(target: string): void {\n console.log(`[Viber] Detaching from terminal: ${target}`);\n this.terminalManager.detach(target);\n this.send({ type: \"terminal:detached\", target });\n }\n\n private handleTerminalInput(target: string, keys: string): void {\n this.terminalManager.sendInput(target, keys);\n }\n\n private handleTerminalResize(\n target: string,\n cols: number,\n rows: number\n ): void {\n const ok = this.terminalManager.resize(target, cols, rows);\n this.send({ type: \"terminal:resized\", target, ok });\n }\n\n // ==================== Communication ====================\n\n private send(message: ControllerClientMessage): void {\n if (this.ws && this.isConnected) {\n this.ws.send(JSON.stringify(message));\n }\n }\n\n // ==================== Heartbeat ====================\n\n private startHeartbeat(): void {\n const interval = this.config.heartbeatInterval || 30000;\n this.heartbeatTimer = setInterval(() => {\n const status: ViberStatus = {\n platform: process.platform,\n uptime: process.uptime(),\n memory: process.memoryUsage(),\n runningTasks: this.runningTasks.size,\n };\n\n this.send({ type: \"heartbeat\", status });\n }, interval);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n // ==================== Reconnection ====================\n\n private scheduleReconnect(): void {\n if (!this.shouldReconnect) return;\n\n const interval = this.config.reconnectInterval || 5000;\n console.log(`[Viber] Reconnecting in ${interval}ms...`);\n\n this.reconnectTimer = setTimeout(() => {\n this.connect();\n }, interval);\n }\n}\n","/**\n * Daemon runtime - thin clawdbot-alike assistant path\n *\n * No Space, no DataAdapter, no Storage. Loads a single agent config from file\n * and runs streamText. Viber Board owns persistence and context; daemon only\n * orchestrates local skills and the LLM.\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport * as yaml from \"yaml\";\nimport { getViberPath } from \"../config\";\nimport type { AgentConfig } from \"../core/config\";\nimport { Agent } from \"../core/agent\";\nimport type { ViberMessage } from \"../core/message\";\n\nexport interface DaemonRunTaskOptions {\n model?: string;\n singleAgentId?: string;\n agentConfig?: AgentConfig;\n signal?: AbortSignal;\n}\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nconst DEFAULTS_AGENTS_DIR = path.join(\n path.dirname(__dirname),\n \"data\",\n \"defaults\",\n \"agents\"\n);\n\n/**\n * Load agent config from file (no DataAdapter).\n * Tries built-in defaults then ~/.openviber/agents/{id}.yaml\n */\nexport async function loadAgentConfig(\n agentId: string\n): Promise<AgentConfig | null> {\n const tryRead = async (filePath: string): Promise<AgentConfig | null> => {\n try {\n const content = await fs.readFile(filePath, \"utf8\");\n const parsed = yaml.parse(content) as Record<string, unknown>;\n if (!parsed || typeof parsed !== \"object\") return null;\n return { ...parsed, id: agentId } as AgentConfig;\n } catch {\n return null;\n }\n };\n\n for (const ext of [\"yaml\", \"yml\"]) {\n const fromDefaults = await tryRead(\n path.join(DEFAULTS_AGENTS_DIR, `${agentId}.${ext}`)\n );\n if (fromDefaults) return fromDefaults;\n }\n\n const root = getViberPath();\n for (const ext of [\"yaml\", \"yml\"]) {\n const fromUser = await tryRead(\n path.join(root, \"agents\", `${agentId}.${ext}`)\n );\n if (fromUser) return fromUser;\n }\n\n // Fallback: in-code default so daemon works out of the box (clawdbot-alike)\n if (agentId === \"default\") {\n return {\n id: \"default\",\n name: \"Default\",\n description: \"General-purpose assistant with local skills.\",\n provider: \"openrouter\",\n model: \"deepseek/deepseek-chat\",\n temperature: 0.7,\n maxTokens: 4096,\n systemPrompt:\n \"You are a helpful AI assistant. You help users accomplish their tasks efficiently and effectively. Be concise, accurate, and helpful.\",\n tools: [],\n skills: [\"tmux\", \"cursor-agent\"],\n } as AgentConfig;\n }\n\n return null;\n}\n\n/**\n * Run a single task: one agent, no Space, no storage.\n * Returns stream result and agent for summary.\n */\nexport async function runTask(\n goal: string,\n options: DaemonRunTaskOptions & { taskId: string },\n messages?: { role: string; content: string }[]\n): Promise<{\n streamResult: Awaited<ReturnType<Agent[\"streamText\"]>>;\n agent: Agent;\n}> {\n const {\n taskId,\n singleAgentId = \"default\",\n agentConfig: overrideConfig,\n model: modelOverride,\n signal,\n } = options;\n\n let config = overrideConfig ?? (await loadAgentConfig(singleAgentId));\n if (!config) {\n throw new Error(\n `Agent '${singleAgentId}' not found. Add ~/.openviber/agents/${singleAgentId}.yaml or use built-in default.`\n );\n }\n\n if (modelOverride) {\n config = { ...config, model: modelOverride };\n }\n\n const agent = new Agent(config as AgentConfig);\n\n const viberMessages: ViberMessage[] =\n messages && messages.length > 0\n ? messages.map((m) => ({\n role: m.role as \"user\" | \"assistant\" | \"system\",\n content: m.content,\n }))\n : [{ role: \"user\" as const, content: goal }];\n\n const streamResult = await agent.streamText({\n messages: viberMessages,\n metadata: { taskId },\n ...(signal && { abortSignal: signal }),\n });\n\n return { streamResult, agent };\n}\n","/**\n * Terminal streaming module - pipe tmux panes to WebSocket\n *\n * Provides:\n * - List tmux sessions/windows/panes\n * - Attach to a pane (start streaming output)\n * - Send input to a pane\n * - Detach from a pane (stop streaming)\n */\n\nimport { spawn, execSync, ChildProcess } from \"child_process\";\nimport { EventEmitter } from \"events\";\n\nexport interface TmuxPane {\n session: string;\n window: string;\n windowName: string;\n pane: string;\n command: string;\n target: string; // e.g. \"coding:1.0\"\n}\n\nexport interface TmuxSession {\n name: string;\n windows: number;\n attached: boolean;\n}\n\n/**\n * List all tmux sessions\n */\nexport function listSessions(): TmuxSession[] {\n try {\n const out = execSync(\n \"tmux list-sessions -F '#{session_name}|#{session_windows}|#{session_attached}' 2>/dev/null\",\n { encoding: \"utf8\", stdio: \"pipe\" }\n ).trim();\n if (!out) return [];\n return out.split(\"\\n\").map((line) => {\n const [name, windows, attached] = line.split(\"|\");\n return {\n name,\n windows: parseInt(windows, 10) || 0,\n attached: attached === \"1\",\n };\n });\n } catch {\n return [];\n }\n}\n\n/**\n * List all panes across all sessions\n */\nexport function listPanes(): TmuxPane[] {\n try {\n const out = execSync(\n \"tmux list-panes -a -F '#{session_name}|#{window_index}|#{window_name}|#{pane_index}|#{pane_current_command}' 2>/dev/null\",\n { encoding: \"utf8\", stdio: \"pipe\" }\n ).trim();\n if (!out) return [];\n return out.split(\"\\n\").map((line) => {\n const [session, window, windowName, pane, command] = line.split(\"|\");\n return {\n session,\n window,\n windowName,\n pane,\n command,\n target: `${session}:${window}.${pane}`,\n };\n });\n } catch {\n return [];\n }\n}\n\n/**\n * Send keys to a tmux target\n */\nexport function sendKeys(target: string, keys: string, pressEnter = false): boolean {\n try {\n const args = [\"send-keys\", \"-t\", target, keys];\n if (pressEnter) args.push(\"Enter\");\n execSync(`tmux ${args.map((a) => `'${a}'`).join(\" \")}`, {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Capture current pane content (snapshot)\n * -p : print to stdout\n * -e : include escape sequences (preserve colors/styles)\n * -a : include alternate screen (for curses/TTY TUIs)\n * We avoid -J so we don't drop carriage returns that the terminal needs.\n */\nexport function capturePane(target: string, lines = 500): string {\n const cmds = [\n `tmux capture-pane -t '${target}' -pae -S -${lines}`,\n `tmux capture-pane -t '${target}' -pe -S -${lines}`,\n ];\n for (const cmd of cmds) {\n try {\n return execSync(cmd, { encoding: \"utf8\", stdio: \"pipe\" });\n } catch {\n // try next fallback\n }\n }\n return \"\";\n}\n\n/**\n * Resize a tmux pane to requested cols/rows.\n */\nexport function resizePane(target: string, cols: number, rows: number): boolean {\n try {\n execSync(`tmux resize-pane -t '${target}' -x ${cols} -y ${rows}`, {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * TerminalStream - streams a tmux pane's output\n *\n * Uses `tmux pipe-pane` to pipe output to a subprocess that we read from.\n * Emits 'data' events with the output chunks.\n */\nexport class TerminalStream extends EventEmitter {\n private target: string;\n private catProcess: ChildProcess | null = null;\n private pipePath: string;\n private isAttached = false;\n\n constructor(target: string) {\n super();\n this.target = target;\n // Use a unique pipe path per target\n this.pipePath = `/tmp/viber-term-${target.replace(/[^a-zA-Z0-9]/g, \"-\")}-${Date.now()}`;\n }\n\n /**\n * Start streaming the pane output\n */\n async attach(): Promise<boolean> {\n if (this.isAttached) return true;\n\n try {\n // First, capture existing content (history)\n const history = capturePane(this.target, 200);\n if (history) {\n this.emit(\"data\", history);\n }\n\n // Create named pipe\n execSync(`mkfifo '${this.pipePath}' 2>/dev/null || true`, { stdio: \"pipe\" });\n\n // Start cat process to read from the pipe\n this.catProcess = spawn(\"cat\", [this.pipePath], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n\n this.catProcess.stdout?.on(\"data\", (chunk: Buffer) => {\n this.emit(\"data\", chunk.toString());\n });\n\n this.catProcess.on(\"close\", () => {\n this.cleanup();\n });\n\n this.catProcess.on(\"error\", (err) => {\n this.emit(\"error\", err);\n this.cleanup();\n });\n\n // Tell tmux to pipe the pane output to our named pipe\n execSync(`tmux pipe-pane -t '${this.target}' -o 'cat >> ${this.pipePath}'`, {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n\n this.isAttached = true;\n return true;\n } catch (err) {\n this.emit(\"error\", err);\n this.cleanup();\n return false;\n }\n }\n\n /**\n * Stop streaming\n */\n detach(): void {\n if (!this.isAttached) return;\n\n try {\n // Stop tmux pipe\n execSync(`tmux pipe-pane -t '${this.target}'`, { stdio: \"pipe\" });\n } catch {\n // Ignore errors\n }\n\n this.cleanup();\n }\n\n /**\n * Send input to the pane\n */\n sendInput(keys: string): boolean {\n return sendKeys(this.target, keys, false);\n }\n\n private cleanup(): void {\n this.isAttached = false;\n\n if (this.catProcess) {\n this.catProcess.kill();\n this.catProcess = null;\n }\n\n try {\n execSync(`rm -f '${this.pipePath}'`, { stdio: \"pipe\" });\n } catch {\n // Ignore\n }\n\n this.emit(\"close\");\n }\n\n get attached(): boolean {\n return this.isAttached;\n }\n}\n\n/**\n * TerminalManager - manages multiple terminal streams\n */\nexport class TerminalManager {\n private streams: Map<string, TerminalStream> = new Map();\n\n /**\n * List all available terminals\n */\n list(): { sessions: TmuxSession[]; panes: TmuxPane[] } {\n return {\n sessions: listSessions(),\n panes: listPanes(),\n };\n }\n\n /**\n * Attach to a pane and return the stream\n */\n async attach(\n target: string,\n onData: (data: string) => void,\n onClose: () => void\n ): Promise<boolean> {\n // If already attached, just add listeners\n let stream = this.streams.get(target);\n if (stream && stream.attached) {\n stream.on(\"data\", onData);\n stream.on(\"close\", onClose);\n return true;\n }\n\n // Create new stream\n stream = new TerminalStream(target);\n stream.on(\"data\", onData);\n stream.on(\"close\", () => {\n this.streams.delete(target);\n onClose();\n });\n\n const ok = await stream.attach();\n if (ok) {\n this.streams.set(target, stream);\n }\n return ok;\n }\n\n /**\n * Detach from a pane\n */\n detach(target: string): void {\n const stream = this.streams.get(target);\n if (stream) {\n stream.detach();\n this.streams.delete(target);\n }\n }\n\n /**\n * Send input to a pane\n */\n sendInput(target: string, keys: string): boolean {\n // Can send input even without a stream attached\n return sendKeys(target, keys, false);\n }\n\n /**\n * Resize pane to match web terminal\n */\n resize(target: string, cols: number, rows: number): boolean {\n return resizePane(target, cols, rows);\n }\n\n /**\n * Detach all streams\n */\n detachAll(): void {\n for (const stream of this.streams.values()) {\n stream.detach();\n }\n this.streams.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAIY,YAuBC;AA3Bb;AAAA;AAAA;AAIO,IAAK,aAAL,kBAAKA,gBAAL;AACL,MAAAA,YAAA,aAAU;AACV,MAAAA,YAAA,aAAU;AACV,MAAAA,YAAA,eAAY;AACZ,MAAAA,YAAA,YAAS;AACT,MAAAA,YAAA,aAAU;AACV,MAAAA,YAAA,eAAY;AANF,aAAAA;AAAA,OAAA;AAuBL,IAAM,OAAN,MAAM,MAAK;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MAEP,YAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS;AAAA,QACT;AAAA,QACA,WAAW;AAAA,QACX;AAAA,QACA,eAAe,CAAC;AAAA,QAChB,QAAQ,CAAC;AAAA,QACT,OAAO,CAAC;AAAA,QACR,WAAW,CAAC;AAAA,MACd,GAYG;AACD,aAAK,KAAK;AAC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AK,gBAAgB;AACvB,oBAAc,KAAK,cAAc;AACjC,WAAK,iBAAiB;AAAA,IACxB;AAAA,EACF;AAAA;AAAA,EAIQ,oBAA0B;AAChC,QAAI,CAAC,KAAK,gBAAiB;AAE3B,UAAM,WAAW,KAAK,OAAO,qBAAqB;AAClD,YAAQ,IAAI,2BAA2B,QAAQ,OAAO;AAEtD,SAAK,iBAAiB,WAAW,MAAM;AACrC,WAAK,QAAQ;AAAA,IACf,GAAG,QAAQ;AAAA,EACb;AACF;","names":["TaskStatus","config","path","os","import_path","fs","path","import_path","path","yaml","config","path","import_path","dirname","SupabaseStorageAdapter","LocalStorageAdapter","path","fs","import_path","init_local","path","generateShortId","config","SupabaseDatabaseAdapter","init_local","config","path","import_fs","init_base","SpaceStorageFactory","fs","import_zod","import_fs","path","init_base","config","fs","content","stats","files","import_zod","config","import_zod","init_base","config","import_zod","init_base","config","resolve","import_zod","init_base","config","resolve","WebSocket","import_zod","init_base","getServerDataAdapter","config","tools","buildToolMap","getServerDataAdapter","__dirname","fs","path","yaml","import_url","import_meta","__filename","config","config","buildToolMap","import_ai","import_zod","config","startSpace","SpaceStorageFactory","space_exports","init_space","config","buildToolMap","init_space","import_ai","getServerDataAdapter","import_events","import_ws","fs","path","import_url","yaml","import_meta","__filename","__dirname","config","import_child_process","window","config","WebSocket","defaultRegistry"]}