nestor-sh 3.5.1 → 3.5.2

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.
@@ -582,7 +582,7 @@ Please change the parent <Route path="${z}"> to <Route path="${z==="/"?"*":`${z}
582
582
  *
583
583
  * This source code is licensed under the ISC license.
584
584
  * See the LICENSE file in the root directory of this source tree.
585
- */const sa=ie("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Pd={en:"English",fr:"Français",es:"Español",de:"Deutsch",pt:"Português",ja:"日本語",zh:"中文",ko:"한국어",ar:"العربية",ru:"Русский",it:"Italiano",nl:"Nederlands"},Kv=["ar"],Vv=Object.keys(Pd);function Wd(n){return Vv.includes(n)}function Yv(n){if(!n)return"en";const i=n.toLowerCase();if(Wd(i))return i;const d=i.split("-")[0];return Wd(d)?d:"en"}const qh={en:{"nav.missions":"Missions","nav.chat":"Chat","nav.history":"History","nav.dashboard":"Dashboard","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Skills","nav.runs":"Runs","nav.approvals":"Approvals","nav.handoffs":"Handoffs","nav.apiKeys":"API Keys","nav.settings":"Settings","nav.users":"Users","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Active Agents","dashboard.runningTasks":"Running Tasks","dashboard.costToday":"Cost Today","dashboard.skillsInstalled":"Skills Installed","dashboard.recentActivity":"Recent Activity","dashboard.quickActions":"Quick Actions","dashboard.systemHealth":"System Health","dashboard.createAgent":"Create Agent","dashboard.runWorkflow":"Run Workflow","dashboard.installSkill":"Install Skill","agents.title":"Agents","agents.create":"Create Agent","agents.empty":"No agents configured yet.","agents.emptyDesc":"Create your first AI agent to get started with automated tasks.","agent.overview":"Overview","agent.runs":"Runs","agent.events":"Events","agent.configuration":"Configuration","agent.budget":"Budget","agent.recentRuns":"Recent Runs","agent.delete":"Delete Agent","agent.start":"Start","agent.stop":"Stop","agent.run":"Run","workflows.title":"Workflows","workflows.create":"Create Workflow","workflows.empty":"No workflows defined yet.","workflows.emptyDesc":"Design your first workflow to orchestrate multiple agents.","workflows.nodes":"{count} nodes","workflows.edit":"Edit","workflow.editor":"Workflow Editor","workflow.addNode":"Add Node","workflow.save":"Save","workflow.run":"Run Workflow","skills.title":"Skills","skills.install":"Install Skill","skills.empty":"No skills installed yet.","skills.emptyDesc":"Browse and install skills to extend your agents' capabilities.","skills.scan":"Scan Directory","skills.source":"Source URL or path","runs.title":"Runs","runs.empty":"No runs recorded yet.","runs.emptyDesc":"Run an agent or workflow to see execution history.","runs.filter":"Filter","run.events":"Events","run.output":"Output","run.cost":"Cost Breakdown","run.duration":"Duration","approvals.title":"Approval Queue","approvals.empty":"No pending approvals.","approvals.emptyDesc":"All clear. Dangerous actions will appear here for review.","approvals.approve":"Approve","approvals.deny":"Deny","approvals.pending":"Pending","nav.analytics":"Analytics","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Memory","nav.goals":"Goals","nav.plans":"Plans","nav.guardrails":"Guardrails","analytics.title":"Cost Analytics","analytics.description":"Track spending, token usage, and budget utilization across agents.","analytics.totalSpend":"Total Spend","analytics.totalRuns":"Total Runs","analytics.avgCostPerRun":"Avg Cost/Run","analytics.monthlyEstimate":"Monthly Estimate","analytics.dailyCosts":"Daily Costs (30 days)","analytics.agentBreakdown":"Cost by Agent","analytics.modelBreakdown":"Cost by Model","analytics.budgetUtilization":"Budget Utilization","analytics.runs":"Runs","analytics.totalCost":"Total Cost","analytics.avgCost":"Avg Cost","analytics.model":"Model","analytics.tokens":"Tokens","analytics.cost":"Cost","analytics.noAgentData":"No agent cost data yet.","analytics.noModelData":"No model cost data yet.","settings.title":"Settings","settings.general":"General","settings.security":"Security","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Save Changes","settings.saved":"Settings saved successfully.","settings.language":"Language","common.loading":"Loading...","common.error":"An error occurred.","common.retry":"Retry","common.cancel":"Cancel","common.save":"Save","common.delete":"Delete","common.close":"Close","common.search":"Search...","common.noResults":"No results found.","common.name":"Name","common.description":"Description","common.status":"Status","common.type":"Type","common.actions":"Actions","common.created":"Created","common.updated":"Updated","status.running":"Running","status.completed":"Completed","status.failed":"Failed","status.pending":"Pending","status.paused":"Paused","status.cancelled":"Cancelled","status.idle":"Idle","trust.builtin":"Built-in","trust.official":"Official","trust.trusted":"Trusted","trust.community":"Community","trust.local":"Local","nav.messaging":"Messaging","messaging.title":"Messaging","messaging.empty":"No messaging adapters configured.","messaging.emptyDesc":"Configure Discord, Slack, or Telegram adapters to get started.","messaging.sendTest":"Send Test Message","messaging.adapter":"Adapter","messaging.channel":"Channel","messaging.selectChannel":"Select a channel","messaging.message":"Message","messaging.messagePlaceholder":"Type a test message...","messaging.send":"Send","messaging.sent":"Message sent successfully.","messaging.recentMessages":"Recent Messages","messaging.noMessages":"No messages yet.","nav.scheduler":"Scheduler","scheduler.title":"Scheduler","scheduler.addSchedule":"Add Schedule","scheduler.empty":"No scheduled agents.","scheduler.emptyDesc":"Schedule agents to run automatically on a cron expression.","scheduler.totalSchedules":"Total Schedules","scheduler.active":"Active","scheduler.paused":"Paused","scheduler.nextRun":"Next Run","scheduler.agent":"Agent","scheduler.schedule":"Schedule","scheduler.lastRun":"Last Run","scheduler.selectAgent":"Select an agent...","scheduler.usePreset":"Use preset","scheduler.useCustom":"Use custom cron","scheduler.pause":"Pause","scheduler.resume":"Resume","scheduler.runHistory":"Run History","nav.evolve":"Evolve","evolve.title":"Evolve","evolve.empty":"No skill candidates found.","evolve.emptyDesc":"Auto-extracted skills from missions will appear here.","evolve.totalCandidates":"Total Candidates","evolve.pending":"Pending","evolve.approved":"Approved","evolve.rejected":"Rejected","evolve.avgConfidence":"Avg Confidence","evolve.all":"All","evolve.source":"Source","evolve.confidence":"Confidence","evolve.preview":"Preview","evolve.edit":"Edit","evolve.approve":"Approve","evolve.reject":"Reject","workflows.run":"Run","workflows.running":"Running...","memory.browse":"Browse","memory.governance":"Governance","memory.governanceTypes":"Memory Types","memory.staleMemories":"Stale Memories","memory.flagged":"flagged","memory.noStale":"No stale memories detected.","memory.ttlEnforcement":"TTL Enforcement","memory.totalMemories":"Total Memories","memory.staleCount":"Stale (>30d)","memory.ttlCandidates":"TTL Candidates"},fr:{"nav.missions":"Missions","nav.chat":"Chat","nav.history":"Historique","nav.dashboard":"Tableau de bord","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Compétences","nav.runs":"Exécutions","nav.approvals":"Approbations","nav.handoffs":"Transferts","nav.apiKeys":"Clés API","nav.settings":"Paramètres","nav.users":"Utilisateurs","nav.prompts":"Prompts","dashboard.title":"Tableau de bord","dashboard.activeAgents":"Agents actifs","dashboard.runningTasks":"Tâches en cours","dashboard.costToday":"Coût aujourd'hui","dashboard.skillsInstalled":"Compétences installées","dashboard.recentActivity":"Activité récente","dashboard.quickActions":"Actions rapides","dashboard.systemHealth":"Santé système","dashboard.createAgent":"Créer un agent","dashboard.runWorkflow":"Lancer un workflow","dashboard.installSkill":"Installer une compétence","agents.title":"Agents","agents.create":"Créer un agent","agents.empty":"Aucun agent configuré.","agents.emptyDesc":"Créez votre premier agent IA pour automatiser vos tâches.","agent.overview":"Aperçu","agent.runs":"Exécutions","agent.events":"Événements","agent.configuration":"Configuration","agent.budget":"Budget","agent.recentRuns":"Exécutions récentes","agent.delete":"Supprimer l'agent","agent.start":"Démarrer","agent.stop":"Arrêter","agent.run":"Exécuter","workflows.title":"Workflows","workflows.create":"Créer un workflow","workflows.empty":"Aucun workflow défini.","workflows.emptyDesc":"Concevez votre premier workflow pour orchestrer vos agents.","workflows.nodes":"{count} nœuds","workflows.edit":"Modifier","workflow.editor":"Éditeur de workflow","workflow.addNode":"Ajouter un nœud","workflow.save":"Enregistrer","workflow.run":"Lancer le workflow","skills.title":"Compétences","skills.install":"Installer","skills.empty":"Aucune compétence installée.","skills.emptyDesc":"Parcourez et installez des compétences pour étendre les capacités de vos agents.","skills.scan":"Scanner un répertoire","skills.source":"URL ou chemin source","runs.title":"Exécutions","runs.empty":"Aucune exécution enregistrée.","runs.emptyDesc":"Lancez un agent ou un workflow pour voir l'historique.","runs.filter":"Filtrer","run.events":"Événements","run.output":"Sortie","run.cost":"Détail des coûts","run.duration":"Durée","approvals.title":"File d'approbation","approvals.empty":"Aucune approbation en attente.","approvals.emptyDesc":"Tout est clair. Les actions dangereuses apparaîtront ici.","approvals.approve":"Approuver","approvals.deny":"Refuser","approvals.pending":"En attente","nav.analytics":"Analytique","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Mémoire","nav.goals":"Objectifs","nav.plans":"Plans","nav.guardrails":"Garde-fous","analytics.title":"Analytique des coûts","analytics.description":"Suivez les dépenses, l'utilisation des tokens et le budget par agent.","analytics.totalSpend":"Dépense totale","analytics.totalRuns":"Total exécutions","analytics.avgCostPerRun":"Coût moyen/exéc.","analytics.monthlyEstimate":"Estimation mensuelle","analytics.dailyCosts":"Coûts quotidiens (30 jours)","analytics.agentBreakdown":"Coûts par agent","analytics.modelBreakdown":"Coûts par modèle","analytics.budgetUtilization":"Utilisation du budget","analytics.runs":"Exécutions","analytics.totalCost":"Coût total","analytics.avgCost":"Coût moyen","analytics.model":"Modèle","analytics.tokens":"Tokens","analytics.cost":"Coût","analytics.noAgentData":"Aucune donnée de coût par agent.","analytics.noModelData":"Aucune donnée de coût par modèle.","settings.title":"Paramètres","settings.general":"Général","settings.security":"Sécurité","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Enregistrer","settings.saved":"Paramètres sauvegardés.","settings.language":"Langue","common.loading":"Chargement...","common.error":"Une erreur est survenue.","common.retry":"Réessayer","common.cancel":"Annuler","common.save":"Enregistrer","common.delete":"Supprimer","common.close":"Fermer","common.search":"Rechercher...","common.noResults":"Aucun résultat.","common.name":"Nom","common.description":"Description","common.status":"Statut","common.type":"Type","common.actions":"Actions","common.created":"Créé","common.updated":"Mis à jour","status.running":"En cours","status.completed":"Terminé","status.failed":"Échoué","status.pending":"En attente","status.paused":"En pause","status.cancelled":"Annulé","status.idle":"Inactif","trust.builtin":"Intégré","trust.official":"Officiel","trust.trusted":"Vérifié","trust.community":"Communautaire","trust.local":"Local","nav.messaging":"Messagerie","messaging.title":"Messagerie","messaging.empty":"Aucun adaptateur de messagerie configuré.","messaging.emptyDesc":"Configurez Discord, Slack ou Telegram pour commencer.","messaging.sendTest":"Envoyer un message test","messaging.adapter":"Adaptateur","messaging.channel":"Canal","messaging.selectChannel":"Sélectionner un canal","messaging.message":"Message","messaging.messagePlaceholder":"Tapez un message test...","messaging.send":"Envoyer","messaging.sent":"Message envoyé avec succès.","messaging.recentMessages":"Messages récents","messaging.noMessages":"Aucun message.","nav.scheduler":"Planificateur","scheduler.title":"Planificateur","scheduler.addSchedule":"Ajouter une planification","scheduler.empty":"Aucun agent planifié.","scheduler.emptyDesc":"Planifiez des agents pour s'exécuter automatiquement via une expression cron.","scheduler.totalSchedules":"Total planifications","scheduler.active":"Actif","scheduler.paused":"En pause","scheduler.nextRun":"Prochaine exéc.","scheduler.agent":"Agent","scheduler.schedule":"Planification","scheduler.lastRun":"Dernière exéc.","scheduler.selectAgent":"Sélectionner un agent...","scheduler.usePreset":"Utiliser un préréglage","scheduler.useCustom":"Cron personnalisé","scheduler.pause":"Mettre en pause","scheduler.resume":"Reprendre","scheduler.runHistory":"Historique des exécutions","nav.evolve":"Évolution","evolve.title":"Évolution","evolve.empty":"Aucun candidat de compétence trouvé.","evolve.emptyDesc":"Les compétences auto-extraites des missions apparaîtront ici.","evolve.totalCandidates":"Total candidats","evolve.pending":"En attente","evolve.approved":"Approuvés","evolve.rejected":"Rejetés","evolve.avgConfidence":"Confiance moy.","evolve.all":"Tous","evolve.source":"Source","evolve.confidence":"Confiance","evolve.preview":"Aperçu","evolve.edit":"Modifier","evolve.approve":"Approuver","evolve.reject":"Rejeter","workflows.run":"Lancer","workflows.running":"En cours...","memory.browse":"Parcourir","memory.governance":"Gouvernance","memory.governanceTypes":"Types de mémoire","memory.staleMemories":"Mémoires obsolètes","memory.flagged":"signalées","memory.noStale":"Aucune mémoire obsolète détectée.","memory.ttlEnforcement":"Application TTL","memory.totalMemories":"Total mémoires","memory.staleCount":"Obsolètes (>30j)","memory.ttlCandidates":"Candidats TTL"},es:{"nav.dashboard":"Panel","nav.agents":"Agentes","nav.workflows":"Flujos de trabajo","nav.skills":"Habilidades","nav.runs":"Ejecuciones","nav.approvals":"Aprobaciones","nav.handoffs":"Transferencias","nav.apiKeys":"Claves API","nav.settings":"Configuración","nav.users":"Usuarios","nav.prompts":"Prompts","dashboard.title":"Panel","dashboard.activeAgents":"Agentes activos","dashboard.runningTasks":"Tareas en ejecución","dashboard.costToday":"Coste hoy","dashboard.skillsInstalled":"Habilidades instaladas","dashboard.recentActivity":"Actividad reciente","dashboard.quickActions":"Acciones rápidas","dashboard.systemHealth":"Estado del sistema","dashboard.createAgent":"Crear agente","dashboard.runWorkflow":"Ejecutar flujo","dashboard.installSkill":"Instalar habilidad","agents.title":"Agentes","agents.create":"Crear agente","agents.empty":"No hay agentes configurados.","agents.emptyDesc":"Crea tu primer agente IA para empezar con tareas automatizadas.","agent.overview":"Resumen","agent.runs":"Ejecuciones","agent.events":"Eventos","agent.configuration":"Configuración","agent.budget":"Presupuesto","agent.recentRuns":"Ejecuciones recientes","agent.delete":"Eliminar agente","agent.start":"Iniciar","agent.stop":"Detener","agent.run":"Ejecutar","workflows.title":"Flujos de trabajo","workflows.create":"Crear flujo","workflows.empty":"No hay flujos definidos.","workflows.emptyDesc":"Diseña tu primer flujo de trabajo para orquestar múltiples agentes.","workflows.nodes":"{count} nodos","workflows.edit":"Editar","workflow.editor":"Editor de flujo","workflow.addNode":"Añadir nodo","workflow.save":"Guardar","workflow.run":"Ejecutar flujo","skills.title":"Habilidades","skills.install":"Instalar","skills.empty":"No hay habilidades instaladas.","skills.emptyDesc":"Explora e instala habilidades para ampliar las capacidades de tus agentes.","skills.scan":"Escanear directorio","skills.source":"URL o ruta de origen","runs.title":"Ejecuciones","runs.empty":"No hay ejecuciones registradas.","runs.emptyDesc":"Ejecuta un agente o flujo para ver el historial.","runs.filter":"Filtrar","run.events":"Eventos","run.output":"Salida","run.cost":"Desglose de costes","run.duration":"Duración","approvals.title":"Cola de aprobación","approvals.empty":"Sin aprobaciones pendientes.","approvals.emptyDesc":"Todo despejado. Las acciones peligrosas aparecerán aquí.","approvals.approve":"Aprobar","approvals.deny":"Denegar","approvals.pending":"Pendiente","nav.analytics":"Analíticas","nav.budget":"Presupuesto","nav.traces":"Trazas","nav.memory":"Memoria","nav.goals":"Objetivos","nav.plans":"Planes","nav.guardrails":"Salvaguardas","analytics.title":"Analíticas de coste","analytics.description":"Seguimiento de gastos, uso de tokens y presupuesto por agente.","analytics.totalSpend":"Gasto total","analytics.totalRuns":"Total ejecuciones","analytics.avgCostPerRun":"Coste medio/ejec.","analytics.monthlyEstimate":"Estimación mensual","analytics.dailyCosts":"Costes diarios (30 días)","analytics.agentBreakdown":"Coste por agente","analytics.modelBreakdown":"Coste por modelo","analytics.budgetUtilization":"Uso del presupuesto","analytics.runs":"Ejecuciones","analytics.totalCost":"Coste total","analytics.avgCost":"Coste medio","analytics.model":"Modelo","analytics.tokens":"Tokens","analytics.cost":"Coste","analytics.noAgentData":"Sin datos de coste por agente.","analytics.noModelData":"Sin datos de coste por modelo.","settings.title":"Configuración","settings.general":"General","settings.security":"Seguridad","settings.llm":"LLM","settings.budget":"Presupuesto","settings.save":"Guardar cambios","settings.saved":"Configuración guardada.","settings.language":"Idioma","common.loading":"Cargando...","common.error":"Se produjo un error.","common.retry":"Reintentar","common.cancel":"Cancelar","common.save":"Guardar","common.delete":"Eliminar","common.close":"Cerrar","common.search":"Buscar...","common.noResults":"Sin resultados.","common.name":"Nombre","common.description":"Descripción","common.status":"Estado","common.type":"Tipo","common.actions":"Acciones","common.created":"Creado","common.updated":"Actualizado","status.running":"En ejecución","status.completed":"Completado","status.failed":"Fallido","status.pending":"Pendiente","status.paused":"En pausa","status.cancelled":"Cancelado","status.idle":"Inactivo","trust.builtin":"Integrado","trust.official":"Oficial","trust.trusted":"Verificado","trust.community":"Comunidad","trust.local":"Local"},de:{"nav.dashboard":"Dashboard","nav.agents":"Agenten","nav.workflows":"Workflows","nav.skills":"Fähigkeiten","nav.runs":"Ausführungen","nav.approvals":"Genehmigungen","nav.handoffs":"Übergaben","nav.apiKeys":"API-Schlüssel","nav.settings":"Einstellungen","nav.users":"Benutzer","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Aktive Agenten","dashboard.runningTasks":"Laufende Aufgaben","dashboard.costToday":"Kosten heute","dashboard.skillsInstalled":"Installierte Fähigkeiten","dashboard.recentActivity":"Letzte Aktivität","dashboard.quickActions":"Schnellaktionen","dashboard.systemHealth":"Systemstatus","dashboard.createAgent":"Agent erstellen","dashboard.runWorkflow":"Workflow starten","dashboard.installSkill":"Fähigkeit installieren","agents.title":"Agenten","agents.create":"Agent erstellen","agents.empty":"Keine Agenten konfiguriert.","agents.emptyDesc":"Erstellen Sie Ihren ersten KI-Agenten für automatisierte Aufgaben.","agent.overview":"Übersicht","agent.runs":"Ausführungen","agent.events":"Ereignisse","agent.configuration":"Konfiguration","agent.budget":"Budget","agent.recentRuns":"Letzte Ausführungen","agent.delete":"Agent löschen","agent.start":"Starten","agent.stop":"Stoppen","agent.run":"Ausführen","workflows.title":"Workflows","workflows.create":"Workflow erstellen","workflows.empty":"Keine Workflows definiert.","workflows.emptyDesc":"Entwerfen Sie Ihren ersten Workflow zur Orchestrierung mehrerer Agenten.","workflows.nodes":"{count} Knoten","workflows.edit":"Bearbeiten","workflow.editor":"Workflow-Editor","workflow.addNode":"Knoten hinzufügen","workflow.save":"Speichern","workflow.run":"Workflow starten","skills.title":"Fähigkeiten","skills.install":"Installieren","skills.empty":"Keine Fähigkeiten installiert.","skills.emptyDesc":"Durchsuchen und installieren Sie Fähigkeiten, um die Möglichkeiten Ihrer Agenten zu erweitern.","skills.scan":"Verzeichnis scannen","skills.source":"Quell-URL oder -pfad","runs.title":"Ausführungen","runs.empty":"Keine Ausführungen aufgezeichnet.","runs.emptyDesc":"Starten Sie einen Agenten oder Workflow, um den Verlauf anzuzeigen.","runs.filter":"Filtern","run.events":"Ereignisse","run.output":"Ausgabe","run.cost":"Kostenaufschlüsselung","run.duration":"Dauer","approvals.title":"Genehmigungswarteschlange","approvals.empty":"Keine ausstehenden Genehmigungen.","approvals.emptyDesc":"Alles in Ordnung. Gefährliche Aktionen erscheinen hier zur Überprüfung.","approvals.approve":"Genehmigen","approvals.deny":"Ablehnen","approvals.pending":"Ausstehend","nav.analytics":"Analytik","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Speicher","nav.goals":"Ziele","nav.plans":"Pläne","nav.guardrails":"Leitplanken","analytics.title":"Kostenanalytik","analytics.description":"Ausgaben, Token-Nutzung und Budgetauslastung pro Agent verfolgen.","analytics.totalSpend":"Gesamtausgaben","analytics.totalRuns":"Gesamtausführungen","analytics.avgCostPerRun":"Ø Kosten/Ausf.","analytics.monthlyEstimate":"Monatliche Schätzung","analytics.dailyCosts":"Tägliche Kosten (30 Tage)","analytics.agentBreakdown":"Kosten pro Agent","analytics.modelBreakdown":"Kosten pro Modell","analytics.budgetUtilization":"Budgetauslastung","analytics.runs":"Ausführungen","analytics.totalCost":"Gesamtkosten","analytics.avgCost":"Ø Kosten","analytics.model":"Modell","analytics.tokens":"Tokens","analytics.cost":"Kosten","analytics.noAgentData":"Noch keine Kostendaten pro Agent.","analytics.noModelData":"Noch keine Kostendaten pro Modell.","settings.title":"Einstellungen","settings.general":"Allgemein","settings.security":"Sicherheit","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Änderungen speichern","settings.saved":"Einstellungen gespeichert.","settings.language":"Sprache","common.loading":"Laden...","common.error":"Ein Fehler ist aufgetreten.","common.retry":"Erneut versuchen","common.cancel":"Abbrechen","common.save":"Speichern","common.delete":"Löschen","common.close":"Schließen","common.search":"Suchen...","common.noResults":"Keine Ergebnisse.","common.name":"Name","common.description":"Beschreibung","common.status":"Status","common.type":"Typ","common.actions":"Aktionen","common.created":"Erstellt","common.updated":"Aktualisiert","status.running":"Läuft","status.completed":"Abgeschlossen","status.failed":"Fehlgeschlagen","status.pending":"Ausstehend","status.paused":"Pausiert","status.cancelled":"Abgebrochen","status.idle":"Inaktiv","trust.builtin":"Integriert","trust.official":"Offiziell","trust.trusted":"Vertrauenswürdig","trust.community":"Community","trust.local":"Lokal"},pt:{"nav.dashboard":"Painel","nav.agents":"Agentes","nav.workflows":"Fluxos de trabalho","nav.skills":"Habilidades","nav.runs":"Execuções","nav.approvals":"Aprovações","nav.handoffs":"Transferências","nav.apiKeys":"Chaves API","nav.settings":"Configurações","nav.users":"Usuários","nav.prompts":"Prompts","dashboard.title":"Painel","dashboard.activeAgents":"Agentes ativos","dashboard.runningTasks":"Tarefas em execução","dashboard.costToday":"Custo hoje","dashboard.skillsInstalled":"Habilidades instaladas","dashboard.recentActivity":"Atividade recente","dashboard.quickActions":"Ações rápidas","dashboard.systemHealth":"Saúde do sistema","dashboard.createAgent":"Criar agente","dashboard.runWorkflow":"Executar fluxo","dashboard.installSkill":"Instalar habilidade","agents.title":"Agentes","agents.create":"Criar agente","agents.empty":"Nenhum agente configurado.","agents.emptyDesc":"Crie seu primeiro agente de IA para começar com tarefas automatizadas.","agent.overview":"Visão geral","agent.runs":"Execuções","agent.events":"Eventos","agent.configuration":"Configuração","agent.budget":"Orçamento","agent.recentRuns":"Execuções recentes","agent.delete":"Excluir agente","agent.start":"Iniciar","agent.stop":"Parar","agent.run":"Executar","workflows.title":"Fluxos de trabalho","workflows.create":"Criar fluxo","workflows.empty":"Nenhum fluxo definido.","workflows.emptyDesc":"Projete seu primeiro fluxo de trabalho para orquestrar múltiplos agentes.","workflows.nodes":"{count} nós","workflows.edit":"Editar","workflow.editor":"Editor de fluxo","workflow.addNode":"Adicionar nó","workflow.save":"Salvar","workflow.run":"Executar fluxo","skills.title":"Habilidades","skills.install":"Instalar","skills.empty":"Nenhuma habilidade instalada.","skills.emptyDesc":"Explore e instale habilidades para ampliar as capacidades dos seus agentes.","skills.scan":"Escanear diretório","skills.source":"URL ou caminho de origem","runs.title":"Execuções","runs.empty":"Nenhuma execução registrada.","runs.emptyDesc":"Execute um agente ou fluxo para ver o histórico.","runs.filter":"Filtrar","run.events":"Eventos","run.output":"Saída","run.cost":"Detalhamento de custos","run.duration":"Duração","approvals.title":"Fila de aprovação","approvals.empty":"Sem aprovações pendentes.","approvals.emptyDesc":"Tudo limpo. Ações perigosas aparecerão aqui para revisão.","approvals.approve":"Aprovar","approvals.deny":"Negar","approvals.pending":"Pendente","nav.analytics":"Análises","nav.budget":"Orçamento","nav.traces":"Rastros","nav.memory":"Memória","nav.goals":"Objetivos","nav.plans":"Planos","nav.guardrails":"Proteções","analytics.title":"Análise de custos","analytics.description":"Acompanhe gastos, uso de tokens e orçamento por agente.","analytics.totalSpend":"Gasto total","analytics.totalRuns":"Total de execuções","analytics.avgCostPerRun":"Custo médio/exec.","analytics.monthlyEstimate":"Estimativa mensal","analytics.dailyCosts":"Custos diários (30 dias)","analytics.agentBreakdown":"Custo por agente","analytics.modelBreakdown":"Custo por modelo","analytics.budgetUtilization":"Utilização do orçamento","analytics.runs":"Execuções","analytics.totalCost":"Custo total","analytics.avgCost":"Custo médio","analytics.model":"Modelo","analytics.tokens":"Tokens","analytics.cost":"Custo","analytics.noAgentData":"Sem dados de custo por agente.","analytics.noModelData":"Sem dados de custo por modelo.","settings.title":"Configurações","settings.general":"Geral","settings.security":"Segurança","settings.llm":"LLM","settings.budget":"Orçamento","settings.save":"Salvar alterações","settings.saved":"Configurações salvas.","settings.language":"Idioma","common.loading":"Carregando...","common.error":"Ocorreu um erro.","common.retry":"Tentar novamente","common.cancel":"Cancelar","common.save":"Salvar","common.delete":"Excluir","common.close":"Fechar","common.search":"Pesquisar...","common.noResults":"Nenhum resultado.","common.name":"Nome","common.description":"Descrição","common.status":"Status","common.type":"Tipo","common.actions":"Ações","common.created":"Criado","common.updated":"Atualizado","status.running":"Em execução","status.completed":"Concluído","status.failed":"Falhou","status.pending":"Pendente","status.paused":"Pausado","status.cancelled":"Cancelado","status.idle":"Inativo","trust.builtin":"Integrado","trust.official":"Oficial","trust.trusted":"Verificado","trust.community":"Comunidade","trust.local":"Local"},ja:{"nav.dashboard":"ダッシュボード","nav.agents":"エージェント","nav.workflows":"ワークフロー","nav.skills":"スキル","nav.runs":"実行履歴","nav.approvals":"承認","nav.handoffs":"引き継ぎ","nav.apiKeys":"APIキー","nav.settings":"設定","nav.users":"ユーザー","nav.prompts":"プロンプト","dashboard.title":"ダッシュボード","dashboard.activeAgents":"アクティブなエージェント","dashboard.runningTasks":"実行中のタスク","dashboard.costToday":"本日のコスト","dashboard.skillsInstalled":"インストール済みスキル","dashboard.recentActivity":"最近のアクティビティ","dashboard.quickActions":"クイックアクション","dashboard.systemHealth":"システム状態","dashboard.createAgent":"エージェント作成","dashboard.runWorkflow":"ワークフロー実行","dashboard.installSkill":"スキルインストール","agents.title":"エージェント","agents.create":"エージェント作成","agents.empty":"エージェントが構成されていません。","agents.emptyDesc":"最初のAIエージェントを作成して自動化タスクを始めましょう。","agent.overview":"概要","agent.runs":"実行履歴","agent.events":"イベント","agent.configuration":"構成","agent.budget":"予算","agent.recentRuns":"最近の実行","agent.delete":"エージェント削除","agent.start":"開始","agent.stop":"停止","agent.run":"実行","workflows.title":"ワークフロー","workflows.create":"ワークフロー作成","workflows.empty":"ワークフローが定義されていません。","workflows.emptyDesc":"最初のワークフローを設計して複数のエージェントをオーケストレーションしましょう。","workflows.nodes":"{count} ノード","workflows.edit":"編集","workflow.editor":"ワークフローエディタ","workflow.addNode":"ノード追加","workflow.save":"保存","workflow.run":"ワークフロー実行","skills.title":"スキル","skills.install":"インストール","skills.empty":"スキルがインストールされていません。","skills.emptyDesc":"スキルを参照・インストールしてエージェントの機能を拡張しましょう。","skills.scan":"ディレクトリスキャン","skills.source":"ソースURLまたはパス","runs.title":"実行履歴","runs.empty":"実行記録がありません。","runs.emptyDesc":"エージェントまたはワークフローを実行して履歴を確認しましょう。","runs.filter":"フィルター","run.events":"イベント","run.output":"出力","run.cost":"コスト内訳","run.duration":"所要時間","approvals.title":"承認キュー","approvals.empty":"保留中の承認はありません。","approvals.emptyDesc":"問題なし。危険なアクションはここに表示されます。","approvals.approve":"承認","approvals.deny":"拒否","approvals.pending":"保留中","nav.analytics":"アナリティクス","nav.budget":"予算","nav.traces":"トレース","nav.memory":"メモリ","nav.goals":"目標","nav.plans":"プラン","nav.guardrails":"ガードレール","analytics.title":"コスト分析","analytics.description":"エージェントごとの支出、トークン使用量、予算利用状況を追跡。","analytics.totalSpend":"総支出","analytics.totalRuns":"総実行数","analytics.avgCostPerRun":"平均コスト/実行","analytics.monthlyEstimate":"月間見積もり","analytics.dailyCosts":"日次コスト(30日間)","analytics.agentBreakdown":"エージェント別コスト","analytics.modelBreakdown":"モデル別コスト","analytics.budgetUtilization":"予算利用率","analytics.runs":"実行回数","analytics.totalCost":"総コスト","analytics.avgCost":"平均コスト","analytics.model":"モデル","analytics.tokens":"トークン","analytics.cost":"コスト","analytics.noAgentData":"エージェントコストデータがまだありません。","analytics.noModelData":"モデルコストデータがまだありません。","settings.title":"設定","settings.general":"一般","settings.security":"セキュリティ","settings.llm":"LLM","settings.budget":"予算","settings.save":"変更を保存","settings.saved":"設定が保存されました。","settings.language":"言語","common.loading":"読み込み中...","common.error":"エラーが発生しました。","common.retry":"再試行","common.cancel":"キャンセル","common.save":"保存","common.delete":"削除","common.close":"閉じる","common.search":"検索...","common.noResults":"結果が見つかりません。","common.name":"名前","common.description":"説明","common.status":"ステータス","common.type":"タイプ","common.actions":"アクション","common.created":"作成日","common.updated":"更新日","status.running":"実行中","status.completed":"完了","status.failed":"失敗","status.pending":"保留中","status.paused":"一時停止","status.cancelled":"キャンセル済み","status.idle":"アイドル","trust.builtin":"組み込み","trust.official":"公式","trust.trusted":"信頼済み","trust.community":"コミュニティ","trust.local":"ローカル"},zh:{"nav.dashboard":"仪表盘","nav.agents":"代理","nav.workflows":"工作流","nav.skills":"技能","nav.runs":"执行记录","nav.approvals":"审批","nav.handoffs":"交接","nav.apiKeys":"API密钥","nav.settings":"设置","nav.users":"用户","nav.prompts":"提示词","dashboard.title":"仪表盘","dashboard.activeAgents":"活跃代理","dashboard.runningTasks":"运行中的任务","dashboard.costToday":"今日费用","dashboard.skillsInstalled":"已安装技能","dashboard.recentActivity":"最近活动","dashboard.quickActions":"快捷操作","dashboard.systemHealth":"系统状态","dashboard.createAgent":"创建代理","dashboard.runWorkflow":"运行工作流","dashboard.installSkill":"安装技能","agents.title":"代理","agents.create":"创建代理","agents.empty":"尚无已配置的代理。","agents.emptyDesc":"创建您的第一个AI代理以开始自动化任务。","agent.overview":"概览","agent.runs":"执行记录","agent.events":"事件","agent.configuration":"配置","agent.budget":"预算","agent.recentRuns":"最近执行","agent.delete":"删除代理","agent.start":"启动","agent.stop":"停止","agent.run":"运行","workflows.title":"工作流","workflows.create":"创建工作流","workflows.empty":"尚无已定义的工作流。","workflows.emptyDesc":"设计您的第一个工作流以编排多个代理。","workflows.nodes":"{count} 个节点","workflows.edit":"编辑","workflow.editor":"工作流编辑器","workflow.addNode":"添加节点","workflow.save":"保存","workflow.run":"运行工作流","skills.title":"技能","skills.install":"安装","skills.empty":"尚无已安装的技能。","skills.emptyDesc":"浏览并安装技能以扩展代理的能力。","skills.scan":"扫描目录","skills.source":"源URL或路径","runs.title":"执行记录","runs.empty":"尚无执行记录。","runs.emptyDesc":"运行代理或工作流以查看执行历史。","runs.filter":"筛选","run.events":"事件","run.output":"输出","run.cost":"费用明细","run.duration":"持续时间","approvals.title":"审批队列","approvals.empty":"没有待审批项。","approvals.emptyDesc":"一切正常。危险操作将在此显示以供审查。","approvals.approve":"批准","approvals.deny":"拒绝","approvals.pending":"待处理","nav.analytics":"分析","nav.budget":"预算","nav.traces":"追踪","nav.memory":"记忆","nav.goals":"目标","nav.plans":"计划","nav.guardrails":"护栏","analytics.title":"费用分析","analytics.description":"追踪各代理的支出、令牌使用量和预算利用率。","analytics.totalSpend":"总支出","analytics.totalRuns":"总执行次数","analytics.avgCostPerRun":"平均费用/次","analytics.monthlyEstimate":"月度估算","analytics.dailyCosts":"每日费用(30天)","analytics.agentBreakdown":"按代理的费用","analytics.modelBreakdown":"按模型的费用","analytics.budgetUtilization":"预算利用率","analytics.runs":"执行次数","analytics.totalCost":"总费用","analytics.avgCost":"平均费用","analytics.model":"模型","analytics.tokens":"令牌","analytics.cost":"费用","analytics.noAgentData":"尚无代理费用数据。","analytics.noModelData":"尚无模型费用数据。","settings.title":"设置","settings.general":"通用","settings.security":"安全","settings.llm":"LLM","settings.budget":"预算","settings.save":"保存更改","settings.saved":"设置已保存。","settings.language":"语言","common.loading":"加载中...","common.error":"发生错误。","common.retry":"重试","common.cancel":"取消","common.save":"保存","common.delete":"删除","common.close":"关闭","common.search":"搜索...","common.noResults":"未找到结果。","common.name":"名称","common.description":"描述","common.status":"状态","common.type":"类型","common.actions":"操作","common.created":"创建时间","common.updated":"更新时间","status.running":"运行中","status.completed":"已完成","status.failed":"失败","status.pending":"待处理","status.paused":"已暂停","status.cancelled":"已取消","status.idle":"空闲","trust.builtin":"内置","trust.official":"官方","trust.trusted":"受信任","trust.community":"社区","trust.local":"本地"},ko:{"nav.dashboard":"대시보드","nav.agents":"에이전트","nav.workflows":"워크플로우","nav.skills":"스킬","nav.runs":"실행 기록","nav.approvals":"승인","nav.handoffs":"인수인계","nav.apiKeys":"API 키","nav.settings":"설정","nav.users":"사용자","nav.prompts":"프롬프트","dashboard.title":"대시보드","dashboard.activeAgents":"활성 에이전트","dashboard.runningTasks":"실행 중인 작업","dashboard.costToday":"오늘 비용","dashboard.skillsInstalled":"설치된 스킬","dashboard.recentActivity":"최근 활동","dashboard.quickActions":"빠른 작업","dashboard.systemHealth":"시스템 상태","dashboard.createAgent":"에이전트 생성","dashboard.runWorkflow":"워크플로우 실행","dashboard.installSkill":"스킬 설치","agents.title":"에이전트","agents.create":"에이전트 생성","agents.empty":"구성된 에이전트가 없습니다.","agents.emptyDesc":"첫 번째 AI 에이전트를 만들어 자동화 작업을 시작하세요.","agent.overview":"개요","agent.runs":"실행 기록","agent.events":"이벤트","agent.configuration":"구성","agent.budget":"예산","agent.recentRuns":"최근 실행","agent.delete":"에이전트 삭제","agent.start":"시작","agent.stop":"중지","agent.run":"실행","workflows.title":"워크플로우","workflows.create":"워크플로우 생성","workflows.empty":"정의된 워크플로우가 없습니다.","workflows.emptyDesc":"첫 번째 워크플로우를 설계하여 여러 에이전트를 조율하세요.","workflows.nodes":"{count}개 노드","workflows.edit":"편집","workflow.editor":"워크플로우 편집기","workflow.addNode":"노드 추가","workflow.save":"저장","workflow.run":"워크플로우 실행","skills.title":"스킬","skills.install":"설치","skills.empty":"설치된 스킬이 없습니다.","skills.emptyDesc":"스킬을 탐색하고 설치하여 에이전트의 기능을 확장하세요.","skills.scan":"디렉토리 스캔","skills.source":"소스 URL 또는 경로","runs.title":"실행 기록","runs.empty":"기록된 실행이 없습니다.","runs.emptyDesc":"에이전트 또는 워크플로우를 실행하여 실행 기록을 확인하세요.","runs.filter":"필터","run.events":"이벤트","run.output":"출력","run.cost":"비용 내역","run.duration":"소요 시간","approvals.title":"승인 대기열","approvals.empty":"대기 중인 승인이 없습니다.","approvals.emptyDesc":"문제 없음. 위험한 작업은 여기에 검토를 위해 표시됩니다.","approvals.approve":"승인","approvals.deny":"거부","approvals.pending":"대기 중","nav.analytics":"분석","nav.budget":"예산","nav.traces":"추적","nav.memory":"메모리","nav.goals":"목표","nav.plans":"계획","nav.guardrails":"가드레일","analytics.title":"비용 분석","analytics.description":"에이전트별 지출, 토큰 사용량 및 예산 활용도를 추적합니다.","analytics.totalSpend":"총 지출","analytics.totalRuns":"총 실행 수","analytics.avgCostPerRun":"평균 비용/실행","analytics.monthlyEstimate":"월간 추정","analytics.dailyCosts":"일별 비용 (30일)","analytics.agentBreakdown":"에이전트별 비용","analytics.modelBreakdown":"모델별 비용","analytics.budgetUtilization":"예산 활용률","analytics.runs":"실행 횟수","analytics.totalCost":"총 비용","analytics.avgCost":"평균 비용","analytics.model":"모델","analytics.tokens":"토큰","analytics.cost":"비용","analytics.noAgentData":"에이전트 비용 데이터가 없습니다.","analytics.noModelData":"모델 비용 데이터가 없습니다.","settings.title":"설정","settings.general":"일반","settings.security":"보안","settings.llm":"LLM","settings.budget":"예산","settings.save":"변경 사항 저장","settings.saved":"설정이 저장되었습니다.","settings.language":"언어","common.loading":"로딩 중...","common.error":"오류가 발생했습니다.","common.retry":"재시도","common.cancel":"취소","common.save":"저장","common.delete":"삭제","common.close":"닫기","common.search":"검색...","common.noResults":"결과를 찾을 수 없습니다.","common.name":"이름","common.description":"설명","common.status":"상태","common.type":"유형","common.actions":"작업","common.created":"생성일","common.updated":"수정일","status.running":"실행 중","status.completed":"완료","status.failed":"실패","status.pending":"대기 중","status.paused":"일시 중지","status.cancelled":"취소됨","status.idle":"유휴","trust.builtin":"내장","trust.official":"공식","trust.trusted":"신뢰됨","trust.community":"커뮤니티","trust.local":"로컬"},ar:{"nav.dashboard":"لوحة التحكم","nav.agents":"الوكلاء","nav.workflows":"مسارات العمل","nav.skills":"المهارات","nav.runs":"عمليات التنفيذ","nav.approvals":"الموافقات","nav.handoffs":"التسليمات","nav.apiKeys":"مفاتيح API","nav.settings":"الإعدادات","nav.users":"المستخدمون","nav.prompts":"التعليمات","dashboard.title":"لوحة التحكم","dashboard.activeAgents":"الوكلاء النشطون","dashboard.runningTasks":"المهام قيد التشغيل","dashboard.costToday":"تكلفة اليوم","dashboard.skillsInstalled":"المهارات المثبتة","dashboard.recentActivity":"النشاط الأخير","dashboard.quickActions":"إجراءات سريعة","dashboard.systemHealth":"حالة النظام","dashboard.createAgent":"إنشاء وكيل","dashboard.runWorkflow":"تشغيل مسار عمل","dashboard.installSkill":"تثبيت مهارة","agents.title":"الوكلاء","agents.create":"إنشاء وكيل","agents.empty":"لا توجد وكلاء مهيأة بعد.","agents.emptyDesc":"أنشئ أول وكيل ذكاء اصطناعي لبدء المهام الآلية.","agent.overview":"نظرة عامة","agent.runs":"عمليات التنفيذ","agent.events":"الأحداث","agent.configuration":"التكوين","agent.budget":"الميزانية","agent.recentRuns":"آخر عمليات التنفيذ","agent.delete":"حذف الوكيل","agent.start":"بدء","agent.stop":"إيقاف","agent.run":"تشغيل","workflows.title":"مسارات العمل","workflows.create":"إنشاء مسار عمل","workflows.empty":"لا توجد مسارات عمل معرّفة بعد.","workflows.emptyDesc":"صمّم أول مسار عمل لتنسيق عدة وكلاء.","workflows.nodes":"{count} عقدة","workflows.edit":"تعديل","workflow.editor":"محرر مسار العمل","workflow.addNode":"إضافة عقدة","workflow.save":"حفظ","workflow.run":"تشغيل مسار العمل","skills.title":"المهارات","skills.install":"تثبيت","skills.empty":"لا توجد مهارات مثبتة بعد.","skills.emptyDesc":"تصفّح وثبّت المهارات لتوسيع قدرات وكلائك.","skills.scan":"فحص المجلد","skills.source":"عنوان URL أو مسار المصدر","runs.title":"عمليات التنفيذ","runs.empty":"لا توجد عمليات تنفيذ مسجلة بعد.","runs.emptyDesc":"شغّل وكيلًا أو مسار عمل لعرض سجل التنفيذ.","runs.filter":"تصفية","run.events":"الأحداث","run.output":"المخرجات","run.cost":"تفصيل التكاليف","run.duration":"المدة","approvals.title":"قائمة الموافقات","approvals.empty":"لا توجد موافقات معلقة.","approvals.emptyDesc":"كل شيء على ما يرام. ستظهر الإجراءات الخطيرة هنا للمراجعة.","approvals.approve":"موافقة","approvals.deny":"رفض","approvals.pending":"معلّق","nav.analytics":"التحليلات","nav.budget":"الميزانية","nav.traces":"التتبع","nav.memory":"الذاكرة","nav.goals":"الأهداف","nav.plans":"الخطط","nav.guardrails":"الحواجز","analytics.title":"تحليل التكاليف","analytics.description":"تتبع الإنفاق واستخدام الرموز وميزانية كل وكيل.","analytics.totalSpend":"إجمالي الإنفاق","analytics.totalRuns":"إجمالي عمليات التنفيذ","analytics.avgCostPerRun":"متوسط التكلفة/تنفيذ","analytics.monthlyEstimate":"التقدير الشهري","analytics.dailyCosts":"التكاليف اليومية (30 يومًا)","analytics.agentBreakdown":"التكلفة حسب الوكيل","analytics.modelBreakdown":"التكلفة حسب النموذج","analytics.budgetUtilization":"استخدام الميزانية","analytics.runs":"عمليات التنفيذ","analytics.totalCost":"التكلفة الإجمالية","analytics.avgCost":"متوسط التكلفة","analytics.model":"النموذج","analytics.tokens":"الرموز","analytics.cost":"التكلفة","analytics.noAgentData":"لا توجد بيانات تكلفة للوكلاء بعد.","analytics.noModelData":"لا توجد بيانات تكلفة للنماذج بعد.","settings.title":"الإعدادات","settings.general":"عام","settings.security":"الأمان","settings.llm":"LLM","settings.budget":"الميزانية","settings.save":"حفظ التغييرات","settings.saved":"تم حفظ الإعدادات بنجاح.","settings.language":"اللغة","common.loading":"جارٍ التحميل...","common.error":"حدث خطأ.","common.retry":"إعادة المحاولة","common.cancel":"إلغاء","common.save":"حفظ","common.delete":"حذف","common.close":"إغلاق","common.search":"بحث...","common.noResults":"لم يتم العثور على نتائج.","common.name":"الاسم","common.description":"الوصف","common.status":"الحالة","common.type":"النوع","common.actions":"الإجراءات","common.created":"تاريخ الإنشاء","common.updated":"تاريخ التحديث","status.running":"قيد التشغيل","status.completed":"مكتمل","status.failed":"فشل","status.pending":"معلّق","status.paused":"متوقف مؤقتًا","status.cancelled":"ملغى","status.idle":"خامل","trust.builtin":"مدمج","trust.official":"رسمي","trust.trusted":"موثوق","trust.community":"مجتمعي","trust.local":"محلي"},ru:{"nav.dashboard":"Панель управления","nav.agents":"Агенты","nav.workflows":"Рабочие процессы","nav.skills":"Навыки","nav.runs":"Запуски","nav.approvals":"Одобрения","nav.handoffs":"Передачи","nav.apiKeys":"API-ключи","nav.settings":"Настройки","nav.users":"Пользователи","nav.prompts":"Промпты","dashboard.title":"Панель управления","dashboard.activeAgents":"Активные агенты","dashboard.runningTasks":"Запущенные задачи","dashboard.costToday":"Расходы сегодня","dashboard.skillsInstalled":"Установленные навыки","dashboard.recentActivity":"Последняя активность","dashboard.quickActions":"Быстрые действия","dashboard.systemHealth":"Состояние системы","dashboard.createAgent":"Создать агента","dashboard.runWorkflow":"Запустить процесс","dashboard.installSkill":"Установить навык","agents.title":"Агенты","agents.create":"Создать агента","agents.empty":"Нет настроенных агентов.","agents.emptyDesc":"Создайте первого ИИ-агента для автоматизации задач.","agent.overview":"Обзор","agent.runs":"Запуски","agent.events":"События","agent.configuration":"Конфигурация","agent.budget":"Бюджет","agent.recentRuns":"Последние запуски","agent.delete":"Удалить агента","agent.start":"Запустить","agent.stop":"Остановить","agent.run":"Выполнить","workflows.title":"Рабочие процессы","workflows.create":"Создать процесс","workflows.empty":"Нет определённых процессов.","workflows.emptyDesc":"Создайте первый рабочий процесс для оркестрации агентов.","workflows.nodes":"{count} узлов","workflows.edit":"Редактировать","workflow.editor":"Редактор процессов","workflow.addNode":"Добавить узел","workflow.save":"Сохранить","workflow.run":"Запустить процесс","skills.title":"Навыки","skills.install":"Установить","skills.empty":"Нет установленных навыков.","skills.emptyDesc":"Просматривайте и устанавливайте навыки для расширения возможностей агентов.","skills.scan":"Сканировать каталог","skills.source":"URL или путь к источнику","runs.title":"Запуски","runs.empty":"Нет записей о запусках.","runs.emptyDesc":"Запустите агента или процесс, чтобы увидеть историю выполнения.","runs.filter":"Фильтр","run.events":"События","run.output":"Вывод","run.cost":"Разбивка стоимости","run.duration":"Длительность","approvals.title":"Очередь одобрений","approvals.empty":"Нет ожидающих одобрений.","approvals.emptyDesc":"Всё в порядке. Опасные действия появятся здесь для проверки.","approvals.approve":"Одобрить","approvals.deny":"Отклонить","approvals.pending":"Ожидает","nav.analytics":"Аналитика","nav.budget":"Бюджет","nav.traces":"Трассировки","nav.memory":"Память","nav.goals":"Цели","nav.plans":"Планы","nav.guardrails":"Ограждения","analytics.title":"Аналитика расходов","analytics.description":"Отслеживание расходов, использования токенов и бюджета по агентам.","analytics.totalSpend":"Общие расходы","analytics.totalRuns":"Всего запусков","analytics.avgCostPerRun":"Ср. стоимость/запуск","analytics.monthlyEstimate":"Месячная оценка","analytics.dailyCosts":"Ежедневные расходы (30 дней)","analytics.agentBreakdown":"Расходы по агентам","analytics.modelBreakdown":"Расходы по моделям","analytics.budgetUtilization":"Использование бюджета","analytics.runs":"Запуски","analytics.totalCost":"Общая стоимость","analytics.avgCost":"Ср. стоимость","analytics.model":"Модель","analytics.tokens":"Токены","analytics.cost":"Стоимость","analytics.noAgentData":"Нет данных о расходах по агентам.","analytics.noModelData":"Нет данных о расходах по моделям.","settings.title":"Настройки","settings.general":"Общие","settings.security":"Безопасность","settings.llm":"LLM","settings.budget":"Бюджет","settings.save":"Сохранить изменения","settings.saved":"Настройки сохранены.","settings.language":"Язык","common.loading":"Загрузка...","common.error":"Произошла ошибка.","common.retry":"Повторить","common.cancel":"Отмена","common.save":"Сохранить","common.delete":"Удалить","common.close":"Закрыть","common.search":"Поиск...","common.noResults":"Результатов не найдено.","common.name":"Название","common.description":"Описание","common.status":"Статус","common.type":"Тип","common.actions":"Действия","common.created":"Создано","common.updated":"Обновлено","status.running":"Выполняется","status.completed":"Завершено","status.failed":"Ошибка","status.pending":"Ожидание","status.paused":"Пауза","status.cancelled":"Отменено","status.idle":"Простой","trust.builtin":"Встроенный","trust.official":"Официальный","trust.trusted":"Доверенный","trust.community":"Сообщество","trust.local":"Локальный"},it:{"nav.dashboard":"Pannello","nav.agents":"Agenti","nav.workflows":"Flussi di lavoro","nav.skills":"Competenze","nav.runs":"Esecuzioni","nav.approvals":"Approvazioni","nav.handoffs":"Passaggi","nav.apiKeys":"Chiavi API","nav.settings":"Impostazioni","nav.users":"Utenti","nav.prompts":"Prompt","dashboard.title":"Pannello","dashboard.activeAgents":"Agenti attivi","dashboard.runningTasks":"Attività in corso","dashboard.costToday":"Costo oggi","dashboard.skillsInstalled":"Competenze installate","dashboard.recentActivity":"Attività recente","dashboard.quickActions":"Azioni rapide","dashboard.systemHealth":"Stato del sistema","dashboard.createAgent":"Crea agente","dashboard.runWorkflow":"Esegui flusso","dashboard.installSkill":"Installa competenza","agents.title":"Agenti","agents.create":"Crea agente","agents.empty":"Nessun agente configurato.","agents.emptyDesc":"Crea il tuo primo agente IA per iniziare con le attività automatizzate.","agent.overview":"Panoramica","agent.runs":"Esecuzioni","agent.events":"Eventi","agent.configuration":"Configurazione","agent.budget":"Budget","agent.recentRuns":"Esecuzioni recenti","agent.delete":"Elimina agente","agent.start":"Avvia","agent.stop":"Arresta","agent.run":"Esegui","workflows.title":"Flussi di lavoro","workflows.create":"Crea flusso","workflows.empty":"Nessun flusso di lavoro definito.","workflows.emptyDesc":"Progetta il tuo primo flusso di lavoro per orchestrare più agenti.","workflows.nodes":"{count} nodi","workflows.edit":"Modifica","workflow.editor":"Editor del flusso","workflow.addNode":"Aggiungi nodo","workflow.save":"Salva","workflow.run":"Esegui flusso","skills.title":"Competenze","skills.install":"Installa","skills.empty":"Nessuna competenza installata.","skills.emptyDesc":"Esplora e installa competenze per ampliare le capacità dei tuoi agenti.","skills.scan":"Scansiona directory","skills.source":"URL o percorso sorgente","runs.title":"Esecuzioni","runs.empty":"Nessuna esecuzione registrata.","runs.emptyDesc":"Esegui un agente o un flusso per vedere la cronologia.","runs.filter":"Filtra","run.events":"Eventi","run.output":"Output","run.cost":"Dettaglio costi","run.duration":"Durata","approvals.title":"Coda di approvazione","approvals.empty":"Nessuna approvazione in sospeso.","approvals.emptyDesc":"Tutto a posto. Le azioni pericolose appariranno qui per la revisione.","approvals.approve":"Approva","approvals.deny":"Nega","approvals.pending":"In sospeso","nav.analytics":"Analisi","nav.budget":"Budget","nav.traces":"Tracce","nav.memory":"Memoria","nav.goals":"Obiettivi","nav.plans":"Piani","nav.guardrails":"Protezioni","analytics.title":"Analisi dei costi","analytics.description":"Monitora spese, utilizzo dei token e budget per agente.","analytics.totalSpend":"Spesa totale","analytics.totalRuns":"Esecuzioni totali","analytics.avgCostPerRun":"Costo medio/esec.","analytics.monthlyEstimate":"Stima mensile","analytics.dailyCosts":"Costi giornalieri (30 giorni)","analytics.agentBreakdown":"Costo per agente","analytics.modelBreakdown":"Costo per modello","analytics.budgetUtilization":"Utilizzo del budget","analytics.runs":"Esecuzioni","analytics.totalCost":"Costo totale","analytics.avgCost":"Costo medio","analytics.model":"Modello","analytics.tokens":"Token","analytics.cost":"Costo","analytics.noAgentData":"Nessun dato di costo per agente.","analytics.noModelData":"Nessun dato di costo per modello.","settings.title":"Impostazioni","settings.general":"Generale","settings.security":"Sicurezza","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Salva modifiche","settings.saved":"Impostazioni salvate.","settings.language":"Lingua","common.loading":"Caricamento...","common.error":"Si è verificato un errore.","common.retry":"Riprova","common.cancel":"Annulla","common.save":"Salva","common.delete":"Elimina","common.close":"Chiudi","common.search":"Cerca...","common.noResults":"Nessun risultato.","common.name":"Nome","common.description":"Descrizione","common.status":"Stato","common.type":"Tipo","common.actions":"Azioni","common.created":"Creato","common.updated":"Aggiornato","status.running":"In esecuzione","status.completed":"Completato","status.failed":"Fallito","status.pending":"In sospeso","status.paused":"In pausa","status.cancelled":"Annullato","status.idle":"Inattivo","trust.builtin":"Integrato","trust.official":"Ufficiale","trust.trusted":"Affidabile","trust.community":"Comunità","trust.local":"Locale"},nl:{"nav.dashboard":"Dashboard","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Vaardigheden","nav.runs":"Uitvoeringen","nav.approvals":"Goedkeuringen","nav.handoffs":"Overdrachten","nav.apiKeys":"API-sleutels","nav.settings":"Instellingen","nav.users":"Gebruikers","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Actieve agents","dashboard.runningTasks":"Lopende taken","dashboard.costToday":"Kosten vandaag","dashboard.skillsInstalled":"Geïnstalleerde vaardigheden","dashboard.recentActivity":"Recente activiteit","dashboard.quickActions":"Snelle acties","dashboard.systemHealth":"Systeemstatus","dashboard.createAgent":"Agent aanmaken","dashboard.runWorkflow":"Workflow uitvoeren","dashboard.installSkill":"Vaardigheid installeren","agents.title":"Agents","agents.create":"Agent aanmaken","agents.empty":"Geen agents geconfigureerd.","agents.emptyDesc":"Maak uw eerste AI-agent aan om te beginnen met geautomatiseerde taken.","agent.overview":"Overzicht","agent.runs":"Uitvoeringen","agent.events":"Gebeurtenissen","agent.configuration":"Configuratie","agent.budget":"Budget","agent.recentRuns":"Recente uitvoeringen","agent.delete":"Agent verwijderen","agent.start":"Starten","agent.stop":"Stoppen","agent.run":"Uitvoeren","workflows.title":"Workflows","workflows.create":"Workflow aanmaken","workflows.empty":"Geen workflows gedefinieerd.","workflows.emptyDesc":"Ontwerp uw eerste workflow om meerdere agents te orkestreren.","workflows.nodes":"{count} knooppunten","workflows.edit":"Bewerken","workflow.editor":"Workflow-editor","workflow.addNode":"Knooppunt toevoegen","workflow.save":"Opslaan","workflow.run":"Workflow uitvoeren","skills.title":"Vaardigheden","skills.install":"Installeren","skills.empty":"Geen vaardigheden geïnstalleerd.","skills.emptyDesc":"Blader door en installeer vaardigheden om de mogelijkheden van uw agents uit te breiden.","skills.scan":"Map scannen","skills.source":"Bron-URL of pad","runs.title":"Uitvoeringen","runs.empty":"Geen uitvoeringen geregistreerd.","runs.emptyDesc":"Voer een agent of workflow uit om de uitvoeringsgeschiedenis te bekijken.","runs.filter":"Filteren","run.events":"Gebeurtenissen","run.output":"Uitvoer","run.cost":"Kostenoverzicht","run.duration":"Duur","approvals.title":"Goedkeuringswachtrij","approvals.empty":"Geen wachtende goedkeuringen.","approvals.emptyDesc":"Alles in orde. Gevaarlijke acties verschijnen hier ter beoordeling.","approvals.approve":"Goedkeuren","approvals.deny":"Weigeren","approvals.pending":"In afwachting","nav.analytics":"Analyse","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Geheugen","nav.goals":"Doelen","nav.plans":"Plannen","nav.guardrails":"Vangrails","analytics.title":"Kostenanalyse","analytics.description":"Volg uitgaven, tokengebruik en budgetbenutting per agent.","analytics.totalSpend":"Totale uitgaven","analytics.totalRuns":"Totaal uitvoeringen","analytics.avgCostPerRun":"Gem. kosten/uitv.","analytics.monthlyEstimate":"Maandelijkse schatting","analytics.dailyCosts":"Dagelijkse kosten (30 dagen)","analytics.agentBreakdown":"Kosten per agent","analytics.modelBreakdown":"Kosten per model","analytics.budgetUtilization":"Budgetbenutting","analytics.runs":"Uitvoeringen","analytics.totalCost":"Totale kosten","analytics.avgCost":"Gem. kosten","analytics.model":"Model","analytics.tokens":"Tokens","analytics.cost":"Kosten","analytics.noAgentData":"Nog geen kostengegevens per agent.","analytics.noModelData":"Nog geen kostengegevens per model.","settings.title":"Instellingen","settings.general":"Algemeen","settings.security":"Beveiliging","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Wijzigingen opslaan","settings.saved":"Instellingen opgeslagen.","settings.language":"Taal","common.loading":"Laden...","common.error":"Er is een fout opgetreden.","common.retry":"Opnieuw proberen","common.cancel":"Annuleren","common.save":"Opslaan","common.delete":"Verwijderen","common.close":"Sluiten","common.search":"Zoeken...","common.noResults":"Geen resultaten gevonden.","common.name":"Naam","common.description":"Beschrijving","common.status":"Status","common.type":"Type","common.actions":"Acties","common.created":"Aangemaakt","common.updated":"Bijgewerkt","status.running":"Actief","status.completed":"Voltooid","status.failed":"Mislukt","status.pending":"In afwachting","status.paused":"Gepauzeerd","status.cancelled":"Geannuleerd","status.idle":"Inactief","trust.builtin":"Ingebouwd","trust.official":"Officieel","trust.trusted":"Vertrouwd","trust.community":"Community","trust.local":"Lokaal"}},_0=u.createContext({lang:"en",setLang:()=>{},t:n=>n,isRTL:!1});function Xv({children:n}){const[i,d]=u.useState(()=>{const h=localStorage.getItem("nestor_lang");return h&&Wd(h)?h:Yv(navigator.language)}),c=Kv.includes(i);u.useEffect(()=>{document.documentElement.dir=c?"rtl":"ltr",document.documentElement.lang=i},[i,c]);const m=u.useCallback(h=>{d(h),localStorage.setItem("nestor_lang",h)},[]),f=u.useCallback((h,b)=>{var p;let g=((p=qh[i])==null?void 0:p[h])??qh.en[h]??h;if(b)for(const[S,y]of Object.entries(b))g=g.replace(`{${S}}`,String(y));return g},[i]);return e.jsx(_0.Provider,{value:{lang:i,setLang:m,t:f,isRTL:c},children:n})}function Je(){return u.useContext(_0)}const Qv={admin:{agents:["create","read","update","delete","execute","admin"],workflows:["create","read","update","delete","execute","admin"],skills:["create","read","update","delete","admin"],settings:["read","update","admin"],users:["create","read","update","delete","admin"],prompts:["create","read","update","delete","admin"]},member:{agents:["create","read","update","execute"],workflows:["create","read","update","execute"],skills:["read","create"],settings:["read"],prompts:["read","create","update"]},viewer:{agents:["read"],workflows:["read"],skills:["read"],settings:["read"],prompts:["read"]}},U0=u.createContext({user:null,loading:!0,login:async()=>{},logout:async()=>{},register:async()=>{},isAdmin:!1,hasPermission:()=>!1,isSyntheticAdmin:!1}),Fv="/api";function Zv(){const n=document.cookie.match(/(?:^|; )nestor-csrf=([^;]*)/);return n?decodeURIComponent(n[1]):null}async function li(n,i){var h;const d={"Content-Type":"application/json",...(i==null?void 0:i.headers)||{}},c=((i==null?void 0:i.method)||"GET").toUpperCase();if(c!=="GET"&&c!=="HEAD"){const b=Zv();b&&(d["X-CSRF-Token"]=b)}const m=await fetch(`${Fv}${n}`,{credentials:"include",headers:d,...i}),f=await m.json().catch(()=>({}));if(!m.ok)throw new Error(((h=f==null?void 0:f.error)==null?void 0:h.message)||`Request failed (${m.status})`);return f}function Jv({children:n}){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(!1);u.useEffect(()=>{li("/auth/me").then(v=>{var k;(k=v.data)!=null&&k.user&&typeof v.data.user=="object"&&(d(v.data.user),h(!1))}).catch(async()=>{try{(await li("/health")).status==="ok"&&(d({id:"local",email:"admin@localhost",name:"Admin",role:"admin"}),h(!0))}catch{}}).finally(()=>m(!1))},[]);const b=u.useCallback(async(v,k)=>{const C=await li("/auth/login",{method:"POST",body:JSON.stringify({email:v,password:k})});d(C.data.user),h(!1)},[]),g=u.useCallback(async()=>{await li("/auth/logout",{method:"POST"}).catch(()=>{}),d(null),h(!1)},[]),p=u.useCallback(async(v,k,C)=>{await li("/auth/register",{method:"POST",body:JSON.stringify({email:v,password:k,name:C})})},[]),S=(i==null?void 0:i.role)==="admin",y=u.useCallback((v,k)=>{if(!i)return!1;const C=Qv[i.role];if(!C)return!1;const w=C[v];return w?w.includes(k)||w.includes("admin"):!1},[i]);return e.jsx(U0.Provider,{value:{user:i,loading:c,login:b,logout:g,register:p,isAdmin:S,hasPermission:y,isSyntheticAdmin:f},children:n})}function ol(){return u.useContext(U0)}const Iv=[{to:"/missions",icon:sa,labelKey:"nav.missions"},{to:"/chat",icon:Pt,labelKey:"nav.chat"},{to:"/agents",icon:Ts,labelKey:"nav.agents"},{to:"/workflows",icon:tc,labelKey:"nav.workflows"},{to:"/runs",icon:Nt,labelKey:"nav.history"}],$0=[{key:"tools",label:"Tools",defaultOpen:!1,items:[{to:"/skills",icon:rc,labelKey:"nav.skills"},{to:"/memory",icon:La,labelKey:"nav.memory"},{to:"/messaging",icon:Pt,labelKey:"nav.messaging"},{to:"/scheduler",icon:vs,labelKey:"nav.scheduler"},{to:"/plans",icon:pv,labelKey:"nav.plans"},{to:"/guardrails",icon:Ds,labelKey:"nav.guardrails"}]},{key:"monitoring",label:"Monitoring",defaultOpen:!1,items:[{to:"/analytics",icon:Rs,labelKey:"nav.analytics"},{to:"/budget",icon:us,labelKey:"nav.budget"},{to:"/traces",icon:It,labelKey:"nav.traces"},{to:"/approvals",icon:hu,labelKey:"nav.approvals"}]},{key:"advanced",label:"Advanced",defaultOpen:!1,items:[{to:"/goals",icon:rn,labelKey:"nav.goals"},{to:"/handoffs",icon:fi,labelKey:"nav.handoffs"},{to:"/evolve",icon:Pr,labelKey:"nav.evolve"},{to:"/keys",icon:Ni,labelKey:"nav.apiKeys"},{to:"/settings",icon:il,labelKey:"nav.settings"}]}],Pv=[{to:"/users",icon:rl,labelKey:"nav.users"},{to:"/admin",icon:il,labelKey:"nav.admin"}],B0="nestor_sidebar_sections";function Wv(){try{const i=localStorage.getItem(B0);if(i)return JSON.parse(i)}catch{}const n={};for(const i of $0)n[i.key]=i.defaultOpen;return n}function ej(n){try{localStorage.setItem(B0,JSON.stringify(n))}catch{}}function tj({onNavigate:n}){const{t:i}=Je(),{user:d,isAdmin:c,logout:m}=ol(),[f,h]=u.useState(Wv);u.useEffect(()=>{ej(f)},[f]);const b=u.useCallback(p=>{h(S=>({...S,[p]:!S[p]}))},[]),g=({isActive:p})=>`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${p?"bg-purple-500/10 text-purple-400":"text-zinc-400 hover:bg-surface-hover hover:text-zinc-200"}`;return e.jsxs("aside",{className:"fixed inset-y-0 left-0 z-30 flex w-60 flex-col border-r border-border bg-surface",children:[e.jsxs("div",{className:"flex h-14 items-center gap-2.5 px-5 border-b border-border",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-purple-600 text-white",children:e.jsx(sa,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-lg font-semibold text-white tracking-tight",children:["Nestor ",e.jsx("span",{className:"text-xs font-normal text-zinc-500",children:"Studio"})]})]}),e.jsxs("nav",{className:"flex-1 space-y-0.5 px-3 py-4 overflow-y-auto",children:[Iv.map(p=>{const S=p.icon;return e.jsxs(di,{to:p.to,end:p.to==="/chat",onClick:n,className:g,children:[e.jsx(S,{className:"h-4 w-4 flex-shrink-0"}),i(p.labelKey)]},p.to)}),$0.map(p=>e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{onClick:()=>b(p.key),className:"flex items-center gap-2 w-full px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-600 hover:text-zinc-400 transition-colors",children:[f[p.key]?e.jsx(na,{className:"h-3 w-3"}):e.jsx(ds,{className:"h-3 w-3"}),p.label]}),f[p.key]&&e.jsx("div",{className:"space-y-0.5",children:p.items.map(S=>{const y=S.icon;return e.jsxs(di,{to:S.to,onClick:n,className:g,children:[e.jsx(y,{className:"h-4 w-4 flex-shrink-0"}),i(S.labelKey)]},S.to)})})]},p.key)),c&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-2 border-t border-border/50"}),e.jsx("div",{className:"px-3 py-1 text-[10px] font-semibold uppercase tracking-wider text-zinc-600",children:"Admin"}),Pv.map(p=>{const S=p.icon;return e.jsxs(di,{to:p.to,onClick:n,className:g,children:[e.jsx(S,{className:"h-4 w-4 flex-shrink-0"}),i(p.labelKey)]},p.to)})]})]}),e.jsxs("div",{className:"border-t border-border px-4 py-3",children:[d&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-zinc-200",children:d.name}),e.jsx("p",{className:"truncate text-xs text-zinc-500",children:d.role})]}),e.jsx("button",{onClick:m,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-surface-hover hover:text-zinc-200",title:"Sign out",children:e.jsx(zv,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-600",children:"Nestor v3.5.1"})]})]})}const sj=["system","agents","runs","approvals"],aj=10,nj=1e3,lj=3e4,ij=3e4,rj=200;function cj(n,i,d){const c=Math.min(i*2**n,d),m=c*Math.random()*.25;return c+m}function oj(){const n=window.location.protocol==="https:"?"wss:":"ws:",i=window.location.host,d=localStorage.getItem("nestor_token"),c=d?`?token=${encodeURIComponent(d)}`:"";return`${n}//${i}/ws${c}`}function pu(n=sj,i){const{reconnect:d=!0,maxRetries:c=aj,baseDelay:m=nj,maxDelay:f=lj}={},[h,b]=u.useState([]),[g,p]=u.useState("disconnected"),[S,y]=u.useState(0),v=u.useRef(null),k=u.useRef(),C=u.useRef(),w=u.useRef(n),N=u.useRef(!1),z=u.useRef(0);w.current=n;const R=u.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=void 0)},[]),D=u.useCallback(()=>{C.current&&(clearInterval(C.current),C.current=void 0)},[]),O=u.useCallback(ce=>{D(),C.current=setInterval(()=>{ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"ping"}))},ij)},[D]),se=u.useCallback((ce,I)=>{for(const le of I)ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"subscribe",channel:le}))},[]),Z=u.useCallback(ce=>{if(!d||N.current)return;if(z.current>=c){console.warn(`[Nestor WS] Max retries (${c}) reached. Giving up.`),p("disconnected");return}const I=cj(z.current,m,f);console.info(`[Nestor WS] Reconnecting in ${Math.round(I)}ms (attempt ${z.current+1}/${c})`),p("reconnecting"),R(),k.current=setTimeout(()=>{z.current+=1,y(z.current),ce()},I)},[d,c,m,f,R]),U=u.useCallback(()=>{if(!(v.current&&(v.current.readyState===WebSocket.OPEN||v.current.readyState===WebSocket.CONNECTING)))try{const ce=oj(),I=new WebSocket(ce);v.current=I,p("connecting"),I.onopen=()=>{console.info("[Nestor WS] Connected"),p("connected"),z.current=0,y(0),N.current=!1,se(I,w.current),O(I)},I.onmessage=le=>{try{const Y=JSON.parse(le.data);if(Y.type==="ping"){I.send(JSON.stringify({type:"pong"}));return}if(Y.type==="pong")return;if(Y.type==="event"){const B=Y;b(ne=>[...ne.slice(-(rj-1)),B])}}catch{}},I.onclose=le=>{if(console.info(`[Nestor WS] Closed (code=${le.code}, reason=${le.reason||"none"})`),v.current=null,D(),N.current){p("disconnected");return}Z(U)},I.onerror=le=>{console.error("[Nestor WS] Error:",le),I.close()}}catch{Z(U)}},[se,O,D,Z]);u.useEffect(()=>(N.current=!1,U(),()=>{N.current=!0,R(),D(),v.current&&(v.current.close(1e3,"Component unmount"),v.current=null)}),[U,R,D]),u.useEffect(()=>{const ce=v.current;!ce||ce.readyState!==WebSocket.OPEN||se(ce,n)},[n,se]);const A=u.useCallback(ce=>{const I=v.current;I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"subscribe",channel:ce}))},[]),F=u.useCallback(ce=>{const I=v.current;I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"unsubscribe",channel:ce}))},[]),$=u.useCallback(()=>{b([])},[]),Q=u.useCallback(()=>{N.current=!0,R(),D(),v.current&&(v.current.close(1e3,"Manual close"),v.current=null),p("disconnected")},[R,D]);return{events:h,connected:g==="connected",status:g,retryCount:S,subscribe:A,unsubscribe:F,clearEvents:$,close:Q}}const dj="/api";class uj extends Error{constructor(i,d,c){super(`API Error ${i}: ${d}`),this.status=i,this.statusText=d,this.body=c,this.name="ApiError"}}function mj(n){const i=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return i?decodeURIComponent(i[1]):null}async function ae(n,i={}){const d=`${dj}${n}`,c={"Content-Type":"application/json",...i.headers},m=localStorage.getItem("nestor_token");m&&(c.Authorization=`Bearer ${m}`);const f=(i.method||"GET").toUpperCase();if(f!=="GET"&&f!=="HEAD"){const g=mj("nestor-csrf");g&&(c["X-CSRF-Token"]=g)}const h=localStorage.getItem("nestor_tenant_id");h&&(c["X-Tenant-ID"]=h);const b=await fetch(d,{...i,headers:c});if(!b.ok){let g;try{g=await b.json()}catch{g=await b.text()}throw new uj(b.status,b.statusText,g)}if(b.status!==204)return b.json()}const la={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/agents${d?`?${d}`:""}`)},get:n=>ae(`/agents/${n}`),create:n=>ae("/agents",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/agents/${n}`,{method:"PATCH",body:JSON.stringify(i)}),delete:n=>ae(`/agents/${n}`,{method:"DELETE"}),run:(n,i)=>ae(`/agents/${n}/run`,{method:"POST",body:JSON.stringify({prompt:i})}),getStatus:n=>ae(`/agents/${n}/status`),start:(n,i="daemon")=>ae(`/agents/${n}/start`,{method:"POST",body:JSON.stringify({mode:i})}),stop:n=>ae(`/agents/${n}/stop`,{method:"POST"})},sc={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/workflows${d?`?${d}`:""}`)},get:n=>ae(`/workflows/${n}`),create:n=>ae("/workflows",{method:"POST",body:JSON.stringify(n)}),run:(n,i={})=>ae(`/workflows/${n}/run`,{method:"POST",body:JSON.stringify({input:i})})},ln={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset)),n!=null&&n.status&&i.set("status",n.status),n!=null&&n.agentId&&i.set("agentId",n.agentId),n!=null&&n.workflowId&&i.set("workflowId",n.workflowId);const d=i.toString();return ae(`/runs${d?`?${d}`:""}`)},get:n=>ae(`/runs/${n}`),getEvents:n=>ae(`/runs/${n}/events`),abort:n=>ae(`/runs/${n}/abort`,{method:"POST"}),delete:n=>ae(`/runs/${n}`,{method:"DELETE"})},Wr={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/skills${d?`?${d}`:""}`)},install:n=>ae("/skills/install",{method:"POST",body:JSON.stringify(n)}),scan:n=>ae("/skills/scan",{method:"POST",body:JSON.stringify({path:n})}),delete:n=>ae(`/skills/${n}`,{method:"DELETE"})},Es={stats:()=>ae("/system/stats"),health:()=>ae("/health"),getConfig:()=>ae("/system/config"),updateConfig:n=>ae("/system/config",{method:"PUT",body:JSON.stringify(n)})},In={summary:n=>{const i=new URLSearchParams;n!=null&&n.from&&i.set("from",String(n.from)),n!=null&&n.to&&i.set("to",String(n.to)),n!=null&&n.agentId&&i.set("agentId",n.agentId);const d=i.toString();return ae(`/analytics/summary${d?`?${d}`:""}`)},daily:(n=30)=>ae(`/analytics/daily?days=${n}`),budget:()=>ae("/analytics/budget"),estimate:()=>ae("/analytics/estimate"),agentBreakdown:n=>ae(`/analytics/agents/${n}`),qualityOverview:(n=30)=>ae(`/analytics/quality?days=${n}`),qualityAgent:(n,i=30)=>ae(`/analytics/quality/${n}?days=${i}`)},Bd={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.status&&i.set("status",n.status);const d=i.toString();return ae(`/traces${d?`?${d}`:""}`)},get:n=>ae(`/traces/${n}`),clear:()=>ae("/traces",{method:"DELETE"})},Gh={list:()=>ae("/tenants"),get:n=>ae(`/tenants/${n}`),create:n=>ae("/tenants",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/tenants/${n}`,{method:"PUT",body:JSON.stringify(i)}),delete:n=>ae(`/tenants/${n}`,{method:"DELETE"}),switch:n=>ae(`/tenants/${n}/switch`,{method:"POST"})},ii={tree:()=>ae("/goals"),get:n=>ae(`/goals/${n}`),create:n=>ae("/goals",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/goals/${n}`,{method:"PUT",body:JSON.stringify(i)}),delete:n=>ae(`/goals/${n}`,{method:"DELETE"}),ancestry:n=>ae(`/goals/${n}/ancestry`),assign:(n,i)=>ae(`/goals/${n}/assign/${i}`,{method:"POST"}),agentGoals:n=>ae(`/agents/${n}/goals`)},ri={list:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status),n!=null&&n.agentId&&i.set("agentId",n.agentId),n!=null&&n.type&&i.set("type",n.type),n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/approvals${d?`?${d}`:""}`)},create:n=>ae("/approvals",{method:"POST",body:JSON.stringify(n)}),get:n=>ae(`/approvals/${n}`),approve:(n,i)=>ae(`/approvals/${n}/approve`,{method:"POST",body:JSON.stringify({decidedBy:(i==null?void 0:i.reviewerId)??"user",comment:i==null?void 0:i.comment})}),reject:(n,i)=>ae(`/approvals/${n}/reject`,{method:"POST",body:JSON.stringify({decidedBy:(i==null?void 0:i.reviewerId)??"user",reason:i==null?void 0:i.reason})}),history:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.agentId&&i.set("agentId",n.agentId);const d=i.toString();return ae(`/approvals/history${d?`?${d}`:""}`)},stats:()=>ae("/approvals/stats")},Hd={forRun:n=>ae(`/runs/${n}/annotations`),create:(n,i)=>ae(`/runs/${n}/annotate`,{method:"POST",body:JSON.stringify(i)}),delete:n=>ae(`/annotations/${n}`,{method:"DELETE"})},ac={list:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status);const d=i.toString();return ae(`/handoffs${d?`?${d}`:""}`)},get:n=>ae(`/handoffs/${n}`),create:(n,i)=>ae(`/runs/${n}/handoff`,{method:"POST",body:JSON.stringify(i)}),resume:(n,i)=>ae(`/handoffs/${n}/resume`,{method:"POST",body:JSON.stringify({humanResolution:i})})},Tt={overview:()=>ae("/admin/overview"),tenants:{list:()=>ae("/tenants"),create:n=>ae("/tenants",{method:"POST",body:JSON.stringify(n)}),get:n=>ae(`/tenants/${n}`),update:(n,i)=>ae(`/tenants/${n}`,{method:"PUT",body:JSON.stringify(i)})},users:{list:n=>{const i=new URLSearchParams;n!=null&&n.tenantId&&i.set("tenantId",n.tenantId),n!=null&&n.role&&i.set("role",n.role);const d=i.toString();return ae(`/users${d?`?${d}`:""}`)},updateRole:(n,i)=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({role:i})}),lock:n=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({isActive:!1})}),unlock:n=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({isActive:!0})})},system:{info:()=>ae("/admin/system-info"),dbStats:()=>ae("/admin/db-stats"),rateLimitStats:()=>ae("/admin/rate-limit-stats")},audit:{query:n=>{const i=new URLSearchParams;n!=null&&n.userId&&i.set("userId",n.userId),n!=null&&n.resourceType&&i.set("resourceType",n.resourceType),n!=null&&n.action&&i.set("action",n.action),n!=null&&n.limit&&i.set("limit",String(n.limit));const d=i.toString();return ae(`/users/audit${d?`?${d}`:""}`)},export:n=>ae(`/users/audit?limit=10000&format=${n}`)},security:{failedLogins:(n=24)=>ae(`/admin/security/failed-logins?hours=${n}`),lockedAccounts:()=>ae("/admin/security/locked-accounts"),activeSessions:()=>ae("/admin/security/active-sessions"),rateLimitViolations:(n=100)=>ae(`/admin/security/rate-violations?limit=${n}`)}},Kh={status:()=>ae("/providers/status"),test:n=>ae("/providers/test",{method:"POST",body:JSON.stringify(n)})},ys={list:()=>ae("/keys"),set:(n,i,d)=>ae("/keys",{method:"POST",body:JSON.stringify({provider:n,key:i,label:d})}),remove:n=>ae(`/keys/${n}`,{method:"DELETE"}),test:n=>ae(`/keys/test/${n}`)},ea={plan:(n,i)=>ae("/missions/plan",{method:"POST",body:JSON.stringify({objective:n,...i})}),list:()=>ae("/missions"),get:n=>ae(`/missions/${n}`),getReport:(n,i)=>ae(`/missions/${n}/report${i==="md"?"?format=md":""}`),cancel:n=>ae(`/missions/${n}/cancel`,{method:"POST"}),templates:()=>ae("/missions/templates")},qd={status:()=>ae("/messaging/status"),channels:()=>ae("/messaging/channels"),send:(n,i,d)=>ae("/messaging/send",{method:"POST",body:JSON.stringify({adapter:n,channel:i,content:d})})},ci={list:()=>ae("/agents?scheduled=true"),setSchedule:(n,i)=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify(i)}),removeSchedule:n=>ae(`/agents/${n}/schedule`,{method:"DELETE"}),pauseSchedule:n=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify({enabled:!1})}),resumeSchedule:n=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify({enabled:!0})})},Br={candidates:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status),n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/evolve/candidates${d?`?${d}`:""}`)},approve:n=>ae(`/evolve/candidates/${n}/approve`,{method:"POST"}),reject:n=>ae(`/evolve/candidates/${n}/reject`,{method:"POST"}),update:(n,i)=>ae(`/evolve/candidates/${n}`,{method:"PATCH",body:JSON.stringify(i)})};function xj({onMenuClick:n,showMenu:i}){const{lang:d,setLang:c,t:m}=Je(),{connected:f}=pu(),[h,b]=u.useState([]),[g,p]=u.useState(()=>localStorage.getItem("nestor_tenant_id")??"default"),[S,y]=u.useState(!1),[v,k]=u.useState(!1),C=u.useRef(null),w=u.useRef(null),N=h.find(O=>O.id===g)??null,z=u.useCallback(async()=>{try{const O=await Gh.list();b(O.data)}catch{}},[]);u.useEffect(()=>{z()},[z]),u.useEffect(()=>{const O=se=>{C.current&&!C.current.contains(se.target)&&y(!1),w.current&&!w.current.contains(se.target)&&k(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const R=async O=>{try{await Gh.switch(O.id),localStorage.setItem("nestor_tenant_id",O.id),p(O.id),y(!1),window.location.reload()}catch(se){console.error("Failed to switch tenant:",se)}},D=Object.keys(Pd);return e.jsxs("header",{className:"header sticky top-0 z-20 flex h-14 items-center justify-between border-b border-border bg-[#0a0a0f]/80 px-6 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[i&&e.jsx("button",{onClick:n,className:"p-2 hover:bg-surface-hover rounded-lg transition-colors","aria-label":"Toggle menu",children:e.jsx(Cv,{className:"h-5 w-5 text-zinc-400"})}),e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{type:"text",placeholder:m("common.search"),className:"input pl-9 max-w-sm"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[h.length>0&&e.jsxs("div",{className:"relative hidden sm:block",ref:C,children:[e.jsxs("button",{onClick:()=>y(!S),className:"flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-1.5 text-sm transition-colors hover:border-zinc-600",children:[e.jsx(du,{className:"h-3.5 w-3.5 text-indigo-400"}),e.jsx("span",{className:"text-zinc-200 max-w-[120px] truncate",children:(N==null?void 0:N.name)??"Default"}),e.jsx(na,{className:`h-3.5 w-3.5 text-zinc-500 transition-transform ${S?"rotate-180":""}`})]}),S&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-56 rounded-lg border border-border bg-surface shadow-xl z-50",children:[e.jsx("div",{className:"px-3 py-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600",children:"Switch Tenant"}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:h.map(O=>e.jsxs("button",{onClick:()=>R(O),className:"flex w-full items-center gap-2 px-3 py-2 text-sm text-zinc-300 transition-colors hover:bg-surface-hover",children:[O.id===g?e.jsx(bt,{className:"h-3.5 w-3.5 text-indigo-400"}):e.jsx("div",{className:"h-3.5 w-3.5"}),e.jsxs("div",{className:"flex-1 text-left",children:[e.jsx("div",{className:"font-medium",children:O.name}),e.jsx("div",{className:"text-xs text-zinc-500",children:O.slug})]})]},O.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[f?e.jsx(Gv,{className:"h-4 w-4 text-green-400"}):e.jsx(qv,{className:"h-4 w-4 text-zinc-500"}),e.jsx("span",{className:`text-xs hidden sm:inline ${f?"text-green-400":"text-zinc-500"}`,children:f?"Connected":"Offline"})]}),e.jsxs("div",{className:"relative",ref:w,children:[e.jsxs("button",{onClick:()=>k(!v),className:"btn-ghost btn-sm flex items-center gap-1.5",title:"Switch language",children:[e.jsx(mu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase",children:d}),e.jsx(na,{className:`h-3 w-3 text-zinc-500 transition-transform ${v?"rotate-180":""}`})]}),v&&e.jsx("div",{className:"absolute right-0 top-full mt-1 w-48 rounded-lg border border-border bg-surface shadow-xl z-50 max-h-80 overflow-y-auto",children:D.map(O=>e.jsxs("button",{onClick:()=>{c(O),k(!1)},className:"flex w-full items-center gap-2 px-3 py-2 text-sm text-zinc-300 transition-colors hover:bg-surface-hover",children:[O===d?e.jsx(bt,{className:"h-3.5 w-3.5 text-indigo-400"}):e.jsx("div",{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"flex-1 text-left",children:Pd[O]}),e.jsx("span",{className:"text-xs text-zinc-500 uppercase",children:O})]},O))})]})]})]})}const fj=[{to:"/",icon:Pt,labelKey:"nav.chat"},{to:"/agents",icon:Ts,labelKey:"nav.agents"},{to:"/dashboard",icon:xu,labelKey:"nav.dashboard"},{to:"/runs",icon:Nt,labelKey:"nav.history"},{to:"/settings",icon:il,labelKey:"nav.settings"}];function hj(){const{t:n}=Je();return e.jsx("nav",{className:"mobile-bottom-nav",children:fj.map(i=>{const d=i.icon;return e.jsxs(di,{to:i.to,end:i.to==="/",className:({isActive:c})=>`mobile-bottom-nav-item ${c?"active":""}`,children:[e.jsx(d,{className:"h-5 w-5"}),e.jsx("span",{className:"mobile-bottom-nav-label",children:n(i.labelKey)})]},i.to)})})}function pj(){const[n,i]=u.useState(!1),[d,c]=u.useState(!1),{isSyntheticAdmin:m}=ol();u.useEffect(()=>{const h=()=>c(window.innerWidth<769);return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]);const f=()=>{d&&i(!1)};return e.jsxs("div",{className:"flex min-h-screen bg-[#0a0a0f]",children:[d&&n&&e.jsx("div",{className:"sidebar-overlay",onClick:()=>i(!1)}),e.jsx("div",{className:`sidebar ${d&&n?"open":""}`,children:e.jsx(tj,{onNavigate:f})}),e.jsxs("div",{className:`flex flex-1 flex-col ${d?"":"pl-60"}`,children:[e.jsx(xj,{onMenuClick:()=>i(!n),showMenu:d}),m&&e.jsxs("div",{role:"status",className:"bg-yellow-500/20 border-b border-yellow-500/40 text-yellow-200 text-sm px-4 py-2 text-center",children:[e.jsx("strong",{children:"Local admin mode"}),' — the auth server is unreachable, so a synthetic "Admin" user was created to keep the UI usable. Sign in to the real server to leave this mode.']}),e.jsx("main",{className:`main-content flex-1 p-6 ${d?"pb-20":""}`,children:e.jsx(Cy,{})}),d&&e.jsx(hj,{})]})]})}class gj extends u.Component{constructor(){super(...arguments);Ad(this,"state",{hasError:!1,error:null});Ad(this,"handleReset",()=>{this.setState({hasError:!1,error:null})})}static getDerivedStateFromError(d){return{hasError:!0,error:d}}componentDidCatch(d,c){var m,f;console.error("[Nestor] UI Error:",d,c),(f=(m=this.props).onError)==null||f.call(m,d,c)}render(){var d;return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[e.jsx("div",{className:"text-red-500 text-xl mb-4",children:"Something went wrong"}),e.jsx("pre",{className:"bg-gray-100 dark:bg-gray-800 p-4 rounded-lg text-sm max-w-lg overflow-auto mb-4",children:(d=this.state.error)==null?void 0:d.message}),e.jsx("button",{onClick:this.handleReset,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:"Try Again"})]}):this.props.children}}function bj(){const n=Dt();return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 mb-6 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"})})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 dark:text-gray-100 mb-2",children:"Page Error"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-8 max-w-md",children:"An unexpected error occurred while rendering this page. The error has been logged for investigation."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Reload Page"}),e.jsx("button",{onClick:()=>n("/"),className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:"Go Home"})]})]})}const yj={node_started:{icon:Nt,color:"text-blue-400"},node_completed:{icon:et,color:"text-green-400"},node_failed:{icon:ft,color:"text-red-400"},tool_call_requested:{icon:sa,color:"text-amber-400"},tool_call_approved:{icon:et,color:"text-green-400"},tool_call_denied:{icon:Ms,color:"text-red-400"},tool_call_completed:{icon:et,color:"text-emerald-400"},approval_requested:{icon:Ms,color:"text-amber-400"},approval_resolved:{icon:et,color:"text-green-400"},budget_warning:{icon:pt,color:"text-amber-400"},budget_exceeded:{icon:us,color:"text-red-400"},run_paused:{icon:tl,color:"text-blue-400"},run_resumed:{icon:D0,color:"text-blue-400"}};function vj(n){try{return new Date(n).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return n}}function jj(n,i){switch(n){case"node_started":return`Node started: ${i.nodeId??i.label??""}`;case"node_completed":return`Node completed: ${i.nodeId??i.label??""}`;case"node_failed":return`Node failed: ${i.error??i.nodeId??""}`;case"tool_call_requested":return`Tool call: ${i.toolName??""}`;case"tool_call_approved":return`Tool approved: ${i.toolName??""}`;case"tool_call_denied":return`Tool denied: ${i.toolName??""}`;case"tool_call_completed":return`Tool completed: ${i.toolName??""}`;case"approval_requested":return`Approval required: ${i.toolName??i.action??""}`;case"approval_resolved":return`Approval resolved: ${i.decision??""}`;case"budget_warning":return`Budget warning: ${i.percent??""}% used`;case"budget_exceeded":return"Budget exceeded";case"run_paused":return"Run paused";case"run_resumed":return"Run resumed";default:return n.replace(/_/g," ")}}function gu({events:n,maxHeight:i="400px"}){return n.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8 text-sm text-zinc-500",children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Waiting for events..."]}):e.jsx("div",{className:"overflow-y-auto",style:{maxHeight:i},children:e.jsx("div",{className:"space-y-0.5",children:[...n].reverse().map(d=>{const c=yj[d.type]??{icon:sa,color:"text-zinc-400"},m=c.icon;return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg px-3 py-2 hover:bg-surface-hover transition-colors",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 ${c.color}`,children:e.jsx(m,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm text-zinc-300 truncate",children:jj(d.type,d.data)}),d.nodeId&&e.jsxs("p",{className:"text-xs text-zinc-500 truncate",children:["Node: ",d.nodeId]})]}),e.jsx("time",{className:"flex-shrink-0 text-xs text-zinc-500",children:vj(d.timestamp)})]},d.id)})})})}function Hr({label:n,value:i,icon:d,color:c,bgColor:m}){return e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-zinc-400",children:n}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-white",children:i})]}),e.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-xl ${m}`,children:e.jsx(d,{className:`h-5 w-5 ${c}`})})]})})}function Nj(){const{t:n}=Je(),{events:i}=pu(),[d,c]=u.useState(null),[m,f]=u.useState("healthy"),[h,b]=u.useState(!0),[g,p]=u.useState(null),[S,y]=u.useState(0);u.useEffect(()=>{Es.stats().then(z=>{c(z.data),f("healthy"),p(null)}).catch(z=>{f("down"),p(z instanceof Error?z.message:"Failed to connect to server")}).finally(()=>{b(!1)}),Es.health().then(z=>{f(z.status==="healthy"?"healthy":"degraded")}).catch(()=>{f("down")});const N=new Date;N.setHours(0,0,0,0),In.summary({from:N.getTime()}).then(z=>{var R;y(((R=z.data)==null?void 0:R.totalCostUsd)??0)}).catch(()=>{})},[]),u.useEffect(()=>{if(i.length===0)return;Es.stats().then(z=>c(z.data)).catch(()=>{});const N=new Date;N.setHours(0,0,0,0),In.summary({from:N.getTime()}).then(z=>{var R;y(((R=z.data)==null?void 0:R.totalCostUsd)??0)}).catch(()=>{})},[i.length]);const k={healthy:{icon:et,color:"text-green-400",bg:"bg-green-500/10",label:"All systems operational"},degraded:{icon:pt,color:"text-amber-400",bg:"bg-amber-500/10",label:"Some services degraded"},down:{icon:ft,color:"text-red-400",bg:"bg-red-500/10",label:"Services unavailable"}}[m],C=k.icon,w=i.map((N,z)=>{var R;return{id:String(z),type:typeof N.data=="object"&&N.data!==null&&"kind"in N.data?N.data.kind:N.channel,data:N.data??{},timestamp:((R=N.data)==null?void 0:R.timestamp)??new Date().toISOString()}});return h?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("dashboard.title")}),g&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:["Unable to connect to the Nestor server. Make sure the server is running.",e.jsx("span",{className:"ml-2 text-xs text-red-500/70",children:g})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Hr,{label:n("dashboard.activeAgents"),value:(d==null?void 0:d.agents.total)??0,icon:Ts,color:"text-indigo-400",bgColor:"bg-indigo-500/10"}),e.jsx(Hr,{label:n("dashboard.runningTasks"),value:(d==null?void 0:d.runs.running)??0,icon:Nt,color:"text-emerald-400",bgColor:"bg-emerald-500/10"}),e.jsx(Hr,{label:n("dashboard.costToday"),value:`$${S.toFixed(2)}`,icon:us,color:"text-amber-400",bgColor:"bg-amber-500/10"}),e.jsx(Hr,{label:n("dashboard.skillsInstalled"),value:(d==null?void 0:d.skills.total)??0,icon:rc,color:"text-violet-400",bgColor:"bg-violet-500/10"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"card lg:col-span-2",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-medium text-zinc-200",children:n("dashboard.recentActivity")}),e.jsx(It,{className:"h-4 w-4 text-zinc-500"})]}),e.jsx(gu,{events:w,maxHeight:"300px"})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:n("dashboard.quickActions")}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ta,{to:"/agents",className:"btn-secondary w-full justify-start",children:[e.jsx(ht,{className:"h-4 w-4"}),n("dashboard.createAgent")]}),e.jsxs(ta,{to:"/workflows",className:"btn-secondary w-full justify-start",children:[e.jsx(tc,{className:"h-4 w-4"}),n("dashboard.runWorkflow")]}),e.jsxs(ta,{to:"/skills",className:"btn-secondary w-full justify-start",children:[e.jsx(hi,{className:"h-4 w-4"}),n("dashboard.installSkill")]})]})]}),e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:n("dashboard.systemHealth")}),e.jsxs("div",{className:`flex items-center gap-3 rounded-lg p-3 ${k.bg}`,children:[e.jsx(C,{className:`h-5 w-5 ${k.color}`}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${k.color}`,children:k.label}),e.jsx("p",{className:"text-xs text-zinc-500",children:d?`${d.agents.total} agents | ${d.workflows.total} workflows | ${d.runs.today} runs today`:"Loading..."})]})]}),(d==null?void 0:d.server)&&e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Version"}),e.jsx("p",{className:"text-zinc-300 font-mono",children:d.server.version})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Uptime"}),e.jsxs("p",{className:"text-zinc-300 font-mono",children:[Math.floor(d.server.uptime/3600),"h ",Math.floor(d.server.uptime%3600/60),"m"]})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Memory (RSS)"}),e.jsxs("p",{className:"text-zinc-300 font-mono",children:[d.server.memoryUsage.rss," MB"]})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"WS Connections"}),e.jsx("p",{className:"text-zinc-300 font-mono",children:d.websocket.connections})]})]})]})]})]})]})}function wj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await la.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch agents")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{agents:n,loading:d,error:m,refetch:h}}function Sj(n){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(null),b=u.useCallback(async()=>{if(n){m(!0),h(null);try{const g=await la.get(n);d(g.data)}catch(g){h(g instanceof Error?g.message:"Failed to fetch agent")}finally{m(!1)}}},[n]);return u.useEffect(()=>{b()},[b]),{agent:i,loading:c,error:f,refetch:b}}const Vh={running:{bg:"bg-emerald-500/10",text:"text-emerald-400",dot:"bg-emerald-400"},completed:{bg:"bg-green-500/10",text:"text-green-400",dot:"bg-green-400"},failed:{bg:"bg-red-500/10",text:"text-red-400",dot:"bg-red-400"},pending:{bg:"bg-amber-500/10",text:"text-amber-400",dot:"bg-amber-400"},paused:{bg:"bg-blue-500/10",text:"text-blue-400",dot:"bg-blue-400"},cancelled:{bg:"bg-zinc-500/10",text:"text-zinc-400",dot:"bg-zinc-400"},idle:{bg:"bg-zinc-500/10",text:"text-zinc-500",dot:"bg-zinc-500"}};function wi({status:n,pulse:i}){const{t:d}=Je(),c=Vh[n]??Vh.idle;return e.jsxs("span",{className:`badge ${c.bg} ${c.text}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${c.dot} ${i&&n==="running"?"animate-pulse":""}`}),d(`status.${n}`)]})}const kj={builtin:{bg:"bg-indigo-500/10",text:"text-indigo-400"},official:{bg:"bg-blue-500/10",text:"text-blue-400"},trusted:{bg:"bg-emerald-500/10",text:"text-emerald-400"},community:{bg:"bg-amber-500/10",text:"text-amber-400"},local:{bg:"bg-zinc-500/10",text:"text-zinc-400"}};function bu({level:n}){const{t:i}=Je(),d=kj[n];return e.jsxs("span",{className:`badge ${d.bg} ${d.text}`,children:[n==="builtin"||n==="official"?e.jsx("svg",{className:"h-3 w-3",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}):null,i(`trust.${n}`)]})}function H0({spent:n,limit:i,currency:d="$"}){const c=i>0?Math.min(n/i*100,100):0,m=c>=75,f=c>=90,h=f?"bg-red-500":m?"bg-amber-500":"bg-indigo-500";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-zinc-400",children:[d,n.toFixed(2)," / ",d,i.toFixed(2)]}),e.jsxs("span",{className:`font-medium ${f?"text-red-400":m?"text-amber-400":"text-zinc-400"}`,children:[c.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-zinc-800",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${h}`,style:{width:`${c}%`}})})]})}const zj={anthropic:Ts,openai:Ts,local:bv};function Cj({agent:n,status:i="idle",budgetSpent:d=0,budgetLimit:c=10}){const m=zj[n.adapterType]??Ts;return e.jsxs(ta,{to:`/agents/${n.id}`,className:"card group hover:border-indigo-500/30 hover:bg-surface-hover transition-all duration-200",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-400 group-hover:bg-indigo-500/20 transition-colors",children:e.jsx(m,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200 group-hover:text-white transition-colors",children:n.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:[n.adapterType," ",n.adapterConfig.model?`/ ${n.adapterConfig.model}`:""]})]})]}),e.jsx(wi,{status:i,pulse:!0})]}),n.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:n.description}),e.jsx("div",{className:"mt-4 flex items-center justify-between",children:e.jsx(bu,{level:n.trustLevel})}),e.jsx("div",{className:"mt-3",children:e.jsx(H0,{spent:d,limit:c})})]})}function cn({icon:n,title:i,description:d,action:c}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4 text-center",children:[e.jsx("div",{className:"mb-4 rounded-2xl bg-surface p-4 text-zinc-500",children:n??e.jsx(jv,{className:"h-8 w-8"})}),e.jsx("h3",{className:"text-lg font-medium text-zinc-300",children:i}),d&&e.jsx("p",{className:"mt-1.5 max-w-sm text-sm text-zinc-500",children:d}),c&&e.jsx("div",{className:"mt-4",children:c})]})}function Aj(){const{t:n}=Je(),{agents:i,loading:d,error:c,refetch:m}=wj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState({name:"",description:"",adapterType:"claude",model:"",trustLevel:"community"}),y=async()=>{if(p.name.trim()){g(!0);try{await la.create({name:p.name,description:p.description||void 0,adapterType:p.adapterType,adapterConfig:p.model?{model:p.model}:{},trustLevel:p.trustLevel}),h(!1),S({name:"",description:"",adapterType:"claude",model:"",trustLevel:"community"}),m()}catch(v){console.error("Failed to create agent:",v)}finally{g(!1)}}};return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("agents.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("agents.create")]})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(Ts,{className:"h-8 w-8"}),title:n("agents.empty"),description:n("agents.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("agents.create")]})}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:i.map(v=>e.jsx(Cj,{agent:v},v.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("agents.create")}),e.jsx("button",{onClick:()=>h(!1),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.name")}),e.jsx("input",{className:"input",value:p.name,onChange:v=>S({...p,name:v.target.value}),placeholder:"My Agent"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.description")}),e.jsx("textarea",{className:"input min-h-[80px] resize-none",value:p.description,onChange:v=>S({...p,description:v.target.value}),placeholder:"What does this agent do?"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Adapter"}),e.jsxs("select",{className:"input",value:p.adapterType,onChange:v=>S({...p,adapterType:v.target.value}),children:[e.jsx("option",{value:"claude",children:"Anthropic (Claude)"}),e.jsx("option",{value:"openai",children:"OpenAI (GPT)"}),e.jsx("option",{value:"gemini",children:"Google (Gemini)"}),e.jsx("option",{value:"grok",children:"xAI (Grok)"}),e.jsx("option",{value:"mistral",children:"Mistral AI"}),e.jsx("option",{value:"ollama",children:"Ollama (Local)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Model"}),e.jsx("input",{className:"input",value:p.model,onChange:v=>S({...p,model:v.target.value}),placeholder:"claude-sonnet-4-20250514"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Trust Level"}),e.jsxs("select",{className:"input",value:p.trustLevel,onChange:v=>S({...p,trustLevel:v.target.value}),children:[e.jsx("option",{value:"builtin",children:"Built-in"}),e.jsx("option",{value:"official",children:"Official"}),e.jsx("option",{value:"trusted",children:"Trusted"}),e.jsx("option",{value:"community",children:"Community"}),e.jsx("option",{value:"local",children:"Local"})]})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>h(!1),className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:y,disabled:!p.name.trim()||b,className:"btn-primary",children:n(b?"common.loading":"agents.create")})]})]})})]})}const Ej="/api";async function Tj(n){const i=localStorage.getItem("nestor_token"),d={"Content-Type":"application/json"};i&&(d.Authorization=`Bearer ${i}`);const c=localStorage.getItem("nestor_tenant_id");c&&(d["X-Tenant-ID"]=c);try{const m=await fetch(`${Ej}/agents/${n}/quality`,{headers:d});return m.ok?(await m.json()).data??null:null}catch{return null}}function Yh(n){return`${(n*100).toFixed(0)}%`}function qr({icon:n,label:i,value:d,subtext:c,color:m}){return e.jsxs("div",{className:"rounded-lg bg-zinc-800/50 p-4 border border-zinc-700/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(n,{className:`h-4 w-4 ${m}`}),e.jsx("span",{className:"text-xs text-zinc-500 uppercase tracking-wide",children:i})]}),e.jsx("p",{className:`text-2xl font-bold ${m}`,children:d}),c&&e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:c})]})}function Rj({agentId:n}){const[i,d]=u.useState(null),[c,m]=u.useState(!0),f=u.useCallback(async()=>{m(!0);const w=await Tj(n);d(w),m(!1)},[n]);if(u.useEffect(()=>{f()},[f]),c)return e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Quality"}),e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})})]});if(!i)return e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Quality"}),e.jsx("p",{className:"text-sm text-zinc-500",children:"No quality data available yet."})]});const h=i.satisfactionRate>=.8?"text-green-400":i.satisfactionRate>=.5?"text-yellow-400":"text-red-400",b=i.successRate>=.8?"text-green-400":i.successRate>=.5?"text-yellow-400":"text-red-400",g=i.recentFeedback.filter(w=>w.rating===1).length,p=i.recentFeedback.length,S=p>0?g/p:0,y=i.satisfactionRate,v=p<3?"stable":S>y+.1?"improving":S<y-.1?"declining":"stable",k=v==="improving"?oc:v==="declining"?Bv:Av,C=v==="improving"?"text-green-400":v==="declining"?"text-red-400":"text-zinc-400";return e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-medium text-zinc-200",children:"Quality"}),e.jsxs("div",{className:`flex items-center gap-1 text-xs ${C}`,children:[e.jsx(k,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"capitalize",children:v})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsx(qr,{icon:yi,label:"Satisfaction",value:Yh(i.satisfactionRate),subtext:`${i.positiveFeedback}/${i.totalFeedback} positive`,color:h}),e.jsx(qr,{icon:et,label:"Success Rate",value:Yh(i.successRate),subtext:`${i.completedRuns} completed, ${i.failedRuns} failed`,color:b}),e.jsx(qr,{icon:us,label:"Avg Cost / Run",value:`$${i.avgCostPerRun.toFixed(4)}`,subtext:`${i.totalRuns} total runs`,color:"text-blue-400"}),e.jsx(qr,{icon:Rs,label:"Total Runs",value:i.totalRuns.toString(),subtext:`${i.totalFeedback} rated`,color:"text-indigo-400"})]}),i.recentFeedback.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("h3",{className:"text-xs font-medium text-zinc-500 uppercase tracking-wide mb-2",children:"Recent Feedback"}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:i.recentFeedback.slice(0,10).map((w,N)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:w.rating===1?"text-green-400":"text-red-400",children:w.rating===1?"+":"-"}),e.jsx("span",{className:"text-zinc-400 flex-1",children:w.comment??(w.rating===1?"Positive":"Negative")}),e.jsx("span",{className:"text-zinc-600 shrink-0",children:new Date(w.createdAt).toLocaleDateString()})]},N))})]})]})}function Mj({event:n}){switch(n.type){case"tool_start":return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-1.5",children:[e.jsx(cl,{className:"h-3.5 w-3.5 text-amber-400"}),e.jsx("span",{className:"text-xs text-amber-300 font-medium",children:n.name}),e.jsx(rt,{className:"h-3 w-3 text-amber-400 animate-spin"})]});case"tool_result":return e.jsxs("div",{className:`flex items-center gap-2 rounded-md border px-3 py-1.5 ${n.success?"border-emerald-500/20 bg-emerald-500/5":"border-red-500/20 bg-red-500/5"}`,children:[n.success?e.jsx(et,{className:"h-3.5 w-3.5 text-emerald-400"}):e.jsx(ft,{className:"h-3.5 w-3.5 text-red-400"}),e.jsxs("span",{className:`text-xs font-medium ${n.success?"text-emerald-300":"text-red-300"}`,children:[n.name," ",n.success?"completed":"failed"]})]});case"reasoning":return e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-yellow-500/20 bg-yellow-500/5 px-3 py-1.5",children:[e.jsx(Zd,{className:"h-3.5 w-3.5 text-yellow-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[n.phase&&e.jsx("span",{className:"text-[10px] uppercase text-yellow-600 font-mono",children:n.phase}),e.jsx("p",{className:"text-xs text-yellow-200/80 break-words",children:n.reasoning}),n.confidence!=null&&e.jsxs("span",{className:"text-[10px] text-yellow-600",children:["confidence: ",(n.confidence*100).toFixed(0),"%"]})]})]});case"error":return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-red-500/20 bg-red-500/5 px-3 py-1.5",children:[e.jsx(ft,{className:"h-3.5 w-3.5 text-red-400"}),e.jsx("span",{className:"text-xs text-red-300",children:n.text})]});default:return null}}function Dj({runId:n,onComplete:i}){const[d,c]=u.useState(""),[m,f]=u.useState([]),[h,b]=u.useState(!0),g=u.useRef(null),p=u.useRef(0),{subscribe:S,unsubscribe:y,events:v,connected:k}=pu([`run:${n}`]);return u.useEffect(()=>(k&&S(`run:${n}`),()=>{y(`run:${n}`)}),[k,n,S,y]),u.useEffect(()=>{for(const C of v){if(C.channel!==`run:${n}`)continue;const w=C.data;if(!w||w.runId!==n)continue;const N=w.type,z=++p.current;switch(N){case"token":c(R=>R+(w.text??""));break;case"tool_start":f(R=>[...R,{id:z,type:"tool_start",name:w.name,args:w.args,timestamp:Date.now()}]);break;case"tool_result":f(R=>[...R,{id:z,type:"tool_result",name:w.name,result:w.result,success:w.success,timestamp:Date.now()}]);break;case"reasoning":{const R=w.entry;f(D=>[...D,{id:z,type:"reasoning",reasoning:(R==null?void 0:R.reasoning)??w.reasoning??"",phase:(R==null?void 0:R.phase)??void 0,confidence:(R==null?void 0:R.confidence)??void 0,timestamp:Date.now()}]);break}case"error":f(R=>[...R,{id:z,type:"error",text:w.message,timestamp:Date.now()}]);break;case"done":b(!1),i==null||i();break}}},[v,n,i]),u.useEffect(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},[d]),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M0,{className:`h-3.5 w-3.5 ${h?"text-green-400 animate-pulse":"text-zinc-500"}`}),e.jsx("span",{className:"text-xs font-medium text-zinc-400",children:h?"Live Output":"Run Completed"}),!k&&e.jsx("span",{className:"text-[10px] text-red-400 ml-auto",children:"Disconnected"})]}),e.jsx("div",{ref:g,className:"bg-gray-900 p-4 rounded-lg max-h-96 overflow-y-auto whitespace-pre-wrap font-mono text-sm text-zinc-200 border border-zinc-700",children:d||e.jsx("span",{className:"text-zinc-500 italic",children:h?"Waiting for output...":"No output produced."})}),m.length>0&&e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:m.map(C=>e.jsx(Mj,{event:C},C.id))})]})}function Oj(){const{id:n}=ll(),i=Dt(),{t:d}=Je(),{agent:c,loading:m,error:f}=Sj(n),[h,b]=u.useState("overview"),[g,p]=u.useState(""),[S,y]=u.useState(!1),[v,k]=u.useState(null);if(m)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})});if(f||!c)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[e.jsx("p",{className:"text-red-400",children:f??"Agent not found"}),e.jsxs("button",{onClick:()=>i("/agents"),className:"btn-secondary mt-4",children:[e.jsx(Wn,{className:"h-4 w-4"})," Back to Agents"]})]});const C=async()=>{var z;if(!(!g.trim()||!n)){y(!0);try{const R=await la.run(n,g),D=((z=R==null?void 0:R.data)==null?void 0:z.id)??null;k(D),p("")}catch(R){console.error("Run failed:",R)}finally{y(!1)}}},w=async()=>{if(n&&window.confirm(`Delete agent "${c.name}"?`))try{await la.delete(n),i("/agents")}catch(z){console.error("Delete failed:",z)}},N=[{key:"overview",label:d("agent.overview"),icon:Rs},{key:"quality",label:"Quality",icon:It},{key:"runs",label:d("agent.runs"),icon:Nt},{key:"events",label:d("agent.events"),icon:It},{key:"configuration",label:d("agent.configuration"),icon:il}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("button",{onClick:()=>i("/agents"),className:"btn-ghost btn-sm",children:e.jsx(Wn,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-400",children:e.jsx(Ts,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:c.name}),e.jsx(wi,{status:"idle"})]}),e.jsxs("p",{className:"text-sm text-zinc-400",children:[c.adapterType,c.adapterConfig.model?` / ${c.adapterConfig.model}`:"",e.jsx("span",{className:"mx-2 text-zinc-600",children:"|"}),e.jsx(bu,{level:c.trustLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"})," ",d("agent.start")]}),e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(Lv,{className:"h-3.5 w-3.5"})," ",d("agent.stop")]}),e.jsxs("button",{onClick:w,className:"btn-danger btn-sm",children:[e.jsx(Ot,{className:"h-3.5 w-3.5"})," ",d("agent.delete")]})]})]}),e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(O0,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{className:"input pl-9",placeholder:"Enter a prompt to run this agent...",value:g,onChange:z=>p(z.target.value),onKeyDown:z=>z.key==="Enter"&&C()})]}),e.jsxs("button",{onClick:C,disabled:!g.trim()||S,className:"btn-primary",children:[e.jsx(Nt,{className:"h-4 w-4"}),d(S?"common.loading":"agent.run")]})]})}),v&&e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M0,{className:"h-4 w-4 text-green-400 animate-pulse"}),e.jsx("h3",{className:"text-sm font-medium text-zinc-200",children:"Live Output"}),e.jsxs("span",{className:"text-[10px] font-mono text-zinc-500",children:[v.slice(0,12),"..."]})]}),e.jsx("button",{onClick:()=>k(null),className:"text-xs text-zinc-500 hover:text-zinc-300 transition-colors",children:"Dismiss"})]}),e.jsx(Dj,{runId:v,onComplete:()=>{}})]}),e.jsx("div",{className:"flex gap-1 border-b border-border",children:N.map(({key:z,label:R,icon:D})=>e.jsxs("button",{onClick:()=>b(z),className:`flex items-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors border-b-2 ${h===z?"border-indigo-500 text-indigo-400":"border-transparent text-zinc-400 hover:text-zinc-200"}`,children:[e.jsx(D,{className:"h-4 w-4"}),R]},z))}),h==="quality"&&n&&e.jsx(Rj,{agentId:n}),h==="overview"&&e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:d("agent.budget")}),e.jsx(H0,{spent:0,limit:10}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-3",children:[e.jsx("p",{className:"text-xs text-zinc-500",children:"Total Spent"}),e.jsx("p",{className:"text-lg font-semibold text-white",children:"$0.00"})]}),e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-3",children:[e.jsx("p",{className:"text-xs text-zinc-500",children:"Runs Today"}),e.jsx("p",{className:"text-lg font-semibold text-white",children:"0"})]})]})]}),e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:d("agent.recentRuns")}),e.jsx("p",{className:"text-sm text-zinc-500",children:"No runs recorded yet."})]}),c.description&&e.jsxs("div",{className:"card lg:col-span-2",children:[e.jsx("h3",{className:"mb-2 text-lg font-medium text-zinc-200",children:d("common.description")}),e.jsx("p",{className:"text-sm text-zinc-400",children:c.description})]})]}),h==="runs"&&e.jsx("div",{className:"card",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-left",children:[e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:"Run ID"}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:d("common.status")}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:d("run.duration")}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:"Cost"}),e.jsx("th",{className:"pb-3 text-zinc-400 font-medium",children:d("common.created")})]})}),e.jsx("tbody",{children:e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-8 text-center text-zinc-500",children:"No runs recorded for this agent."})})})]})})}),h==="events"&&e.jsx("div",{className:"card",children:e.jsx(gu,{events:[],maxHeight:"500px"})}),h==="configuration"&&e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Agent Configuration"}),e.jsx("pre",{className:"overflow-auto rounded-lg bg-[#0a0a0f] p-4 text-sm text-zinc-300",children:JSON.stringify(c,null,2)})]})]})}function Lj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await sc.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch workflows")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{workflows:n,loading:d,error:m,refetch:h}}function _j(n){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(null),b=u.useCallback(async()=>{if(n){m(!0),h(null);try{const g=await sc.get(n);d(g.data)}catch(g){h(g instanceof Error?g.message:"Failed to fetch workflow")}finally{m(!1)}}},[n]);return u.useEffect(()=>{b()},[b]),{workflow:i,loading:c,error:f,refetch:b}}const Uj=[{id:"tdd-loop",name:"TDD Loop",description:"spec → code → test → fix → repeat",icon:e.jsx(xt,{className:"h-5 w-5"}),color:"text-green-400 bg-green-500/10",entryNodeId:"spec",nodes:[{id:"spec",type:"agent",label:"Write Spec",config:{role:"spec-writer",prompt:"Write a detailed specification for the feature"},next:["code"]},{id:"code",type:"agent",label:"Implement Code",config:{role:"developer",prompt:"Implement the code based on the specification"},next:["test"]},{id:"test",type:"agent",label:"Run Tests",config:{role:"tester",prompt:"Write and run tests against the implementation"},next:["check"]},{id:"check",type:"condition",label:"Tests Pass?",config:{},condition:"result.allPassed === true",next:["done","fix"]},{id:"fix",type:"agent",label:"Fix Issues",config:{role:"developer",prompt:"Fix the failing tests based on error output"},next:["test"]},{id:"done",type:"agent",label:"Complete",config:{role:"reporter",prompt:"Generate a summary of the implementation and test results"},next:[]}]},{id:"content-pipeline",name:"Content Pipeline",description:"research → draft → review → publish",icon:e.jsx(Ua,{className:"h-5 w-5"}),color:"text-amber-400 bg-amber-500/10",entryNodeId:"research",nodes:[{id:"research",type:"agent",label:"Research",config:{role:"researcher",prompt:"Research the topic and gather relevant sources and data"},next:["draft"]},{id:"draft",type:"agent",label:"Draft",config:{role:"writer",prompt:"Write a draft based on the research findings"},next:["review"]},{id:"review",type:"agent",label:"Review",config:{role:"editor",prompt:"Review the draft for accuracy, style, and completeness"},next:["publish"]},{id:"publish",type:"agent",label:"Publish",config:{role:"publisher",prompt:"Format and prepare the final content for publication"},next:[]}]},{id:"ralph-3phase",name:"Ralph 3-Phase",description:"spec-writer → planner → builder (with backpressure)",icon:e.jsx(wv,{className:"h-5 w-5"}),color:"text-purple-400 bg-purple-500/10",entryNodeId:"spec-writer",nodes:[{id:"spec-writer",type:"agent",label:"Spec Writer",config:{role:"spec-writer",prompt:"Analyze requirements and produce a detailed technical specification",backpressure:{validator:"spec",strictness:"strict"}},next:["planner"]},{id:"planner",type:"agent",label:"Planner",config:{role:"planner",prompt:"Break the specification into an ordered plan of implementation tasks",backpressure:{validator:"plan",strictness:"strict"}},next:["builder"]},{id:"builder",type:"agent",label:"Builder",config:{role:"builder",prompt:"Execute each task from the plan, implementing the specification",backpressure:{validator:"code",strictness:"normal"}},next:[]}]}];function $j(){const{t:n}=Je(),{workflows:i,loading:d,error:c,refetch:m}=Lj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState({name:"",description:""}),[y,v]=u.useState(null),[k,C]=u.useState(null),[w,N]=u.useState([]),[z,R]=u.useState(null),D=u.useRef(null),O=u.useCallback(async A=>{C(A),N([]),R(null);try{const $=(await sc.run(A)).data.id,Q=localStorage.getItem("nestor_token"),ce=localStorage.getItem("nestor_tenant_id"),I=new URLSearchParams;I.set("channels",`run:${$}`),Q&&I.set("token",Q),ce&&I.set("tenantId",ce);const le=new EventSource(`/api/events/stream?${I.toString()}`);D.current=le,le.onmessage=Y=>{var B;try{const ne=JSON.parse(Y.data);(ne.type==="run:progress"||ne.type==="node:start"||ne.type==="node:complete")&&N(me=>{var ue,je;return[...me,((ue=ne.data)==null?void 0:ue.message)||((je=ne.data)==null?void 0:je.node)||ne.type]}),(ne.type==="run:complete"||ne.type==="run:completed")&&(R({id:A,status:"completed",message:"Workflow completed successfully"}),le.close(),C(null),m()),(ne.type==="run:failed"||ne.type==="run:error")&&(R({id:A,status:"failed",message:((B=ne.data)==null?void 0:B.error)||"Workflow failed"}),le.close(),C(null))}catch{}},le.onerror=()=>{le.close(),setTimeout(()=>{C(null),z||R({id:A,status:"completed",message:"Run started (stream ended)"}),m()},2e3)}}catch(F){R({id:A,status:"failed",message:F instanceof Error?F.message:"Failed to start"}),C(null)}},[m,z]),se=A=>{v(A),S({name:A.name,description:A.description})},Z=()=>{v(null),S({name:"",description:""})},U=async()=>{if(p.name.trim()){g(!0);try{const A=y?y.nodes:[{id:"start",type:"agent",label:"Start",config:{},next:[]}],F=y?y.entryNodeId:"start";await sc.create({name:p.name,description:p.description||void 0,nodes:A,entryNodeId:F}),h(!1),S({name:"",description:""}),v(null),m()}catch(A){console.error("Failed to create workflow:",A)}finally{g(!1)}}};return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("workflows.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("workflows.create")]})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(tc,{className:"h-8 w-8"}),title:n("workflows.empty"),description:n("workflows.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("workflows.create")]})}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:i.map(A=>e.jsxs("div",{className:"card group hover:border-indigo-500/30 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500/10 text-blue-400",children:e.jsx(tc,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:A.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["v",A.currentVersion]})]})]}),e.jsx(wi,{status:"idle"})]}),A.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:A.description}),k===A.id&&w.length>0&&e.jsxs("div",{className:"mt-3 rounded-md bg-purple-500/5 border border-purple-500/10 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(rt,{className:"h-3 w-3 animate-spin text-purple-400"}),e.jsx("span",{className:"text-xs font-medium text-purple-300",children:n("workflows.running")})]}),e.jsx("div",{className:"max-h-16 overflow-y-auto",children:w.slice(-3).map((F,$)=>e.jsx("p",{className:"text-[11px] text-zinc-400 truncate",children:F},$))})]}),z&&z.id===A.id&&e.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-md p-2 text-xs ${z.status==="completed"?"bg-green-500/5 border border-green-500/10 text-green-400":"bg-red-500/5 border border-red-500/10 text-red-400"}`,children:[z.status==="completed"?e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(ft,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:z.message}),e.jsx("button",{onClick:()=>R(null),className:"ml-auto flex-shrink-0 text-zinc-500 hover:text-zinc-300",children:e.jsx(Ze,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-zinc-500",children:[n("common.updated"),": ",new Date(A.updatedAt).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(ta,{to:`/workflows/${A.id}/edit`,className:"btn-ghost btn-sm",children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>O(A.id),disabled:k!==null,className:"btn-ghost btn-sm text-green-400 disabled:opacity-50",title:n("workflows.run"),children:k===A.id?e.jsx(rt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5"})})]})]})]},A.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-border bg-surface p-6 shadow-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("workflows.create")}),e.jsx("button",{onClick:()=>{h(!1),Z()},className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-medium text-zinc-500 uppercase tracking-wider mb-3",children:"Start from a template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Uj.map(A=>e.jsxs("button",{onClick:()=>se(A),className:`group text-left rounded-xl border p-3 transition-all ${(y==null?void 0:y.id)===A.id?"border-indigo-500/50 bg-indigo-500/10 ring-1 ring-indigo-500/30":"border-border/50 bg-zinc-900/60 hover:border-indigo-500/30 hover:bg-indigo-500/5"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:`flex h-7 w-7 items-center justify-center rounded-lg ${A.color}`,children:A.icon}),e.jsx("span",{className:"text-sm font-medium text-zinc-200",children:A.name})]}),e.jsx("p",{className:"text-[11px] text-zinc-500 leading-relaxed",children:A.description}),e.jsxs("p",{className:"text-[10px] text-zinc-600 mt-1.5",children:[A.nodes.length," nodes"]})]},A.id))}),y&&e.jsx("button",{onClick:Z,className:"mt-2 text-xs text-zinc-500 hover:text-zinc-300 underline",children:"Clear template selection"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.name")}),e.jsx("input",{className:"input",value:p.name,onChange:A=>S({...p,name:A.target.value}),placeholder:"My Workflow"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.description")}),e.jsx("textarea",{className:"input min-h-[80px] resize-none",value:p.description,onChange:A=>S({...p,description:A.target.value}),placeholder:"What does this workflow do?"})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>{h(!1),Z()},className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:U,disabled:!p.name.trim()||b,className:"btn-primary",children:n(b?"common.loading":"workflows.create")})]})]})})]})}const Xh={agent:"border-indigo-500 bg-indigo-500/10",tool:"border-emerald-500 bg-emerald-500/10",condition:"border-amber-500 bg-amber-500/10",parallel:"border-blue-500 bg-blue-500/10",loop:"border-violet-500 bg-violet-500/10",human:"border-rose-500 bg-rose-500/10"},Gr={agent:"Agent",tool:"Tool",condition:"Condition",parallel:"Parallel",loop:"Loop",human:"Human"};function Bj(n,i){var g;const d=new Map;if(n.length===0)return d;const c=new Set,m=[],f=new Map,h=i??((g=n[0])==null?void 0:g.id);for(h&&m.push({id:h,depth:0,index:0});m.length>0;){const{id:p,depth:S}=m.shift();if(c.has(p))continue;c.add(p);const y=f.get(S)??0;f.set(S,y+1),d.set(p,{x:80+y*220,y:60+S*120});const v=n.find(k=>k.id===p);if(v)for(const k of v.next)c.has(k)||m.push({id:k,depth:S+1,index:0})}let b=(f.get(0)??0)*220+80;for(const p of n)c.has(p.id)||(d.set(p.id,{x:b,y:60}),b+=220);return d}function Hj(){const{id:n}=ll(),i=Dt(),{t:d}=Je(),{workflow:c,loading:m,error:f}=_j(n),[h,b]=u.useState([]),[g,p]=u.useState(),[S,y]=u.useState(null),[v,k]=u.useState(!1),[C,w]=u.useState({label:"",type:"agent"});u.useEffect(()=>{c!=null&&c.nodes&&(b(c.nodes),p(c.entryNodeId))},[c]);const N=u.useMemo(()=>Bj(h,g),[h,g]),z=Math.max(800,...Array.from(N.values()).map(U=>U.x+200)),R=Math.max(400,...Array.from(N.values()).map(U=>U.y+100)),D=u.useMemo(()=>{const U=[];for(const A of h){const F=N.get(A.id);if(F)for(const $ of A.next){const Q=N.get($);Q&&U.push({from:F,to:Q,fromId:A.id,toId:$})}}return U},[h,N]),O=u.useCallback(()=>{if(!C.label.trim())return;const U=`node_${Date.now()}`;b(A=>[...A,{id:U,type:C.type,label:C.label,config:{},next:[]}]),h.length===0&&p(U),w({label:"",type:"agent"}),k(!1)},[C,h.length]),se=u.useCallback(U=>{var A;b(F=>F.filter(Q=>Q.id!==U).map(Q=>({...Q,next:Q.next.filter(ce=>ce!==U)}))),S===U&&y(null),g===U&&p((A=h.find(F=>F.id!==U))==null?void 0:A.id)},[S,g,h]),Z=h.find(U=>U.id===S);return m?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[e.jsx("p",{className:"text-red-400",children:f}),e.jsxs("button",{onClick:()=>i("/workflows"),className:"btn-secondary mt-4",children:[e.jsx(Wn,{className:"h-4 w-4"})," Back to Workflows"]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>i("/workflows"),className:"btn-ghost btn-sm",children:e.jsx(Wn,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-2xl font-semibold text-white",children:(c==null?void 0:c.name)??d("workflow.editor")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>k(!0),className:"btn-secondary btn-sm",children:[e.jsx(ht,{className:"h-3.5 w-3.5"})," ",d("workflow.addNode")]}),e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(cc,{className:"h-3.5 w-3.5"})," ",d("workflow.save")]}),e.jsxs("button",{className:"btn-primary btn-sm",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"})," ",d("workflow.run")]})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"card flex-1 overflow-auto p-0",style:{minHeight:"500px"},children:[e.jsxs("svg",{width:z,height:R,className:"w-full",children:[D.map((U,A)=>{const F=U.from.x+80,$=U.from.y+40,Q=U.to.x+80,ce=U.to.y,I=($+ce)/2;return e.jsx("path",{d:`M ${F} ${$} C ${F} ${I}, ${Q} ${I}, ${Q} ${ce}`,fill:"none",stroke:"#2a2a35",strokeWidth:"2",markerEnd:"url(#arrowhead)"},A)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"8",markerHeight:"6",refX:"7",refY:"3",orient:"auto",children:e.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"#2a2a35"})})})]}),e.jsx("div",{className:"absolute inset-0",style:{width:z,height:R},children:h.map(U=>{const A=N.get(U.id);if(!A)return null;const F=U.id===g,$=U.id===S;return e.jsxs("div",{className:`absolute cursor-pointer rounded-lg border-2 px-4 py-2.5 text-sm transition-all ${Xh[U.type]} ${$?"ring-2 ring-indigo-500 ring-offset-2 ring-offset-[#0a0a0f]":""} ${F?"shadow-lg":""}`,style:{left:A.x,top:A.y,width:160},onClick:()=>y(U.id),children:[e.jsx("div",{className:"font-medium text-zinc-200 truncate",children:U.label}),e.jsx("div",{className:"text-xs text-zinc-500 mt-0.5",children:Gr[U.type]}),F&&e.jsx("div",{className:"absolute -top-2 -right-2 h-4 w-4 rounded-full bg-indigo-500 border-2 border-[#0a0a0f]"})]},U.id)})}),h.length===0&&e.jsx("div",{className:"flex items-center justify-center h-full text-zinc-500 text-sm",children:"Add nodes to build your workflow DAG"})]}),Z&&e.jsxs("div",{className:"w-72 card space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:"Node Properties"}),e.jsx("button",{onClick:()=>y(null),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Label"}),e.jsx("input",{className:"input",value:Z.label,onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,label:U.target.value}:F))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:d("common.type")}),e.jsx("select",{className:"input",value:Z.type,onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,type:U.target.value}:F)),children:Object.entries(Gr).map(([U,A])=>e.jsx("option",{value:U,children:A},U))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Agent ID"}),e.jsx("input",{className:"input",value:Z.agentId??"",onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,agentId:U.target.value||void 0}:F)),placeholder:"Optional agent ID"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Connect to"}),e.jsxs("select",{className:"input",value:"",onChange:U=>{U.target.value&&b(A=>A.map(F=>F.id===Z.id&&!F.next.includes(U.target.value)?{...F,next:[...F.next,U.target.value]}:F))},children:[e.jsx("option",{value:"",children:"Select a node..."}),h.filter(U=>U.id!==Z.id&&!Z.next.includes(U.id)).map(U=>e.jsx("option",{value:U.id,children:U.label},U.id))]}),Z.next.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:Z.next.map(U=>{const A=h.find(F=>F.id===U);return e.jsxs("div",{className:"flex items-center justify-between rounded bg-[#0a0a0f] px-2 py-1 text-xs",children:[e.jsx("span",{className:"text-zinc-400",children:(A==null?void 0:A.label)??U}),e.jsx("button",{onClick:()=>b(F=>F.map($=>$.id===Z.id?{...$,next:$.next.filter(Q=>Q!==U)}:$)),className:"text-zinc-500 hover:text-red-400",children:e.jsx(Ze,{className:"h-3 w-3"})})]},U)})})]}),e.jsxs("button",{onClick:()=>se(Z.id),className:"btn-danger w-full",children:[e.jsx(Ot,{className:"h-3.5 w-3.5"}),"Delete Node"]})]})]}),v&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:d("workflow.addNode")}),e.jsx("button",{onClick:()=>k(!1),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Label"}),e.jsx("input",{className:"input",value:C.label,onChange:U=>w({...C,label:U.target.value}),placeholder:"Node label"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:d("common.type")}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Object.keys(Gr).map(U=>e.jsx("button",{onClick:()=>w({...C,type:U}),className:`rounded-lg border-2 p-2.5 text-center text-xs font-medium transition-colors ${C.type===U?Xh[U]:"border-border text-zinc-400 hover:border-zinc-600"}`,children:Gr[U]},U))})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>k(!1),className:"btn-secondary",children:d("common.cancel")}),e.jsx("button",{onClick:O,disabled:!C.label.trim(),className:"btn-primary",children:d("workflow.addNode")})]})]})})]})}function qj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await Wr.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch skills")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{skills:n,loading:d,error:m,refetch:h}}function Gj({skill:n,onDelete:i}){return e.jsxs("div",{className:"card group hover:border-indigo-500/30 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-violet-500/10 text-violet-400",children:e.jsx(rc,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:n.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["v",n.version," by ",n.author]})]})]}),e.jsx(bu,{level:n.trustLevel})]}),n.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:n.description}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.tags.slice(0,3).map(d=>e.jsx("span",{className:"rounded-md bg-zinc-800 px-2 py-0.5 text-xs text-zinc-400",children:d},d)),n.tags.length>3&&e.jsxs("span",{className:"text-xs text-zinc-500",children:["+",n.tags.length-3]})]}),i&&e.jsx("button",{onClick:d=>{d.preventDefault(),i(n.id)},className:"btn-ghost btn-sm text-zinc-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})]})]})}function Kj(){const{t:n}=Je(),{skills:i,loading:d,error:c,refetch:m}=qj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState(""),[y,v]=u.useState({source:"",type:"local",name:"",trustLevel:"community"}),[k,C]=u.useState(null),w=async()=>{if(y.source.trim()){g(!0);try{await Wr.install({source:y.source,type:y.type,name:y.name||void 0,trustLevel:y.trustLevel}),h(!1),v({source:"",type:"local",name:"",trustLevel:"community"}),m()}catch(D){console.error("Failed to install skill:",D)}finally{g(!1)}}},N=async D=>{if(window.confirm("Remove this skill?"))try{await Wr.delete(D),m()}catch(O){console.error("Failed to delete skill:",O)}},z=async()=>{if(y.source.trim())try{const D=await Wr.scan(y.source);C(D)}catch(D){console.error("Scan failed:",D)}},R=i.filter(D=>!p||D.name.toLowerCase().includes(p.toLowerCase())||D.description.toLowerCase().includes(p.toLowerCase())||D.tags.some(O=>O.toLowerCase().includes(p.toLowerCase())));return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("skills.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("skills.install")]})]}),i.length>0&&e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{type:"text",className:"input pl-9",placeholder:n("common.search"),value:p,onChange:D=>S(D.target.value)})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(rc,{className:"h-8 w-8"}),title:n("skills.empty"),description:n("skills.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("skills.install")]})}):R.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-zinc-500",children:n("common.noResults")}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:R.map(D=>e.jsx(Gj,{skill:D,onDelete:N},D.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("skills.install")}),e.jsx("button",{onClick:()=>{h(!1),C(null)},className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("skills.source")}),e.jsx("input",{className:"input",value:y.source,onChange:D=>v({...y,source:D.target.value}),placeholder:"/path/to/skill or https://..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.type")}),e.jsxs("select",{className:"input",value:y.type,onChange:D=>v({...y,type:D.target.value}),children:[e.jsx("option",{value:"local",children:"Local"}),e.jsx("option",{value:"npm",children:"NPM"}),e.jsx("option",{value:"git",children:"Git"}),e.jsx("option",{value:"url",children:"URL"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"label",children:[n("common.name")," (optional)"]}),e.jsx("input",{className:"input",value:y.name,onChange:D=>v({...y,name:D.target.value}),placeholder:"my-skill"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Trust Level"}),e.jsxs("select",{className:"input",value:y.trustLevel,onChange:D=>v({...y,trustLevel:D.target.value}),children:[e.jsx("option",{value:"builtin",children:"Built-in"}),e.jsx("option",{value:"official",children:"Official"}),e.jsx("option",{value:"trusted",children:"Trusted"}),e.jsx("option",{value:"community",children:"Community"}),e.jsx("option",{value:"local",children:"Local"})]})]}),k&&e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-4",children:[e.jsx("h4",{className:"text-sm font-medium text-zinc-300 mb-2",children:"Scan Results"}),e.jsx("pre",{className:"text-xs text-zinc-400 overflow-auto max-h-40",children:JSON.stringify(k,null,2)})]})]}),e.jsxs("div",{className:"mt-6 flex justify-between",children:[e.jsxs("button",{onClick:z,disabled:!y.source.trim(),className:"btn-secondary",children:[e.jsx(yv,{className:"h-4 w-4"}),n("skills.scan")]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>{h(!1),C(null)},className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:w,disabled:!y.source.trim()||b,className:"btn-primary",children:n(b?"common.loading":"skills.install")})]})]})]})})]})}function Vj(){const{t:n}=Je(),[i,d]=u.useState([]),[c,m]=u.useState(!0),[f,h]=u.useState(null),[b,g]=u.useState("all"),p=u.useCallback(async()=>{m(!0),h(null);try{const v={limit:100};b!=="all"&&(v.status=b);const k=await ln.list(v);d(k.data)}catch(v){h(v instanceof Error?v.message:"Failed to fetch runs"),d([])}finally{m(!1)}},[b]);u.useEffect(()=>{p()},[p]);const S=async v=>{try{await ln.abort(v),p()}catch(k){console.error("Abort failed:",k)}},y=async v=>{if(window.confirm("Delete this run record?"))try{await ln.delete(v),d(k=>k.filter(C=>C.id!==v))}catch(k){console.error("Delete failed:",k)}};return c?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("runs.title")}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:p,className:"btn-ghost btn-sm",children:e.jsx(xt,{className:"h-4 w-4"})}),e.jsx(R0,{className:"h-4 w-4 text-zinc-500"}),e.jsxs("select",{className:"input w-auto",value:b,onChange:v=>g(v.target.value),children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"running",children:n("status.running")}),e.jsx("option",{value:"completed",children:n("status.completed")}),e.jsx("option",{value:"failed",children:n("status.failed")}),e.jsx("option",{value:"pending",children:n("status.pending")}),e.jsx("option",{value:"paused",children:n("status.paused")}),e.jsx("option",{value:"cancelled",children:n("status.cancelled")})]})]})]}),f&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[f,e.jsx("button",{onClick:p,className:"ml-3 underline",children:n("common.retry")})]}),i.length===0&&!f?e.jsx(cn,{icon:e.jsx(Nt,{className:"h-8 w-8"}),title:n("runs.empty"),description:n("runs.emptyDesc")}):i.length>0?e.jsx("div",{className:"card overflow-hidden p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-surface",children:[e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Run ID"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Workflow"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("common.status")}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Started"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("run.duration")}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("common.actions")})]})}),e.jsx("tbody",{children:i.map(v=>{var C;const k=v.completedAt&&v.startedAt?Math.round((new Date(v.completedAt).getTime()-new Date(v.startedAt).getTime())/1e3):null;return e.jsxs("tr",{className:"border-b border-border hover:bg-surface-hover transition-colors",children:[e.jsx("td",{className:"px-5 py-3",children:e.jsxs(ta,{to:`/runs/${v.id}`,className:"text-indigo-400 hover:text-indigo-300 font-mono text-xs",children:[v.id.slice(0,8),"..."]})}),e.jsxs("td",{className:"px-5 py-3 text-zinc-300 font-mono text-xs",children:[((C=v.workflowId)==null?void 0:C.slice(0,8))??"—","..."]}),e.jsx("td",{className:"px-5 py-3",children:e.jsx(wi,{status:v.status,pulse:!0})}),e.jsx("td",{className:"px-5 py-3 text-zinc-400 text-xs",children:new Date(v.startedAt).toLocaleString()}),e.jsx("td",{className:"px-5 py-3 text-zinc-400 text-xs",children:k!==null?`${k}s`:"—"}),e.jsx("td",{className:"px-5 py-3",children:e.jsxs("div",{className:"flex gap-1",children:[(v.status==="running"||v.status==="pending")&&e.jsx("button",{onClick:()=>S(v.id),className:"btn-ghost btn-sm text-amber-400",title:"Abort run",children:e.jsx(E0,{className:"h-3.5 w-3.5"})}),(v.status==="completed"||v.status==="failed"||v.status==="cancelled")&&e.jsx("button",{onClick:()=>y(v.id),className:"btn-ghost btn-sm text-zinc-400 hover:text-red-400",title:"Delete run",children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})]})})]},v.id)})})]})})}):null]})}const q0="/api";async function Yj(n){const i=localStorage.getItem("nestor_token"),d={"Content-Type":"application/json"};i&&(d.Authorization=`Bearer ${i}`);const c=localStorage.getItem("nestor_tenant_id");c&&(d["X-Tenant-ID"]=c);const m=await fetch(`${q0}/runs/${n}/feedback`,{headers:d});return m.ok?(await m.json()).data??[]:[]}async function Qh(n,i,d,c){const m=localStorage.getItem("nestor_token"),f={"Content-Type":"application/json"};m&&(f.Authorization=`Bearer ${m}`);const h=localStorage.getItem("nestor_tenant_id");h&&(f["X-Tenant-ID"]=h),await fetch(`${q0}/runs/${n}/feedback`,{method:"POST",headers:f,body:JSON.stringify({rating:i,comment:d||void 0,agentId:c})})}function Xj({runId:n,agentId:i}){const[d,c]=u.useState([]),[m,f]=u.useState(!1),[h,b]=u.useState(null),[g,p]=u.useState(""),[S,y]=u.useState(!1),v=u.useCallback(async()=>{const w=await Yj(n);c(w),w.length>0&&(f(!0),b(w[0].rating))},[n]);u.useEffect(()=>{v()},[v]);const k=async w=>{m||(b(w),w===1?(await Qh(n,w,void 0,i),f(!0),v()):y(!0))},C=async()=>{h!==null&&(await Qh(n,h,g||void 0,i),f(!0),y(!1),v())};return e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium text-zinc-400",children:"Was this helpful?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>k(1),disabled:m,className:`rounded-lg p-2 transition-colors ${h===1?"bg-green-500/20 text-green-400":m?"text-zinc-600 cursor-not-allowed":"text-zinc-400 hover:bg-green-500/10 hover:text-green-400"}`,title:"Helpful",children:e.jsx(yi,{className:"h-5 w-5"})}),e.jsx("button",{onClick:()=>k(-1),disabled:m,className:`rounded-lg p-2 transition-colors ${h===-1?"bg-red-500/20 text-red-400":m?"text-zinc-600 cursor-not-allowed":"text-zinc-400 hover:bg-red-500/10 hover:text-red-400"}`,title:"Not helpful",children:e.jsx(Id,{className:"h-5 w-5"})})]})]}),S&&!m&&e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx("input",{type:"text",value:g,onChange:w=>p(w.target.value),placeholder:"What could be improved? (optional)",className:"flex-1 rounded-lg bg-zinc-800 px-3 py-2 text-sm text-zinc-200 placeholder-zinc-500 border border-zinc-700 focus:border-indigo-500 focus:outline-none",onKeyDown:w=>{w.key==="Enter"&&C()}}),e.jsx("button",{onClick:C,className:"rounded-lg bg-indigo-600 px-3 py-2 text-sm text-white hover:bg-indigo-500 transition-colors",children:e.jsx(gi,{className:"h-4 w-4"})})]}),m&&e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:[h===1?"Thanks for the positive feedback!":"Thanks for your feedback.",d.length>0&&d[0].comment&&e.jsxs("span",{className:"text-zinc-600",children:[" — “",d[0].comment,"”"]})]})]})}const Qj={llm_request:{icon:La,color:"text-purple-400",bgColor:"bg-purple-500/10",label:"LLM Request"},llm_response:{icon:Pt,color:"text-blue-400",bgColor:"bg-blue-500/10",label:"LLM Response"},tool_call_requested:{icon:cl,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Tool Call"},tool_call_completed:{icon:et,color:"text-emerald-400",bgColor:"bg-emerald-500/10",label:"Tool Result"},tool_call_denied:{icon:ft,color:"text-red-400",bgColor:"bg-red-500/10",label:"Tool Denied"},node_started:{icon:Nt,color:"text-blue-400",bgColor:"bg-blue-500/10",label:"Step Started"},node_completed:{icon:et,color:"text-green-400",bgColor:"bg-green-500/10",label:"Step Completed"},node_failed:{icon:ft,color:"text-red-400",bgColor:"bg-red-500/10",label:"Step Failed"},thinking:{icon:Zd,color:"text-yellow-400",bgColor:"bg-yellow-500/10",label:"Thinking"},reasoning:{icon:Zd,color:"text-yellow-400",bgColor:"bg-yellow-500/10",label:"Reasoning"},approval_requested:{icon:Ms,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Approval Requested"},budget_warning:{icon:pt,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Budget Warning"},budget_exceeded:{icon:us,color:"text-red-400",bgColor:"bg-red-500/10",label:"Budget Exceeded"},error:{icon:pt,color:"text-red-400",bgColor:"bg-red-500/10",label:"Error"}},Fj={icon:Nt,color:"text-zinc-400",bgColor:"bg-zinc-500/10",label:"Event"};function Zj(n){try{return new Date(n).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3})}catch{return n}}function Fh(n,i){try{return new Date(i).getTime()-new Date(n).getTime()}catch{return 0}}function Jj(n){return n<1e3?`${n}ms`:n<6e4?`${(n/1e3).toFixed(1)}s`:`${Math.floor(n/6e4)}m ${Math.floor(n%6e4/1e3)}s`}function Ij(n){const i=n.data;if(!i)return"";if(typeof i.reasoning=="string")return i.reasoning;if(typeof i.content=="string")return i.content;if(typeof i.text=="string")return i.text;if(typeof i.output=="string")return i.output;if(typeof i.prompt=="string")return i.prompt;if(typeof i.error=="string")return i.error;if(typeof i.tool=="string"){const c=i.args?` (${JSON.stringify(i.args).slice(0,120)})`:"";return`${i.tool}${c}`}const d=JSON.stringify(i,null,2);return d.length>300?d.slice(0,300)+"...":d}function Pj(n,i){let d=0;for(let c=0;c<=i&&c<n.length;c++){const m=n[c].data;typeof m.estimatedCostUsd=="number"?d=m.estimatedCostUsd:typeof m.cost=="number"&&(d+=m.cost)}return d}function Wj({runId:n}){const[i,d]=u.useState([]),[c,m]=u.useState(!0),[f,h]=u.useState(null),[b,g]=u.useState(-1),[p,S]=u.useState(!1),[y,v]=u.useState(1),k=u.useRef(null),C=u.useRef(null),w=u.useRef(new Map);u.useEffect(()=>{let $=!1;return m(!0),h(null),ln.getEvents(n).then(Q=>{$||d(Q.data.sort((ce,I)=>new Date(ce.timestamp).getTime()-new Date(I.timestamp).getTime()))}).catch(Q=>{$||h(Q instanceof Error?Q.message:"Failed to load events")}).finally(()=>{$||m(!1)}),()=>{$=!0}},[n]);const N=u.useCallback(()=>{S(!1),k.current&&(clearTimeout(k.current),k.current=null)},[]),z=u.useCallback(()=>{g($=>{const Q=$+1;if(Q>=i.length)return N(),$;const ce=i[$]??i[0],I=i[Q];if(ce&&I){const le=Fh(ce.timestamp,I.timestamp),Y=Math.max(50,Math.min(le/y,2e3/y));k.current=setTimeout(z,Y)}return Q})},[i,y,N]),R=u.useCallback(()=>{i.length!==0&&(S(!0),g($=>{const Q=$>=i.length-1?0:$,ce=300/y;return k.current=setTimeout(z,ce),Q}))},[i,y,z]),D=u.useCallback(()=>{p?N():R()},[p,N,R]),O=u.useCallback(()=>{N(),g($=>Math.min($+1,i.length-1))},[i.length,N]),se=u.useCallback(()=>{N(),g($=>Math.max($-1,0))},[N]),Z=u.useCallback($=>{N(),g($)},[N]),U=u.useCallback(()=>{v($=>{const Q=[1,2,4,8],ce=Q.indexOf($);return Q[(ce+1)%Q.length]})},[]);if(u.useEffect(()=>{if(b>=0){const $=w.current.get(b);$==null||$.scrollIntoView({behavior:"smooth",block:"nearest"})}},[b]),u.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]),c)return e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"}),e.jsx("span",{className:"ml-3 text-sm text-zinc-400",children:"Loading events..."})]});if(f)return e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4",children:e.jsx("p",{className:"text-sm text-red-400",children:f})});if(i.length===0)return e.jsx("div",{className:"rounded-lg border border-zinc-700 bg-zinc-800/50 p-6 text-center",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"No events recorded for this run."})});const A=i.length>0?(b+1)/i.length*100:0,F=b>=0?Pj(i,b):0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-zinc-700 bg-zinc-800/80 px-4 py-3",children:[e.jsx("button",{onClick:se,disabled:b<=0,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-zinc-700 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Step backward",children:e.jsx(Dv,{className:"h-4 w-4"})}),e.jsx("button",{onClick:D,className:"flex h-9 w-9 items-center justify-center rounded-full bg-indigo-600 text-white transition-colors hover:bg-indigo-500",title:p?"Pause":"Play",children:p?e.jsx(tl,{className:"h-4 w-4"}):e.jsx(Nt,{className:"h-4 w-4 ml-0.5"})}),e.jsx("button",{onClick:O,disabled:b>=i.length-1,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-zinc-700 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Step forward",children:e.jsx(Ov,{className:"h-4 w-4"})}),e.jsxs("button",{onClick:U,className:"rounded border border-zinc-600 px-2 py-1 text-xs font-mono text-zinc-300 transition-colors hover:bg-zinc-700",title:"Cycle playback speed",children:[y,"x"]}),e.jsx("div",{className:"flex-1 mx-2",children:e.jsxs("div",{className:"relative h-2 rounded-full bg-zinc-700 cursor-pointer",onClick:$=>{const Q=$.currentTarget.getBoundingClientRect(),ce=($.clientX-Q.left)/Q.width,I=Math.round(ce*(i.length-1));Z(Math.max(0,Math.min(I,i.length-1)))},children:[e.jsx("div",{className:"absolute top-0 left-0 h-full rounded-full bg-indigo-500 transition-all duration-150",style:{width:`${A}%`}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-3.5 w-3.5 rounded-full border-2 border-indigo-400 bg-zinc-900 transition-all duration-150",style:{left:`calc(${A}% - 7px)`}})]})}),e.jsxs("span",{className:"text-xs font-mono text-zinc-500 whitespace-nowrap",children:[b+1," / ",i.length]}),F>0&&e.jsxs("span",{className:"flex items-center gap-1 text-xs font-mono text-amber-400 whitespace-nowrap",children:[e.jsx(us,{className:"h-3 w-3"}),F.toFixed(4)]})]}),e.jsx("div",{ref:C,className:"max-h-[600px] overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900/50",children:e.jsx("div",{className:"divide-y divide-zinc-800",children:i.map(($,Q)=>{const ce=Qj[$.type]??Fj,I=ce.icon,le=Q===b,Y=b<0||Q<=b,B=Ij($),ne=Q>0?Fh(i[Q-1].timestamp,$.timestamp):0;return e.jsxs("div",{ref:me=>{me&&w.current.set(Q,me)},className:`
585
+ */const sa=ie("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Pd={en:"English",fr:"Français",es:"Español",de:"Deutsch",pt:"Português",ja:"日本語",zh:"中文",ko:"한국어",ar:"العربية",ru:"Русский",it:"Italiano",nl:"Nederlands"},Kv=["ar"],Vv=Object.keys(Pd);function Wd(n){return Vv.includes(n)}function Yv(n){if(!n)return"en";const i=n.toLowerCase();if(Wd(i))return i;const d=i.split("-")[0];return Wd(d)?d:"en"}const qh={en:{"nav.missions":"Missions","nav.chat":"Chat","nav.history":"History","nav.dashboard":"Dashboard","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Skills","nav.runs":"Runs","nav.approvals":"Approvals","nav.handoffs":"Handoffs","nav.apiKeys":"API Keys","nav.settings":"Settings","nav.users":"Users","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Active Agents","dashboard.runningTasks":"Running Tasks","dashboard.costToday":"Cost Today","dashboard.skillsInstalled":"Skills Installed","dashboard.recentActivity":"Recent Activity","dashboard.quickActions":"Quick Actions","dashboard.systemHealth":"System Health","dashboard.createAgent":"Create Agent","dashboard.runWorkflow":"Run Workflow","dashboard.installSkill":"Install Skill","agents.title":"Agents","agents.create":"Create Agent","agents.empty":"No agents configured yet.","agents.emptyDesc":"Create your first AI agent to get started with automated tasks.","agent.overview":"Overview","agent.runs":"Runs","agent.events":"Events","agent.configuration":"Configuration","agent.budget":"Budget","agent.recentRuns":"Recent Runs","agent.delete":"Delete Agent","agent.start":"Start","agent.stop":"Stop","agent.run":"Run","workflows.title":"Workflows","workflows.create":"Create Workflow","workflows.empty":"No workflows defined yet.","workflows.emptyDesc":"Design your first workflow to orchestrate multiple agents.","workflows.nodes":"{count} nodes","workflows.edit":"Edit","workflow.editor":"Workflow Editor","workflow.addNode":"Add Node","workflow.save":"Save","workflow.run":"Run Workflow","skills.title":"Skills","skills.install":"Install Skill","skills.empty":"No skills installed yet.","skills.emptyDesc":"Browse and install skills to extend your agents' capabilities.","skills.scan":"Scan Directory","skills.source":"Source URL or path","runs.title":"Runs","runs.empty":"No runs recorded yet.","runs.emptyDesc":"Run an agent or workflow to see execution history.","runs.filter":"Filter","run.events":"Events","run.output":"Output","run.cost":"Cost Breakdown","run.duration":"Duration","approvals.title":"Approval Queue","approvals.empty":"No pending approvals.","approvals.emptyDesc":"All clear. Dangerous actions will appear here for review.","approvals.approve":"Approve","approvals.deny":"Deny","approvals.pending":"Pending","nav.analytics":"Analytics","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Memory","nav.goals":"Goals","nav.plans":"Plans","nav.guardrails":"Guardrails","analytics.title":"Cost Analytics","analytics.description":"Track spending, token usage, and budget utilization across agents.","analytics.totalSpend":"Total Spend","analytics.totalRuns":"Total Runs","analytics.avgCostPerRun":"Avg Cost/Run","analytics.monthlyEstimate":"Monthly Estimate","analytics.dailyCosts":"Daily Costs (30 days)","analytics.agentBreakdown":"Cost by Agent","analytics.modelBreakdown":"Cost by Model","analytics.budgetUtilization":"Budget Utilization","analytics.runs":"Runs","analytics.totalCost":"Total Cost","analytics.avgCost":"Avg Cost","analytics.model":"Model","analytics.tokens":"Tokens","analytics.cost":"Cost","analytics.noAgentData":"No agent cost data yet.","analytics.noModelData":"No model cost data yet.","settings.title":"Settings","settings.general":"General","settings.security":"Security","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Save Changes","settings.saved":"Settings saved successfully.","settings.language":"Language","common.loading":"Loading...","common.error":"An error occurred.","common.retry":"Retry","common.cancel":"Cancel","common.save":"Save","common.delete":"Delete","common.close":"Close","common.search":"Search...","common.noResults":"No results found.","common.name":"Name","common.description":"Description","common.status":"Status","common.type":"Type","common.actions":"Actions","common.created":"Created","common.updated":"Updated","status.running":"Running","status.completed":"Completed","status.failed":"Failed","status.pending":"Pending","status.paused":"Paused","status.cancelled":"Cancelled","status.idle":"Idle","trust.builtin":"Built-in","trust.official":"Official","trust.trusted":"Trusted","trust.community":"Community","trust.local":"Local","nav.messaging":"Messaging","messaging.title":"Messaging","messaging.empty":"No messaging adapters configured.","messaging.emptyDesc":"Configure Discord, Slack, or Telegram adapters to get started.","messaging.sendTest":"Send Test Message","messaging.adapter":"Adapter","messaging.channel":"Channel","messaging.selectChannel":"Select a channel","messaging.message":"Message","messaging.messagePlaceholder":"Type a test message...","messaging.send":"Send","messaging.sent":"Message sent successfully.","messaging.recentMessages":"Recent Messages","messaging.noMessages":"No messages yet.","nav.scheduler":"Scheduler","scheduler.title":"Scheduler","scheduler.addSchedule":"Add Schedule","scheduler.empty":"No scheduled agents.","scheduler.emptyDesc":"Schedule agents to run automatically on a cron expression.","scheduler.totalSchedules":"Total Schedules","scheduler.active":"Active","scheduler.paused":"Paused","scheduler.nextRun":"Next Run","scheduler.agent":"Agent","scheduler.schedule":"Schedule","scheduler.lastRun":"Last Run","scheduler.selectAgent":"Select an agent...","scheduler.usePreset":"Use preset","scheduler.useCustom":"Use custom cron","scheduler.pause":"Pause","scheduler.resume":"Resume","scheduler.runHistory":"Run History","nav.evolve":"Evolve","evolve.title":"Evolve","evolve.empty":"No skill candidates found.","evolve.emptyDesc":"Auto-extracted skills from missions will appear here.","evolve.totalCandidates":"Total Candidates","evolve.pending":"Pending","evolve.approved":"Approved","evolve.rejected":"Rejected","evolve.avgConfidence":"Avg Confidence","evolve.all":"All","evolve.source":"Source","evolve.confidence":"Confidence","evolve.preview":"Preview","evolve.edit":"Edit","evolve.approve":"Approve","evolve.reject":"Reject","workflows.run":"Run","workflows.running":"Running...","memory.browse":"Browse","memory.governance":"Governance","memory.governanceTypes":"Memory Types","memory.staleMemories":"Stale Memories","memory.flagged":"flagged","memory.noStale":"No stale memories detected.","memory.ttlEnforcement":"TTL Enforcement","memory.totalMemories":"Total Memories","memory.staleCount":"Stale (>30d)","memory.ttlCandidates":"TTL Candidates"},fr:{"nav.missions":"Missions","nav.chat":"Chat","nav.history":"Historique","nav.dashboard":"Tableau de bord","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Compétences","nav.runs":"Exécutions","nav.approvals":"Approbations","nav.handoffs":"Transferts","nav.apiKeys":"Clés API","nav.settings":"Paramètres","nav.users":"Utilisateurs","nav.prompts":"Prompts","dashboard.title":"Tableau de bord","dashboard.activeAgents":"Agents actifs","dashboard.runningTasks":"Tâches en cours","dashboard.costToday":"Coût aujourd'hui","dashboard.skillsInstalled":"Compétences installées","dashboard.recentActivity":"Activité récente","dashboard.quickActions":"Actions rapides","dashboard.systemHealth":"Santé système","dashboard.createAgent":"Créer un agent","dashboard.runWorkflow":"Lancer un workflow","dashboard.installSkill":"Installer une compétence","agents.title":"Agents","agents.create":"Créer un agent","agents.empty":"Aucun agent configuré.","agents.emptyDesc":"Créez votre premier agent IA pour automatiser vos tâches.","agent.overview":"Aperçu","agent.runs":"Exécutions","agent.events":"Événements","agent.configuration":"Configuration","agent.budget":"Budget","agent.recentRuns":"Exécutions récentes","agent.delete":"Supprimer l'agent","agent.start":"Démarrer","agent.stop":"Arrêter","agent.run":"Exécuter","workflows.title":"Workflows","workflows.create":"Créer un workflow","workflows.empty":"Aucun workflow défini.","workflows.emptyDesc":"Concevez votre premier workflow pour orchestrer vos agents.","workflows.nodes":"{count} nœuds","workflows.edit":"Modifier","workflow.editor":"Éditeur de workflow","workflow.addNode":"Ajouter un nœud","workflow.save":"Enregistrer","workflow.run":"Lancer le workflow","skills.title":"Compétences","skills.install":"Installer","skills.empty":"Aucune compétence installée.","skills.emptyDesc":"Parcourez et installez des compétences pour étendre les capacités de vos agents.","skills.scan":"Scanner un répertoire","skills.source":"URL ou chemin source","runs.title":"Exécutions","runs.empty":"Aucune exécution enregistrée.","runs.emptyDesc":"Lancez un agent ou un workflow pour voir l'historique.","runs.filter":"Filtrer","run.events":"Événements","run.output":"Sortie","run.cost":"Détail des coûts","run.duration":"Durée","approvals.title":"File d'approbation","approvals.empty":"Aucune approbation en attente.","approvals.emptyDesc":"Tout est clair. Les actions dangereuses apparaîtront ici.","approvals.approve":"Approuver","approvals.deny":"Refuser","approvals.pending":"En attente","nav.analytics":"Analytique","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Mémoire","nav.goals":"Objectifs","nav.plans":"Plans","nav.guardrails":"Garde-fous","analytics.title":"Analytique des coûts","analytics.description":"Suivez les dépenses, l'utilisation des tokens et le budget par agent.","analytics.totalSpend":"Dépense totale","analytics.totalRuns":"Total exécutions","analytics.avgCostPerRun":"Coût moyen/exéc.","analytics.monthlyEstimate":"Estimation mensuelle","analytics.dailyCosts":"Coûts quotidiens (30 jours)","analytics.agentBreakdown":"Coûts par agent","analytics.modelBreakdown":"Coûts par modèle","analytics.budgetUtilization":"Utilisation du budget","analytics.runs":"Exécutions","analytics.totalCost":"Coût total","analytics.avgCost":"Coût moyen","analytics.model":"Modèle","analytics.tokens":"Tokens","analytics.cost":"Coût","analytics.noAgentData":"Aucune donnée de coût par agent.","analytics.noModelData":"Aucune donnée de coût par modèle.","settings.title":"Paramètres","settings.general":"Général","settings.security":"Sécurité","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Enregistrer","settings.saved":"Paramètres sauvegardés.","settings.language":"Langue","common.loading":"Chargement...","common.error":"Une erreur est survenue.","common.retry":"Réessayer","common.cancel":"Annuler","common.save":"Enregistrer","common.delete":"Supprimer","common.close":"Fermer","common.search":"Rechercher...","common.noResults":"Aucun résultat.","common.name":"Nom","common.description":"Description","common.status":"Statut","common.type":"Type","common.actions":"Actions","common.created":"Créé","common.updated":"Mis à jour","status.running":"En cours","status.completed":"Terminé","status.failed":"Échoué","status.pending":"En attente","status.paused":"En pause","status.cancelled":"Annulé","status.idle":"Inactif","trust.builtin":"Intégré","trust.official":"Officiel","trust.trusted":"Vérifié","trust.community":"Communautaire","trust.local":"Local","nav.messaging":"Messagerie","messaging.title":"Messagerie","messaging.empty":"Aucun adaptateur de messagerie configuré.","messaging.emptyDesc":"Configurez Discord, Slack ou Telegram pour commencer.","messaging.sendTest":"Envoyer un message test","messaging.adapter":"Adaptateur","messaging.channel":"Canal","messaging.selectChannel":"Sélectionner un canal","messaging.message":"Message","messaging.messagePlaceholder":"Tapez un message test...","messaging.send":"Envoyer","messaging.sent":"Message envoyé avec succès.","messaging.recentMessages":"Messages récents","messaging.noMessages":"Aucun message.","nav.scheduler":"Planificateur","scheduler.title":"Planificateur","scheduler.addSchedule":"Ajouter une planification","scheduler.empty":"Aucun agent planifié.","scheduler.emptyDesc":"Planifiez des agents pour s'exécuter automatiquement via une expression cron.","scheduler.totalSchedules":"Total planifications","scheduler.active":"Actif","scheduler.paused":"En pause","scheduler.nextRun":"Prochaine exéc.","scheduler.agent":"Agent","scheduler.schedule":"Planification","scheduler.lastRun":"Dernière exéc.","scheduler.selectAgent":"Sélectionner un agent...","scheduler.usePreset":"Utiliser un préréglage","scheduler.useCustom":"Cron personnalisé","scheduler.pause":"Mettre en pause","scheduler.resume":"Reprendre","scheduler.runHistory":"Historique des exécutions","nav.evolve":"Évolution","evolve.title":"Évolution","evolve.empty":"Aucun candidat de compétence trouvé.","evolve.emptyDesc":"Les compétences auto-extraites des missions apparaîtront ici.","evolve.totalCandidates":"Total candidats","evolve.pending":"En attente","evolve.approved":"Approuvés","evolve.rejected":"Rejetés","evolve.avgConfidence":"Confiance moy.","evolve.all":"Tous","evolve.source":"Source","evolve.confidence":"Confiance","evolve.preview":"Aperçu","evolve.edit":"Modifier","evolve.approve":"Approuver","evolve.reject":"Rejeter","workflows.run":"Lancer","workflows.running":"En cours...","memory.browse":"Parcourir","memory.governance":"Gouvernance","memory.governanceTypes":"Types de mémoire","memory.staleMemories":"Mémoires obsolètes","memory.flagged":"signalées","memory.noStale":"Aucune mémoire obsolète détectée.","memory.ttlEnforcement":"Application TTL","memory.totalMemories":"Total mémoires","memory.staleCount":"Obsolètes (>30j)","memory.ttlCandidates":"Candidats TTL"},es:{"nav.dashboard":"Panel","nav.agents":"Agentes","nav.workflows":"Flujos de trabajo","nav.skills":"Habilidades","nav.runs":"Ejecuciones","nav.approvals":"Aprobaciones","nav.handoffs":"Transferencias","nav.apiKeys":"Claves API","nav.settings":"Configuración","nav.users":"Usuarios","nav.prompts":"Prompts","dashboard.title":"Panel","dashboard.activeAgents":"Agentes activos","dashboard.runningTasks":"Tareas en ejecución","dashboard.costToday":"Coste hoy","dashboard.skillsInstalled":"Habilidades instaladas","dashboard.recentActivity":"Actividad reciente","dashboard.quickActions":"Acciones rápidas","dashboard.systemHealth":"Estado del sistema","dashboard.createAgent":"Crear agente","dashboard.runWorkflow":"Ejecutar flujo","dashboard.installSkill":"Instalar habilidad","agents.title":"Agentes","agents.create":"Crear agente","agents.empty":"No hay agentes configurados.","agents.emptyDesc":"Crea tu primer agente IA para empezar con tareas automatizadas.","agent.overview":"Resumen","agent.runs":"Ejecuciones","agent.events":"Eventos","agent.configuration":"Configuración","agent.budget":"Presupuesto","agent.recentRuns":"Ejecuciones recientes","agent.delete":"Eliminar agente","agent.start":"Iniciar","agent.stop":"Detener","agent.run":"Ejecutar","workflows.title":"Flujos de trabajo","workflows.create":"Crear flujo","workflows.empty":"No hay flujos definidos.","workflows.emptyDesc":"Diseña tu primer flujo de trabajo para orquestar múltiples agentes.","workflows.nodes":"{count} nodos","workflows.edit":"Editar","workflow.editor":"Editor de flujo","workflow.addNode":"Añadir nodo","workflow.save":"Guardar","workflow.run":"Ejecutar flujo","skills.title":"Habilidades","skills.install":"Instalar","skills.empty":"No hay habilidades instaladas.","skills.emptyDesc":"Explora e instala habilidades para ampliar las capacidades de tus agentes.","skills.scan":"Escanear directorio","skills.source":"URL o ruta de origen","runs.title":"Ejecuciones","runs.empty":"No hay ejecuciones registradas.","runs.emptyDesc":"Ejecuta un agente o flujo para ver el historial.","runs.filter":"Filtrar","run.events":"Eventos","run.output":"Salida","run.cost":"Desglose de costes","run.duration":"Duración","approvals.title":"Cola de aprobación","approvals.empty":"Sin aprobaciones pendientes.","approvals.emptyDesc":"Todo despejado. Las acciones peligrosas aparecerán aquí.","approvals.approve":"Aprobar","approvals.deny":"Denegar","approvals.pending":"Pendiente","nav.analytics":"Analíticas","nav.budget":"Presupuesto","nav.traces":"Trazas","nav.memory":"Memoria","nav.goals":"Objetivos","nav.plans":"Planes","nav.guardrails":"Salvaguardas","analytics.title":"Analíticas de coste","analytics.description":"Seguimiento de gastos, uso de tokens y presupuesto por agente.","analytics.totalSpend":"Gasto total","analytics.totalRuns":"Total ejecuciones","analytics.avgCostPerRun":"Coste medio/ejec.","analytics.monthlyEstimate":"Estimación mensual","analytics.dailyCosts":"Costes diarios (30 días)","analytics.agentBreakdown":"Coste por agente","analytics.modelBreakdown":"Coste por modelo","analytics.budgetUtilization":"Uso del presupuesto","analytics.runs":"Ejecuciones","analytics.totalCost":"Coste total","analytics.avgCost":"Coste medio","analytics.model":"Modelo","analytics.tokens":"Tokens","analytics.cost":"Coste","analytics.noAgentData":"Sin datos de coste por agente.","analytics.noModelData":"Sin datos de coste por modelo.","settings.title":"Configuración","settings.general":"General","settings.security":"Seguridad","settings.llm":"LLM","settings.budget":"Presupuesto","settings.save":"Guardar cambios","settings.saved":"Configuración guardada.","settings.language":"Idioma","common.loading":"Cargando...","common.error":"Se produjo un error.","common.retry":"Reintentar","common.cancel":"Cancelar","common.save":"Guardar","common.delete":"Eliminar","common.close":"Cerrar","common.search":"Buscar...","common.noResults":"Sin resultados.","common.name":"Nombre","common.description":"Descripción","common.status":"Estado","common.type":"Tipo","common.actions":"Acciones","common.created":"Creado","common.updated":"Actualizado","status.running":"En ejecución","status.completed":"Completado","status.failed":"Fallido","status.pending":"Pendiente","status.paused":"En pausa","status.cancelled":"Cancelado","status.idle":"Inactivo","trust.builtin":"Integrado","trust.official":"Oficial","trust.trusted":"Verificado","trust.community":"Comunidad","trust.local":"Local"},de:{"nav.dashboard":"Dashboard","nav.agents":"Agenten","nav.workflows":"Workflows","nav.skills":"Fähigkeiten","nav.runs":"Ausführungen","nav.approvals":"Genehmigungen","nav.handoffs":"Übergaben","nav.apiKeys":"API-Schlüssel","nav.settings":"Einstellungen","nav.users":"Benutzer","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Aktive Agenten","dashboard.runningTasks":"Laufende Aufgaben","dashboard.costToday":"Kosten heute","dashboard.skillsInstalled":"Installierte Fähigkeiten","dashboard.recentActivity":"Letzte Aktivität","dashboard.quickActions":"Schnellaktionen","dashboard.systemHealth":"Systemstatus","dashboard.createAgent":"Agent erstellen","dashboard.runWorkflow":"Workflow starten","dashboard.installSkill":"Fähigkeit installieren","agents.title":"Agenten","agents.create":"Agent erstellen","agents.empty":"Keine Agenten konfiguriert.","agents.emptyDesc":"Erstellen Sie Ihren ersten KI-Agenten für automatisierte Aufgaben.","agent.overview":"Übersicht","agent.runs":"Ausführungen","agent.events":"Ereignisse","agent.configuration":"Konfiguration","agent.budget":"Budget","agent.recentRuns":"Letzte Ausführungen","agent.delete":"Agent löschen","agent.start":"Starten","agent.stop":"Stoppen","agent.run":"Ausführen","workflows.title":"Workflows","workflows.create":"Workflow erstellen","workflows.empty":"Keine Workflows definiert.","workflows.emptyDesc":"Entwerfen Sie Ihren ersten Workflow zur Orchestrierung mehrerer Agenten.","workflows.nodes":"{count} Knoten","workflows.edit":"Bearbeiten","workflow.editor":"Workflow-Editor","workflow.addNode":"Knoten hinzufügen","workflow.save":"Speichern","workflow.run":"Workflow starten","skills.title":"Fähigkeiten","skills.install":"Installieren","skills.empty":"Keine Fähigkeiten installiert.","skills.emptyDesc":"Durchsuchen und installieren Sie Fähigkeiten, um die Möglichkeiten Ihrer Agenten zu erweitern.","skills.scan":"Verzeichnis scannen","skills.source":"Quell-URL oder -pfad","runs.title":"Ausführungen","runs.empty":"Keine Ausführungen aufgezeichnet.","runs.emptyDesc":"Starten Sie einen Agenten oder Workflow, um den Verlauf anzuzeigen.","runs.filter":"Filtern","run.events":"Ereignisse","run.output":"Ausgabe","run.cost":"Kostenaufschlüsselung","run.duration":"Dauer","approvals.title":"Genehmigungswarteschlange","approvals.empty":"Keine ausstehenden Genehmigungen.","approvals.emptyDesc":"Alles in Ordnung. Gefährliche Aktionen erscheinen hier zur Überprüfung.","approvals.approve":"Genehmigen","approvals.deny":"Ablehnen","approvals.pending":"Ausstehend","nav.analytics":"Analytik","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Speicher","nav.goals":"Ziele","nav.plans":"Pläne","nav.guardrails":"Leitplanken","analytics.title":"Kostenanalytik","analytics.description":"Ausgaben, Token-Nutzung und Budgetauslastung pro Agent verfolgen.","analytics.totalSpend":"Gesamtausgaben","analytics.totalRuns":"Gesamtausführungen","analytics.avgCostPerRun":"Ø Kosten/Ausf.","analytics.monthlyEstimate":"Monatliche Schätzung","analytics.dailyCosts":"Tägliche Kosten (30 Tage)","analytics.agentBreakdown":"Kosten pro Agent","analytics.modelBreakdown":"Kosten pro Modell","analytics.budgetUtilization":"Budgetauslastung","analytics.runs":"Ausführungen","analytics.totalCost":"Gesamtkosten","analytics.avgCost":"Ø Kosten","analytics.model":"Modell","analytics.tokens":"Tokens","analytics.cost":"Kosten","analytics.noAgentData":"Noch keine Kostendaten pro Agent.","analytics.noModelData":"Noch keine Kostendaten pro Modell.","settings.title":"Einstellungen","settings.general":"Allgemein","settings.security":"Sicherheit","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Änderungen speichern","settings.saved":"Einstellungen gespeichert.","settings.language":"Sprache","common.loading":"Laden...","common.error":"Ein Fehler ist aufgetreten.","common.retry":"Erneut versuchen","common.cancel":"Abbrechen","common.save":"Speichern","common.delete":"Löschen","common.close":"Schließen","common.search":"Suchen...","common.noResults":"Keine Ergebnisse.","common.name":"Name","common.description":"Beschreibung","common.status":"Status","common.type":"Typ","common.actions":"Aktionen","common.created":"Erstellt","common.updated":"Aktualisiert","status.running":"Läuft","status.completed":"Abgeschlossen","status.failed":"Fehlgeschlagen","status.pending":"Ausstehend","status.paused":"Pausiert","status.cancelled":"Abgebrochen","status.idle":"Inaktiv","trust.builtin":"Integriert","trust.official":"Offiziell","trust.trusted":"Vertrauenswürdig","trust.community":"Community","trust.local":"Lokal"},pt:{"nav.dashboard":"Painel","nav.agents":"Agentes","nav.workflows":"Fluxos de trabalho","nav.skills":"Habilidades","nav.runs":"Execuções","nav.approvals":"Aprovações","nav.handoffs":"Transferências","nav.apiKeys":"Chaves API","nav.settings":"Configurações","nav.users":"Usuários","nav.prompts":"Prompts","dashboard.title":"Painel","dashboard.activeAgents":"Agentes ativos","dashboard.runningTasks":"Tarefas em execução","dashboard.costToday":"Custo hoje","dashboard.skillsInstalled":"Habilidades instaladas","dashboard.recentActivity":"Atividade recente","dashboard.quickActions":"Ações rápidas","dashboard.systemHealth":"Saúde do sistema","dashboard.createAgent":"Criar agente","dashboard.runWorkflow":"Executar fluxo","dashboard.installSkill":"Instalar habilidade","agents.title":"Agentes","agents.create":"Criar agente","agents.empty":"Nenhum agente configurado.","agents.emptyDesc":"Crie seu primeiro agente de IA para começar com tarefas automatizadas.","agent.overview":"Visão geral","agent.runs":"Execuções","agent.events":"Eventos","agent.configuration":"Configuração","agent.budget":"Orçamento","agent.recentRuns":"Execuções recentes","agent.delete":"Excluir agente","agent.start":"Iniciar","agent.stop":"Parar","agent.run":"Executar","workflows.title":"Fluxos de trabalho","workflows.create":"Criar fluxo","workflows.empty":"Nenhum fluxo definido.","workflows.emptyDesc":"Projete seu primeiro fluxo de trabalho para orquestrar múltiplos agentes.","workflows.nodes":"{count} nós","workflows.edit":"Editar","workflow.editor":"Editor de fluxo","workflow.addNode":"Adicionar nó","workflow.save":"Salvar","workflow.run":"Executar fluxo","skills.title":"Habilidades","skills.install":"Instalar","skills.empty":"Nenhuma habilidade instalada.","skills.emptyDesc":"Explore e instale habilidades para ampliar as capacidades dos seus agentes.","skills.scan":"Escanear diretório","skills.source":"URL ou caminho de origem","runs.title":"Execuções","runs.empty":"Nenhuma execução registrada.","runs.emptyDesc":"Execute um agente ou fluxo para ver o histórico.","runs.filter":"Filtrar","run.events":"Eventos","run.output":"Saída","run.cost":"Detalhamento de custos","run.duration":"Duração","approvals.title":"Fila de aprovação","approvals.empty":"Sem aprovações pendentes.","approvals.emptyDesc":"Tudo limpo. Ações perigosas aparecerão aqui para revisão.","approvals.approve":"Aprovar","approvals.deny":"Negar","approvals.pending":"Pendente","nav.analytics":"Análises","nav.budget":"Orçamento","nav.traces":"Rastros","nav.memory":"Memória","nav.goals":"Objetivos","nav.plans":"Planos","nav.guardrails":"Proteções","analytics.title":"Análise de custos","analytics.description":"Acompanhe gastos, uso de tokens e orçamento por agente.","analytics.totalSpend":"Gasto total","analytics.totalRuns":"Total de execuções","analytics.avgCostPerRun":"Custo médio/exec.","analytics.monthlyEstimate":"Estimativa mensal","analytics.dailyCosts":"Custos diários (30 dias)","analytics.agentBreakdown":"Custo por agente","analytics.modelBreakdown":"Custo por modelo","analytics.budgetUtilization":"Utilização do orçamento","analytics.runs":"Execuções","analytics.totalCost":"Custo total","analytics.avgCost":"Custo médio","analytics.model":"Modelo","analytics.tokens":"Tokens","analytics.cost":"Custo","analytics.noAgentData":"Sem dados de custo por agente.","analytics.noModelData":"Sem dados de custo por modelo.","settings.title":"Configurações","settings.general":"Geral","settings.security":"Segurança","settings.llm":"LLM","settings.budget":"Orçamento","settings.save":"Salvar alterações","settings.saved":"Configurações salvas.","settings.language":"Idioma","common.loading":"Carregando...","common.error":"Ocorreu um erro.","common.retry":"Tentar novamente","common.cancel":"Cancelar","common.save":"Salvar","common.delete":"Excluir","common.close":"Fechar","common.search":"Pesquisar...","common.noResults":"Nenhum resultado.","common.name":"Nome","common.description":"Descrição","common.status":"Status","common.type":"Tipo","common.actions":"Ações","common.created":"Criado","common.updated":"Atualizado","status.running":"Em execução","status.completed":"Concluído","status.failed":"Falhou","status.pending":"Pendente","status.paused":"Pausado","status.cancelled":"Cancelado","status.idle":"Inativo","trust.builtin":"Integrado","trust.official":"Oficial","trust.trusted":"Verificado","trust.community":"Comunidade","trust.local":"Local"},ja:{"nav.dashboard":"ダッシュボード","nav.agents":"エージェント","nav.workflows":"ワークフロー","nav.skills":"スキル","nav.runs":"実行履歴","nav.approvals":"承認","nav.handoffs":"引き継ぎ","nav.apiKeys":"APIキー","nav.settings":"設定","nav.users":"ユーザー","nav.prompts":"プロンプト","dashboard.title":"ダッシュボード","dashboard.activeAgents":"アクティブなエージェント","dashboard.runningTasks":"実行中のタスク","dashboard.costToday":"本日のコスト","dashboard.skillsInstalled":"インストール済みスキル","dashboard.recentActivity":"最近のアクティビティ","dashboard.quickActions":"クイックアクション","dashboard.systemHealth":"システム状態","dashboard.createAgent":"エージェント作成","dashboard.runWorkflow":"ワークフロー実行","dashboard.installSkill":"スキルインストール","agents.title":"エージェント","agents.create":"エージェント作成","agents.empty":"エージェントが構成されていません。","agents.emptyDesc":"最初のAIエージェントを作成して自動化タスクを始めましょう。","agent.overview":"概要","agent.runs":"実行履歴","agent.events":"イベント","agent.configuration":"構成","agent.budget":"予算","agent.recentRuns":"最近の実行","agent.delete":"エージェント削除","agent.start":"開始","agent.stop":"停止","agent.run":"実行","workflows.title":"ワークフロー","workflows.create":"ワークフロー作成","workflows.empty":"ワークフローが定義されていません。","workflows.emptyDesc":"最初のワークフローを設計して複数のエージェントをオーケストレーションしましょう。","workflows.nodes":"{count} ノード","workflows.edit":"編集","workflow.editor":"ワークフローエディタ","workflow.addNode":"ノード追加","workflow.save":"保存","workflow.run":"ワークフロー実行","skills.title":"スキル","skills.install":"インストール","skills.empty":"スキルがインストールされていません。","skills.emptyDesc":"スキルを参照・インストールしてエージェントの機能を拡張しましょう。","skills.scan":"ディレクトリスキャン","skills.source":"ソースURLまたはパス","runs.title":"実行履歴","runs.empty":"実行記録がありません。","runs.emptyDesc":"エージェントまたはワークフローを実行して履歴を確認しましょう。","runs.filter":"フィルター","run.events":"イベント","run.output":"出力","run.cost":"コスト内訳","run.duration":"所要時間","approvals.title":"承認キュー","approvals.empty":"保留中の承認はありません。","approvals.emptyDesc":"問題なし。危険なアクションはここに表示されます。","approvals.approve":"承認","approvals.deny":"拒否","approvals.pending":"保留中","nav.analytics":"アナリティクス","nav.budget":"予算","nav.traces":"トレース","nav.memory":"メモリ","nav.goals":"目標","nav.plans":"プラン","nav.guardrails":"ガードレール","analytics.title":"コスト分析","analytics.description":"エージェントごとの支出、トークン使用量、予算利用状況を追跡。","analytics.totalSpend":"総支出","analytics.totalRuns":"総実行数","analytics.avgCostPerRun":"平均コスト/実行","analytics.monthlyEstimate":"月間見積もり","analytics.dailyCosts":"日次コスト(30日間)","analytics.agentBreakdown":"エージェント別コスト","analytics.modelBreakdown":"モデル別コスト","analytics.budgetUtilization":"予算利用率","analytics.runs":"実行回数","analytics.totalCost":"総コスト","analytics.avgCost":"平均コスト","analytics.model":"モデル","analytics.tokens":"トークン","analytics.cost":"コスト","analytics.noAgentData":"エージェントコストデータがまだありません。","analytics.noModelData":"モデルコストデータがまだありません。","settings.title":"設定","settings.general":"一般","settings.security":"セキュリティ","settings.llm":"LLM","settings.budget":"予算","settings.save":"変更を保存","settings.saved":"設定が保存されました。","settings.language":"言語","common.loading":"読み込み中...","common.error":"エラーが発生しました。","common.retry":"再試行","common.cancel":"キャンセル","common.save":"保存","common.delete":"削除","common.close":"閉じる","common.search":"検索...","common.noResults":"結果が見つかりません。","common.name":"名前","common.description":"説明","common.status":"ステータス","common.type":"タイプ","common.actions":"アクション","common.created":"作成日","common.updated":"更新日","status.running":"実行中","status.completed":"完了","status.failed":"失敗","status.pending":"保留中","status.paused":"一時停止","status.cancelled":"キャンセル済み","status.idle":"アイドル","trust.builtin":"組み込み","trust.official":"公式","trust.trusted":"信頼済み","trust.community":"コミュニティ","trust.local":"ローカル"},zh:{"nav.dashboard":"仪表盘","nav.agents":"代理","nav.workflows":"工作流","nav.skills":"技能","nav.runs":"执行记录","nav.approvals":"审批","nav.handoffs":"交接","nav.apiKeys":"API密钥","nav.settings":"设置","nav.users":"用户","nav.prompts":"提示词","dashboard.title":"仪表盘","dashboard.activeAgents":"活跃代理","dashboard.runningTasks":"运行中的任务","dashboard.costToday":"今日费用","dashboard.skillsInstalled":"已安装技能","dashboard.recentActivity":"最近活动","dashboard.quickActions":"快捷操作","dashboard.systemHealth":"系统状态","dashboard.createAgent":"创建代理","dashboard.runWorkflow":"运行工作流","dashboard.installSkill":"安装技能","agents.title":"代理","agents.create":"创建代理","agents.empty":"尚无已配置的代理。","agents.emptyDesc":"创建您的第一个AI代理以开始自动化任务。","agent.overview":"概览","agent.runs":"执行记录","agent.events":"事件","agent.configuration":"配置","agent.budget":"预算","agent.recentRuns":"最近执行","agent.delete":"删除代理","agent.start":"启动","agent.stop":"停止","agent.run":"运行","workflows.title":"工作流","workflows.create":"创建工作流","workflows.empty":"尚无已定义的工作流。","workflows.emptyDesc":"设计您的第一个工作流以编排多个代理。","workflows.nodes":"{count} 个节点","workflows.edit":"编辑","workflow.editor":"工作流编辑器","workflow.addNode":"添加节点","workflow.save":"保存","workflow.run":"运行工作流","skills.title":"技能","skills.install":"安装","skills.empty":"尚无已安装的技能。","skills.emptyDesc":"浏览并安装技能以扩展代理的能力。","skills.scan":"扫描目录","skills.source":"源URL或路径","runs.title":"执行记录","runs.empty":"尚无执行记录。","runs.emptyDesc":"运行代理或工作流以查看执行历史。","runs.filter":"筛选","run.events":"事件","run.output":"输出","run.cost":"费用明细","run.duration":"持续时间","approvals.title":"审批队列","approvals.empty":"没有待审批项。","approvals.emptyDesc":"一切正常。危险操作将在此显示以供审查。","approvals.approve":"批准","approvals.deny":"拒绝","approvals.pending":"待处理","nav.analytics":"分析","nav.budget":"预算","nav.traces":"追踪","nav.memory":"记忆","nav.goals":"目标","nav.plans":"计划","nav.guardrails":"护栏","analytics.title":"费用分析","analytics.description":"追踪各代理的支出、令牌使用量和预算利用率。","analytics.totalSpend":"总支出","analytics.totalRuns":"总执行次数","analytics.avgCostPerRun":"平均费用/次","analytics.monthlyEstimate":"月度估算","analytics.dailyCosts":"每日费用(30天)","analytics.agentBreakdown":"按代理的费用","analytics.modelBreakdown":"按模型的费用","analytics.budgetUtilization":"预算利用率","analytics.runs":"执行次数","analytics.totalCost":"总费用","analytics.avgCost":"平均费用","analytics.model":"模型","analytics.tokens":"令牌","analytics.cost":"费用","analytics.noAgentData":"尚无代理费用数据。","analytics.noModelData":"尚无模型费用数据。","settings.title":"设置","settings.general":"通用","settings.security":"安全","settings.llm":"LLM","settings.budget":"预算","settings.save":"保存更改","settings.saved":"设置已保存。","settings.language":"语言","common.loading":"加载中...","common.error":"发生错误。","common.retry":"重试","common.cancel":"取消","common.save":"保存","common.delete":"删除","common.close":"关闭","common.search":"搜索...","common.noResults":"未找到结果。","common.name":"名称","common.description":"描述","common.status":"状态","common.type":"类型","common.actions":"操作","common.created":"创建时间","common.updated":"更新时间","status.running":"运行中","status.completed":"已完成","status.failed":"失败","status.pending":"待处理","status.paused":"已暂停","status.cancelled":"已取消","status.idle":"空闲","trust.builtin":"内置","trust.official":"官方","trust.trusted":"受信任","trust.community":"社区","trust.local":"本地"},ko:{"nav.dashboard":"대시보드","nav.agents":"에이전트","nav.workflows":"워크플로우","nav.skills":"스킬","nav.runs":"실행 기록","nav.approvals":"승인","nav.handoffs":"인수인계","nav.apiKeys":"API 키","nav.settings":"설정","nav.users":"사용자","nav.prompts":"프롬프트","dashboard.title":"대시보드","dashboard.activeAgents":"활성 에이전트","dashboard.runningTasks":"실행 중인 작업","dashboard.costToday":"오늘 비용","dashboard.skillsInstalled":"설치된 스킬","dashboard.recentActivity":"최근 활동","dashboard.quickActions":"빠른 작업","dashboard.systemHealth":"시스템 상태","dashboard.createAgent":"에이전트 생성","dashboard.runWorkflow":"워크플로우 실행","dashboard.installSkill":"스킬 설치","agents.title":"에이전트","agents.create":"에이전트 생성","agents.empty":"구성된 에이전트가 없습니다.","agents.emptyDesc":"첫 번째 AI 에이전트를 만들어 자동화 작업을 시작하세요.","agent.overview":"개요","agent.runs":"실행 기록","agent.events":"이벤트","agent.configuration":"구성","agent.budget":"예산","agent.recentRuns":"최근 실행","agent.delete":"에이전트 삭제","agent.start":"시작","agent.stop":"중지","agent.run":"실행","workflows.title":"워크플로우","workflows.create":"워크플로우 생성","workflows.empty":"정의된 워크플로우가 없습니다.","workflows.emptyDesc":"첫 번째 워크플로우를 설계하여 여러 에이전트를 조율하세요.","workflows.nodes":"{count}개 노드","workflows.edit":"편집","workflow.editor":"워크플로우 편집기","workflow.addNode":"노드 추가","workflow.save":"저장","workflow.run":"워크플로우 실행","skills.title":"스킬","skills.install":"설치","skills.empty":"설치된 스킬이 없습니다.","skills.emptyDesc":"스킬을 탐색하고 설치하여 에이전트의 기능을 확장하세요.","skills.scan":"디렉토리 스캔","skills.source":"소스 URL 또는 경로","runs.title":"실행 기록","runs.empty":"기록된 실행이 없습니다.","runs.emptyDesc":"에이전트 또는 워크플로우를 실행하여 실행 기록을 확인하세요.","runs.filter":"필터","run.events":"이벤트","run.output":"출력","run.cost":"비용 내역","run.duration":"소요 시간","approvals.title":"승인 대기열","approvals.empty":"대기 중인 승인이 없습니다.","approvals.emptyDesc":"문제 없음. 위험한 작업은 여기에 검토를 위해 표시됩니다.","approvals.approve":"승인","approvals.deny":"거부","approvals.pending":"대기 중","nav.analytics":"분석","nav.budget":"예산","nav.traces":"추적","nav.memory":"메모리","nav.goals":"목표","nav.plans":"계획","nav.guardrails":"가드레일","analytics.title":"비용 분석","analytics.description":"에이전트별 지출, 토큰 사용량 및 예산 활용도를 추적합니다.","analytics.totalSpend":"총 지출","analytics.totalRuns":"총 실행 수","analytics.avgCostPerRun":"평균 비용/실행","analytics.monthlyEstimate":"월간 추정","analytics.dailyCosts":"일별 비용 (30일)","analytics.agentBreakdown":"에이전트별 비용","analytics.modelBreakdown":"모델별 비용","analytics.budgetUtilization":"예산 활용률","analytics.runs":"실행 횟수","analytics.totalCost":"총 비용","analytics.avgCost":"평균 비용","analytics.model":"모델","analytics.tokens":"토큰","analytics.cost":"비용","analytics.noAgentData":"에이전트 비용 데이터가 없습니다.","analytics.noModelData":"모델 비용 데이터가 없습니다.","settings.title":"설정","settings.general":"일반","settings.security":"보안","settings.llm":"LLM","settings.budget":"예산","settings.save":"변경 사항 저장","settings.saved":"설정이 저장되었습니다.","settings.language":"언어","common.loading":"로딩 중...","common.error":"오류가 발생했습니다.","common.retry":"재시도","common.cancel":"취소","common.save":"저장","common.delete":"삭제","common.close":"닫기","common.search":"검색...","common.noResults":"결과를 찾을 수 없습니다.","common.name":"이름","common.description":"설명","common.status":"상태","common.type":"유형","common.actions":"작업","common.created":"생성일","common.updated":"수정일","status.running":"실행 중","status.completed":"완료","status.failed":"실패","status.pending":"대기 중","status.paused":"일시 중지","status.cancelled":"취소됨","status.idle":"유휴","trust.builtin":"내장","trust.official":"공식","trust.trusted":"신뢰됨","trust.community":"커뮤니티","trust.local":"로컬"},ar:{"nav.dashboard":"لوحة التحكم","nav.agents":"الوكلاء","nav.workflows":"مسارات العمل","nav.skills":"المهارات","nav.runs":"عمليات التنفيذ","nav.approvals":"الموافقات","nav.handoffs":"التسليمات","nav.apiKeys":"مفاتيح API","nav.settings":"الإعدادات","nav.users":"المستخدمون","nav.prompts":"التعليمات","dashboard.title":"لوحة التحكم","dashboard.activeAgents":"الوكلاء النشطون","dashboard.runningTasks":"المهام قيد التشغيل","dashboard.costToday":"تكلفة اليوم","dashboard.skillsInstalled":"المهارات المثبتة","dashboard.recentActivity":"النشاط الأخير","dashboard.quickActions":"إجراءات سريعة","dashboard.systemHealth":"حالة النظام","dashboard.createAgent":"إنشاء وكيل","dashboard.runWorkflow":"تشغيل مسار عمل","dashboard.installSkill":"تثبيت مهارة","agents.title":"الوكلاء","agents.create":"إنشاء وكيل","agents.empty":"لا توجد وكلاء مهيأة بعد.","agents.emptyDesc":"أنشئ أول وكيل ذكاء اصطناعي لبدء المهام الآلية.","agent.overview":"نظرة عامة","agent.runs":"عمليات التنفيذ","agent.events":"الأحداث","agent.configuration":"التكوين","agent.budget":"الميزانية","agent.recentRuns":"آخر عمليات التنفيذ","agent.delete":"حذف الوكيل","agent.start":"بدء","agent.stop":"إيقاف","agent.run":"تشغيل","workflows.title":"مسارات العمل","workflows.create":"إنشاء مسار عمل","workflows.empty":"لا توجد مسارات عمل معرّفة بعد.","workflows.emptyDesc":"صمّم أول مسار عمل لتنسيق عدة وكلاء.","workflows.nodes":"{count} عقدة","workflows.edit":"تعديل","workflow.editor":"محرر مسار العمل","workflow.addNode":"إضافة عقدة","workflow.save":"حفظ","workflow.run":"تشغيل مسار العمل","skills.title":"المهارات","skills.install":"تثبيت","skills.empty":"لا توجد مهارات مثبتة بعد.","skills.emptyDesc":"تصفّح وثبّت المهارات لتوسيع قدرات وكلائك.","skills.scan":"فحص المجلد","skills.source":"عنوان URL أو مسار المصدر","runs.title":"عمليات التنفيذ","runs.empty":"لا توجد عمليات تنفيذ مسجلة بعد.","runs.emptyDesc":"شغّل وكيلًا أو مسار عمل لعرض سجل التنفيذ.","runs.filter":"تصفية","run.events":"الأحداث","run.output":"المخرجات","run.cost":"تفصيل التكاليف","run.duration":"المدة","approvals.title":"قائمة الموافقات","approvals.empty":"لا توجد موافقات معلقة.","approvals.emptyDesc":"كل شيء على ما يرام. ستظهر الإجراءات الخطيرة هنا للمراجعة.","approvals.approve":"موافقة","approvals.deny":"رفض","approvals.pending":"معلّق","nav.analytics":"التحليلات","nav.budget":"الميزانية","nav.traces":"التتبع","nav.memory":"الذاكرة","nav.goals":"الأهداف","nav.plans":"الخطط","nav.guardrails":"الحواجز","analytics.title":"تحليل التكاليف","analytics.description":"تتبع الإنفاق واستخدام الرموز وميزانية كل وكيل.","analytics.totalSpend":"إجمالي الإنفاق","analytics.totalRuns":"إجمالي عمليات التنفيذ","analytics.avgCostPerRun":"متوسط التكلفة/تنفيذ","analytics.monthlyEstimate":"التقدير الشهري","analytics.dailyCosts":"التكاليف اليومية (30 يومًا)","analytics.agentBreakdown":"التكلفة حسب الوكيل","analytics.modelBreakdown":"التكلفة حسب النموذج","analytics.budgetUtilization":"استخدام الميزانية","analytics.runs":"عمليات التنفيذ","analytics.totalCost":"التكلفة الإجمالية","analytics.avgCost":"متوسط التكلفة","analytics.model":"النموذج","analytics.tokens":"الرموز","analytics.cost":"التكلفة","analytics.noAgentData":"لا توجد بيانات تكلفة للوكلاء بعد.","analytics.noModelData":"لا توجد بيانات تكلفة للنماذج بعد.","settings.title":"الإعدادات","settings.general":"عام","settings.security":"الأمان","settings.llm":"LLM","settings.budget":"الميزانية","settings.save":"حفظ التغييرات","settings.saved":"تم حفظ الإعدادات بنجاح.","settings.language":"اللغة","common.loading":"جارٍ التحميل...","common.error":"حدث خطأ.","common.retry":"إعادة المحاولة","common.cancel":"إلغاء","common.save":"حفظ","common.delete":"حذف","common.close":"إغلاق","common.search":"بحث...","common.noResults":"لم يتم العثور على نتائج.","common.name":"الاسم","common.description":"الوصف","common.status":"الحالة","common.type":"النوع","common.actions":"الإجراءات","common.created":"تاريخ الإنشاء","common.updated":"تاريخ التحديث","status.running":"قيد التشغيل","status.completed":"مكتمل","status.failed":"فشل","status.pending":"معلّق","status.paused":"متوقف مؤقتًا","status.cancelled":"ملغى","status.idle":"خامل","trust.builtin":"مدمج","trust.official":"رسمي","trust.trusted":"موثوق","trust.community":"مجتمعي","trust.local":"محلي"},ru:{"nav.dashboard":"Панель управления","nav.agents":"Агенты","nav.workflows":"Рабочие процессы","nav.skills":"Навыки","nav.runs":"Запуски","nav.approvals":"Одобрения","nav.handoffs":"Передачи","nav.apiKeys":"API-ключи","nav.settings":"Настройки","nav.users":"Пользователи","nav.prompts":"Промпты","dashboard.title":"Панель управления","dashboard.activeAgents":"Активные агенты","dashboard.runningTasks":"Запущенные задачи","dashboard.costToday":"Расходы сегодня","dashboard.skillsInstalled":"Установленные навыки","dashboard.recentActivity":"Последняя активность","dashboard.quickActions":"Быстрые действия","dashboard.systemHealth":"Состояние системы","dashboard.createAgent":"Создать агента","dashboard.runWorkflow":"Запустить процесс","dashboard.installSkill":"Установить навык","agents.title":"Агенты","agents.create":"Создать агента","agents.empty":"Нет настроенных агентов.","agents.emptyDesc":"Создайте первого ИИ-агента для автоматизации задач.","agent.overview":"Обзор","agent.runs":"Запуски","agent.events":"События","agent.configuration":"Конфигурация","agent.budget":"Бюджет","agent.recentRuns":"Последние запуски","agent.delete":"Удалить агента","agent.start":"Запустить","agent.stop":"Остановить","agent.run":"Выполнить","workflows.title":"Рабочие процессы","workflows.create":"Создать процесс","workflows.empty":"Нет определённых процессов.","workflows.emptyDesc":"Создайте первый рабочий процесс для оркестрации агентов.","workflows.nodes":"{count} узлов","workflows.edit":"Редактировать","workflow.editor":"Редактор процессов","workflow.addNode":"Добавить узел","workflow.save":"Сохранить","workflow.run":"Запустить процесс","skills.title":"Навыки","skills.install":"Установить","skills.empty":"Нет установленных навыков.","skills.emptyDesc":"Просматривайте и устанавливайте навыки для расширения возможностей агентов.","skills.scan":"Сканировать каталог","skills.source":"URL или путь к источнику","runs.title":"Запуски","runs.empty":"Нет записей о запусках.","runs.emptyDesc":"Запустите агента или процесс, чтобы увидеть историю выполнения.","runs.filter":"Фильтр","run.events":"События","run.output":"Вывод","run.cost":"Разбивка стоимости","run.duration":"Длительность","approvals.title":"Очередь одобрений","approvals.empty":"Нет ожидающих одобрений.","approvals.emptyDesc":"Всё в порядке. Опасные действия появятся здесь для проверки.","approvals.approve":"Одобрить","approvals.deny":"Отклонить","approvals.pending":"Ожидает","nav.analytics":"Аналитика","nav.budget":"Бюджет","nav.traces":"Трассировки","nav.memory":"Память","nav.goals":"Цели","nav.plans":"Планы","nav.guardrails":"Ограждения","analytics.title":"Аналитика расходов","analytics.description":"Отслеживание расходов, использования токенов и бюджета по агентам.","analytics.totalSpend":"Общие расходы","analytics.totalRuns":"Всего запусков","analytics.avgCostPerRun":"Ср. стоимость/запуск","analytics.monthlyEstimate":"Месячная оценка","analytics.dailyCosts":"Ежедневные расходы (30 дней)","analytics.agentBreakdown":"Расходы по агентам","analytics.modelBreakdown":"Расходы по моделям","analytics.budgetUtilization":"Использование бюджета","analytics.runs":"Запуски","analytics.totalCost":"Общая стоимость","analytics.avgCost":"Ср. стоимость","analytics.model":"Модель","analytics.tokens":"Токены","analytics.cost":"Стоимость","analytics.noAgentData":"Нет данных о расходах по агентам.","analytics.noModelData":"Нет данных о расходах по моделям.","settings.title":"Настройки","settings.general":"Общие","settings.security":"Безопасность","settings.llm":"LLM","settings.budget":"Бюджет","settings.save":"Сохранить изменения","settings.saved":"Настройки сохранены.","settings.language":"Язык","common.loading":"Загрузка...","common.error":"Произошла ошибка.","common.retry":"Повторить","common.cancel":"Отмена","common.save":"Сохранить","common.delete":"Удалить","common.close":"Закрыть","common.search":"Поиск...","common.noResults":"Результатов не найдено.","common.name":"Название","common.description":"Описание","common.status":"Статус","common.type":"Тип","common.actions":"Действия","common.created":"Создано","common.updated":"Обновлено","status.running":"Выполняется","status.completed":"Завершено","status.failed":"Ошибка","status.pending":"Ожидание","status.paused":"Пауза","status.cancelled":"Отменено","status.idle":"Простой","trust.builtin":"Встроенный","trust.official":"Официальный","trust.trusted":"Доверенный","trust.community":"Сообщество","trust.local":"Локальный"},it:{"nav.dashboard":"Pannello","nav.agents":"Agenti","nav.workflows":"Flussi di lavoro","nav.skills":"Competenze","nav.runs":"Esecuzioni","nav.approvals":"Approvazioni","nav.handoffs":"Passaggi","nav.apiKeys":"Chiavi API","nav.settings":"Impostazioni","nav.users":"Utenti","nav.prompts":"Prompt","dashboard.title":"Pannello","dashboard.activeAgents":"Agenti attivi","dashboard.runningTasks":"Attività in corso","dashboard.costToday":"Costo oggi","dashboard.skillsInstalled":"Competenze installate","dashboard.recentActivity":"Attività recente","dashboard.quickActions":"Azioni rapide","dashboard.systemHealth":"Stato del sistema","dashboard.createAgent":"Crea agente","dashboard.runWorkflow":"Esegui flusso","dashboard.installSkill":"Installa competenza","agents.title":"Agenti","agents.create":"Crea agente","agents.empty":"Nessun agente configurato.","agents.emptyDesc":"Crea il tuo primo agente IA per iniziare con le attività automatizzate.","agent.overview":"Panoramica","agent.runs":"Esecuzioni","agent.events":"Eventi","agent.configuration":"Configurazione","agent.budget":"Budget","agent.recentRuns":"Esecuzioni recenti","agent.delete":"Elimina agente","agent.start":"Avvia","agent.stop":"Arresta","agent.run":"Esegui","workflows.title":"Flussi di lavoro","workflows.create":"Crea flusso","workflows.empty":"Nessun flusso di lavoro definito.","workflows.emptyDesc":"Progetta il tuo primo flusso di lavoro per orchestrare più agenti.","workflows.nodes":"{count} nodi","workflows.edit":"Modifica","workflow.editor":"Editor del flusso","workflow.addNode":"Aggiungi nodo","workflow.save":"Salva","workflow.run":"Esegui flusso","skills.title":"Competenze","skills.install":"Installa","skills.empty":"Nessuna competenza installata.","skills.emptyDesc":"Esplora e installa competenze per ampliare le capacità dei tuoi agenti.","skills.scan":"Scansiona directory","skills.source":"URL o percorso sorgente","runs.title":"Esecuzioni","runs.empty":"Nessuna esecuzione registrata.","runs.emptyDesc":"Esegui un agente o un flusso per vedere la cronologia.","runs.filter":"Filtra","run.events":"Eventi","run.output":"Output","run.cost":"Dettaglio costi","run.duration":"Durata","approvals.title":"Coda di approvazione","approvals.empty":"Nessuna approvazione in sospeso.","approvals.emptyDesc":"Tutto a posto. Le azioni pericolose appariranno qui per la revisione.","approvals.approve":"Approva","approvals.deny":"Nega","approvals.pending":"In sospeso","nav.analytics":"Analisi","nav.budget":"Budget","nav.traces":"Tracce","nav.memory":"Memoria","nav.goals":"Obiettivi","nav.plans":"Piani","nav.guardrails":"Protezioni","analytics.title":"Analisi dei costi","analytics.description":"Monitora spese, utilizzo dei token e budget per agente.","analytics.totalSpend":"Spesa totale","analytics.totalRuns":"Esecuzioni totali","analytics.avgCostPerRun":"Costo medio/esec.","analytics.monthlyEstimate":"Stima mensile","analytics.dailyCosts":"Costi giornalieri (30 giorni)","analytics.agentBreakdown":"Costo per agente","analytics.modelBreakdown":"Costo per modello","analytics.budgetUtilization":"Utilizzo del budget","analytics.runs":"Esecuzioni","analytics.totalCost":"Costo totale","analytics.avgCost":"Costo medio","analytics.model":"Modello","analytics.tokens":"Token","analytics.cost":"Costo","analytics.noAgentData":"Nessun dato di costo per agente.","analytics.noModelData":"Nessun dato di costo per modello.","settings.title":"Impostazioni","settings.general":"Generale","settings.security":"Sicurezza","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Salva modifiche","settings.saved":"Impostazioni salvate.","settings.language":"Lingua","common.loading":"Caricamento...","common.error":"Si è verificato un errore.","common.retry":"Riprova","common.cancel":"Annulla","common.save":"Salva","common.delete":"Elimina","common.close":"Chiudi","common.search":"Cerca...","common.noResults":"Nessun risultato.","common.name":"Nome","common.description":"Descrizione","common.status":"Stato","common.type":"Tipo","common.actions":"Azioni","common.created":"Creato","common.updated":"Aggiornato","status.running":"In esecuzione","status.completed":"Completato","status.failed":"Fallito","status.pending":"In sospeso","status.paused":"In pausa","status.cancelled":"Annullato","status.idle":"Inattivo","trust.builtin":"Integrato","trust.official":"Ufficiale","trust.trusted":"Affidabile","trust.community":"Comunità","trust.local":"Locale"},nl:{"nav.dashboard":"Dashboard","nav.agents":"Agents","nav.workflows":"Workflows","nav.skills":"Vaardigheden","nav.runs":"Uitvoeringen","nav.approvals":"Goedkeuringen","nav.handoffs":"Overdrachten","nav.apiKeys":"API-sleutels","nav.settings":"Instellingen","nav.users":"Gebruikers","nav.prompts":"Prompts","dashboard.title":"Dashboard","dashboard.activeAgents":"Actieve agents","dashboard.runningTasks":"Lopende taken","dashboard.costToday":"Kosten vandaag","dashboard.skillsInstalled":"Geïnstalleerde vaardigheden","dashboard.recentActivity":"Recente activiteit","dashboard.quickActions":"Snelle acties","dashboard.systemHealth":"Systeemstatus","dashboard.createAgent":"Agent aanmaken","dashboard.runWorkflow":"Workflow uitvoeren","dashboard.installSkill":"Vaardigheid installeren","agents.title":"Agents","agents.create":"Agent aanmaken","agents.empty":"Geen agents geconfigureerd.","agents.emptyDesc":"Maak uw eerste AI-agent aan om te beginnen met geautomatiseerde taken.","agent.overview":"Overzicht","agent.runs":"Uitvoeringen","agent.events":"Gebeurtenissen","agent.configuration":"Configuratie","agent.budget":"Budget","agent.recentRuns":"Recente uitvoeringen","agent.delete":"Agent verwijderen","agent.start":"Starten","agent.stop":"Stoppen","agent.run":"Uitvoeren","workflows.title":"Workflows","workflows.create":"Workflow aanmaken","workflows.empty":"Geen workflows gedefinieerd.","workflows.emptyDesc":"Ontwerp uw eerste workflow om meerdere agents te orkestreren.","workflows.nodes":"{count} knooppunten","workflows.edit":"Bewerken","workflow.editor":"Workflow-editor","workflow.addNode":"Knooppunt toevoegen","workflow.save":"Opslaan","workflow.run":"Workflow uitvoeren","skills.title":"Vaardigheden","skills.install":"Installeren","skills.empty":"Geen vaardigheden geïnstalleerd.","skills.emptyDesc":"Blader door en installeer vaardigheden om de mogelijkheden van uw agents uit te breiden.","skills.scan":"Map scannen","skills.source":"Bron-URL of pad","runs.title":"Uitvoeringen","runs.empty":"Geen uitvoeringen geregistreerd.","runs.emptyDesc":"Voer een agent of workflow uit om de uitvoeringsgeschiedenis te bekijken.","runs.filter":"Filteren","run.events":"Gebeurtenissen","run.output":"Uitvoer","run.cost":"Kostenoverzicht","run.duration":"Duur","approvals.title":"Goedkeuringswachtrij","approvals.empty":"Geen wachtende goedkeuringen.","approvals.emptyDesc":"Alles in orde. Gevaarlijke acties verschijnen hier ter beoordeling.","approvals.approve":"Goedkeuren","approvals.deny":"Weigeren","approvals.pending":"In afwachting","nav.analytics":"Analyse","nav.budget":"Budget","nav.traces":"Traces","nav.memory":"Geheugen","nav.goals":"Doelen","nav.plans":"Plannen","nav.guardrails":"Vangrails","analytics.title":"Kostenanalyse","analytics.description":"Volg uitgaven, tokengebruik en budgetbenutting per agent.","analytics.totalSpend":"Totale uitgaven","analytics.totalRuns":"Totaal uitvoeringen","analytics.avgCostPerRun":"Gem. kosten/uitv.","analytics.monthlyEstimate":"Maandelijkse schatting","analytics.dailyCosts":"Dagelijkse kosten (30 dagen)","analytics.agentBreakdown":"Kosten per agent","analytics.modelBreakdown":"Kosten per model","analytics.budgetUtilization":"Budgetbenutting","analytics.runs":"Uitvoeringen","analytics.totalCost":"Totale kosten","analytics.avgCost":"Gem. kosten","analytics.model":"Model","analytics.tokens":"Tokens","analytics.cost":"Kosten","analytics.noAgentData":"Nog geen kostengegevens per agent.","analytics.noModelData":"Nog geen kostengegevens per model.","settings.title":"Instellingen","settings.general":"Algemeen","settings.security":"Beveiliging","settings.llm":"LLM","settings.budget":"Budget","settings.save":"Wijzigingen opslaan","settings.saved":"Instellingen opgeslagen.","settings.language":"Taal","common.loading":"Laden...","common.error":"Er is een fout opgetreden.","common.retry":"Opnieuw proberen","common.cancel":"Annuleren","common.save":"Opslaan","common.delete":"Verwijderen","common.close":"Sluiten","common.search":"Zoeken...","common.noResults":"Geen resultaten gevonden.","common.name":"Naam","common.description":"Beschrijving","common.status":"Status","common.type":"Type","common.actions":"Acties","common.created":"Aangemaakt","common.updated":"Bijgewerkt","status.running":"Actief","status.completed":"Voltooid","status.failed":"Mislukt","status.pending":"In afwachting","status.paused":"Gepauzeerd","status.cancelled":"Geannuleerd","status.idle":"Inactief","trust.builtin":"Ingebouwd","trust.official":"Officieel","trust.trusted":"Vertrouwd","trust.community":"Community","trust.local":"Lokaal"}},_0=u.createContext({lang:"en",setLang:()=>{},t:n=>n,isRTL:!1});function Xv({children:n}){const[i,d]=u.useState(()=>{const h=localStorage.getItem("nestor_lang");return h&&Wd(h)?h:Yv(navigator.language)}),c=Kv.includes(i);u.useEffect(()=>{document.documentElement.dir=c?"rtl":"ltr",document.documentElement.lang=i},[i,c]);const m=u.useCallback(h=>{d(h),localStorage.setItem("nestor_lang",h)},[]),f=u.useCallback((h,b)=>{var p;let g=((p=qh[i])==null?void 0:p[h])??qh.en[h]??h;if(b)for(const[S,y]of Object.entries(b))g=g.replace(`{${S}}`,String(y));return g},[i]);return e.jsx(_0.Provider,{value:{lang:i,setLang:m,t:f,isRTL:c},children:n})}function Je(){return u.useContext(_0)}const Qv={admin:{agents:["create","read","update","delete","execute","admin"],workflows:["create","read","update","delete","execute","admin"],skills:["create","read","update","delete","admin"],settings:["read","update","admin"],users:["create","read","update","delete","admin"],prompts:["create","read","update","delete","admin"]},member:{agents:["create","read","update","execute"],workflows:["create","read","update","execute"],skills:["read","create"],settings:["read"],prompts:["read","create","update"]},viewer:{agents:["read"],workflows:["read"],skills:["read"],settings:["read"],prompts:["read"]}},U0=u.createContext({user:null,loading:!0,login:async()=>{},logout:async()=>{},register:async()=>{},isAdmin:!1,hasPermission:()=>!1,isSyntheticAdmin:!1}),Fv="/api";function Zv(){const n=document.cookie.match(/(?:^|; )nestor-csrf=([^;]*)/);return n?decodeURIComponent(n[1]):null}async function li(n,i){var h;const d={"Content-Type":"application/json",...(i==null?void 0:i.headers)||{}},c=((i==null?void 0:i.method)||"GET").toUpperCase();if(c!=="GET"&&c!=="HEAD"){const b=Zv();b&&(d["X-CSRF-Token"]=b)}const m=await fetch(`${Fv}${n}`,{credentials:"include",headers:d,...i}),f=await m.json().catch(()=>({}));if(!m.ok)throw new Error(((h=f==null?void 0:f.error)==null?void 0:h.message)||`Request failed (${m.status})`);return f}function Jv({children:n}){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(!1);u.useEffect(()=>{li("/auth/me").then(v=>{var k;(k=v.data)!=null&&k.user&&typeof v.data.user=="object"&&(d(v.data.user),h(!1))}).catch(async()=>{try{(await li("/health")).status==="ok"&&(d({id:"local",email:"admin@localhost",name:"Admin",role:"admin"}),h(!0))}catch{}}).finally(()=>m(!1))},[]);const b=u.useCallback(async(v,k)=>{const C=await li("/auth/login",{method:"POST",body:JSON.stringify({email:v,password:k})});d(C.data.user),h(!1)},[]),g=u.useCallback(async()=>{await li("/auth/logout",{method:"POST"}).catch(()=>{}),d(null),h(!1)},[]),p=u.useCallback(async(v,k,C)=>{await li("/auth/register",{method:"POST",body:JSON.stringify({email:v,password:k,name:C})})},[]),S=(i==null?void 0:i.role)==="admin",y=u.useCallback((v,k)=>{if(!i)return!1;const C=Qv[i.role];if(!C)return!1;const w=C[v];return w?w.includes(k)||w.includes("admin"):!1},[i]);return e.jsx(U0.Provider,{value:{user:i,loading:c,login:b,logout:g,register:p,isAdmin:S,hasPermission:y,isSyntheticAdmin:f},children:n})}function ol(){return u.useContext(U0)}const Iv=[{to:"/missions",icon:sa,labelKey:"nav.missions"},{to:"/chat",icon:Pt,labelKey:"nav.chat"},{to:"/agents",icon:Ts,labelKey:"nav.agents"},{to:"/workflows",icon:tc,labelKey:"nav.workflows"},{to:"/runs",icon:Nt,labelKey:"nav.history"}],$0=[{key:"tools",label:"Tools",defaultOpen:!1,items:[{to:"/skills",icon:rc,labelKey:"nav.skills"},{to:"/memory",icon:La,labelKey:"nav.memory"},{to:"/messaging",icon:Pt,labelKey:"nav.messaging"},{to:"/scheduler",icon:vs,labelKey:"nav.scheduler"},{to:"/plans",icon:pv,labelKey:"nav.plans"},{to:"/guardrails",icon:Ds,labelKey:"nav.guardrails"}]},{key:"monitoring",label:"Monitoring",defaultOpen:!1,items:[{to:"/analytics",icon:Rs,labelKey:"nav.analytics"},{to:"/budget",icon:us,labelKey:"nav.budget"},{to:"/traces",icon:It,labelKey:"nav.traces"},{to:"/approvals",icon:hu,labelKey:"nav.approvals"}]},{key:"advanced",label:"Advanced",defaultOpen:!1,items:[{to:"/goals",icon:rn,labelKey:"nav.goals"},{to:"/handoffs",icon:fi,labelKey:"nav.handoffs"},{to:"/evolve",icon:Pr,labelKey:"nav.evolve"},{to:"/keys",icon:Ni,labelKey:"nav.apiKeys"},{to:"/settings",icon:il,labelKey:"nav.settings"}]}],Pv=[{to:"/users",icon:rl,labelKey:"nav.users"},{to:"/admin",icon:il,labelKey:"nav.admin"}],B0="nestor_sidebar_sections";function Wv(){try{const i=localStorage.getItem(B0);if(i)return JSON.parse(i)}catch{}const n={};for(const i of $0)n[i.key]=i.defaultOpen;return n}function ej(n){try{localStorage.setItem(B0,JSON.stringify(n))}catch{}}function tj({onNavigate:n}){const{t:i}=Je(),{user:d,isAdmin:c,logout:m}=ol(),[f,h]=u.useState(Wv);u.useEffect(()=>{ej(f)},[f]);const b=u.useCallback(p=>{h(S=>({...S,[p]:!S[p]}))},[]),g=({isActive:p})=>`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${p?"bg-purple-500/10 text-purple-400":"text-zinc-400 hover:bg-surface-hover hover:text-zinc-200"}`;return e.jsxs("aside",{className:"fixed inset-y-0 left-0 z-30 flex w-60 flex-col border-r border-border bg-surface",children:[e.jsxs("div",{className:"flex h-14 items-center gap-2.5 px-5 border-b border-border",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-purple-600 text-white",children:e.jsx(sa,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-lg font-semibold text-white tracking-tight",children:["Nestor ",e.jsx("span",{className:"text-xs font-normal text-zinc-500",children:"Studio"})]})]}),e.jsxs("nav",{className:"flex-1 space-y-0.5 px-3 py-4 overflow-y-auto",children:[Iv.map(p=>{const S=p.icon;return e.jsxs(di,{to:p.to,end:p.to==="/chat",onClick:n,className:g,children:[e.jsx(S,{className:"h-4 w-4 flex-shrink-0"}),i(p.labelKey)]},p.to)}),$0.map(p=>e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{onClick:()=>b(p.key),className:"flex items-center gap-2 w-full px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-zinc-600 hover:text-zinc-400 transition-colors",children:[f[p.key]?e.jsx(na,{className:"h-3 w-3"}):e.jsx(ds,{className:"h-3 w-3"}),p.label]}),f[p.key]&&e.jsx("div",{className:"space-y-0.5",children:p.items.map(S=>{const y=S.icon;return e.jsxs(di,{to:S.to,onClick:n,className:g,children:[e.jsx(y,{className:"h-4 w-4 flex-shrink-0"}),i(S.labelKey)]},S.to)})})]},p.key)),c&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-2 border-t border-border/50"}),e.jsx("div",{className:"px-3 py-1 text-[10px] font-semibold uppercase tracking-wider text-zinc-600",children:"Admin"}),Pv.map(p=>{const S=p.icon;return e.jsxs(di,{to:p.to,onClick:n,className:g,children:[e.jsx(S,{className:"h-4 w-4 flex-shrink-0"}),i(p.labelKey)]},p.to)})]})]}),e.jsxs("div",{className:"border-t border-border px-4 py-3",children:[d&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-zinc-200",children:d.name}),e.jsx("p",{className:"truncate text-xs text-zinc-500",children:d.role})]}),e.jsx("button",{onClick:m,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-surface-hover hover:text-zinc-200",title:"Sign out",children:e.jsx(zv,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-600",children:"Nestor v3.5.2"})]})]})}const sj=["system","agents","runs","approvals"],aj=10,nj=1e3,lj=3e4,ij=3e4,rj=200;function cj(n,i,d){const c=Math.min(i*2**n,d),m=c*Math.random()*.25;return c+m}function oj(){const n=window.location.protocol==="https:"?"wss:":"ws:",i=window.location.host,d=localStorage.getItem("nestor_token"),c=d?`?token=${encodeURIComponent(d)}`:"";return`${n}//${i}/ws${c}`}function pu(n=sj,i){const{reconnect:d=!0,maxRetries:c=aj,baseDelay:m=nj,maxDelay:f=lj}={},[h,b]=u.useState([]),[g,p]=u.useState("disconnected"),[S,y]=u.useState(0),v=u.useRef(null),k=u.useRef(),C=u.useRef(),w=u.useRef(n),N=u.useRef(!1),z=u.useRef(0);w.current=n;const R=u.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=void 0)},[]),D=u.useCallback(()=>{C.current&&(clearInterval(C.current),C.current=void 0)},[]),O=u.useCallback(ce=>{D(),C.current=setInterval(()=>{ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"ping"}))},ij)},[D]),se=u.useCallback((ce,I)=>{for(const le of I)ce.readyState===WebSocket.OPEN&&ce.send(JSON.stringify({type:"subscribe",channel:le}))},[]),Z=u.useCallback(ce=>{if(!d||N.current)return;if(z.current>=c){console.warn(`[Nestor WS] Max retries (${c}) reached. Giving up.`),p("disconnected");return}const I=cj(z.current,m,f);console.info(`[Nestor WS] Reconnecting in ${Math.round(I)}ms (attempt ${z.current+1}/${c})`),p("reconnecting"),R(),k.current=setTimeout(()=>{z.current+=1,y(z.current),ce()},I)},[d,c,m,f,R]),U=u.useCallback(()=>{if(!(v.current&&(v.current.readyState===WebSocket.OPEN||v.current.readyState===WebSocket.CONNECTING)))try{const ce=oj(),I=new WebSocket(ce);v.current=I,p("connecting"),I.onopen=()=>{console.info("[Nestor WS] Connected"),p("connected"),z.current=0,y(0),N.current=!1,se(I,w.current),O(I)},I.onmessage=le=>{try{const Y=JSON.parse(le.data);if(Y.type==="ping"){I.send(JSON.stringify({type:"pong"}));return}if(Y.type==="pong")return;if(Y.type==="event"){const B=Y;b(ne=>[...ne.slice(-(rj-1)),B])}}catch{}},I.onclose=le=>{if(console.info(`[Nestor WS] Closed (code=${le.code}, reason=${le.reason||"none"})`),v.current=null,D(),N.current){p("disconnected");return}Z(U)},I.onerror=le=>{console.error("[Nestor WS] Error:",le),I.close()}}catch{Z(U)}},[se,O,D,Z]);u.useEffect(()=>(N.current=!1,U(),()=>{N.current=!0,R(),D(),v.current&&(v.current.close(1e3,"Component unmount"),v.current=null)}),[U,R,D]),u.useEffect(()=>{const ce=v.current;!ce||ce.readyState!==WebSocket.OPEN||se(ce,n)},[n,se]);const A=u.useCallback(ce=>{const I=v.current;I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"subscribe",channel:ce}))},[]),F=u.useCallback(ce=>{const I=v.current;I&&I.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"unsubscribe",channel:ce}))},[]),$=u.useCallback(()=>{b([])},[]),Q=u.useCallback(()=>{N.current=!0,R(),D(),v.current&&(v.current.close(1e3,"Manual close"),v.current=null),p("disconnected")},[R,D]);return{events:h,connected:g==="connected",status:g,retryCount:S,subscribe:A,unsubscribe:F,clearEvents:$,close:Q}}const dj="/api";class uj extends Error{constructor(i,d,c){super(`API Error ${i}: ${d}`),this.status=i,this.statusText=d,this.body=c,this.name="ApiError"}}function mj(n){const i=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return i?decodeURIComponent(i[1]):null}async function ae(n,i={}){const d=`${dj}${n}`,c={"Content-Type":"application/json",...i.headers},m=localStorage.getItem("nestor_token");m&&(c.Authorization=`Bearer ${m}`);const f=(i.method||"GET").toUpperCase();if(f!=="GET"&&f!=="HEAD"){const g=mj("nestor-csrf");g&&(c["X-CSRF-Token"]=g)}const h=localStorage.getItem("nestor_tenant_id");h&&(c["X-Tenant-ID"]=h);const b=await fetch(d,{...i,headers:c});if(!b.ok){let g;try{g=await b.json()}catch{g=await b.text()}throw new uj(b.status,b.statusText,g)}if(b.status!==204)return b.json()}const la={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/agents${d?`?${d}`:""}`)},get:n=>ae(`/agents/${n}`),create:n=>ae("/agents",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/agents/${n}`,{method:"PATCH",body:JSON.stringify(i)}),delete:n=>ae(`/agents/${n}`,{method:"DELETE"}),run:(n,i)=>ae(`/agents/${n}/run`,{method:"POST",body:JSON.stringify({prompt:i})}),getStatus:n=>ae(`/agents/${n}/status`),start:(n,i="daemon")=>ae(`/agents/${n}/start`,{method:"POST",body:JSON.stringify({mode:i})}),stop:n=>ae(`/agents/${n}/stop`,{method:"POST"})},sc={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/workflows${d?`?${d}`:""}`)},get:n=>ae(`/workflows/${n}`),create:n=>ae("/workflows",{method:"POST",body:JSON.stringify(n)}),run:(n,i={})=>ae(`/workflows/${n}/run`,{method:"POST",body:JSON.stringify({input:i})})},ln={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset)),n!=null&&n.status&&i.set("status",n.status),n!=null&&n.agentId&&i.set("agentId",n.agentId),n!=null&&n.workflowId&&i.set("workflowId",n.workflowId);const d=i.toString();return ae(`/runs${d?`?${d}`:""}`)},get:n=>ae(`/runs/${n}`),getEvents:n=>ae(`/runs/${n}/events`),abort:n=>ae(`/runs/${n}/abort`,{method:"POST"}),delete:n=>ae(`/runs/${n}`,{method:"DELETE"})},Wr={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/skills${d?`?${d}`:""}`)},install:n=>ae("/skills/install",{method:"POST",body:JSON.stringify(n)}),scan:n=>ae("/skills/scan",{method:"POST",body:JSON.stringify({path:n})}),delete:n=>ae(`/skills/${n}`,{method:"DELETE"})},Es={stats:()=>ae("/system/stats"),health:()=>ae("/health"),getConfig:()=>ae("/system/config"),updateConfig:n=>ae("/system/config",{method:"PUT",body:JSON.stringify(n)})},In={summary:n=>{const i=new URLSearchParams;n!=null&&n.from&&i.set("from",String(n.from)),n!=null&&n.to&&i.set("to",String(n.to)),n!=null&&n.agentId&&i.set("agentId",n.agentId);const d=i.toString();return ae(`/analytics/summary${d?`?${d}`:""}`)},daily:(n=30)=>ae(`/analytics/daily?days=${n}`),budget:()=>ae("/analytics/budget"),estimate:()=>ae("/analytics/estimate"),agentBreakdown:n=>ae(`/analytics/agents/${n}`),qualityOverview:(n=30)=>ae(`/analytics/quality?days=${n}`),qualityAgent:(n,i=30)=>ae(`/analytics/quality/${n}?days=${i}`)},Bd={list:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.status&&i.set("status",n.status);const d=i.toString();return ae(`/traces${d?`?${d}`:""}`)},get:n=>ae(`/traces/${n}`),clear:()=>ae("/traces",{method:"DELETE"})},Gh={list:()=>ae("/tenants"),get:n=>ae(`/tenants/${n}`),create:n=>ae("/tenants",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/tenants/${n}`,{method:"PUT",body:JSON.stringify(i)}),delete:n=>ae(`/tenants/${n}`,{method:"DELETE"}),switch:n=>ae(`/tenants/${n}/switch`,{method:"POST"})},ii={tree:()=>ae("/goals"),get:n=>ae(`/goals/${n}`),create:n=>ae("/goals",{method:"POST",body:JSON.stringify(n)}),update:(n,i)=>ae(`/goals/${n}`,{method:"PUT",body:JSON.stringify(i)}),delete:n=>ae(`/goals/${n}`,{method:"DELETE"}),ancestry:n=>ae(`/goals/${n}/ancestry`),assign:(n,i)=>ae(`/goals/${n}/assign/${i}`,{method:"POST"}),agentGoals:n=>ae(`/agents/${n}/goals`)},ri={list:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status),n!=null&&n.agentId&&i.set("agentId",n.agentId),n!=null&&n.type&&i.set("type",n.type),n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/approvals${d?`?${d}`:""}`)},create:n=>ae("/approvals",{method:"POST",body:JSON.stringify(n)}),get:n=>ae(`/approvals/${n}`),approve:(n,i)=>ae(`/approvals/${n}/approve`,{method:"POST",body:JSON.stringify({decidedBy:(i==null?void 0:i.reviewerId)??"user",comment:i==null?void 0:i.comment})}),reject:(n,i)=>ae(`/approvals/${n}/reject`,{method:"POST",body:JSON.stringify({decidedBy:(i==null?void 0:i.reviewerId)??"user",reason:i==null?void 0:i.reason})}),history:n=>{const i=new URLSearchParams;n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.agentId&&i.set("agentId",n.agentId);const d=i.toString();return ae(`/approvals/history${d?`?${d}`:""}`)},stats:()=>ae("/approvals/stats")},Hd={forRun:n=>ae(`/runs/${n}/annotations`),create:(n,i)=>ae(`/runs/${n}/annotate`,{method:"POST",body:JSON.stringify(i)}),delete:n=>ae(`/annotations/${n}`,{method:"DELETE"})},ac={list:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status);const d=i.toString();return ae(`/handoffs${d?`?${d}`:""}`)},get:n=>ae(`/handoffs/${n}`),create:(n,i)=>ae(`/runs/${n}/handoff`,{method:"POST",body:JSON.stringify(i)}),resume:(n,i)=>ae(`/handoffs/${n}/resume`,{method:"POST",body:JSON.stringify({humanResolution:i})})},Tt={overview:()=>ae("/admin/overview"),tenants:{list:()=>ae("/tenants"),create:n=>ae("/tenants",{method:"POST",body:JSON.stringify(n)}),get:n=>ae(`/tenants/${n}`),update:(n,i)=>ae(`/tenants/${n}`,{method:"PUT",body:JSON.stringify(i)})},users:{list:n=>{const i=new URLSearchParams;n!=null&&n.tenantId&&i.set("tenantId",n.tenantId),n!=null&&n.role&&i.set("role",n.role);const d=i.toString();return ae(`/users${d?`?${d}`:""}`)},updateRole:(n,i)=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({role:i})}),lock:n=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({isActive:!1})}),unlock:n=>ae(`/users/${n}`,{method:"PATCH",body:JSON.stringify({isActive:!0})})},system:{info:()=>ae("/admin/system-info"),dbStats:()=>ae("/admin/db-stats"),rateLimitStats:()=>ae("/admin/rate-limit-stats")},audit:{query:n=>{const i=new URLSearchParams;n!=null&&n.userId&&i.set("userId",n.userId),n!=null&&n.resourceType&&i.set("resourceType",n.resourceType),n!=null&&n.action&&i.set("action",n.action),n!=null&&n.limit&&i.set("limit",String(n.limit));const d=i.toString();return ae(`/users/audit${d?`?${d}`:""}`)},export:n=>ae(`/users/audit?limit=10000&format=${n}`)},security:{failedLogins:(n=24)=>ae(`/admin/security/failed-logins?hours=${n}`),lockedAccounts:()=>ae("/admin/security/locked-accounts"),activeSessions:()=>ae("/admin/security/active-sessions"),rateLimitViolations:(n=100)=>ae(`/admin/security/rate-violations?limit=${n}`)}},Kh={status:()=>ae("/providers/status"),test:n=>ae("/providers/test",{method:"POST",body:JSON.stringify(n)})},ys={list:()=>ae("/keys"),set:(n,i,d)=>ae("/keys",{method:"POST",body:JSON.stringify({provider:n,key:i,label:d})}),remove:n=>ae(`/keys/${n}`,{method:"DELETE"}),test:n=>ae(`/keys/test/${n}`)},ea={plan:(n,i)=>ae("/missions/plan",{method:"POST",body:JSON.stringify({objective:n,...i})}),list:()=>ae("/missions"),get:n=>ae(`/missions/${n}`),getReport:(n,i)=>ae(`/missions/${n}/report${i==="md"?"?format=md":""}`),cancel:n=>ae(`/missions/${n}/cancel`,{method:"POST"}),templates:()=>ae("/missions/templates")},qd={status:()=>ae("/messaging/status"),channels:()=>ae("/messaging/channels"),send:(n,i,d)=>ae("/messaging/send",{method:"POST",body:JSON.stringify({adapter:n,channel:i,content:d})})},ci={list:()=>ae("/agents?scheduled=true"),setSchedule:(n,i)=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify(i)}),removeSchedule:n=>ae(`/agents/${n}/schedule`,{method:"DELETE"}),pauseSchedule:n=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify({enabled:!1})}),resumeSchedule:n=>ae(`/agents/${n}/schedule`,{method:"POST",body:JSON.stringify({enabled:!0})})},Br={candidates:n=>{const i=new URLSearchParams;n!=null&&n.status&&i.set("status",n.status),n!=null&&n.limit&&i.set("limit",String(n.limit)),n!=null&&n.offset&&i.set("offset",String(n.offset));const d=i.toString();return ae(`/evolve/candidates${d?`?${d}`:""}`)},approve:n=>ae(`/evolve/candidates/${n}/approve`,{method:"POST"}),reject:n=>ae(`/evolve/candidates/${n}/reject`,{method:"POST"}),update:(n,i)=>ae(`/evolve/candidates/${n}`,{method:"PATCH",body:JSON.stringify(i)})};function xj({onMenuClick:n,showMenu:i}){const{lang:d,setLang:c,t:m}=Je(),{connected:f}=pu(),[h,b]=u.useState([]),[g,p]=u.useState(()=>localStorage.getItem("nestor_tenant_id")??"default"),[S,y]=u.useState(!1),[v,k]=u.useState(!1),C=u.useRef(null),w=u.useRef(null),N=h.find(O=>O.id===g)??null,z=u.useCallback(async()=>{try{const O=await Gh.list();b(O.data)}catch{}},[]);u.useEffect(()=>{z()},[z]),u.useEffect(()=>{const O=se=>{C.current&&!C.current.contains(se.target)&&y(!1),w.current&&!w.current.contains(se.target)&&k(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const R=async O=>{try{await Gh.switch(O.id),localStorage.setItem("nestor_tenant_id",O.id),p(O.id),y(!1),window.location.reload()}catch(se){console.error("Failed to switch tenant:",se)}},D=Object.keys(Pd);return e.jsxs("header",{className:"header sticky top-0 z-20 flex h-14 items-center justify-between border-b border-border bg-[#0a0a0f]/80 px-6 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[i&&e.jsx("button",{onClick:n,className:"p-2 hover:bg-surface-hover rounded-lg transition-colors","aria-label":"Toggle menu",children:e.jsx(Cv,{className:"h-5 w-5 text-zinc-400"})}),e.jsxs("div",{className:"relative max-w-md flex-1",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{type:"text",placeholder:m("common.search"),className:"input pl-9 max-w-sm"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[h.length>0&&e.jsxs("div",{className:"relative hidden sm:block",ref:C,children:[e.jsxs("button",{onClick:()=>y(!S),className:"flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-1.5 text-sm transition-colors hover:border-zinc-600",children:[e.jsx(du,{className:"h-3.5 w-3.5 text-indigo-400"}),e.jsx("span",{className:"text-zinc-200 max-w-[120px] truncate",children:(N==null?void 0:N.name)??"Default"}),e.jsx(na,{className:`h-3.5 w-3.5 text-zinc-500 transition-transform ${S?"rotate-180":""}`})]}),S&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 w-56 rounded-lg border border-border bg-surface shadow-xl z-50",children:[e.jsx("div",{className:"px-3 py-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-600",children:"Switch Tenant"}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:h.map(O=>e.jsxs("button",{onClick:()=>R(O),className:"flex w-full items-center gap-2 px-3 py-2 text-sm text-zinc-300 transition-colors hover:bg-surface-hover",children:[O.id===g?e.jsx(bt,{className:"h-3.5 w-3.5 text-indigo-400"}):e.jsx("div",{className:"h-3.5 w-3.5"}),e.jsxs("div",{className:"flex-1 text-left",children:[e.jsx("div",{className:"font-medium",children:O.name}),e.jsx("div",{className:"text-xs text-zinc-500",children:O.slug})]})]},O.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[f?e.jsx(Gv,{className:"h-4 w-4 text-green-400"}):e.jsx(qv,{className:"h-4 w-4 text-zinc-500"}),e.jsx("span",{className:`text-xs hidden sm:inline ${f?"text-green-400":"text-zinc-500"}`,children:f?"Connected":"Offline"})]}),e.jsxs("div",{className:"relative",ref:w,children:[e.jsxs("button",{onClick:()=>k(!v),className:"btn-ghost btn-sm flex items-center gap-1.5",title:"Switch language",children:[e.jsx(mu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase",children:d}),e.jsx(na,{className:`h-3 w-3 text-zinc-500 transition-transform ${v?"rotate-180":""}`})]}),v&&e.jsx("div",{className:"absolute right-0 top-full mt-1 w-48 rounded-lg border border-border bg-surface shadow-xl z-50 max-h-80 overflow-y-auto",children:D.map(O=>e.jsxs("button",{onClick:()=>{c(O),k(!1)},className:"flex w-full items-center gap-2 px-3 py-2 text-sm text-zinc-300 transition-colors hover:bg-surface-hover",children:[O===d?e.jsx(bt,{className:"h-3.5 w-3.5 text-indigo-400"}):e.jsx("div",{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"flex-1 text-left",children:Pd[O]}),e.jsx("span",{className:"text-xs text-zinc-500 uppercase",children:O})]},O))})]})]})]})}const fj=[{to:"/",icon:Pt,labelKey:"nav.chat"},{to:"/agents",icon:Ts,labelKey:"nav.agents"},{to:"/dashboard",icon:xu,labelKey:"nav.dashboard"},{to:"/runs",icon:Nt,labelKey:"nav.history"},{to:"/settings",icon:il,labelKey:"nav.settings"}];function hj(){const{t:n}=Je();return e.jsx("nav",{className:"mobile-bottom-nav",children:fj.map(i=>{const d=i.icon;return e.jsxs(di,{to:i.to,end:i.to==="/",className:({isActive:c})=>`mobile-bottom-nav-item ${c?"active":""}`,children:[e.jsx(d,{className:"h-5 w-5"}),e.jsx("span",{className:"mobile-bottom-nav-label",children:n(i.labelKey)})]},i.to)})})}function pj(){const[n,i]=u.useState(!1),[d,c]=u.useState(!1),{isSyntheticAdmin:m}=ol();u.useEffect(()=>{const h=()=>c(window.innerWidth<769);return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]);const f=()=>{d&&i(!1)};return e.jsxs("div",{className:"flex min-h-screen bg-[#0a0a0f]",children:[d&&n&&e.jsx("div",{className:"sidebar-overlay",onClick:()=>i(!1)}),e.jsx("div",{className:`sidebar ${d&&n?"open":""}`,children:e.jsx(tj,{onNavigate:f})}),e.jsxs("div",{className:`flex flex-1 flex-col ${d?"":"pl-60"}`,children:[e.jsx(xj,{onMenuClick:()=>i(!n),showMenu:d}),m&&e.jsxs("div",{role:"status",className:"bg-yellow-500/20 border-b border-yellow-500/40 text-yellow-200 text-sm px-4 py-2 text-center",children:[e.jsx("strong",{children:"Local admin mode"}),' — the auth server is unreachable, so a synthetic "Admin" user was created to keep the UI usable. Sign in to the real server to leave this mode.']}),e.jsx("main",{className:`main-content flex-1 p-6 ${d?"pb-20":""}`,children:e.jsx(Cy,{})}),d&&e.jsx(hj,{})]})]})}class gj extends u.Component{constructor(){super(...arguments);Ad(this,"state",{hasError:!1,error:null});Ad(this,"handleReset",()=>{this.setState({hasError:!1,error:null})})}static getDerivedStateFromError(d){return{hasError:!0,error:d}}componentDidCatch(d,c){var m,f;console.error("[Nestor] UI Error:",d,c),(f=(m=this.props).onError)==null||f.call(m,d,c)}render(){var d;return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8",children:[e.jsx("div",{className:"text-red-500 text-xl mb-4",children:"Something went wrong"}),e.jsx("pre",{className:"bg-gray-100 dark:bg-gray-800 p-4 rounded-lg text-sm max-w-lg overflow-auto mb-4",children:(d=this.state.error)==null?void 0:d.message}),e.jsx("button",{onClick:this.handleReset,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:"Try Again"})]}):this.props.children}}function bj(){const n=Dt();return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[60vh] p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 mb-6 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center",children:e.jsx("svg",{className:"w-8 h-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"})})}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 dark:text-gray-100 mb-2",children:"Page Error"}),e.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-8 max-w-md",children:"An unexpected error occurred while rendering this page. The error has been logged for investigation."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Reload Page"}),e.jsx("button",{onClick:()=>n("/"),className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:"Go Home"})]})]})}const yj={node_started:{icon:Nt,color:"text-blue-400"},node_completed:{icon:et,color:"text-green-400"},node_failed:{icon:ft,color:"text-red-400"},tool_call_requested:{icon:sa,color:"text-amber-400"},tool_call_approved:{icon:et,color:"text-green-400"},tool_call_denied:{icon:Ms,color:"text-red-400"},tool_call_completed:{icon:et,color:"text-emerald-400"},approval_requested:{icon:Ms,color:"text-amber-400"},approval_resolved:{icon:et,color:"text-green-400"},budget_warning:{icon:pt,color:"text-amber-400"},budget_exceeded:{icon:us,color:"text-red-400"},run_paused:{icon:tl,color:"text-blue-400"},run_resumed:{icon:D0,color:"text-blue-400"}};function vj(n){try{return new Date(n).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return n}}function jj(n,i){switch(n){case"node_started":return`Node started: ${i.nodeId??i.label??""}`;case"node_completed":return`Node completed: ${i.nodeId??i.label??""}`;case"node_failed":return`Node failed: ${i.error??i.nodeId??""}`;case"tool_call_requested":return`Tool call: ${i.toolName??""}`;case"tool_call_approved":return`Tool approved: ${i.toolName??""}`;case"tool_call_denied":return`Tool denied: ${i.toolName??""}`;case"tool_call_completed":return`Tool completed: ${i.toolName??""}`;case"approval_requested":return`Approval required: ${i.toolName??i.action??""}`;case"approval_resolved":return`Approval resolved: ${i.decision??""}`;case"budget_warning":return`Budget warning: ${i.percent??""}% used`;case"budget_exceeded":return"Budget exceeded";case"run_paused":return"Run paused";case"run_resumed":return"Run resumed";default:return n.replace(/_/g," ")}}function gu({events:n,maxHeight:i="400px"}){return n.length===0?e.jsxs("div",{className:"flex items-center justify-center py-8 text-sm text-zinc-500",children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Waiting for events..."]}):e.jsx("div",{className:"overflow-y-auto",style:{maxHeight:i},children:e.jsx("div",{className:"space-y-0.5",children:[...n].reverse().map(d=>{const c=yj[d.type]??{icon:sa,color:"text-zinc-400"},m=c.icon;return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg px-3 py-2 hover:bg-surface-hover transition-colors",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 ${c.color}`,children:e.jsx(m,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm text-zinc-300 truncate",children:jj(d.type,d.data)}),d.nodeId&&e.jsxs("p",{className:"text-xs text-zinc-500 truncate",children:["Node: ",d.nodeId]})]}),e.jsx("time",{className:"flex-shrink-0 text-xs text-zinc-500",children:vj(d.timestamp)})]},d.id)})})})}function Hr({label:n,value:i,icon:d,color:c,bgColor:m}){return e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-zinc-400",children:n}),e.jsx("p",{className:"mt-1 text-2xl font-semibold text-white",children:i})]}),e.jsx("div",{className:`flex h-11 w-11 items-center justify-center rounded-xl ${m}`,children:e.jsx(d,{className:`h-5 w-5 ${c}`})})]})})}function Nj(){const{t:n}=Je(),{events:i}=pu(),[d,c]=u.useState(null),[m,f]=u.useState("healthy"),[h,b]=u.useState(!0),[g,p]=u.useState(null),[S,y]=u.useState(0);u.useEffect(()=>{Es.stats().then(z=>{c(z.data),f("healthy"),p(null)}).catch(z=>{f("down"),p(z instanceof Error?z.message:"Failed to connect to server")}).finally(()=>{b(!1)}),Es.health().then(z=>{f(z.status==="healthy"?"healthy":"degraded")}).catch(()=>{f("down")});const N=new Date;N.setHours(0,0,0,0),In.summary({from:N.getTime()}).then(z=>{var R;y(((R=z.data)==null?void 0:R.totalCostUsd)??0)}).catch(()=>{})},[]),u.useEffect(()=>{if(i.length===0)return;Es.stats().then(z=>c(z.data)).catch(()=>{});const N=new Date;N.setHours(0,0,0,0),In.summary({from:N.getTime()}).then(z=>{var R;y(((R=z.data)==null?void 0:R.totalCostUsd)??0)}).catch(()=>{})},[i.length]);const k={healthy:{icon:et,color:"text-green-400",bg:"bg-green-500/10",label:"All systems operational"},degraded:{icon:pt,color:"text-amber-400",bg:"bg-amber-500/10",label:"Some services degraded"},down:{icon:ft,color:"text-red-400",bg:"bg-red-500/10",label:"Services unavailable"}}[m],C=k.icon,w=i.map((N,z)=>{var R;return{id:String(z),type:typeof N.data=="object"&&N.data!==null&&"kind"in N.data?N.data.kind:N.channel,data:N.data??{},timestamp:((R=N.data)==null?void 0:R.timestamp)??new Date().toISOString()}});return h?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("dashboard.title")}),g&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:["Unable to connect to the Nestor server. Make sure the server is running.",e.jsx("span",{className:"ml-2 text-xs text-red-500/70",children:g})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Hr,{label:n("dashboard.activeAgents"),value:(d==null?void 0:d.agents.total)??0,icon:Ts,color:"text-indigo-400",bgColor:"bg-indigo-500/10"}),e.jsx(Hr,{label:n("dashboard.runningTasks"),value:(d==null?void 0:d.runs.running)??0,icon:Nt,color:"text-emerald-400",bgColor:"bg-emerald-500/10"}),e.jsx(Hr,{label:n("dashboard.costToday"),value:`$${S.toFixed(2)}`,icon:us,color:"text-amber-400",bgColor:"bg-amber-500/10"}),e.jsx(Hr,{label:n("dashboard.skillsInstalled"),value:(d==null?void 0:d.skills.total)??0,icon:rc,color:"text-violet-400",bgColor:"bg-violet-500/10"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"card lg:col-span-2",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-medium text-zinc-200",children:n("dashboard.recentActivity")}),e.jsx(It,{className:"h-4 w-4 text-zinc-500"})]}),e.jsx(gu,{events:w,maxHeight:"300px"})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:n("dashboard.quickActions")}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ta,{to:"/agents",className:"btn-secondary w-full justify-start",children:[e.jsx(ht,{className:"h-4 w-4"}),n("dashboard.createAgent")]}),e.jsxs(ta,{to:"/workflows",className:"btn-secondary w-full justify-start",children:[e.jsx(tc,{className:"h-4 w-4"}),n("dashboard.runWorkflow")]}),e.jsxs(ta,{to:"/skills",className:"btn-secondary w-full justify-start",children:[e.jsx(hi,{className:"h-4 w-4"}),n("dashboard.installSkill")]})]})]}),e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:n("dashboard.systemHealth")}),e.jsxs("div",{className:`flex items-center gap-3 rounded-lg p-3 ${k.bg}`,children:[e.jsx(C,{className:`h-5 w-5 ${k.color}`}),e.jsxs("div",{children:[e.jsx("p",{className:`text-sm font-medium ${k.color}`,children:k.label}),e.jsx("p",{className:"text-xs text-zinc-500",children:d?`${d.agents.total} agents | ${d.workflows.total} workflows | ${d.runs.today} runs today`:"Loading..."})]})]}),(d==null?void 0:d.server)&&e.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Version"}),e.jsx("p",{className:"text-zinc-300 font-mono",children:d.server.version})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Uptime"}),e.jsxs("p",{className:"text-zinc-300 font-mono",children:[Math.floor(d.server.uptime/3600),"h ",Math.floor(d.server.uptime%3600/60),"m"]})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"Memory (RSS)"}),e.jsxs("p",{className:"text-zinc-300 font-mono",children:[d.server.memoryUsage.rss," MB"]})]}),e.jsxs("div",{className:"rounded bg-[#0a0a0f] p-2",children:[e.jsx("span",{className:"text-zinc-500",children:"WS Connections"}),e.jsx("p",{className:"text-zinc-300 font-mono",children:d.websocket.connections})]})]})]})]})]})]})}function wj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await la.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch agents")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{agents:n,loading:d,error:m,refetch:h}}function Sj(n){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(null),b=u.useCallback(async()=>{if(n){m(!0),h(null);try{const g=await la.get(n);d(g.data)}catch(g){h(g instanceof Error?g.message:"Failed to fetch agent")}finally{m(!1)}}},[n]);return u.useEffect(()=>{b()},[b]),{agent:i,loading:c,error:f,refetch:b}}const Vh={running:{bg:"bg-emerald-500/10",text:"text-emerald-400",dot:"bg-emerald-400"},completed:{bg:"bg-green-500/10",text:"text-green-400",dot:"bg-green-400"},failed:{bg:"bg-red-500/10",text:"text-red-400",dot:"bg-red-400"},pending:{bg:"bg-amber-500/10",text:"text-amber-400",dot:"bg-amber-400"},paused:{bg:"bg-blue-500/10",text:"text-blue-400",dot:"bg-blue-400"},cancelled:{bg:"bg-zinc-500/10",text:"text-zinc-400",dot:"bg-zinc-400"},idle:{bg:"bg-zinc-500/10",text:"text-zinc-500",dot:"bg-zinc-500"}};function wi({status:n,pulse:i}){const{t:d}=Je(),c=Vh[n]??Vh.idle;return e.jsxs("span",{className:`badge ${c.bg} ${c.text}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${c.dot} ${i&&n==="running"?"animate-pulse":""}`}),d(`status.${n}`)]})}const kj={builtin:{bg:"bg-indigo-500/10",text:"text-indigo-400"},official:{bg:"bg-blue-500/10",text:"text-blue-400"},trusted:{bg:"bg-emerald-500/10",text:"text-emerald-400"},community:{bg:"bg-amber-500/10",text:"text-amber-400"},local:{bg:"bg-zinc-500/10",text:"text-zinc-400"}};function bu({level:n}){const{t:i}=Je(),d=kj[n];return e.jsxs("span",{className:`badge ${d.bg} ${d.text}`,children:[n==="builtin"||n==="official"?e.jsx("svg",{className:"h-3 w-3",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}):null,i(`trust.${n}`)]})}function H0({spent:n,limit:i,currency:d="$"}){const c=i>0?Math.min(n/i*100,100):0,m=c>=75,f=c>=90,h=f?"bg-red-500":m?"bg-amber-500":"bg-indigo-500";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-zinc-400",children:[d,n.toFixed(2)," / ",d,i.toFixed(2)]}),e.jsxs("span",{className:`font-medium ${f?"text-red-400":m?"text-amber-400":"text-zinc-400"}`,children:[c.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-zinc-800",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${h}`,style:{width:`${c}%`}})})]})}const zj={anthropic:Ts,openai:Ts,local:bv};function Cj({agent:n,status:i="idle",budgetSpent:d=0,budgetLimit:c=10}){const m=zj[n.adapterType]??Ts;return e.jsxs(ta,{to:`/agents/${n.id}`,className:"card group hover:border-indigo-500/30 hover:bg-surface-hover transition-all duration-200",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-500/10 text-indigo-400 group-hover:bg-indigo-500/20 transition-colors",children:e.jsx(m,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200 group-hover:text-white transition-colors",children:n.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:[n.adapterType," ",n.adapterConfig.model?`/ ${n.adapterConfig.model}`:""]})]})]}),e.jsx(wi,{status:i,pulse:!0})]}),n.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:n.description}),e.jsx("div",{className:"mt-4 flex items-center justify-between",children:e.jsx(bu,{level:n.trustLevel})}),e.jsx("div",{className:"mt-3",children:e.jsx(H0,{spent:d,limit:c})})]})}function cn({icon:n,title:i,description:d,action:c}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4 text-center",children:[e.jsx("div",{className:"mb-4 rounded-2xl bg-surface p-4 text-zinc-500",children:n??e.jsx(jv,{className:"h-8 w-8"})}),e.jsx("h3",{className:"text-lg font-medium text-zinc-300",children:i}),d&&e.jsx("p",{className:"mt-1.5 max-w-sm text-sm text-zinc-500",children:d}),c&&e.jsx("div",{className:"mt-4",children:c})]})}function Aj(){const{t:n}=Je(),{agents:i,loading:d,error:c,refetch:m}=wj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState({name:"",description:"",adapterType:"claude",model:"",trustLevel:"community"}),y=async()=>{if(p.name.trim()){g(!0);try{await la.create({name:p.name,description:p.description||void 0,adapterType:p.adapterType,adapterConfig:p.model?{model:p.model}:{},trustLevel:p.trustLevel}),h(!1),S({name:"",description:"",adapterType:"claude",model:"",trustLevel:"community"}),m()}catch(v){console.error("Failed to create agent:",v)}finally{g(!1)}}};return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("agents.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("agents.create")]})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(Ts,{className:"h-8 w-8"}),title:n("agents.empty"),description:n("agents.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("agents.create")]})}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:i.map(v=>e.jsx(Cj,{agent:v},v.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("agents.create")}),e.jsx("button",{onClick:()=>h(!1),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.name")}),e.jsx("input",{className:"input",value:p.name,onChange:v=>S({...p,name:v.target.value}),placeholder:"My Agent"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.description")}),e.jsx("textarea",{className:"input min-h-[80px] resize-none",value:p.description,onChange:v=>S({...p,description:v.target.value}),placeholder:"What does this agent do?"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Adapter"}),e.jsxs("select",{className:"input",value:p.adapterType,onChange:v=>S({...p,adapterType:v.target.value}),children:[e.jsx("option",{value:"claude",children:"Anthropic (Claude)"}),e.jsx("option",{value:"openai",children:"OpenAI (GPT)"}),e.jsx("option",{value:"gemini",children:"Google (Gemini)"}),e.jsx("option",{value:"grok",children:"xAI (Grok)"}),e.jsx("option",{value:"mistral",children:"Mistral AI"}),e.jsx("option",{value:"ollama",children:"Ollama (Local)"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Model"}),e.jsx("input",{className:"input",value:p.model,onChange:v=>S({...p,model:v.target.value}),placeholder:"claude-sonnet-4-20250514"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Trust Level"}),e.jsxs("select",{className:"input",value:p.trustLevel,onChange:v=>S({...p,trustLevel:v.target.value}),children:[e.jsx("option",{value:"builtin",children:"Built-in"}),e.jsx("option",{value:"official",children:"Official"}),e.jsx("option",{value:"trusted",children:"Trusted"}),e.jsx("option",{value:"community",children:"Community"}),e.jsx("option",{value:"local",children:"Local"})]})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>h(!1),className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:y,disabled:!p.name.trim()||b,className:"btn-primary",children:n(b?"common.loading":"agents.create")})]})]})})]})}const Ej="/api";async function Tj(n){const i=localStorage.getItem("nestor_token"),d={"Content-Type":"application/json"};i&&(d.Authorization=`Bearer ${i}`);const c=localStorage.getItem("nestor_tenant_id");c&&(d["X-Tenant-ID"]=c);try{const m=await fetch(`${Ej}/agents/${n}/quality`,{headers:d});return m.ok?(await m.json()).data??null:null}catch{return null}}function Yh(n){return`${(n*100).toFixed(0)}%`}function qr({icon:n,label:i,value:d,subtext:c,color:m}){return e.jsxs("div",{className:"rounded-lg bg-zinc-800/50 p-4 border border-zinc-700/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(n,{className:`h-4 w-4 ${m}`}),e.jsx("span",{className:"text-xs text-zinc-500 uppercase tracking-wide",children:i})]}),e.jsx("p",{className:`text-2xl font-bold ${m}`,children:d}),c&&e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:c})]})}function Rj({agentId:n}){const[i,d]=u.useState(null),[c,m]=u.useState(!0),f=u.useCallback(async()=>{m(!0);const w=await Tj(n);d(w),m(!1)},[n]);if(u.useEffect(()=>{f()},[f]),c)return e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Quality"}),e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})})]});if(!i)return e.jsxs("div",{className:"card",children:[e.jsx("h2",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Quality"}),e.jsx("p",{className:"text-sm text-zinc-500",children:"No quality data available yet."})]});const h=i.satisfactionRate>=.8?"text-green-400":i.satisfactionRate>=.5?"text-yellow-400":"text-red-400",b=i.successRate>=.8?"text-green-400":i.successRate>=.5?"text-yellow-400":"text-red-400",g=i.recentFeedback.filter(w=>w.rating===1).length,p=i.recentFeedback.length,S=p>0?g/p:0,y=i.satisfactionRate,v=p<3?"stable":S>y+.1?"improving":S<y-.1?"declining":"stable",k=v==="improving"?oc:v==="declining"?Bv:Av,C=v==="improving"?"text-green-400":v==="declining"?"text-red-400":"text-zinc-400";return e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-medium text-zinc-200",children:"Quality"}),e.jsxs("div",{className:`flex items-center gap-1 text-xs ${C}`,children:[e.jsx(k,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"capitalize",children:v})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[e.jsx(qr,{icon:yi,label:"Satisfaction",value:Yh(i.satisfactionRate),subtext:`${i.positiveFeedback}/${i.totalFeedback} positive`,color:h}),e.jsx(qr,{icon:et,label:"Success Rate",value:Yh(i.successRate),subtext:`${i.completedRuns} completed, ${i.failedRuns} failed`,color:b}),e.jsx(qr,{icon:us,label:"Avg Cost / Run",value:`$${i.avgCostPerRun.toFixed(4)}`,subtext:`${i.totalRuns} total runs`,color:"text-blue-400"}),e.jsx(qr,{icon:Rs,label:"Total Runs",value:i.totalRuns.toString(),subtext:`${i.totalFeedback} rated`,color:"text-indigo-400"})]}),i.recentFeedback.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("h3",{className:"text-xs font-medium text-zinc-500 uppercase tracking-wide mb-2",children:"Recent Feedback"}),e.jsx("div",{className:"space-y-1 max-h-40 overflow-y-auto",children:i.recentFeedback.slice(0,10).map((w,N)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:w.rating===1?"text-green-400":"text-red-400",children:w.rating===1?"+":"-"}),e.jsx("span",{className:"text-zinc-400 flex-1",children:w.comment??(w.rating===1?"Positive":"Negative")}),e.jsx("span",{className:"text-zinc-600 shrink-0",children:new Date(w.createdAt).toLocaleDateString()})]},N))})]})]})}function Mj({event:n}){switch(n.type){case"tool_start":return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-1.5",children:[e.jsx(cl,{className:"h-3.5 w-3.5 text-amber-400"}),e.jsx("span",{className:"text-xs text-amber-300 font-medium",children:n.name}),e.jsx(rt,{className:"h-3 w-3 text-amber-400 animate-spin"})]});case"tool_result":return e.jsxs("div",{className:`flex items-center gap-2 rounded-md border px-3 py-1.5 ${n.success?"border-emerald-500/20 bg-emerald-500/5":"border-red-500/20 bg-red-500/5"}`,children:[n.success?e.jsx(et,{className:"h-3.5 w-3.5 text-emerald-400"}):e.jsx(ft,{className:"h-3.5 w-3.5 text-red-400"}),e.jsxs("span",{className:`text-xs font-medium ${n.success?"text-emerald-300":"text-red-300"}`,children:[n.name," ",n.success?"completed":"failed"]})]});case"reasoning":return e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-yellow-500/20 bg-yellow-500/5 px-3 py-1.5",children:[e.jsx(Zd,{className:"h-3.5 w-3.5 text-yellow-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[n.phase&&e.jsx("span",{className:"text-[10px] uppercase text-yellow-600 font-mono",children:n.phase}),e.jsx("p",{className:"text-xs text-yellow-200/80 break-words",children:n.reasoning}),n.confidence!=null&&e.jsxs("span",{className:"text-[10px] text-yellow-600",children:["confidence: ",(n.confidence*100).toFixed(0),"%"]})]})]});case"error":return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-red-500/20 bg-red-500/5 px-3 py-1.5",children:[e.jsx(ft,{className:"h-3.5 w-3.5 text-red-400"}),e.jsx("span",{className:"text-xs text-red-300",children:n.text})]});default:return null}}function Dj({runId:n,onComplete:i}){const[d,c]=u.useState(""),[m,f]=u.useState([]),[h,b]=u.useState(!0),g=u.useRef(null),p=u.useRef(0),{subscribe:S,unsubscribe:y,events:v,connected:k}=pu([`run:${n}`]);return u.useEffect(()=>(k&&S(`run:${n}`),()=>{y(`run:${n}`)}),[k,n,S,y]),u.useEffect(()=>{for(const C of v){if(C.channel!==`run:${n}`)continue;const w=C.data;if(!w||w.runId!==n)continue;const N=w.type,z=++p.current;switch(N){case"token":c(R=>R+(w.text??""));break;case"tool_start":f(R=>[...R,{id:z,type:"tool_start",name:w.name,args:w.args,timestamp:Date.now()}]);break;case"tool_result":f(R=>[...R,{id:z,type:"tool_result",name:w.name,result:w.result,success:w.success,timestamp:Date.now()}]);break;case"reasoning":{const R=w.entry;f(D=>[...D,{id:z,type:"reasoning",reasoning:(R==null?void 0:R.reasoning)??w.reasoning??"",phase:(R==null?void 0:R.phase)??void 0,confidence:(R==null?void 0:R.confidence)??void 0,timestamp:Date.now()}]);break}case"error":f(R=>[...R,{id:z,type:"error",text:w.message,timestamp:Date.now()}]);break;case"done":b(!1),i==null||i();break}}},[v,n,i]),u.useEffect(()=>{g.current&&(g.current.scrollTop=g.current.scrollHeight)},[d]),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M0,{className:`h-3.5 w-3.5 ${h?"text-green-400 animate-pulse":"text-zinc-500"}`}),e.jsx("span",{className:"text-xs font-medium text-zinc-400",children:h?"Live Output":"Run Completed"}),!k&&e.jsx("span",{className:"text-[10px] text-red-400 ml-auto",children:"Disconnected"})]}),e.jsx("div",{ref:g,className:"bg-gray-900 p-4 rounded-lg max-h-96 overflow-y-auto whitespace-pre-wrap font-mono text-sm text-zinc-200 border border-zinc-700",children:d||e.jsx("span",{className:"text-zinc-500 italic",children:h?"Waiting for output...":"No output produced."})}),m.length>0&&e.jsx("div",{className:"space-y-2 max-h-60 overflow-y-auto",children:m.map(C=>e.jsx(Mj,{event:C},C.id))})]})}function Oj(){const{id:n}=ll(),i=Dt(),{t:d}=Je(),{agent:c,loading:m,error:f}=Sj(n),[h,b]=u.useState("overview"),[g,p]=u.useState(""),[S,y]=u.useState(!1),[v,k]=u.useState(null);if(m)return e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})});if(f||!c)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[e.jsx("p",{className:"text-red-400",children:f??"Agent not found"}),e.jsxs("button",{onClick:()=>i("/agents"),className:"btn-secondary mt-4",children:[e.jsx(Wn,{className:"h-4 w-4"})," Back to Agents"]})]});const C=async()=>{var z;if(!(!g.trim()||!n)){y(!0);try{const R=await la.run(n,g),D=((z=R==null?void 0:R.data)==null?void 0:z.id)??null;k(D),p("")}catch(R){console.error("Run failed:",R)}finally{y(!1)}}},w=async()=>{if(n&&window.confirm(`Delete agent "${c.name}"?`))try{await la.delete(n),i("/agents")}catch(z){console.error("Delete failed:",z)}},N=[{key:"overview",label:d("agent.overview"),icon:Rs},{key:"quality",label:"Quality",icon:It},{key:"runs",label:d("agent.runs"),icon:Nt},{key:"events",label:d("agent.events"),icon:It},{key:"configuration",label:d("agent.configuration"),icon:il}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("button",{onClick:()=>i("/agents"),className:"btn-ghost btn-sm",children:e.jsx(Wn,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-xl bg-indigo-500/10 text-indigo-400",children:e.jsx(Ts,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:c.name}),e.jsx(wi,{status:"idle"})]}),e.jsxs("p",{className:"text-sm text-zinc-400",children:[c.adapterType,c.adapterConfig.model?` / ${c.adapterConfig.model}`:"",e.jsx("span",{className:"mx-2 text-zinc-600",children:"|"}),e.jsx(bu,{level:c.trustLevel})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"})," ",d("agent.start")]}),e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(Lv,{className:"h-3.5 w-3.5"})," ",d("agent.stop")]}),e.jsxs("button",{onClick:w,className:"btn-danger btn-sm",children:[e.jsx(Ot,{className:"h-3.5 w-3.5"})," ",d("agent.delete")]})]})]}),e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(O0,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{className:"input pl-9",placeholder:"Enter a prompt to run this agent...",value:g,onChange:z=>p(z.target.value),onKeyDown:z=>z.key==="Enter"&&C()})]}),e.jsxs("button",{onClick:C,disabled:!g.trim()||S,className:"btn-primary",children:[e.jsx(Nt,{className:"h-4 w-4"}),d(S?"common.loading":"agent.run")]})]})}),v&&e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M0,{className:"h-4 w-4 text-green-400 animate-pulse"}),e.jsx("h3",{className:"text-sm font-medium text-zinc-200",children:"Live Output"}),e.jsxs("span",{className:"text-[10px] font-mono text-zinc-500",children:[v.slice(0,12),"..."]})]}),e.jsx("button",{onClick:()=>k(null),className:"text-xs text-zinc-500 hover:text-zinc-300 transition-colors",children:"Dismiss"})]}),e.jsx(Dj,{runId:v,onComplete:()=>{}})]}),e.jsx("div",{className:"flex gap-1 border-b border-border",children:N.map(({key:z,label:R,icon:D})=>e.jsxs("button",{onClick:()=>b(z),className:`flex items-center gap-2 px-4 py-2.5 text-sm font-medium transition-colors border-b-2 ${h===z?"border-indigo-500 text-indigo-400":"border-transparent text-zinc-400 hover:text-zinc-200"}`,children:[e.jsx(D,{className:"h-4 w-4"}),R]},z))}),h==="quality"&&n&&e.jsx(Rj,{agentId:n}),h==="overview"&&e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:d("agent.budget")}),e.jsx(H0,{spent:0,limit:10}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-3",children:[e.jsx("p",{className:"text-xs text-zinc-500",children:"Total Spent"}),e.jsx("p",{className:"text-lg font-semibold text-white",children:"$0.00"})]}),e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-3",children:[e.jsx("p",{className:"text-xs text-zinc-500",children:"Runs Today"}),e.jsx("p",{className:"text-lg font-semibold text-white",children:"0"})]})]})]}),e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:d("agent.recentRuns")}),e.jsx("p",{className:"text-sm text-zinc-500",children:"No runs recorded yet."})]}),c.description&&e.jsxs("div",{className:"card lg:col-span-2",children:[e.jsx("h3",{className:"mb-2 text-lg font-medium text-zinc-200",children:d("common.description")}),e.jsx("p",{className:"text-sm text-zinc-400",children:c.description})]})]}),h==="runs"&&e.jsx("div",{className:"card",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-left",children:[e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:"Run ID"}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:d("common.status")}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:d("run.duration")}),e.jsx("th",{className:"pb-3 pr-4 text-zinc-400 font-medium",children:"Cost"}),e.jsx("th",{className:"pb-3 text-zinc-400 font-medium",children:d("common.created")})]})}),e.jsx("tbody",{children:e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-8 text-center text-zinc-500",children:"No runs recorded for this agent."})})})]})})}),h==="events"&&e.jsx("div",{className:"card",children:e.jsx(gu,{events:[],maxHeight:"500px"})}),h==="configuration"&&e.jsxs("div",{className:"card",children:[e.jsx("h3",{className:"mb-4 text-lg font-medium text-zinc-200",children:"Agent Configuration"}),e.jsx("pre",{className:"overflow-auto rounded-lg bg-[#0a0a0f] p-4 text-sm text-zinc-300",children:JSON.stringify(c,null,2)})]})]})}function Lj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await sc.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch workflows")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{workflows:n,loading:d,error:m,refetch:h}}function _j(n){const[i,d]=u.useState(null),[c,m]=u.useState(!0),[f,h]=u.useState(null),b=u.useCallback(async()=>{if(n){m(!0),h(null);try{const g=await sc.get(n);d(g.data)}catch(g){h(g instanceof Error?g.message:"Failed to fetch workflow")}finally{m(!1)}}},[n]);return u.useEffect(()=>{b()},[b]),{workflow:i,loading:c,error:f,refetch:b}}const Uj=[{id:"tdd-loop",name:"TDD Loop",description:"spec → code → test → fix → repeat",icon:e.jsx(xt,{className:"h-5 w-5"}),color:"text-green-400 bg-green-500/10",entryNodeId:"spec",nodes:[{id:"spec",type:"agent",label:"Write Spec",config:{role:"spec-writer",prompt:"Write a detailed specification for the feature"},next:["code"]},{id:"code",type:"agent",label:"Implement Code",config:{role:"developer",prompt:"Implement the code based on the specification"},next:["test"]},{id:"test",type:"agent",label:"Run Tests",config:{role:"tester",prompt:"Write and run tests against the implementation"},next:["check"]},{id:"check",type:"condition",label:"Tests Pass?",config:{},condition:"result.allPassed === true",next:["done","fix"]},{id:"fix",type:"agent",label:"Fix Issues",config:{role:"developer",prompt:"Fix the failing tests based on error output"},next:["test"]},{id:"done",type:"agent",label:"Complete",config:{role:"reporter",prompt:"Generate a summary of the implementation and test results"},next:[]}]},{id:"content-pipeline",name:"Content Pipeline",description:"research → draft → review → publish",icon:e.jsx(Ua,{className:"h-5 w-5"}),color:"text-amber-400 bg-amber-500/10",entryNodeId:"research",nodes:[{id:"research",type:"agent",label:"Research",config:{role:"researcher",prompt:"Research the topic and gather relevant sources and data"},next:["draft"]},{id:"draft",type:"agent",label:"Draft",config:{role:"writer",prompt:"Write a draft based on the research findings"},next:["review"]},{id:"review",type:"agent",label:"Review",config:{role:"editor",prompt:"Review the draft for accuracy, style, and completeness"},next:["publish"]},{id:"publish",type:"agent",label:"Publish",config:{role:"publisher",prompt:"Format and prepare the final content for publication"},next:[]}]},{id:"ralph-3phase",name:"Ralph 3-Phase",description:"spec-writer → planner → builder (with backpressure)",icon:e.jsx(wv,{className:"h-5 w-5"}),color:"text-purple-400 bg-purple-500/10",entryNodeId:"spec-writer",nodes:[{id:"spec-writer",type:"agent",label:"Spec Writer",config:{role:"spec-writer",prompt:"Analyze requirements and produce a detailed technical specification",backpressure:{validator:"spec",strictness:"strict"}},next:["planner"]},{id:"planner",type:"agent",label:"Planner",config:{role:"planner",prompt:"Break the specification into an ordered plan of implementation tasks",backpressure:{validator:"plan",strictness:"strict"}},next:["builder"]},{id:"builder",type:"agent",label:"Builder",config:{role:"builder",prompt:"Execute each task from the plan, implementing the specification",backpressure:{validator:"code",strictness:"normal"}},next:[]}]}];function $j(){const{t:n}=Je(),{workflows:i,loading:d,error:c,refetch:m}=Lj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState({name:"",description:""}),[y,v]=u.useState(null),[k,C]=u.useState(null),[w,N]=u.useState([]),[z,R]=u.useState(null),D=u.useRef(null),O=u.useCallback(async A=>{C(A),N([]),R(null);try{const $=(await sc.run(A)).data.id,Q=localStorage.getItem("nestor_token"),ce=localStorage.getItem("nestor_tenant_id"),I=new URLSearchParams;I.set("channels",`run:${$}`),Q&&I.set("token",Q),ce&&I.set("tenantId",ce);const le=new EventSource(`/api/events/stream?${I.toString()}`);D.current=le,le.onmessage=Y=>{var B;try{const ne=JSON.parse(Y.data);(ne.type==="run:progress"||ne.type==="node:start"||ne.type==="node:complete")&&N(me=>{var ue,je;return[...me,((ue=ne.data)==null?void 0:ue.message)||((je=ne.data)==null?void 0:je.node)||ne.type]}),(ne.type==="run:complete"||ne.type==="run:completed")&&(R({id:A,status:"completed",message:"Workflow completed successfully"}),le.close(),C(null),m()),(ne.type==="run:failed"||ne.type==="run:error")&&(R({id:A,status:"failed",message:((B=ne.data)==null?void 0:B.error)||"Workflow failed"}),le.close(),C(null))}catch{}},le.onerror=()=>{le.close(),setTimeout(()=>{C(null),z||R({id:A,status:"completed",message:"Run started (stream ended)"}),m()},2e3)}}catch(F){R({id:A,status:"failed",message:F instanceof Error?F.message:"Failed to start"}),C(null)}},[m,z]),se=A=>{v(A),S({name:A.name,description:A.description})},Z=()=>{v(null),S({name:"",description:""})},U=async()=>{if(p.name.trim()){g(!0);try{const A=y?y.nodes:[{id:"start",type:"agent",label:"Start",config:{},next:[]}],F=y?y.entryNodeId:"start";await sc.create({name:p.name,description:p.description||void 0,nodes:A,entryNodeId:F}),h(!1),S({name:"",description:""}),v(null),m()}catch(A){console.error("Failed to create workflow:",A)}finally{g(!1)}}};return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("workflows.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("workflows.create")]})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(tc,{className:"h-8 w-8"}),title:n("workflows.empty"),description:n("workflows.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("workflows.create")]})}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:i.map(A=>e.jsxs("div",{className:"card group hover:border-indigo-500/30 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-blue-500/10 text-blue-400",children:e.jsx(tc,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:A.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["v",A.currentVersion]})]})]}),e.jsx(wi,{status:"idle"})]}),A.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:A.description}),k===A.id&&w.length>0&&e.jsxs("div",{className:"mt-3 rounded-md bg-purple-500/5 border border-purple-500/10 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(rt,{className:"h-3 w-3 animate-spin text-purple-400"}),e.jsx("span",{className:"text-xs font-medium text-purple-300",children:n("workflows.running")})]}),e.jsx("div",{className:"max-h-16 overflow-y-auto",children:w.slice(-3).map((F,$)=>e.jsx("p",{className:"text-[11px] text-zinc-400 truncate",children:F},$))})]}),z&&z.id===A.id&&e.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-md p-2 text-xs ${z.status==="completed"?"bg-green-500/5 border border-green-500/10 text-green-400":"bg-red-500/5 border border-red-500/10 text-red-400"}`,children:[z.status==="completed"?e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(ft,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:z.message}),e.jsx("button",{onClick:()=>R(null),className:"ml-auto flex-shrink-0 text-zinc-500 hover:text-zinc-300",children:e.jsx(Ze,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-zinc-500",children:[n("common.updated"),": ",new Date(A.updatedAt).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(ta,{to:`/workflows/${A.id}/edit`,className:"btn-ghost btn-sm",children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>O(A.id),disabled:k!==null,className:"btn-ghost btn-sm text-green-400 disabled:opacity-50",title:n("workflows.run"),children:k===A.id?e.jsx(rt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nt,{className:"h-3.5 w-3.5"})})]})]})]},A.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-border bg-surface p-6 shadow-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("workflows.create")}),e.jsx("button",{onClick:()=>{h(!1),Z()},className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-medium text-zinc-500 uppercase tracking-wider mb-3",children:"Start from a template"}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Uj.map(A=>e.jsxs("button",{onClick:()=>se(A),className:`group text-left rounded-xl border p-3 transition-all ${(y==null?void 0:y.id)===A.id?"border-indigo-500/50 bg-indigo-500/10 ring-1 ring-indigo-500/30":"border-border/50 bg-zinc-900/60 hover:border-indigo-500/30 hover:bg-indigo-500/5"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("span",{className:`flex h-7 w-7 items-center justify-center rounded-lg ${A.color}`,children:A.icon}),e.jsx("span",{className:"text-sm font-medium text-zinc-200",children:A.name})]}),e.jsx("p",{className:"text-[11px] text-zinc-500 leading-relaxed",children:A.description}),e.jsxs("p",{className:"text-[10px] text-zinc-600 mt-1.5",children:[A.nodes.length," nodes"]})]},A.id))}),y&&e.jsx("button",{onClick:Z,className:"mt-2 text-xs text-zinc-500 hover:text-zinc-300 underline",children:"Clear template selection"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.name")}),e.jsx("input",{className:"input",value:p.name,onChange:A=>S({...p,name:A.target.value}),placeholder:"My Workflow"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.description")}),e.jsx("textarea",{className:"input min-h-[80px] resize-none",value:p.description,onChange:A=>S({...p,description:A.target.value}),placeholder:"What does this workflow do?"})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>{h(!1),Z()},className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:U,disabled:!p.name.trim()||b,className:"btn-primary",children:n(b?"common.loading":"workflows.create")})]})]})})]})}const Xh={agent:"border-indigo-500 bg-indigo-500/10",tool:"border-emerald-500 bg-emerald-500/10",condition:"border-amber-500 bg-amber-500/10",parallel:"border-blue-500 bg-blue-500/10",loop:"border-violet-500 bg-violet-500/10",human:"border-rose-500 bg-rose-500/10"},Gr={agent:"Agent",tool:"Tool",condition:"Condition",parallel:"Parallel",loop:"Loop",human:"Human"};function Bj(n,i){var g;const d=new Map;if(n.length===0)return d;const c=new Set,m=[],f=new Map,h=i??((g=n[0])==null?void 0:g.id);for(h&&m.push({id:h,depth:0,index:0});m.length>0;){const{id:p,depth:S}=m.shift();if(c.has(p))continue;c.add(p);const y=f.get(S)??0;f.set(S,y+1),d.set(p,{x:80+y*220,y:60+S*120});const v=n.find(k=>k.id===p);if(v)for(const k of v.next)c.has(k)||m.push({id:k,depth:S+1,index:0})}let b=(f.get(0)??0)*220+80;for(const p of n)c.has(p.id)||(d.set(p.id,{x:b,y:60}),b+=220);return d}function Hj(){const{id:n}=ll(),i=Dt(),{t:d}=Je(),{workflow:c,loading:m,error:f}=_j(n),[h,b]=u.useState([]),[g,p]=u.useState(),[S,y]=u.useState(null),[v,k]=u.useState(!1),[C,w]=u.useState({label:"",type:"agent"});u.useEffect(()=>{c!=null&&c.nodes&&(b(c.nodes),p(c.entryNodeId))},[c]);const N=u.useMemo(()=>Bj(h,g),[h,g]),z=Math.max(800,...Array.from(N.values()).map(U=>U.x+200)),R=Math.max(400,...Array.from(N.values()).map(U=>U.y+100)),D=u.useMemo(()=>{const U=[];for(const A of h){const F=N.get(A.id);if(F)for(const $ of A.next){const Q=N.get($);Q&&U.push({from:F,to:Q,fromId:A.id,toId:$})}}return U},[h,N]),O=u.useCallback(()=>{if(!C.label.trim())return;const U=`node_${Date.now()}`;b(A=>[...A,{id:U,type:C.type,label:C.label,config:{},next:[]}]),h.length===0&&p(U),w({label:"",type:"agent"}),k(!1)},[C,h.length]),se=u.useCallback(U=>{var A;b(F=>F.filter(Q=>Q.id!==U).map(Q=>({...Q,next:Q.next.filter(ce=>ce!==U)}))),S===U&&y(null),g===U&&p((A=h.find(F=>F.id!==U))==null?void 0:A.id)},[S,g,h]),Z=h.find(U=>U.id===S);return m?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):f?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[e.jsx("p",{className:"text-red-400",children:f}),e.jsxs("button",{onClick:()=>i("/workflows"),className:"btn-secondary mt-4",children:[e.jsx(Wn,{className:"h-4 w-4"})," Back to Workflows"]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>i("/workflows"),className:"btn-ghost btn-sm",children:e.jsx(Wn,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-2xl font-semibold text-white",children:(c==null?void 0:c.name)??d("workflow.editor")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>k(!0),className:"btn-secondary btn-sm",children:[e.jsx(ht,{className:"h-3.5 w-3.5"})," ",d("workflow.addNode")]}),e.jsxs("button",{className:"btn-secondary btn-sm",children:[e.jsx(cc,{className:"h-3.5 w-3.5"})," ",d("workflow.save")]}),e.jsxs("button",{className:"btn-primary btn-sm",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"})," ",d("workflow.run")]})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"card flex-1 overflow-auto p-0",style:{minHeight:"500px"},children:[e.jsxs("svg",{width:z,height:R,className:"w-full",children:[D.map((U,A)=>{const F=U.from.x+80,$=U.from.y+40,Q=U.to.x+80,ce=U.to.y,I=($+ce)/2;return e.jsx("path",{d:`M ${F} ${$} C ${F} ${I}, ${Q} ${I}, ${Q} ${ce}`,fill:"none",stroke:"#2a2a35",strokeWidth:"2",markerEnd:"url(#arrowhead)"},A)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"8",markerHeight:"6",refX:"7",refY:"3",orient:"auto",children:e.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"#2a2a35"})})})]}),e.jsx("div",{className:"absolute inset-0",style:{width:z,height:R},children:h.map(U=>{const A=N.get(U.id);if(!A)return null;const F=U.id===g,$=U.id===S;return e.jsxs("div",{className:`absolute cursor-pointer rounded-lg border-2 px-4 py-2.5 text-sm transition-all ${Xh[U.type]} ${$?"ring-2 ring-indigo-500 ring-offset-2 ring-offset-[#0a0a0f]":""} ${F?"shadow-lg":""}`,style:{left:A.x,top:A.y,width:160},onClick:()=>y(U.id),children:[e.jsx("div",{className:"font-medium text-zinc-200 truncate",children:U.label}),e.jsx("div",{className:"text-xs text-zinc-500 mt-0.5",children:Gr[U.type]}),F&&e.jsx("div",{className:"absolute -top-2 -right-2 h-4 w-4 rounded-full bg-indigo-500 border-2 border-[#0a0a0f]"})]},U.id)})}),h.length===0&&e.jsx("div",{className:"flex items-center justify-center h-full text-zinc-500 text-sm",children:"Add nodes to build your workflow DAG"})]}),Z&&e.jsxs("div",{className:"w-72 card space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:"Node Properties"}),e.jsx("button",{onClick:()=>y(null),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Label"}),e.jsx("input",{className:"input",value:Z.label,onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,label:U.target.value}:F))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:d("common.type")}),e.jsx("select",{className:"input",value:Z.type,onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,type:U.target.value}:F)),children:Object.entries(Gr).map(([U,A])=>e.jsx("option",{value:U,children:A},U))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Agent ID"}),e.jsx("input",{className:"input",value:Z.agentId??"",onChange:U=>b(A=>A.map(F=>F.id===Z.id?{...F,agentId:U.target.value||void 0}:F)),placeholder:"Optional agent ID"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Connect to"}),e.jsxs("select",{className:"input",value:"",onChange:U=>{U.target.value&&b(A=>A.map(F=>F.id===Z.id&&!F.next.includes(U.target.value)?{...F,next:[...F.next,U.target.value]}:F))},children:[e.jsx("option",{value:"",children:"Select a node..."}),h.filter(U=>U.id!==Z.id&&!Z.next.includes(U.id)).map(U=>e.jsx("option",{value:U.id,children:U.label},U.id))]}),Z.next.length>0&&e.jsx("div",{className:"mt-2 space-y-1",children:Z.next.map(U=>{const A=h.find(F=>F.id===U);return e.jsxs("div",{className:"flex items-center justify-between rounded bg-[#0a0a0f] px-2 py-1 text-xs",children:[e.jsx("span",{className:"text-zinc-400",children:(A==null?void 0:A.label)??U}),e.jsx("button",{onClick:()=>b(F=>F.map($=>$.id===Z.id?{...$,next:$.next.filter(Q=>Q!==U)}:$)),className:"text-zinc-500 hover:text-red-400",children:e.jsx(Ze,{className:"h-3 w-3"})})]},U)})})]}),e.jsxs("button",{onClick:()=>se(Z.id),className:"btn-danger w-full",children:[e.jsx(Ot,{className:"h-3.5 w-3.5"}),"Delete Node"]})]})]}),v&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:d("workflow.addNode")}),e.jsx("button",{onClick:()=>k(!1),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Label"}),e.jsx("input",{className:"input",value:C.label,onChange:U=>w({...C,label:U.target.value}),placeholder:"Node label"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:d("common.type")}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Object.keys(Gr).map(U=>e.jsx("button",{onClick:()=>w({...C,type:U}),className:`rounded-lg border-2 p-2.5 text-center text-xs font-medium transition-colors ${C.type===U?Xh[U]:"border-border text-zinc-400 hover:border-zinc-600"}`,children:Gr[U]},U))})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>k(!1),className:"btn-secondary",children:d("common.cancel")}),e.jsx("button",{onClick:O,disabled:!C.label.trim(),className:"btn-primary",children:d("workflow.addNode")})]})]})})]})}function qj(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),h=u.useCallback(async()=>{c(!0),f(null);try{const b=await Wr.list({limit:200});i(b.data)}catch(b){f(b instanceof Error?b.message:"Failed to fetch skills")}finally{c(!1)}},[]);return u.useEffect(()=>{h()},[h]),{skills:n,loading:d,error:m,refetch:h}}function Gj({skill:n,onDelete:i}){return e.jsxs("div",{className:"card group hover:border-indigo-500/30 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-violet-500/10 text-violet-400",children:e.jsx(rc,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:n.name}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["v",n.version," by ",n.author]})]})]}),e.jsx(bu,{level:n.trustLevel})]}),n.description&&e.jsx("p",{className:"mt-3 text-sm text-zinc-400 line-clamp-2",children:n.description}),e.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.tags.slice(0,3).map(d=>e.jsx("span",{className:"rounded-md bg-zinc-800 px-2 py-0.5 text-xs text-zinc-400",children:d},d)),n.tags.length>3&&e.jsxs("span",{className:"text-xs text-zinc-500",children:["+",n.tags.length-3]})]}),i&&e.jsx("button",{onClick:d=>{d.preventDefault(),i(n.id)},className:"btn-ghost btn-sm text-zinc-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})]})]})}function Kj(){const{t:n}=Je(),{skills:i,loading:d,error:c,refetch:m}=qj(),[f,h]=u.useState(!1),[b,g]=u.useState(!1),[p,S]=u.useState(""),[y,v]=u.useState({source:"",type:"local",name:"",trustLevel:"community"}),[k,C]=u.useState(null),w=async()=>{if(y.source.trim()){g(!0);try{await Wr.install({source:y.source,type:y.type,name:y.name||void 0,trustLevel:y.trustLevel}),h(!1),v({source:"",type:"local",name:"",trustLevel:"community"}),m()}catch(D){console.error("Failed to install skill:",D)}finally{g(!1)}}},N=async D=>{if(window.confirm("Remove this skill?"))try{await Wr.delete(D),m()}catch(O){console.error("Failed to delete skill:",O)}},z=async()=>{if(y.source.trim())try{const D=await Wr.scan(y.source);C(D)}catch(D){console.error("Scan failed:",D)}},R=i.filter(D=>!p||D.name.toLowerCase().includes(p.toLowerCase())||D.description.toLowerCase().includes(p.toLowerCase())||D.tags.some(O=>O.toLowerCase().includes(p.toLowerCase())));return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("skills.title")}),e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("skills.install")]})]}),i.length>0&&e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(_a,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500"}),e.jsx("input",{type:"text",className:"input pl-9",placeholder:n("common.search"),value:p,onChange:D=>S(D.target.value)})]}),c&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[c,e.jsx("button",{onClick:m,className:"ml-3 underline",children:"Retry"})]}),i.length===0&&!c?e.jsx(cn,{icon:e.jsx(rc,{className:"h-8 w-8"}),title:n("skills.empty"),description:n("skills.emptyDesc"),action:e.jsxs("button",{onClick:()=>h(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("skills.install")]})}):R.length===0?e.jsx("div",{className:"py-8 text-center text-sm text-zinc-500",children:n("common.noResults")}):e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:R.map(D=>e.jsx(Gj,{skill:D,onDelete:N},D.id))}),f&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("skills.install")}),e.jsx("button",{onClick:()=>{h(!1),C(null)},className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("skills.source")}),e.jsx("input",{className:"input",value:y.source,onChange:D=>v({...y,source:D.target.value}),placeholder:"/path/to/skill or https://..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("common.type")}),e.jsxs("select",{className:"input",value:y.type,onChange:D=>v({...y,type:D.target.value}),children:[e.jsx("option",{value:"local",children:"Local"}),e.jsx("option",{value:"npm",children:"NPM"}),e.jsx("option",{value:"git",children:"Git"}),e.jsx("option",{value:"url",children:"URL"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"label",children:[n("common.name")," (optional)"]}),e.jsx("input",{className:"input",value:y.name,onChange:D=>v({...y,name:D.target.value}),placeholder:"my-skill"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:"Trust Level"}),e.jsxs("select",{className:"input",value:y.trustLevel,onChange:D=>v({...y,trustLevel:D.target.value}),children:[e.jsx("option",{value:"builtin",children:"Built-in"}),e.jsx("option",{value:"official",children:"Official"}),e.jsx("option",{value:"trusted",children:"Trusted"}),e.jsx("option",{value:"community",children:"Community"}),e.jsx("option",{value:"local",children:"Local"})]})]}),k&&e.jsxs("div",{className:"rounded-lg bg-[#0a0a0f] p-4",children:[e.jsx("h4",{className:"text-sm font-medium text-zinc-300 mb-2",children:"Scan Results"}),e.jsx("pre",{className:"text-xs text-zinc-400 overflow-auto max-h-40",children:JSON.stringify(k,null,2)})]})]}),e.jsxs("div",{className:"mt-6 flex justify-between",children:[e.jsxs("button",{onClick:z,disabled:!y.source.trim(),className:"btn-secondary",children:[e.jsx(yv,{className:"h-4 w-4"}),n("skills.scan")]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>{h(!1),C(null)},className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:w,disabled:!y.source.trim()||b,className:"btn-primary",children:n(b?"common.loading":"skills.install")})]})]})]})})]})}function Vj(){const{t:n}=Je(),[i,d]=u.useState([]),[c,m]=u.useState(!0),[f,h]=u.useState(null),[b,g]=u.useState("all"),p=u.useCallback(async()=>{m(!0),h(null);try{const v={limit:100};b!=="all"&&(v.status=b);const k=await ln.list(v);d(k.data)}catch(v){h(v instanceof Error?v.message:"Failed to fetch runs"),d([])}finally{m(!1)}},[b]);u.useEffect(()=>{p()},[p]);const S=async v=>{try{await ln.abort(v),p()}catch(k){console.error("Abort failed:",k)}},y=async v=>{if(window.confirm("Delete this run record?"))try{await ln.delete(v),d(k=>k.filter(C=>C.id!==v))}catch(k){console.error("Delete failed:",k)}};return c?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("runs.title")}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:p,className:"btn-ghost btn-sm",children:e.jsx(xt,{className:"h-4 w-4"})}),e.jsx(R0,{className:"h-4 w-4 text-zinc-500"}),e.jsxs("select",{className:"input w-auto",value:b,onChange:v=>g(v.target.value),children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"running",children:n("status.running")}),e.jsx("option",{value:"completed",children:n("status.completed")}),e.jsx("option",{value:"failed",children:n("status.failed")}),e.jsx("option",{value:"pending",children:n("status.pending")}),e.jsx("option",{value:"paused",children:n("status.paused")}),e.jsx("option",{value:"cancelled",children:n("status.cancelled")})]})]})]}),f&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[f,e.jsx("button",{onClick:p,className:"ml-3 underline",children:n("common.retry")})]}),i.length===0&&!f?e.jsx(cn,{icon:e.jsx(Nt,{className:"h-8 w-8"}),title:n("runs.empty"),description:n("runs.emptyDesc")}):i.length>0?e.jsx("div",{className:"card overflow-hidden p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-surface",children:[e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Run ID"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Workflow"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("common.status")}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:"Started"}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("run.duration")}),e.jsx("th",{className:"px-5 py-3 text-left text-zinc-400 font-medium",children:n("common.actions")})]})}),e.jsx("tbody",{children:i.map(v=>{var C;const k=v.completedAt&&v.startedAt?Math.round((new Date(v.completedAt).getTime()-new Date(v.startedAt).getTime())/1e3):null;return e.jsxs("tr",{className:"border-b border-border hover:bg-surface-hover transition-colors",children:[e.jsx("td",{className:"px-5 py-3",children:e.jsxs(ta,{to:`/runs/${v.id}`,className:"text-indigo-400 hover:text-indigo-300 font-mono text-xs",children:[v.id.slice(0,8),"..."]})}),e.jsxs("td",{className:"px-5 py-3 text-zinc-300 font-mono text-xs",children:[((C=v.workflowId)==null?void 0:C.slice(0,8))??"—","..."]}),e.jsx("td",{className:"px-5 py-3",children:e.jsx(wi,{status:v.status,pulse:!0})}),e.jsx("td",{className:"px-5 py-3 text-zinc-400 text-xs",children:new Date(v.startedAt).toLocaleString()}),e.jsx("td",{className:"px-5 py-3 text-zinc-400 text-xs",children:k!==null?`${k}s`:"—"}),e.jsx("td",{className:"px-5 py-3",children:e.jsxs("div",{className:"flex gap-1",children:[(v.status==="running"||v.status==="pending")&&e.jsx("button",{onClick:()=>S(v.id),className:"btn-ghost btn-sm text-amber-400",title:"Abort run",children:e.jsx(E0,{className:"h-3.5 w-3.5"})}),(v.status==="completed"||v.status==="failed"||v.status==="cancelled")&&e.jsx("button",{onClick:()=>y(v.id),className:"btn-ghost btn-sm text-zinc-400 hover:text-red-400",title:"Delete run",children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})]})})]},v.id)})})]})})}):null]})}const q0="/api";async function Yj(n){const i=localStorage.getItem("nestor_token"),d={"Content-Type":"application/json"};i&&(d.Authorization=`Bearer ${i}`);const c=localStorage.getItem("nestor_tenant_id");c&&(d["X-Tenant-ID"]=c);const m=await fetch(`${q0}/runs/${n}/feedback`,{headers:d});return m.ok?(await m.json()).data??[]:[]}async function Qh(n,i,d,c){const m=localStorage.getItem("nestor_token"),f={"Content-Type":"application/json"};m&&(f.Authorization=`Bearer ${m}`);const h=localStorage.getItem("nestor_tenant_id");h&&(f["X-Tenant-ID"]=h),await fetch(`${q0}/runs/${n}/feedback`,{method:"POST",headers:f,body:JSON.stringify({rating:i,comment:d||void 0,agentId:c})})}function Xj({runId:n,agentId:i}){const[d,c]=u.useState([]),[m,f]=u.useState(!1),[h,b]=u.useState(null),[g,p]=u.useState(""),[S,y]=u.useState(!1),v=u.useCallback(async()=>{const w=await Yj(n);c(w),w.length>0&&(f(!0),b(w[0].rating))},[n]);u.useEffect(()=>{v()},[v]);const k=async w=>{m||(b(w),w===1?(await Qh(n,w,void 0,i),f(!0),v()):y(!0))},C=async()=>{h!==null&&(await Qh(n,h,g||void 0,i),f(!0),y(!1),v())};return e.jsxs("div",{className:"card",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-medium text-zinc-400",children:"Was this helpful?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>k(1),disabled:m,className:`rounded-lg p-2 transition-colors ${h===1?"bg-green-500/20 text-green-400":m?"text-zinc-600 cursor-not-allowed":"text-zinc-400 hover:bg-green-500/10 hover:text-green-400"}`,title:"Helpful",children:e.jsx(yi,{className:"h-5 w-5"})}),e.jsx("button",{onClick:()=>k(-1),disabled:m,className:`rounded-lg p-2 transition-colors ${h===-1?"bg-red-500/20 text-red-400":m?"text-zinc-600 cursor-not-allowed":"text-zinc-400 hover:bg-red-500/10 hover:text-red-400"}`,title:"Not helpful",children:e.jsx(Id,{className:"h-5 w-5"})})]})]}),S&&!m&&e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx("input",{type:"text",value:g,onChange:w=>p(w.target.value),placeholder:"What could be improved? (optional)",className:"flex-1 rounded-lg bg-zinc-800 px-3 py-2 text-sm text-zinc-200 placeholder-zinc-500 border border-zinc-700 focus:border-indigo-500 focus:outline-none",onKeyDown:w=>{w.key==="Enter"&&C()}}),e.jsx("button",{onClick:C,className:"rounded-lg bg-indigo-600 px-3 py-2 text-sm text-white hover:bg-indigo-500 transition-colors",children:e.jsx(gi,{className:"h-4 w-4"})})]}),m&&e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:[h===1?"Thanks for the positive feedback!":"Thanks for your feedback.",d.length>0&&d[0].comment&&e.jsxs("span",{className:"text-zinc-600",children:[" — “",d[0].comment,"”"]})]})]})}const Qj={llm_request:{icon:La,color:"text-purple-400",bgColor:"bg-purple-500/10",label:"LLM Request"},llm_response:{icon:Pt,color:"text-blue-400",bgColor:"bg-blue-500/10",label:"LLM Response"},tool_call_requested:{icon:cl,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Tool Call"},tool_call_completed:{icon:et,color:"text-emerald-400",bgColor:"bg-emerald-500/10",label:"Tool Result"},tool_call_denied:{icon:ft,color:"text-red-400",bgColor:"bg-red-500/10",label:"Tool Denied"},node_started:{icon:Nt,color:"text-blue-400",bgColor:"bg-blue-500/10",label:"Step Started"},node_completed:{icon:et,color:"text-green-400",bgColor:"bg-green-500/10",label:"Step Completed"},node_failed:{icon:ft,color:"text-red-400",bgColor:"bg-red-500/10",label:"Step Failed"},thinking:{icon:Zd,color:"text-yellow-400",bgColor:"bg-yellow-500/10",label:"Thinking"},reasoning:{icon:Zd,color:"text-yellow-400",bgColor:"bg-yellow-500/10",label:"Reasoning"},approval_requested:{icon:Ms,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Approval Requested"},budget_warning:{icon:pt,color:"text-amber-400",bgColor:"bg-amber-500/10",label:"Budget Warning"},budget_exceeded:{icon:us,color:"text-red-400",bgColor:"bg-red-500/10",label:"Budget Exceeded"},error:{icon:pt,color:"text-red-400",bgColor:"bg-red-500/10",label:"Error"}},Fj={icon:Nt,color:"text-zinc-400",bgColor:"bg-zinc-500/10",label:"Event"};function Zj(n){try{return new Date(n).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3})}catch{return n}}function Fh(n,i){try{return new Date(i).getTime()-new Date(n).getTime()}catch{return 0}}function Jj(n){return n<1e3?`${n}ms`:n<6e4?`${(n/1e3).toFixed(1)}s`:`${Math.floor(n/6e4)}m ${Math.floor(n%6e4/1e3)}s`}function Ij(n){const i=n.data;if(!i)return"";if(typeof i.reasoning=="string")return i.reasoning;if(typeof i.content=="string")return i.content;if(typeof i.text=="string")return i.text;if(typeof i.output=="string")return i.output;if(typeof i.prompt=="string")return i.prompt;if(typeof i.error=="string")return i.error;if(typeof i.tool=="string"){const c=i.args?` (${JSON.stringify(i.args).slice(0,120)})`:"";return`${i.tool}${c}`}const d=JSON.stringify(i,null,2);return d.length>300?d.slice(0,300)+"...":d}function Pj(n,i){let d=0;for(let c=0;c<=i&&c<n.length;c++){const m=n[c].data;typeof m.estimatedCostUsd=="number"?d=m.estimatedCostUsd:typeof m.cost=="number"&&(d+=m.cost)}return d}function Wj({runId:n}){const[i,d]=u.useState([]),[c,m]=u.useState(!0),[f,h]=u.useState(null),[b,g]=u.useState(-1),[p,S]=u.useState(!1),[y,v]=u.useState(1),k=u.useRef(null),C=u.useRef(null),w=u.useRef(new Map);u.useEffect(()=>{let $=!1;return m(!0),h(null),ln.getEvents(n).then(Q=>{$||d(Q.data.sort((ce,I)=>new Date(ce.timestamp).getTime()-new Date(I.timestamp).getTime()))}).catch(Q=>{$||h(Q instanceof Error?Q.message:"Failed to load events")}).finally(()=>{$||m(!1)}),()=>{$=!0}},[n]);const N=u.useCallback(()=>{S(!1),k.current&&(clearTimeout(k.current),k.current=null)},[]),z=u.useCallback(()=>{g($=>{const Q=$+1;if(Q>=i.length)return N(),$;const ce=i[$]??i[0],I=i[Q];if(ce&&I){const le=Fh(ce.timestamp,I.timestamp),Y=Math.max(50,Math.min(le/y,2e3/y));k.current=setTimeout(z,Y)}return Q})},[i,y,N]),R=u.useCallback(()=>{i.length!==0&&(S(!0),g($=>{const Q=$>=i.length-1?0:$,ce=300/y;return k.current=setTimeout(z,ce),Q}))},[i,y,z]),D=u.useCallback(()=>{p?N():R()},[p,N,R]),O=u.useCallback(()=>{N(),g($=>Math.min($+1,i.length-1))},[i.length,N]),se=u.useCallback(()=>{N(),g($=>Math.max($-1,0))},[N]),Z=u.useCallback($=>{N(),g($)},[N]),U=u.useCallback(()=>{v($=>{const Q=[1,2,4,8],ce=Q.indexOf($);return Q[(ce+1)%Q.length]})},[]);if(u.useEffect(()=>{if(b>=0){const $=w.current.get(b);$==null||$.scrollIntoView({behavior:"smooth",block:"nearest"})}},[b]),u.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]),c)return e.jsxs("div",{className:"flex items-center justify-center py-12",children:[e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent"}),e.jsx("span",{className:"ml-3 text-sm text-zinc-400",children:"Loading events..."})]});if(f)return e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4",children:e.jsx("p",{className:"text-sm text-red-400",children:f})});if(i.length===0)return e.jsx("div",{className:"rounded-lg border border-zinc-700 bg-zinc-800/50 p-6 text-center",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"No events recorded for this run."})});const A=i.length>0?(b+1)/i.length*100:0,F=b>=0?Pj(i,b):0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-zinc-700 bg-zinc-800/80 px-4 py-3",children:[e.jsx("button",{onClick:se,disabled:b<=0,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-zinc-700 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Step backward",children:e.jsx(Dv,{className:"h-4 w-4"})}),e.jsx("button",{onClick:D,className:"flex h-9 w-9 items-center justify-center rounded-full bg-indigo-600 text-white transition-colors hover:bg-indigo-500",title:p?"Pause":"Play",children:p?e.jsx(tl,{className:"h-4 w-4"}):e.jsx(Nt,{className:"h-4 w-4 ml-0.5"})}),e.jsx("button",{onClick:O,disabled:b>=i.length-1,className:"rounded p-1.5 text-zinc-400 transition-colors hover:bg-zinc-700 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",title:"Step forward",children:e.jsx(Ov,{className:"h-4 w-4"})}),e.jsxs("button",{onClick:U,className:"rounded border border-zinc-600 px-2 py-1 text-xs font-mono text-zinc-300 transition-colors hover:bg-zinc-700",title:"Cycle playback speed",children:[y,"x"]}),e.jsx("div",{className:"flex-1 mx-2",children:e.jsxs("div",{className:"relative h-2 rounded-full bg-zinc-700 cursor-pointer",onClick:$=>{const Q=$.currentTarget.getBoundingClientRect(),ce=($.clientX-Q.left)/Q.width,I=Math.round(ce*(i.length-1));Z(Math.max(0,Math.min(I,i.length-1)))},children:[e.jsx("div",{className:"absolute top-0 left-0 h-full rounded-full bg-indigo-500 transition-all duration-150",style:{width:`${A}%`}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-3.5 w-3.5 rounded-full border-2 border-indigo-400 bg-zinc-900 transition-all duration-150",style:{left:`calc(${A}% - 7px)`}})]})}),e.jsxs("span",{className:"text-xs font-mono text-zinc-500 whitespace-nowrap",children:[b+1," / ",i.length]}),F>0&&e.jsxs("span",{className:"flex items-center gap-1 text-xs font-mono text-amber-400 whitespace-nowrap",children:[e.jsx(us,{className:"h-3 w-3"}),F.toFixed(4)]})]}),e.jsx("div",{ref:C,className:"max-h-[600px] overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900/50",children:e.jsx("div",{className:"divide-y divide-zinc-800",children:i.map(($,Q)=>{const ce=Qj[$.type]??Fj,I=ce.icon,le=Q===b,Y=b<0||Q<=b,B=Ij($),ne=Q>0?Fh(i[Q-1].timestamp,$.timestamp):0;return e.jsxs("div",{ref:me=>{me&&w.current.set(Q,me)},className:`
586
586
  flex items-start gap-3 px-4 py-3 cursor-pointer transition-all duration-200
587
587
  ${le?"bg-indigo-500/10 border-l-2 border-l-indigo-500":"border-l-2 border-l-transparent"}
588
588
  ${Y?"opacity-100":"opacity-30"}
@@ -604,4 +604,4 @@ ${K.evaluation.gaps.map(Oe=>`- ${Oe}`).join(`
604
604
  `)}
605
605
 
606
606
  Previous findings are available in the knowledge graph. Do NOT repeat what was already found. Use different approaches and sources than the original mission.`,Se=await ea.plan(we,{maxBudget:3});Se.data&&(oe("Deep-dive mission created!","success"),b(Se.data),f(we),p([]),c("planned"))}catch(we){oe(we instanceof Error?we.message:"Deep dive planning failed","error")}finally{tt(!1)}}},[oe]),We=u.useCallback(async K=>{Lt(!0);try{const re=L();(await fetch(`/api/brain/reindex/${K}`,{method:"POST",headers:re})).ok?(oe("Archived to Knowledge Graph","success"),qe(!0)):oe("Archive failed — brain endpoint may not be available.","error")}catch{oe("Archive failed — brain endpoint may not be available.","error")}finally{Lt(!1)}},[oe,L]),fs=u.useCallback(async K=>{At(!0);try{oe("Re-running mission...","info");const re=await ea.plan(K.objective,{maxBudget:K.maxBudgetUsd});re.data&&(b(re.data),f(K.objective),p([]),c("planned"),oe("Fresh mission planned. Executing...","success"),setTimeout(()=>{le()},500))}catch(re){oe(re instanceof Error?re.message:"Re-run planning failed","error")}finally{At(!1)}},[oe,le]),hs=u.useCallback(K=>{const re=(K.findings||[]).sort((Oe,ct)=>(ct.confidence??0)-(Oe.confidence??0)).slice(0,3).map(Oe=>Oe.title).join(", "),we=re?`Key findings: ${re}`:"",Se=encodeURIComponent(`Mission: ${K.title}. ${we}`);P(`/chat?context=mission:${K.id}&prefill=${Se}`)},[P]),yt=u.useCallback(K=>{const re=new Blob([JSON.stringify(K,null,2)],{type:"application/json"}),we=URL.createObjectURL(re),Se=document.createElement("a");Se.href=we,Se.download=`mission-${K.id.substring(0,8)}-${(K.title||"export").replace(/[^a-z0-9]/gi,"-").substring(0,30)}.json`,Se.click(),URL.revokeObjectURL(we)},[]),dn=(h==null?void 0:h.subObjectives.filter(K=>K.status==="completed").length)||0,$a=(h==null?void 0:h.subObjectives.length)||1,Ba=Math.round(dn/$a*100);return e.jsxs("div",{className:"flex h-full",children:[e.jsx(jN,{toasts:de,removeToast:fe}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 h-14 px-6 border-b border-border bg-surface flex-shrink-0",children:[e.jsx(sa,{className:"h-5 w-5 text-purple-400"}),e.jsx("h1",{className:"text-lg font-semibold text-zinc-100",children:"Missions"}),h&&d!=="empty"&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto text-xs text-zinc-500",children:[h.type&&e.jsxs("span",{className:`flex items-center gap-1 px-2 py-0.5 rounded border ${su(h.type)}`,children:[n0(h.type),h.type]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(us,{className:"h-3 w-3"}),"$",h.spentUsd.toFixed(4)," / $",h.maxBudgetUsd.toFixed(2)]}),h.iteration>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"h-3 w-3"}),"Iteration ",h.iteration,"/",h.maxIterations]}),e.jsx("button",{onClick:me,className:"ml-2 p-1 rounded text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors",title:"New mission",children:e.jsx(Ze,{className:"h-4 w-4"})})]})]}),d==="empty"&&e.jsx("div",{className:"flex-1 flex flex-col items-center justify-center px-6",children:e.jsxs("div",{className:"w-full max-w-2xl",children:[e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-2xl bg-purple-600/20 border border-purple-500/20",children:e.jsx(sa,{className:"h-8 w-8 text-purple-400"})})}),e.jsx("h2",{className:"text-2xl font-bold text-zinc-100 text-center mb-2",children:"What's your mission?"}),e.jsx("p",{className:"text-sm text-zinc-500 text-center mb-8",children:"Autonomous AI agents will plan, execute, and deliver results."}),e.jsx(kN,{missions:v,selectedId:null,onSelect:ue}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:O,type:"text",value:m,onChange:K=>f(K.target.value),onKeyDown:K=>K.key==="Enter"&&I(),placeholder:"Describe your mission objective...",className:"flex-1 rounded-lg border border-border bg-zinc-900 px-4 py-3 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:ring-2 focus:ring-purple-500/40 focus:border-purple-500/40",autoFocus:!0}),e.jsxs("button",{onClick:()=>I(),disabled:!m.trim(),className:"flex items-center gap-2 rounded-lg bg-purple-600 px-5 py-3 text-sm font-medium text-white hover:bg-purple-500 disabled:opacity-40 disabled:cursor-not-allowed transition-colors",children:[e.jsx(rn,{className:"h-4 w-4"}),"Plan"]})]}),Z.length>0?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 mt-6 w-full max-w-4xl mx-auto",children:Z.map(K=>e.jsxs("button",{onClick:()=>{var re;f(K.objective),(re=O.current)==null||re.focus()},className:"group text-left rounded-xl border border-border/50 bg-zinc-900/60 hover:border-purple-500/40 hover:bg-purple-500/5 p-4 transition-all",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-purple-500/10 text-purple-400 group-hover:bg-purple-500/20 transition-colors",children:n0(K.type)}),e.jsx("span",{className:"text-sm font-medium text-zinc-200 group-hover:text-white transition-colors",children:K.name})]}),e.jsx("p",{className:"text-xs text-zinc-500 line-clamp-2 mb-2",children:K.description}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-600",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(us,{className:"h-3 w-3"}),"$",K.suggestedBudget.toFixed(2)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xt,{className:"h-3 w-3"}),K.suggestedIterations," iter"]})]})]},K.id))}):e.jsx("div",{className:"flex flex-wrap gap-2 mt-4 justify-center",children:NN.map(K=>e.jsx("button",{onClick:()=>T(K.prompt),className:"px-3 py-1.5 rounded-full border border-border/50 text-xs text-zinc-500 hover:text-zinc-300 hover:border-purple-500/30 hover:bg-purple-500/5 transition-colors",children:K.label},K.label))})]})}),d==="planning"&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-6",children:[e.jsx(rt,{className:"h-10 w-10 text-purple-400 animate-spin mb-4"}),e.jsx("h2",{className:"text-lg font-semibold text-zinc-200 mb-1",children:"Analyzing objective..."}),e.jsx("p",{className:"text-sm text-zinc-500",children:"Decomposing into sub-objectives"})]}),d==="error"&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-6",children:[e.jsx(pt,{className:"h-10 w-10 text-red-400 mb-4"}),e.jsx("h2",{className:"text-lg font-semibold text-zinc-200 mb-1",children:"Something went wrong"}),e.jsx("p",{className:"text-sm text-red-400/80 mb-4 max-w-md text-center",children:S}),e.jsx("button",{onClick:me,className:"px-4 py-2 rounded-lg border border-border text-sm text-zinc-300 hover:bg-zinc-800 transition-colors",children:"Try again"})]}),h&&(d==="planned"||d==="executing"||d==="evaluating"||d==="complete")&&e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsxs("div",{className:"w-[420px] flex-shrink-0 border-r border-border overflow-y-auto p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-zinc-100 mb-1",children:h.title}),e.jsx("p",{className:"text-xs text-zinc-500 leading-relaxed",children:h.objective})]}),(d==="executing"||d==="evaluating"||d==="complete")&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex justify-between text-[10px] text-zinc-500 mb-1",children:[e.jsx("span",{children:"Progress"}),e.jsxs("span",{children:[Ba,"%"]})]}),e.jsx("div",{className:"h-2 bg-zinc-800 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d==="complete"?"bg-green-500":"bg-purple-500"}`,style:{width:`${Ba}%`}})})]}),(d==="executing"||d==="evaluating")&&$>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/5 border border-amber-500/10",children:[e.jsx(us,{className:"h-3.5 w-3.5 text-amber-400"}),e.jsxs("span",{className:"text-xs text-amber-400 font-mono tabular-nums",children:["$",$.toFixed(4)]}),e.jsx("span",{className:"text-[10px] text-zinc-500",children:"spent so far"})]}),e.jsx("div",{className:"space-y-1",children:h.subObjectives.map((K,re)=>e.jsxs("div",{className:`flex items-start gap-3 px-3 py-2.5 rounded-lg transition-colors ${N===K.id?"bg-purple-500/10 border border-purple-500/20":"hover:bg-zinc-800/30"}`,children:[e.jsxs("div",{className:"flex flex-col items-center flex-shrink-0",children:[e.jsx("div",{className:"flex items-center justify-center h-5 w-5",children:e.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${K.status==="completed"?"bg-green-500":K.status==="in_progress"?"bg-blue-500 animate-pulse":K.status==="failed"?"bg-red-500":"bg-zinc-600"}`})}),re<h.subObjectives.length-1&&e.jsx("div",{className:"w-px h-6 bg-border/50 mt-1"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-200 truncate",children:K.name}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border ${su(K.type)}`,children:K.type})]}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 line-clamp-2",children:K.description}),K.findings.length>0&&e.jsxs("span",{className:"text-[10px] text-zinc-600 mt-1 inline-block",children:[K.findings.length," finding",K.findings.length!==1?"s":""]})]})]},K.id))}),A.length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("h3",{className:"text-[10px] uppercase tracking-wider text-zinc-600 mb-2",children:"Event Timeline"}),e.jsx("div",{ref:ce,className:"max-h-48 overflow-y-auto space-y-0.5",children:A.map(K=>{const re=new Date(K.timestamp),we=`${String(re.getHours()).padStart(2,"0")}:${String(re.getMinutes()).padStart(2,"0")}:${String(re.getSeconds()).padStart(2,"0")}`,Se=K.type==="error"?"bg-red-500":K.type==="complete"?"bg-green-500":K.type==="finding"?"bg-emerald-400":K.type==="evaluation"?"bg-amber-400":K.type==="sub_objective_start"?"bg-blue-400":K.type==="sub_objective_complete"?"bg-green-400":K.type==="iteration"?"bg-purple-400":"bg-zinc-500";return e.jsxs("div",{className:"flex items-start gap-2 px-2 py-1 text-[11px] rounded hover:bg-zinc-800/30",children:[e.jsxs("span",{className:"text-zinc-600 font-mono flex-shrink-0",children:["[",we,"]"]}),e.jsx("div",{className:`h-1.5 w-1.5 rounded-full mt-1.5 flex-shrink-0 ${Se}`}),e.jsx("span",{className:"text-zinc-400 break-words",children:K.label})]},K.id)})})]}),e.jsxs("div",{className:"mt-6 space-y-2",children:[d==="planned"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{onClick:le,className:"flex-1 flex items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-purple-500 transition-colors",children:[e.jsx(sa,{className:"h-4 w-4"}),"Execute Mission"]}),e.jsx("button",{onClick:ne,className:"rounded-lg border border-border px-4 py-2.5 text-sm text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:"Cancel"})]}),d==="executing"&&e.jsxs("button",{onClick:ne,className:"w-full flex items-center justify-center gap-2 rounded-lg border border-red-500/30 px-4 py-2.5 text-sm text-red-400 hover:bg-red-500/10 transition-colors",children:[e.jsx(ft,{className:"h-4 w-4"}),"Cancel Execution"]}),d==="evaluating"&&e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-amber-400 py-2",children:[e.jsx(rt,{className:"h-4 w-4 animate-spin"}),"Evaluating results..."]})]}),h.evaluation&&(d==="complete"||d==="evaluating")&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-zinc-500 mb-3",children:"Quality Evaluation"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Fr,{label:"Completeness",score:h.evaluation.completeness}),e.jsx(Fr,{label:"Accuracy",score:h.evaluation.accuracy}),e.jsx(Fr,{label:"Depth",score:h.evaluation.depth}),e.jsx(Fr,{label:"Relevance",score:h.evaluation.relevance})]}),e.jsxs("div",{className:`mt-2 rounded-lg border p-3 text-center ${sp(h.evaluation.overall)}`,children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-zinc-500",children:"Overall"}),e.jsxs("div",{className:`text-3xl font-bold tabular-nums ${Nu(h.evaluation.overall)}`,children:[Math.round(h.evaluation.overall*100),"%"]}),e.jsxs("div",{className:"text-xs text-zinc-500 mt-1 capitalize",children:["Recommendation: ",e.jsx("span",{className:h.evaluation.recommendation==="deliver"?"text-green-400":h.evaluation.recommendation==="iterate"?"text-amber-400":"text-red-400",children:h.evaluation.recommendation})]})]}),h.evaluation.gaps.length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("h4",{className:"text-[10px] uppercase tracking-wider text-zinc-600 mb-1",children:"Gaps"}),h.evaluation.gaps.map((K,re)=>e.jsxs("p",{className:"text-[11px] text-zinc-500 flex items-start gap-1 mt-0.5",children:[e.jsx(pt,{className:"h-3 w-3 text-amber-500/60 flex-shrink-0 mt-0.5"}),K]},re))]})]}),d==="complete"&&h.report&&e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs("button",{onClick:()=>w(!C),className:"flex-1 flex items-center justify-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-zinc-300 hover:bg-zinc-800 transition-colors",children:[e.jsx(Ua,{className:"h-4 w-4"}),C?"Hide Report":"View Report"]}),e.jsx("button",{onClick:je,className:"flex items-center justify-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-zinc-300 hover:bg-zinc-800 transition-colors",title:"Download as Markdown",children:e.jsx(hi,{className:"h-4 w-4"})})]}),d==="complete"&&e.jsxs("button",{onClick:me,className:"mt-3 w-full flex items-center justify-center gap-2 rounded-lg bg-purple-600/20 border border-purple-500/20 px-4 py-2.5 text-sm text-purple-400 hover:bg-purple-600/30 transition-colors",children:[e.jsx(k0,{className:"h-4 w-4"}),"New Mission"]}),(d==="complete"||(h==null?void 0:h.status)==="completed"||(h==null?void 0:h.status)==="failed")&&h&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[((Os=h.evaluation)==null?void 0:Os.recommendation)==="iterate"&&e.jsx(Qr,{onClick:()=>te(h.id),loading:be,disabled:nt&&!be,className:"flex items-center justify-center gap-2 px-3 py-2.5 bg-yellow-600 hover:bg-yellow-500 text-white rounded-lg text-xs font-medium transition-colors",icon:e.jsx(xt,{className:"h-3.5 w-3.5"}),loadingText:"Iterating...",children:"Iterate on Gaps"}),((Si=h.evaluation)==null?void 0:Si.gaps)&&h.evaluation.gaps.length>0&&e.jsx(Qr,{onClick:()=>ye(h),loading:ve,disabled:nt&&!ve,className:"flex items-center justify-center gap-2 px-3 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-xs font-medium transition-colors",icon:e.jsx(_a,{className:"h-3.5 w-3.5"}),loadingText:"Planning...",children:"Deep Dive Gaps"}),e.jsx(Qr,{onClick:()=>We(h.id),loading:Xe,disabled:Kt||nt&&!Xe,className:`flex items-center justify-center gap-2 px-3 py-2.5 text-white rounded-lg text-xs font-medium transition-colors ${Kt?"bg-green-800 cursor-default":"bg-green-600 hover:bg-green-500"}`,icon:Kt?e.jsx(bt,{className:"h-3.5 w-3.5"}):e.jsx(La,{className:"h-3.5 w-3.5"}),loadingText:"Archiving...",children:Kt?"Archived":"Archive to Brain"}),e.jsxs("button",{onClick:()=>hs(h),className:"flex items-center justify-center gap-2 px-3 py-2.5 bg-purple-600 hover:bg-purple-500 text-white rounded-lg text-xs font-medium transition-colors",children:[e.jsx(gi,{className:"h-3.5 w-3.5"}),"Chat About This"]}),e.jsx(Qr,{onClick:()=>fs(h),loading:Ns,disabled:nt&&!Ns,className:"flex items-center justify-center gap-2 px-3 py-2.5 bg-zinc-700 hover:bg-zinc-600 text-white rounded-lg text-xs font-medium transition-colors",icon:e.jsx(xt,{className:"h-3.5 w-3.5"}),loadingText:"Re-running...",children:"Re-run Fresh"}),e.jsxs("button",{onClick:()=>yt(h),className:"flex items-center justify-center gap-2 px-3 py-2.5 bg-zinc-700 hover:bg-zinc-600 text-white rounded-lg text-xs font-medium transition-colors",children:[e.jsx(hi,{className:"h-3.5 w-3.5"}),"Export Full Data"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",ref:D,children:C&&h.report?e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:"Mission Report"}),e.jsx("button",{onClick:()=>w(!1),className:"text-zinc-500 hover:text-zinc-300",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"rounded-lg border border-border bg-zinc-900/50 p-6",children:e.jsx(SN,{content:h.report})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-zinc-500 mb-3",children:["Findings",g.length>0&&e.jsxs("span",{className:"ml-2 text-zinc-600",children:["(",g.length,")"]})]}),g.length===0&&d==="planned"&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-zinc-600",children:[e.jsx(_a,{className:"h-8 w-8 mb-2 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Findings will appear here during execution"})]}),g.length===0&&d==="executing"&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-zinc-600",children:[e.jsx(rt,{className:"h-8 w-8 mb-2 animate-spin opacity-40"}),e.jsx("p",{className:"text-sm",children:"Agents are working..."})]}),e.jsx("div",{className:"space-y-2",children:g.map(K=>e.jsx(wN,{finding:K},K.id))})]})})]})]})]})}const l0=[{id:"claude",name:"Claude",provider:"Anthropic",emoji:"🟣",color:"text-purple-400",bgColor:"bg-purple-500/10",borderColor:"border-purple-500/30",keyUrl:"https://console.anthropic.com/settings/keys",keyUrlLabel:"console.anthropic.com",envVar:"ANTHROPIC_API_KEY",needsKey:!0},{id:"openai",name:"OpenAI",provider:"OpenAI",emoji:"🟢",color:"text-green-400",bgColor:"bg-green-500/10",borderColor:"border-green-500/30",keyUrl:"https://platform.openai.com/api-keys",keyUrlLabel:"platform.openai.com",envVar:"OPENAI_API_KEY",needsKey:!0},{id:"gemini",name:"Google Gemini",provider:"Google",emoji:"🔵",color:"text-blue-400",bgColor:"bg-blue-500/10",borderColor:"border-blue-500/30",keyUrl:"https://aistudio.google.com/apikey",keyUrlLabel:"aistudio.google.com",envVar:"GEMINI_API_KEY",needsKey:!0},{id:"grok",name:"Grok",provider:"xAI",emoji:"⚪",color:"text-zinc-300",bgColor:"bg-zinc-500/10",borderColor:"border-zinc-500/30",keyUrl:"https://console.x.ai/team/default/api-keys",keyUrlLabel:"console.x.ai",envVar:"XAI_API_KEY",needsKey:!0},{id:"mistral",name:"Mistral AI",provider:"Mistral",emoji:"🟠",color:"text-orange-400",bgColor:"bg-orange-500/10",borderColor:"border-orange-500/30",keyUrl:"https://console.mistral.ai/api-keys",keyUrlLabel:"console.mistral.ai",envVar:"MISTRAL_API_KEY",needsKey:!0},{id:"ollama",name:"Ollama",provider:"Local",emoji:"🟤",color:"text-amber-400",bgColor:"bg-amber-500/10",borderColor:"border-amber-500/30",keyUrl:"https://ollama.ai/download",keyUrlLabel:"ollama.ai",envVar:"",needsKey:!1}];function CN(n){if(!n)return"";const i=Date.now()-new Date(n+"Z").getTime(),d=Math.floor(i/6e4);if(d<1)return"Just now";if(d<60)return`${d}m ago`;const c=Math.floor(d/60);if(c<24)return`${c}h ago`;const m=Math.floor(c/24);return m<30?`${m}d ago`:new Date(n).toLocaleDateString()}function AN({entry:n}){return n.configured&&n.source==="db"?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-green-500/10 px-2.5 py-0.5 text-xs font-medium text-green-400",children:[e.jsx(bt,{className:"h-3 w-3"}),"Configured"]}):n.configured&&n.source==="env"?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-yellow-500/10 px-2.5 py-0.5 text-xs font-medium text-yellow-400",children:[e.jsx(pt,{className:"h-3 w-3"}),"From env"]}):n.provider==="ollama"&&n.configured?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-blue-500/10 px-2.5 py-0.5 text-xs font-medium text-blue-400",children:[e.jsx(bt,{className:"h-3 w-3"}),"Local"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-red-500/10 px-2.5 py-0.5 text-xs font-medium text-red-400",children:[e.jsx(Ze,{className:"h-3 w-3"}),"Not configured"]})}function EN({provider:n,onClose:i,onSaved:d}){const[c,m]=u.useState(""),[f,h]=u.useState(""),[b,g]=u.useState(!1),[p,S]=u.useState(!1),[y,v]=u.useState(!1),[k,C]=u.useState(null),[w,N]=u.useState(null),z=async()=>{if(c.trim()){v(!0),C(null),N(null);try{await ys.set(n.id,c.trim(),f||void 0);const D=await ys.test(n.id);C(D.data)}catch(D){N(D instanceof Error?D.message:"Test failed")}finally{v(!1)}}},R=async()=>{if(c.trim()){S(!0),N(null);try{await ys.set(n.id,c.trim(),f||void 0),d()}catch(D){N(D instanceof Error?D.message:"Failed to save")}finally{S(!1)}}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:n.emoji}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-white",children:n.name}),e.jsx("p",{className:"text-xs text-zinc-500",children:n.provider})]})]}),e.jsx("button",{onClick:i,className:"rounded-lg p-2 text-zinc-400 hover:bg-surface-hover hover:text-zinc-200",children:e.jsx(Ze,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:c,onChange:D=>m(D.target.value),placeholder:`Enter your ${n.provider} API key`,className:"w-full rounded-lg border border-border bg-background px-4 py-2.5 pr-10 text-sm text-zinc-200 focus:border-purple-500 focus:outline-none placeholder:text-zinc-600",autoFocus:!0}),e.jsx("button",{type:"button",onClick:()=>g(!b),className:"absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300",children:b?e.jsx(uu,{className:"h-4 w-4"}):e.jsx(el,{className:"h-4 w-4"})})]}),n.envVar&&e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["Env var: ",e.jsx("code",{className:"text-zinc-500",children:n.envVar})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:["Label ",e.jsx("span",{className:"text-zinc-600",children:"(optional)"})]}),e.jsx("input",{type:"text",value:f,onChange:D=>h(D.target.value),placeholder:"e.g. Production key, Personal key",className:"w-full rounded-lg border border-border bg-background px-4 py-2.5 text-sm text-zinc-200 focus:border-purple-500 focus:outline-none placeholder:text-zinc-600"})]}),k&&e.jsxs("div",{className:`rounded-lg border p-3 ${k.valid?"border-green-500/30 bg-green-500/5 text-green-400":"border-red-500/30 bg-red-500/5 text-red-400"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[k.valid?e.jsx(bt,{className:"h-4 w-4"}):e.jsx(Ze,{className:"h-4 w-4"}),k.valid?"Key is valid":"Key validation failed"]}),e.jsx("p",{className:"mt-1 text-xs opacity-80",children:k.message}),k.models&&k.models.length>0&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[k.models.slice(0,6).map(D=>e.jsx("span",{className:"rounded-md bg-white/5 px-2 py-0.5 text-[10px] font-mono",children:D},D)),k.models.length>6&&e.jsxs("span",{className:"rounded-md bg-white/5 px-2 py-0.5 text-[10px]",children:["+",k.models.length-6," more"]})]})]}),w&&e.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/5 p-3 text-sm text-red-400",children:w}),e.jsxs("a",{href:n.keyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-purple-400 hover:text-purple-300 transition-colors",children:[e.jsx(Pn,{className:"h-3 w-3"}),"Get API key at ",n.keyUrlLabel]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-end gap-3",children:[e.jsxs("button",{onClick:z,disabled:!c.trim()||y,className:"inline-flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-zinc-300 transition-colors hover:bg-surface-hover disabled:opacity-50 disabled:cursor-not-allowed",children:[y?e.jsx(rt,{className:"h-4 w-4 animate-spin"}):e.jsx(bi,{className:"h-4 w-4"}),"Test Key"]}),e.jsxs("button",{onClick:R,disabled:!c.trim()||p,className:"inline-flex items-center gap-2 rounded-lg bg-purple-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",children:[p?e.jsx(rt,{className:"h-4 w-4 animate-spin"}):e.jsx(bt,{className:"h-4 w-4"}),"Save"]})]})]})})}function TN({meta:n,entry:i,onAdd:d,onTest:c,onRemove:m,testingProvider:f,testResult:h}){const b=(i==null?void 0:i.configured)??!1,g=f===n.id,p=(h==null?void 0:h.provider)===n.id?h.result:null;return e.jsxs("div",{className:`rounded-xl border ${b?n.borderColor:"border-border"} bg-surface p-5 transition-all hover:shadow-lg hover:shadow-black/20`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:n.emoji}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-white",children:n.name}),e.jsx("p",{className:"text-xs text-zinc-500",children:n.provider})]})]}),i&&e.jsx(AN,{entry:i})]}),b&&(i==null?void 0:i.maskedKey)&&e.jsxs("div",{className:"mb-3 rounded-lg bg-background/50 px-3 py-2",children:[e.jsx("p",{className:"font-mono text-xs text-zinc-400",children:i.maskedKey}),i.label&&i.source==="db"&&e.jsx("p",{className:"text-[10px] text-zinc-600 mt-0.5",children:i.label}),i.updatedAt&&i.source==="db"&&e.jsxs("p",{className:"text-[10px] text-zinc-600 mt-0.5",children:["Updated ",CN(i.updatedAt)]}),i.source==="env"&&e.jsxs("p",{className:"text-[10px] text-yellow-500/80 mt-0.5",children:["Set via ",e.jsx("code",{className:"font-mono",children:n.envVar})," environment variable"]})]}),p&&e.jsxs("div",{className:`mb-3 rounded-lg border p-2.5 text-xs ${p.valid?"border-green-500/20 bg-green-500/5 text-green-400":"border-red-500/20 bg-red-500/5 text-red-400"}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 font-medium",children:[p.valid?e.jsx(bt,{className:"h-3 w-3"}):e.jsx(Ze,{className:"h-3 w-3"}),p.valid?"Working":"Failed"]}),e.jsx("p",{className:"mt-0.5 text-[10px] opacity-80",children:p.message}),p.models&&p.models.length>0&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1",children:[p.models.slice(0,4).map(S=>e.jsx("span",{className:"rounded bg-white/5 px-1.5 py-0.5 text-[9px] font-mono",children:S},S)),p.models.length>4&&e.jsxs("span",{className:"rounded bg-white/5 px-1.5 py-0.5 text-[9px]",children:["+",p.models.length-4]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:b?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:c,disabled:g,className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-zinc-400 transition-colors hover:bg-surface-hover hover:text-zinc-200 disabled:opacity-50",children:[g?e.jsx(rt,{className:"h-3 w-3 animate-spin"}):e.jsx(bi,{className:"h-3 w-3"}),"Test"]}),n.needsKey&&e.jsxs("button",{onClick:d,className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-zinc-400 transition-colors hover:bg-surface-hover hover:text-zinc-200",children:[e.jsx(Ni,{className:"h-3 w-3"}),"Edit"]}),(i==null?void 0:i.source)==="db"&&e.jsxs("button",{onClick:m,className:"inline-flex items-center gap-1.5 rounded-lg border border-red-500/20 px-3 py-1.5 text-xs font-medium text-red-400 transition-colors hover:bg-red-500/10",children:[e.jsx(Ot,{className:"h-3 w-3"}),"Remove"]})]}):e.jsxs("button",{onClick:d,className:"inline-flex items-center gap-1.5 rounded-lg bg-purple-600 px-4 py-1.5 text-xs font-medium text-white transition-colors hover:bg-purple-700",children:[e.jsx(ht,{className:"h-3 w-3"}),"Add Key"]})}),e.jsx("div",{className:"mt-3 border-t border-border/50 pt-2.5",children:e.jsxs("a",{href:n.keyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[10px] text-zinc-600 hover:text-zinc-400 transition-colors",children:[e.jsx(Pn,{className:"h-2.5 w-2.5"}),n.keyUrlLabel]})})]})}function RN(){const[n,i]=u.useState([]),[d,c]=u.useState(!0),[m,f]=u.useState(null),[h,b]=u.useState(null),[g,p]=u.useState(null),S=u.useCallback(async()=>{try{const w=await ys.list();i(w.data)}catch{}finally{c(!1)}},[]);u.useEffect(()=>{S()},[S]);const y=async w=>{b(w),p(null);try{const N=await ys.test(w);p({provider:w,result:N.data})}catch(N){p({provider:w,result:{valid:!1,message:N instanceof Error?N.message:"Test failed"}})}finally{b(null)}},v=async w=>{try{await ys.remove(w),await S(),(g==null?void 0:g.provider)===w&&p(null)}catch{}},k=w=>n.find(N=>N.provider===w)||null,C=n.filter(w=>w.configured).length;return d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-purple-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-purple-500/10",children:e.jsx(Ni,{className:"h-5 w-5 text-purple-400"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold text-white",children:"API Keys"}),e.jsx("p",{className:"text-sm text-zinc-500",children:"Manage your LLM provider credentials securely."})]})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-surface px-3 py-1.5 border border-border",children:[e.jsx(Ds,{className:"h-3.5 w-3.5 text-green-400"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:[C,"/",l0.length," configured"]})]}),e.jsxs("button",{onClick:()=>{c(!0),S()},className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-zinc-400 hover:bg-surface-hover hover:text-zinc-200 transition-colors",children:[e.jsx(xt,{className:"h-3 w-3"}),"Refresh"]})]})]}),e.jsx("div",{className:"rounded-xl border border-border bg-surface/50 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ds,{className:"h-5 w-5 text-purple-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-xs text-zinc-400 space-y-1",children:[e.jsxs("p",{children:["API keys are encrypted with AES-256-GCM and stored locally in the Nestor database. The encryption key is derived from a master secret in ",e.jsx("code",{className:"text-zinc-300",children:"~/.nestor/.vault-key"}),"."]}),e.jsx("p",{children:"Keys set via environment variables take precedence over database-stored keys."})]})]})}),e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3",children:l0.map(w=>e.jsx(TN,{meta:w,entry:k(w.id),onAdd:()=>f(w),onTest:()=>y(w.id),onRemove:()=>v(w.id),testingProvider:h,testResult:g},w.id))}),m&&e.jsx(EN,{provider:m,onClose:()=>f(null),onSaved:()=>{f(null),S()}})]})}const Yd=[{id:"gemini",name:"Gemini",provider:"Google",description:"Multimodal AI with large context window",defaultModel:"gemini-2.5-flash",keyUrl:"https://aistudio.google.com/apikey",keyUrlLabel:"aistudio.google.com",emoji:"🔵",needsApiKey:!0},{id:"claude",name:"Claude",provider:"Anthropic",description:"Best for reasoning, analysis, and code generation",defaultModel:"claude-sonnet-4-6",keyUrl:"https://console.anthropic.com/settings/keys",keyUrlLabel:"console.anthropic.com",emoji:"🟣",needsApiKey:!0},{id:"openai",name:"GPT-4o",provider:"OpenAI",description:"Versatile model with strong general capabilities",defaultModel:"gpt-4o",keyUrl:"https://platform.openai.com/api-keys",keyUrlLabel:"platform.openai.com",emoji:"🟢",needsApiKey:!0},{id:"grok",name:"Grok",provider:"xAI",description:"Real-time knowledge with web access",defaultModel:"grok-3",keyUrl:"https://console.x.ai/",keyUrlLabel:"console.x.ai",emoji:"⚪",needsApiKey:!0},{id:"mistral",name:"Mistral",provider:"Mistral AI",description:"Efficient European AI with strong multilingual support",defaultModel:"mistral-large-latest",keyUrl:"https://console.mistral.ai/api-keys",keyUrlLabel:"console.mistral.ai",emoji:"🟠",needsApiKey:!0},{id:"openrouter",name:"OpenRouter",provider:"OpenRouter",description:"Access 200+ models through a single API",defaultModel:"google/gemini-2.5-flash-preview",keyUrl:"https://openrouter.ai/keys",keyUrlLabel:"openrouter.ai",emoji:"🔀",needsApiKey:!0},{id:"ollama",name:"Ollama",provider:"Local",description:"Run open-source models locally, no API key needed",defaultModel:"llama3.1",keyUrl:"https://ollama.ai/download",keyUrlLabel:"ollama.ai",emoji:"🦙",needsApiKey:!1,note:"Free, runs on your machine"}];function MN(){var me;const n=Dt(),[i,d]=u.useState(0),[c,m]=u.useState("gemini"),[f,h]=u.useState("gemini-2.5-flash"),[b,g]=u.useState(""),[p,S]=u.useState(!1),[y,v]=u.useState({}),[k,C]=u.useState(!0),[w,N]=u.useState(!1),[z,R]=u.useState(null),[D,O]=u.useState("my-agent"),[se,Z]=u.useState("My first Nestor agent"),[U,A]=u.useState(!1),[F,$]=u.useState("");u.useEffect(()=>{Kh.status().then(ue=>{ue!=null&&ue.data&&typeof ue.data=="object"&&v(ue.data)}).catch(()=>{}).finally(()=>C(!1))},[]);const Q=u.useCallback(ue=>{m(ue);const je=Yd.find(T=>T.id===ue);je&&h(je.defaultModel),g(""),S(!1),R(null)},[]),ce=u.useCallback(()=>{d(ue=>Math.min(ue+1,2))},[]),I=u.useCallback(()=>{d(ue=>Math.max(ue-1,0))},[]),le=Yd.find(ue=>ue.id===c),Y=((me=y[c])==null?void 0:me.configured)??!1,B=u.useCallback(async()=>{N(!0),R(null);try{const ue=await Kh.test({provider:c,apiKey:b.trim()||void 0,model:f});R(ue)}catch(ue){R({success:!1,message:ue instanceof Error?ue.message:"Connection test failed"})}finally{N(!1)}},[c,b,f]),ne=u.useCallback(async()=>{if(!D.trim()){$("Please enter an agent name.");return}A(!0),$("");try{b.trim()&&(le!=null&&le.needsApiKey)&&await ys.set(c,b.trim(),"Onboarding key"),await la.create({name:D.trim(),description:se.trim()||void 0,adapterType:c,adapterConfig:{model:f},trustLevel:"trusted"}),localStorage.setItem("nestor_onboarding_complete","true"),n("/chat")}catch(ue){$(ue instanceof Error?ue.message:"Failed to create agent")}finally{A(!1)}},[D,se,c,f,b,le,n]);return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-2xl",children:[e.jsx("div",{className:"flex items-center justify-center gap-2 mb-8",children:[0,1,2].map(ue=>e.jsx("div",{className:`h-1.5 rounded-full transition-all duration-500 ${ue===i?"w-10 bg-purple-500":ue<i?"w-10 bg-purple-500/40":"w-10 bg-zinc-700"}`},ue))}),e.jsxs("div",{className:"relative",children:[i===0&&e.jsxs("div",{className:"text-center onboarding-fade-in",children:[e.jsx("div",{className:"flex justify-center mb-6",children:e.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-2xl bg-purple-600 text-white shadow-lg shadow-purple-500/30",children:e.jsx(sa,{className:"h-10 w-10"})})}),e.jsx("h1",{className:"text-4xl font-bold text-white mb-3",children:"Welcome to Nestor"}),e.jsx("p",{className:"text-zinc-400 text-lg mb-2",children:"Your AI agent platform is ready."}),e.jsx("p",{className:"text-zinc-500 mb-12",children:"Let's create your first agent in 30 seconds."}),e.jsxs("button",{onClick:ce,className:"inline-flex items-center gap-2 px-8 py-3.5 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-medium transition-all text-lg shadow-lg shadow-purple-500/25 hover:shadow-purple-500/40 hover:scale-[1.02] active:scale-[0.98]",children:["Get Started",e.jsx(ds,{className:"h-5 w-5"})]})]}),i===1&&e.jsxs("div",{className:"onboarding-fade-in",children:[e.jsx("h2",{className:"text-2xl font-bold text-white mb-1 text-center",children:"Choose your AI provider"}),e.jsx("p",{className:"text-zinc-500 mb-6 text-center text-sm",children:"Select which LLM to power your agent"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6",children:Yd.map(ue=>{var P;const je=c===ue.id,T=((P=y[ue.id])==null?void 0:P.configured)??!1;return e.jsxs("button",{onClick:()=>Q(ue.id),className:`relative text-left p-4 rounded-xl border-2 transition-all duration-200 hover:scale-[1.02] ${je?"border-purple-500 bg-purple-500/10 shadow-lg shadow-purple-500/10":"border-border bg-surface hover:border-zinc-600 hover:bg-surface-hover"}`,children:[T&&e.jsx("span",{className:"absolute top-2 right-2 text-green-400",title:"API key configured",children:e.jsx(bt,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"text-lg mb-1",children:ue.emoji}),e.jsx("div",{className:"font-semibold text-sm text-zinc-100",children:ue.name}),e.jsx("div",{className:"text-[11px] text-zinc-500",children:ue.provider}),ue.note&&e.jsx("div",{className:"text-[10px] text-green-400/80 mt-1",children:ue.note}),ue.needsApiKey&&e.jsxs("a",{href:ue.keyUrl,target:"_blank",rel:"noopener noreferrer",onClick:de=>de.stopPropagation(),className:"inline-flex items-center gap-1 text-[10px] text-purple-400 hover:text-purple-300 mt-1.5 transition-colors",children:["Get API Key ",e.jsx(Pn,{className:"h-2.5 w-2.5"})]})]},ue.id)})}),e.jsxs("div",{className:"space-y-3",children:[(le==null?void 0:le.needsApiKey)&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:["API Key",Y&&e.jsxs("span",{className:"ml-2 text-xs text-green-400 font-normal",children:[e.jsx(bt,{className:"inline h-3 w-3 mr-0.5"}),"Already configured"]})]}),Y?e.jsx("p",{className:"text-xs text-zinc-500 mb-2",children:"Your API key is already set. You can skip this field or enter a new key to update it."}):null,e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:p?"text":"password",value:b,onChange:ue=>{g(ue.target.value),R(null)},className:"w-full bg-background border border-border rounded-lg px-3 py-2.5 pr-10 text-sm text-zinc-200 focus:outline-none focus:border-purple-500 placeholder-zinc-600 transition-colors",placeholder:`Enter your ${le.provider} API key`}),e.jsx("button",{type:"button",onClick:()=>S(!p),className:"absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300 transition-colors",children:p?e.jsx(uu,{className:"h-4 w-4"}):e.jsx(el,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex items-center justify-between mt-1.5",children:e.jsxs("a",{href:le.keyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-purple-400 hover:text-purple-300 transition-colors",children:["Get your API key ",e.jsx(Pn,{className:"h-3 w-3"})]})})]}),c==="ollama"&&e.jsxs("div",{className:"bg-surface border border-border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-zinc-300 font-medium mb-1",children:"No API key needed"}),e.jsxs("p",{className:"text-xs text-zinc-400",children:["Make sure Ollama is running on ",e.jsx("code",{className:"text-zinc-300",children:"localhost:11434"})]}),e.jsxs("a",{href:"https://ollama.ai/download",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-purple-400 hover:text-purple-300 mt-2 transition-colors",children:["Download Ollama ",e.jsx(Pn,{className:"h-3 w-3"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-zinc-300 mb-1",children:"Model"}),e.jsx("input",{type:"text",value:f,onChange:ue=>h(ue.target.value),className:"w-full bg-background border border-border rounded-lg px-3 py-2 text-sm text-zinc-200 focus:outline-none focus:border-purple-500 placeholder-zinc-600 transition-colors",placeholder:"e.g. gemini-2.5-flash"})]}),e.jsx("button",{onClick:B,disabled:w||!b.trim()&&(le==null?void 0:le.needsApiKey)&&!Y,className:"w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border border-border text-sm font-medium text-zinc-300 transition-all hover:bg-surface-hover hover:text-white disabled:opacity-40 disabled:cursor-not-allowed",children:w?e.jsxs(e.Fragment,{children:[e.jsx(rt,{className:"h-4 w-4 animate-spin"}),"Testing connection..."]}):e.jsxs(e.Fragment,{children:[e.jsx(bi,{className:"h-4 w-4"}),"Test Connection"]})}),z&&e.jsx("div",{className:`rounded-lg border p-3 text-sm transition-all ${z.success?"border-green-500/30 bg-green-500/5 text-green-400":"border-red-500/30 bg-red-500/5 text-red-400"}`,children:e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[z.success?e.jsx(bt,{className:"h-4 w-4"}):e.jsx(xi,{className:"h-4 w-4"}),z.message]})})]}),e.jsxs("div",{className:"flex justify-between mt-8",children:[e.jsxs("button",{onClick:I,className:"flex items-center gap-1 px-4 py-2 text-sm text-zinc-400 hover:text-zinc-200 transition-colors",children:[e.jsx($h,{className:"h-4 w-4"}),"Back"]}),e.jsxs("button",{onClick:ce,className:"flex items-center gap-2 px-6 py-2.5 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-medium transition-all text-sm hover:shadow-lg hover:shadow-purple-500/20",children:["Continue",e.jsx(ds,{className:"h-4 w-4"})]})]})]}),i===2&&e.jsxs("div",{className:"onboarding-fade-in",children:[e.jsx("h2",{className:"text-2xl font-bold text-white mb-1 text-center",children:"Name your agent"}),e.jsx("p",{className:"text-zinc-500 mb-6 text-center text-sm",children:"Almost there! Give your agent a name."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-zinc-300 mb-1",children:"Agent name"}),e.jsx("input",{type:"text",value:D,onChange:ue=>O(ue.target.value),className:"w-full bg-background border border-border rounded-lg px-3 py-2.5 text-sm text-zinc-200 focus:outline-none focus:border-purple-500 placeholder-zinc-600 transition-colors",placeholder:"e.g. my-agent"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-zinc-300 mb-1",children:"Description"}),e.jsx("textarea",{value:se,onChange:ue=>Z(ue.target.value),rows:2,className:"w-full bg-background border border-border rounded-lg px-3 py-2.5 text-sm text-zinc-200 focus:outline-none focus:border-purple-500 placeholder-zinc-600 resize-none transition-colors",placeholder:"What does this agent do?"})]}),e.jsxs("div",{className:"bg-surface border border-border rounded-xl p-4",children:[e.jsx("p",{className:"text-xs text-zinc-500 mb-2 font-medium uppercase tracking-wider",children:"Summary"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("p",{className:"text-sm text-zinc-300",children:[e.jsx("span",{className:"text-zinc-500",children:"Agent:"})," ",e.jsx("span",{className:"font-medium text-zinc-100",children:D||"—"})]}),e.jsxs("p",{className:"text-sm text-zinc-300",children:[e.jsx("span",{className:"text-zinc-500",children:"Provider:"})," ",e.jsx("span",{className:"text-purple-400",children:le==null?void 0:le.name})," ",e.jsxs("span",{className:"text-zinc-500",children:["(",f,")"]})]}),b.trim()&&(le==null?void 0:le.needsApiKey)&&e.jsxs("p",{className:"text-sm text-zinc-300",children:[e.jsx("span",{className:"text-zinc-500",children:"API Key:"})," ",e.jsx("span",{className:"text-green-400",children:"Will be saved securely"})]})]})]}),F&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-400",children:[e.jsx(xi,{className:"h-4 w-4 flex-shrink-0"}),F]})]}),e.jsxs("div",{className:"flex justify-between mt-8",children:[e.jsxs("button",{onClick:I,className:"flex items-center gap-1 px-4 py-2 text-sm text-zinc-400 hover:text-zinc-200 transition-colors",children:[e.jsx($h,{className:"h-4 w-4"}),"Back"]}),e.jsx("button",{onClick:ne,disabled:U||!D.trim(),className:"flex items-center gap-2 px-6 py-2.5 bg-purple-600 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-xl font-medium transition-all text-sm shadow-lg shadow-purple-500/20 hover:shadow-purple-500/40 hover:scale-[1.02] active:scale-[0.98]",children:U?e.jsxs(e.Fragment,{children:[e.jsx(rt,{className:"h-4 w-4 animate-spin"}),"Creating..."]}):e.jsxs(e.Fragment,{children:["Create & Start Chatting",e.jsx(ds,{className:"h-4 w-4"})]})})]})]})]}),e.jsx("div",{className:"text-center mt-12",children:e.jsx("p",{className:"text-xs text-zinc-600",children:"You can always add more agents and change settings later."})})]})})}const DN={discord:{color:"bg-indigo-500/20 text-indigo-400",envVar:"DISCORD_BOT_TOKEN"},slack:{color:"bg-green-500/20 text-green-400",envVar:"SLACK_BOT_TOKEN"},telegram:{color:"bg-blue-500/20 text-blue-400",envVar:"TELEGRAM_BOT_TOKEN"}};function ON({adapter:n}){const i=DN[n.adapter]??{color:"bg-zinc-500/20 text-zinc-400",envVar:"N/A"};return e.jsxs("div",{className:"rounded-lg border border-border bg-surface p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex h-10 w-10 items-center justify-center rounded-lg ${i.color}`,children:e.jsx(Pt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium capitalize text-zinc-200",children:n.adapter}),e.jsx("p",{className:"text-xs text-zinc-500",children:n.envVar||i.envVar})]})]}),n.configured?e.jsxs("span",{className:"flex items-center gap-1.5 rounded-full bg-green-500/10 px-3 py-1 text-xs font-medium text-green-400",children:[e.jsx(et,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1.5 rounded-full bg-zinc-500/10 px-3 py-1 text-xs font-medium text-zinc-400",children:[e.jsx(ft,{className:"h-3 w-3"})," Not configured"]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-md bg-zinc-900/50 p-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-zinc-500",children:"Channels"}),e.jsx("p",{className:"mt-1 text-lg font-semibold text-white",children:n.channelCount})]}),e.jsxs("div",{className:"rounded-md bg-zinc-900/50 p-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wider text-zinc-500",children:"Last Message"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-300",children:n.lastMessageAt?new Date(n.lastMessageAt).toLocaleTimeString():"--"})]})]})]})}function LN(){const{t:n}=Je(),[i,d]=u.useState([]),[c,m]=u.useState([]),[f,h]=u.useState([]),[b,g]=u.useState(!0),[p,S]=u.useState(null),[y,v]=u.useState(""),[k,C]=u.useState(""),[w,N]=u.useState(""),[z,R]=u.useState(!1),[D,O]=u.useState(null),se=u.useCallback(async()=>{g(!0),S(null);try{const[A,F]=await Promise.all([qd.status(),qd.channels()]);if(d(A.data.adapters),m(A.data.recentMessages),h(F.data),A.data.adapters.length>0&&!y){const $=A.data.adapters.find(Q=>Q.configured);$&&v($.adapter)}}catch(A){S(A instanceof Error?A.message:"Failed to load messaging status")}finally{g(!1)}},[y]);u.useEffect(()=>{se()},[se]);const Z=f.filter(A=>!y||A.adapter===y),U=async A=>{if(A.preventDefault(),!(!y||!k||!w.trim())){R(!0),O(null);try{await qd.send(y,k,w.trim()),O("success"),N(""),setTimeout(()=>se(),1e3)}catch(F){O(F instanceof Error?F.message:"Send failed")}finally{R(!1)}}};return b?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-purple-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pt,{className:"h-6 w-6 text-purple-400"}),e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("messaging.title")})]}),e.jsxs("button",{onClick:se,className:"btn-ghost btn-sm",children:[e.jsx(xt,{className:"h-4 w-4"}),n("common.retry")]})]}),p&&e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:p}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[i.map(A=>e.jsx(ON,{adapter:A},A.adapter)),i.length===0&&e.jsxs("div",{className:"col-span-3 flex flex-col items-center justify-center rounded-lg border border-border bg-surface py-12",children:[e.jsx(Pt,{className:"h-12 w-12 text-zinc-600"}),e.jsx("p",{className:"mt-4 text-sm text-zinc-400",children:n("messaging.empty")}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:n("messaging.emptyDesc")})]})]}),i.some(A=>A.configured)&&e.jsxs("div",{className:"rounded-lg border border-border bg-surface p-5",children:[e.jsx("h2",{className:"mb-4 text-sm font-medium text-zinc-300",children:n("messaging.sendTest")}),e.jsxs("form",{onSubmit:U,className:"flex flex-col gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"flex-shrink-0",children:[e.jsx("label",{className:"label",children:n("messaging.adapter")}),e.jsx("select",{value:y,onChange:A=>{v(A.target.value),C("")},className:"rounded-lg border border-border bg-surface px-3 py-2 text-sm text-white focus:border-purple-500 focus:outline-none",children:i.filter(A=>A.configured).map(A=>e.jsx("option",{value:A.adapter,children:A.adapter},A.adapter))})]}),e.jsxs("div",{className:"flex-shrink-0",children:[e.jsx("label",{className:"label",children:n("messaging.channel")}),e.jsxs("select",{value:k,onChange:A=>C(A.target.value),className:"rounded-lg border border-border bg-surface px-3 py-2 text-sm text-white focus:border-purple-500 focus:outline-none",children:[e.jsx("option",{value:"",children:n("messaging.selectChannel")}),Z.map(A=>e.jsxs("option",{value:A.id,children:["#",A.name]},A.id))]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"label",children:n("messaging.message")}),e.jsx("input",{type:"text",value:w,onChange:A=>N(A.target.value),placeholder:n("messaging.messagePlaceholder"),className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-white placeholder:text-zinc-500 focus:border-purple-500 focus:outline-none"})]}),e.jsxs("button",{type:"submit",disabled:!k||!w.trim()||z,className:"btn-primary flex-shrink-0",children:[e.jsx(gi,{className:"h-4 w-4"}),n(z?"common.loading":"messaging.send")]})]}),D&&e.jsx("p",{className:`mt-2 text-xs ${D==="success"?"text-green-400":"text-red-400"}`,children:D==="success"?n("messaging.sent"):D})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-surface",children:[e.jsx("div",{className:"border-b border-border px-5 py-3",children:e.jsx("h2",{className:"text-sm font-medium text-zinc-300",children:n("messaging.recentMessages")})}),c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(vs,{className:"h-8 w-8 text-zinc-600"}),e.jsx("p",{className:"mt-3 text-sm text-zinc-400",children:n("messaging.noMessages")})]}):e.jsx("div",{className:"divide-y divide-border",children:c.slice(0,20).map(A=>e.jsxs("div",{className:"flex items-center gap-4 px-5 py-3",children:[e.jsx("div",{className:`flex h-7 w-7 items-center justify-center rounded ${A.direction==="incoming"?"bg-blue-500/10 text-blue-400":"bg-green-500/10 text-green-400"}`,children:A.direction==="incoming"?e.jsx(Pt,{className:"h-3.5 w-3.5"}):e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium capitalize text-zinc-400",children:A.adapter}),e.jsxs("span",{className:"flex items-center gap-1 text-xs text-zinc-500",children:[e.jsx(vv,{className:"h-3 w-3"}),A.channel]})]}),e.jsx("p",{className:"mt-0.5 truncate text-sm text-zinc-200",children:A.content})]}),e.jsx("span",{className:"flex-shrink-0 text-xs text-zinc-500",children:new Date(A.timestamp).toLocaleTimeString()})]},A.id))})]})]})}const ap=[{label:"Every hour",cron:"0 * * * *"},{label:"Daily at 9am",cron:"0 9 * * *"},{label:"Weekly (Mon 9am)",cron:"0 9 * * 1"},{label:"Monthly (1st, 9am)",cron:"0 9 1 * *"},{label:"Every 15 minutes",cron:"*/15 * * * *"},{label:"Daily at midnight",cron:"0 0 * * *"}];function _N(n){const i=ap.find(d=>d.cron===n);return i?i.label:n}function Zr({label:n,value:i,icon:d}){return e.jsxs("div",{className:"rounded-lg border border-border bg-surface p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-zinc-400",children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:n})]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold text-white",children:i})]})}function UN(){var le;const{t:n}=Je(),[i,d]=u.useState([]),[c,m]=u.useState([]),[f,h]=u.useState(!0),[b,g]=u.useState(null),[p,S]=u.useState(!1),[y,v]=u.useState(""),[k,C]=u.useState("0 9 * * *"),[w,N]=u.useState(""),[z,R]=u.useState(!1),[D,O]=u.useState(!1),[se,Z]=u.useState(null),U=u.useCallback(async()=>{h(!0),g(null);try{const[Y,B]=await Promise.all([ci.list(),la.list({limit:200})]);d(Y.data),m(B.data.map(ne=>({id:ne.id,name:ne.name})))}catch(Y){g(Y instanceof Error?Y.message:"Failed to load scheduler data")}finally{h(!1)}},[]);u.useEffect(()=>{U()},[U]);const A=async()=>{if(!y)return;const Y=z?w:k;if(Y.trim()){O(!0);try{await ci.setSchedule(y,{cron:Y,enabled:!0}),S(!1),v(""),C("0 9 * * *"),N(""),R(!1),U()}catch(B){console.error("Failed to create schedule:",B)}finally{O(!1)}}},F=async Y=>{Z(Y);try{await ci.pauseSchedule(Y),U()}finally{Z(null)}},$=async Y=>{Z(Y);try{await ci.resumeSchedule(Y),U()}finally{Z(null)}},Q=async Y=>{Z(Y);try{await ci.removeSchedule(Y),U()}finally{Z(null)}},ce=i.filter(Y=>Y.status==="active").length,I=i.filter(Y=>Y.status==="paused").length;return f?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-purple-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vs,{className:"h-6 w-6 text-purple-400"}),e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("scheduler.title")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:U,className:"btn-ghost btn-sm",children:e.jsx(xt,{className:"h-4 w-4"})}),e.jsxs("button",{onClick:()=>S(!0),className:"btn-primary",children:[e.jsx(ht,{className:"h-4 w-4"}),n("scheduler.addSchedule")]})]})]}),b&&e.jsxs("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:[b,e.jsx("button",{onClick:U,className:"ml-3 underline",children:n("common.retry")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[e.jsx(Zr,{label:n("scheduler.totalSchedules"),value:i.length,icon:C0}),e.jsx(Zr,{label:n("scheduler.active"),value:ce,icon:Nt}),e.jsx(Zr,{label:n("scheduler.paused"),value:I,icon:tl}),e.jsx(Zr,{label:n("scheduler.nextRun"),value:(le=i.filter(Y=>Y.status==="active"&&Y.nextRun).sort((Y,B)=>new Date(Y.nextRun).getTime()-new Date(B.nextRun).getTime())[0])!=null&&le.nextRun?new Date(i.filter(Y=>Y.status==="active"&&Y.nextRun).sort((Y,B)=>new Date(Y.nextRun).getTime()-new Date(B.nextRun).getTime())[0].nextRun).toLocaleTimeString():"--",icon:L0})]}),i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg border border-border bg-surface py-16",children:[e.jsx(vs,{className:"h-12 w-12 text-zinc-600"}),e.jsx("p",{className:"mt-4 text-sm text-zinc-400",children:n("scheduler.empty")}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:n("scheduler.emptyDesc")}),e.jsxs("button",{onClick:()=>S(!0),className:"btn-primary mt-4",children:[e.jsx(ht,{className:"h-4 w-4"}),n("scheduler.addSchedule")]})]}):e.jsx("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-left text-xs font-medium uppercase tracking-wider text-zinc-500",children:[e.jsx("th",{className:"px-5 py-3",children:n("scheduler.agent")}),e.jsx("th",{className:"px-5 py-3",children:n("scheduler.schedule")}),e.jsx("th",{className:"px-5 py-3",children:n("scheduler.lastRun")}),e.jsx("th",{className:"px-5 py-3",children:n("scheduler.nextRun")}),e.jsx("th",{className:"px-5 py-3",children:n("common.status")}),e.jsx("th",{className:"px-5 py-3 text-right",children:n("common.actions")})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:i.map(Y=>e.jsxs("tr",{className:"group hover:bg-zinc-900/30",children:[e.jsx("td",{className:"px-5 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ts,{className:"h-4 w-4 text-purple-400"}),e.jsx("span",{className:"font-medium text-zinc-200",children:Y.agentName})]})}),e.jsxs("td",{className:"px-5 py-3",children:[e.jsx("code",{className:"rounded bg-zinc-800 px-2 py-0.5 text-xs text-purple-300",children:Y.cron}),e.jsx("p",{className:"mt-0.5 text-[11px] text-zinc-500",children:_N(Y.cron)})]}),e.jsx("td",{className:"px-5 py-3 text-zinc-400",children:Y.lastRun?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs",children:new Date(Y.lastRun).toLocaleString()}),Y.lastDurationMs!==void 0&&e.jsxs("p",{className:"text-[11px] text-zinc-500",children:[(Y.lastDurationMs/1e3).toFixed(1),"s"]})]}):e.jsx("span",{className:"text-xs text-zinc-600",children:"--"})}),e.jsx("td",{className:"px-5 py-3 text-zinc-400 text-xs",children:Y.nextRun?new Date(Y.nextRun).toLocaleString():"--"}),e.jsx("td",{className:"px-5 py-3",children:e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${Y.status==="active"?"bg-green-500/10 text-green-400":"bg-zinc-500/10 text-zinc-400"}`,children:Y.status==="active"?n("scheduler.active"):n("scheduler.paused")})}),e.jsx("td",{className:"px-5 py-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[Y.status==="active"?e.jsx("button",{onClick:()=>F(Y.agentId),disabled:se===Y.agentId,className:"btn-ghost btn-sm text-amber-400",title:n("scheduler.pause"),children:e.jsx(tl,{className:"h-3.5 w-3.5"})}):e.jsx("button",{onClick:()=>$(Y.agentId),disabled:se===Y.agentId,className:"btn-ghost btn-sm text-green-400",title:n("scheduler.resume"),children:e.jsx(Nt,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>Q(Y.agentId),disabled:se===Y.agentId,className:"btn-ghost btn-sm text-red-400",title:n("common.delete"),children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})]})})]},Y.id))})]})}),i.some(Y=>Y.runHistory&&Y.runHistory.length>0)&&e.jsxs("div",{className:"rounded-lg border border-border bg-surface",children:[e.jsx("div",{className:"border-b border-border px-5 py-3",children:e.jsx("h2",{className:"text-sm font-medium text-zinc-300",children:n("scheduler.runHistory")})}),e.jsx("div",{className:"divide-y divide-border",children:i.flatMap(Y=>(Y.runHistory||[]).map(B=>({...B,agentName:Y.agentName}))).sort((Y,B)=>new Date(B.startedAt).getTime()-new Date(Y.startedAt).getTime()).slice(0,10).map(Y=>e.jsxs("div",{className:"flex items-center gap-4 px-5 py-3",children:[e.jsx("span",{className:`inline-flex h-2 w-2 rounded-full ${Y.status==="completed"?"bg-green-400":Y.status==="failed"?"bg-red-400":"bg-amber-400"}`}),e.jsx("span",{className:"text-sm font-medium text-zinc-200",children:Y.agentName}),e.jsx("span",{className:"text-xs text-zinc-500",children:new Date(Y.startedAt).toLocaleString()}),e.jsxs("span",{className:"text-xs text-zinc-400",children:[(Y.durationMs/1e3).toFixed(1),"s"]}),Y.costUsd>0&&e.jsxs("span",{className:"text-xs text-zinc-500",children:["$",Y.costUsd.toFixed(4)]}),e.jsx("span",{className:`ml-auto text-xs font-medium ${Y.status==="completed"?"text-green-400":Y.status==="failed"?"text-red-400":"text-amber-400"}`,children:Y.status})]},Y.runId))})]}),p&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-border bg-surface p-6 shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsx("h2",{className:"text-lg font-semibold text-white",children:n("scheduler.addSchedule")}),e.jsx("button",{onClick:()=>S(!1),className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("scheduler.agent")}),e.jsxs("select",{value:y,onChange:Y=>v(Y.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-white focus:border-purple-500 focus:outline-none",children:[e.jsx("option",{value:"",children:n("scheduler.selectAgent")}),c.map(Y=>e.jsx("option",{value:Y.id,children:Y.name},Y.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"label",children:n("scheduler.schedule")}),!z&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ap.map(Y=>e.jsxs("button",{onClick:()=>C(Y.cron),className:`rounded-lg border p-2 text-left text-xs transition-all ${k===Y.cron?"border-purple-500/50 bg-purple-500/10 text-purple-300":"border-border/50 bg-zinc-900/60 text-zinc-400 hover:border-purple-500/30"}`,children:[e.jsx("p",{className:"font-medium",children:Y.label}),e.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-zinc-500",children:Y.cron})]},Y.cron))}),e.jsx("button",{onClick:()=>R(!z),className:"mt-2 text-xs text-zinc-500 hover:text-zinc-300 underline",children:n(z?"scheduler.usePreset":"scheduler.useCustom")}),z&&e.jsx("input",{type:"text",value:w,onChange:Y=>N(Y.target.value),placeholder:"*/15 * * * *",className:"mt-2 w-full rounded-lg border border-border bg-surface px-3 py-2 font-mono text-sm text-white placeholder:text-zinc-500 focus:border-purple-500 focus:outline-none"})]})]}),e.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[e.jsx("button",{onClick:()=>S(!1),className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:A,disabled:!y||D,className:"btn-primary",children:n(D?"common.loading":"scheduler.addSchedule")})]})]})})]})}function $N({value:n}){const i=Math.round(n*100),d=i>=80?"bg-green-500":i>=50?"bg-amber-500":"bg-red-500";return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-16 rounded-full bg-zinc-700",children:e.jsx("div",{className:`h-full rounded-full ${d}`,style:{width:`${i}%`}})}),e.jsxs("span",{className:"text-xs text-zinc-500",children:[i,"%"]})]})}function oi({label:n,value:i,icon:d,color:c}){return e.jsxs("div",{className:"rounded-lg border border-border bg-surface p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-zinc-400",children:[e.jsx(d,{className:`h-4 w-4 ${c??""}`}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider",children:n})]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold text-white",children:i})]})}function BN(){const{t:n}=Je(),[i,d]=u.useState([]),[c,m]=u.useState(null),[f,h]=u.useState(!0),[b,g]=u.useState(null),[p,S]=u.useState(""),[y,v]=u.useState(null),[k,C]=u.useState(!1),[w,N]=u.useState(""),[z,R]=u.useState(""),[D,O]=u.useState(null),se=u.useCallback(async()=>{h(!0),g(null);try{const $=await Br.candidates({status:p||void 0,limit:100});d($.data),m($.meta)}catch($){g($ instanceof Error?$.message:"Failed to load evolve data")}finally{h(!1)}},[p]);u.useEffect(()=>{se()},[se]);const Z=async $=>{O($);try{await Br.approve($),se()}finally{O(null)}},U=async $=>{O($);try{await Br.reject($),se()}finally{O(null)}},A=async()=>{if(y){O(y.id);try{await Br.update(y.id,{name:z,skillContent:w}),C(!1),v(null),se()}finally{O(null)}}},F=$=>{v($),R($.name),N($.skillContent),C(!1)};return f?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-purple-500 border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pr,{className:"h-6 w-6 text-purple-400"}),e.jsx("h1",{className:"text-2xl font-semibold text-white",children:n("evolve.title")})]}),e.jsxs("button",{onClick:se,className:"btn-ghost btn-sm",children:[e.jsx(xt,{className:"h-4 w-4"}),n("common.retry")]})]}),b&&e.jsx("div",{className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:b}),c&&e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-5",children:[e.jsx(oi,{label:n("evolve.totalCandidates"),value:c.total,icon:Pr,color:"text-purple-400"}),e.jsx(oi,{label:n("evolve.pending"),value:c.pending,icon:el,color:"text-amber-400"}),e.jsx(oi,{label:n("evolve.approved"),value:c.approved,icon:et,color:"text-green-400"}),e.jsx(oi,{label:n("evolve.rejected"),value:c.rejected,icon:ft,color:"text-red-400"}),e.jsx(oi,{label:n("evolve.avgConfidence"),value:`${Math.round(c.avgConfidence*100)}%`,icon:oc,color:"text-blue-400"})]}),e.jsx("div",{className:"flex gap-2",children:["","pending","approved","rejected"].map($=>e.jsx("button",{onClick:()=>S($),className:`rounded-lg px-3 py-1.5 text-xs font-medium transition-colors ${p===$?"bg-purple-500/20 text-purple-300":"bg-zinc-800/50 text-zinc-400 hover:text-zinc-200"}`,children:n($===""?"evolve.all":$==="pending"?"evolve.pending":$==="approved"?"evolve.approved":"evolve.rejected")},$))}),i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center rounded-lg border border-border bg-surface py-16",children:[e.jsx(Pr,{className:"h-12 w-12 text-zinc-600"}),e.jsx("p",{className:"mt-4 text-sm text-zinc-400",children:n("evolve.empty")}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:n("evolve.emptyDesc")})]}):e.jsx("div",{className:"space-y-3",children:i.map($=>e.jsx("div",{className:"group rounded-lg border border-border bg-surface p-4 transition-colors hover:border-purple-500/20",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("h3",{className:"font-medium text-zinc-200",children:$.name}),e.jsx($N,{value:$.confidence}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${$.status==="pending"?"bg-amber-500/10 text-amber-400":$.status==="approved"?"bg-green-500/10 text-green-400":"bg-red-500/10 text-red-400"}`,children:$.status})]}),e.jsx("p",{className:"mt-1 text-sm text-zinc-400",children:$.description}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] text-zinc-500",children:[n("evolve.source"),": ",$.sourceMission]}),e.jsx("span",{className:"text-[11px] text-zinc-600",children:new Date($.createdAt).toLocaleDateString()}),$.tags.length>0&&e.jsx("div",{className:"flex gap-1",children:$.tags.map(Q=>e.jsx("span",{className:"rounded bg-zinc-800 px-1.5 py-0.5 text-[10px] text-zinc-400",children:Q},Q))})]})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>F($),className:"btn-ghost btn-sm",title:n("evolve.preview"),children:e.jsx(el,{className:"h-3.5 w-3.5"})}),$.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>{F($),C(!0)},className:"btn-ghost btn-sm text-blue-400",title:n("evolve.edit"),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>Z($.id),disabled:D===$.id,className:"btn-ghost btn-sm text-green-400",title:n("evolve.approve"),children:e.jsx(et,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>U($.id),disabled:D===$.id,className:"btn-ghost btn-sm text-red-400",title:n("evolve.reject"),children:e.jsx(ft,{className:"h-3.5 w-3.5"})})]})]})]})},$.id))}),y&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:e.jsxs("div",{className:"w-full max-w-3xl rounded-2xl border border-border bg-surface p-6 shadow-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[k?e.jsx("input",{value:z,onChange:$=>R($.target.value),className:"bg-transparent text-lg font-semibold text-white border-b border-purple-500 focus:outline-none"}):e.jsx("h2",{className:"text-lg font-semibold text-white",children:y.name}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:[n("evolve.source"),": ",y.sourceMission," | ",n("evolve.confidence"),": ",Math.round(y.confidence*100),"%"]})]}),e.jsx("button",{onClick:()=>{v(null),C(!1)},className:"btn-ghost btn-sm",children:e.jsx(Ze,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"rounded-lg border border-border bg-zinc-900/50 p-4",children:[e.jsx("p",{className:"mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500",children:"SKILL.md"}),k?e.jsx("textarea",{value:w,onChange:$=>N($.target.value),className:"w-full min-h-[300px] bg-transparent font-mono text-sm text-zinc-200 resize-y focus:outline-none"}):e.jsx("pre",{className:"whitespace-pre-wrap font-mono text-sm text-zinc-200 leading-relaxed max-h-[400px] overflow-y-auto",children:y.skillContent})]}),e.jsx("div",{className:"mt-4 flex justify-end gap-3",children:k?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>C(!1),className:"btn-secondary",children:n("common.cancel")}),e.jsx("button",{onClick:A,disabled:D===y.id,className:"btn-primary",children:n("common.save")})]}):y.status==="pending"?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>C(!0),className:"btn-secondary",children:[e.jsx(pi,{className:"h-4 w-4"}),n("evolve.edit")]}),e.jsxs("button",{onClick:()=>U(y.id),disabled:D===y.id,className:"rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm font-medium text-red-400 hover:bg-red-500/20",children:[e.jsx(ft,{className:"mr-1.5 inline h-4 w-4"}),n("evolve.reject")]}),e.jsxs("button",{onClick:()=>Z(y.id),disabled:D===y.id,className:"btn-primary",children:[e.jsx(et,{className:"mr-1.5 inline h-4 w-4"}),n("evolve.approve")]})]}):e.jsx("button",{onClick:()=>v(null),className:"btn-secondary",children:n("common.close")})})]})})]})}function HN({children:n}){const[i,d]=u.useState(!1),c=Dt(),m=js();return u.useEffect(()=>{if(m.pathname==="/onboarding"){d(!0);return}if(localStorage.getItem("nestor_onboarding_complete")==="true"||localStorage.getItem("nestor_onboarded")==="true"){d(!0);return}la.list().then(f=>{!f.data||f.data.length===0?c("/onboarding"):localStorage.setItem("nestor_onboarding_complete","true"),d(!0)}).catch(()=>d(!0))},[m.pathname,c]),i?e.jsx(e.Fragment,{children:n}):e.jsx("div",{className:"flex items-center justify-center h-screen bg-background",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-purple-500 border-t-transparent"})})}function He(n){return e.jsx(gj,{fallback:e.jsx(bj,{}),children:n})}function qN(){const{user:n,loading:i}=ol();return i?e.jsx("div",{className:"flex h-screen items-center justify-center bg-background text-zinc-400",children:"Loading..."}):n?e.jsx(HN,{children:e.jsxs(y0,{children:[e.jsx(Me,{path:"/onboarding",element:e.jsx(MN,{})}),e.jsxs(Me,{element:e.jsx(pj,{}),children:[e.jsx(Me,{path:"/",element:e.jsx(_h,{to:"/missions",replace:!0})}),e.jsx(Me,{path:"/missions",element:He(e.jsx(zN,{}))}),e.jsx(Me,{path:"/chat",element:He(e.jsx(bN,{}))}),e.jsx(Me,{path:"/dashboard",element:He(e.jsx(Nj,{}))}),e.jsx(Me,{path:"/agents",element:He(e.jsx(Aj,{}))}),e.jsx(Me,{path:"/agents/:id",element:He(e.jsx(Oj,{}))}),e.jsx(Me,{path:"/agents/:id/prompts",element:He(e.jsx(S1,{}))}),e.jsx(Me,{path:"/agents/:id/memory-store",element:He(e.jsx(W1,{}))}),e.jsx(Me,{path:"/workflows",element:He(e.jsx($j,{}))}),e.jsx(Me,{path:"/workflows/:id/edit",element:He(e.jsx(Hj,{}))}),e.jsx(Me,{path:"/skills",element:He(e.jsx(Kj,{}))}),e.jsx(Me,{path:"/runs",element:He(e.jsx(Vj,{}))}),e.jsx(Me,{path:"/runs/:id",element:He(e.jsx(e1,{}))}),e.jsx(Me,{path:"/goals",element:He(e.jsx(B1,{}))}),e.jsx(Me,{path:"/approvals",element:He(e.jsx(l1,{}))}),e.jsx(Me,{path:"/handoffs",element:He(e.jsx(H1,{}))}),e.jsx(Me,{path:"/analytics",element:He(e.jsx(g1,{}))}),e.jsx(Me,{path:"/budget",element:He(e.jsx(O1,{}))}),e.jsx(Me,{path:"/traces",element:He(e.jsx(N1,{}))}),e.jsx(Me,{path:"/memory",element:He(e.jsx(E1,{}))}),e.jsx(Me,{path:"/users",element:He(e.jsx(w1,{}))}),e.jsx(Me,{path:"/plans",element:He(e.jsx(Y1,{}))}),e.jsx(Me,{path:"/plans/:id",element:He(e.jsx(X1,{}))}),e.jsx(Me,{path:"/guardrails",element:He(e.jsx(P1,{}))}),e.jsx(Me,{path:"/messaging",element:He(e.jsx(LN,{}))}),e.jsx(Me,{path:"/scheduler",element:He(e.jsx(UN,{}))}),e.jsx(Me,{path:"/evolve",element:He(e.jsx(BN,{}))}),e.jsx(Me,{path:"/admin",element:He(e.jsx(dN,{}))}),e.jsx(Me,{path:"/settings",element:He(e.jsx(t1,{}))}),e.jsx(Me,{path:"/keys",element:He(e.jsx(RN,{}))}),e.jsx(Me,{path:"*",element:e.jsx(_h,{to:"/missions",replace:!0})})]})]})}):e.jsx(X0,{})}function GN(){return e.jsx(Xv,{children:e.jsx(Jv,{children:e.jsxs(y0,{children:[e.jsx(Me,{path:"/login",element:e.jsx(X0,{})}),e.jsx(Me,{path:"/*",element:e.jsx(qN,{})})]})})})}const np=document.getElementById("root");if(!np)throw new Error("Root element not found");Eb.createRoot(np).render(e.jsx(u.StrictMode,{children:e.jsx(Wy,{children:e.jsx(GN,{})})}));
607
- //# sourceMappingURL=index-BaEZS9kE.js.map
607
+ //# sourceMappingURL=index-CW3V4jSR.js.map