UNPKG

automagik-cli

Version:

Automagik CLI - A powerful command-line interface for interacting with Automagik Hive multi-agent AI systems

141 lines (140 loc) 5.28 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { appConfig } from '../../config/settings.js'; import { resolve } from 'path'; import { writeFile, readFile, mkdir } from 'fs/promises'; import { existsSync } from 'fs'; const SessionContext = createContext(undefined); export const useSession = () => { const context = useContext(SessionContext); if (!context) { throw new Error('useSession must be used within a SessionProvider'); } return context; }; export const SessionProvider = ({ children }) => { const [history, setHistory] = useState([]); const [currentSessionId, setCurrentSessionId] = useState(''); const [nextMessageId, setNextMessageId] = useState(1); // Initialize session useEffect(() => { const initSession = async () => { const sessionId = generateSessionId(); setCurrentSessionId(sessionId); // Ensure session directory exists try { const sessionDir = getSessionDir(); if (!existsSync(sessionDir)) { await mkdir(sessionDir, { recursive: true }); } } catch (error) { console.error('Failed to create session directory:', error); } }; initSession(); }, []); const generateSessionId = useCallback(() => { return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; }, []); const getSessionDir = useCallback(() => { const sessionDir = appConfig.sessionDir.replace('~', process.env.HOME || ''); return resolve(sessionDir); }, []); const getSessionFilePath = useCallback((sessionId) => { return resolve(getSessionDir(), `${sessionId}.json`); }, [getSessionDir]); const addMessage = useCallback((message) => { const newMessage = { ...message, id: nextMessageId, }; setHistory(prev => [...prev, newMessage]); setNextMessageId(prev => prev + 1); // Auto-save if enabled if (appConfig.sessionAutoSave) { setTimeout(() => saveSessionData(), 100); // Debounce saves } }, [nextMessageId]); const clearHistory = useCallback(() => { setHistory([]); setNextMessageId(1); }, []); const saveSessionData = useCallback(async () => { if (!currentSessionId || history.length === 0) { return; } const sessionData = { id: currentSessionId, messages: history, createdAt: history[0]?.timestamp || Date.now(), updatedAt: Date.now(), metadata: { totalMessages: history.length, lastTarget: history[history.length - 1]?.metadata?.target, }, }; try { const filePath = getSessionFilePath(currentSessionId); await writeFile(filePath, JSON.stringify(sessionData, null, 2), 'utf8'); if (appConfig.cliDebug) { console.log(`Session saved: ${filePath}`); } } catch (error) { console.error('Failed to save session:', error); } }, [currentSessionId, history, getSessionFilePath]); const loadSessionData = useCallback(async (sessionId) => { try { const filePath = getSessionFilePath(sessionId); const data = await readFile(filePath, 'utf8'); const sessionData = JSON.parse(data); setHistory(sessionData.messages); setCurrentSessionId(sessionId); setNextMessageId(Math.max(...sessionData.messages.map(m => m.id), 0) + 1); if (appConfig.cliDebug) { console.log(`Session loaded: ${filePath}`); } } catch (error) { console.error('Failed to load session:', error); throw error; } }, [getSessionFilePath]); const createNewSession = useCallback(() => { const newSessionId = generateSessionId(); setCurrentSessionId(newSessionId); setHistory([]); setNextMessageId(1); }, [generateSessionId]); const listSessions = useCallback(async () => { try { const { readdir } = await import('fs/promises'); const sessionDir = getSessionDir(); if (!existsSync(sessionDir)) { return []; } const files = await readdir(sessionDir); return files .filter(file => file.endsWith('.json')) .map(file => file.replace('.json', '')) .sort((a, b) => b.localeCompare(a)); // Most recent first } catch (error) { console.error('Failed to list sessions:', error); return []; } }, [getSessionDir]); const contextValue = { history, currentSessionId, addMessage, clearHistory, saveSession: saveSessionData, loadSession: loadSessionData, createNewSession, listSessions, }; return (_jsx(SessionContext.Provider, { value: contextValue, children: children })); };