/** * Pi-SuperIntel - Autonomous Self-Extending Universal Agent * * Core Capabilities: * 1. Task Analysis - Break down any task into components * 2. Capability Assessment - Check what's needed vs. what's available * 3. Research & Discovery - Find tools, extensions, or knowledge gaps * 4. Self-Extension - Install packages, create skills, spawn agents * 5. Execution & Orchestration - Complete tasks using acquired capabilities * 6. Learning & Persistence - Save successful patterns for reuse */ import { spawn } from "node:child_process"; import * as fs from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; import { StringEnum } from "@mariozechner/pi-ai"; import { type ExtensionAPI, } from "@mariozechner/pi-coding-agent"; import { Type } from "@sinclair/typebox"; // ============================================================================= // Configuration & Constants // ============================================================================= const SUPERINTEL_DIR = path.join(os.homedir(), ".superintel"); const CAPABILITIES_FILE = "capabilities.json"; const EXECUTION_LOG_FILE = "execution-log.json"; const AUTOPILOT_FILE = "autopilot.json"; // ============================================================================= // Core Types // ============================================================================= interface Capability { name: string; description: string; type: "builtin" | "extension" | "skill" | "tool" | "agent"; available: boolean; confidence: number; // 0-1 installCommand?: string; source?: string; lastUsed?: string; successRate?: number; } interface TaskAnalysis { task: string; complexity: "simple" | "moderate" | "complex" | "unknown"; components: string[]; requiredCapabilities: string[]; estimatedSteps: number; risks: string[]; researchNeeded: boolean; } interface ExecutionPlan { id: string; task: string; strategy: "direct" | "research-first" | "acquire-capabilities" | "multi-agent" | "workflow"; steps: PlanStep[]; capabilitiesToAcquire: string[]; fallbackStrategies: string[]; estimatedDuration: string; } interface PlanStep { id: string; description: string; action: string; capabilities: string[]; dependencies: string[]; estimatedDuration: string; canFail: boolean; fallback?: string; } interface ExecutionResult { success: boolean; output?: string; error?: string; stepsCompleted: number; totalSteps: number; capabilitiesUsed: string[]; newCapabilitiesAcquired: string[]; lessons?: string[]; artifacts?: string[]; } interface ResearchResult { topic: string; findings: string[]; sources: string[]; confidence: number; recommendations: string[]; } // ============================================================================= // Core Engine - The Autonomous Brain // ============================================================================= class SuperIntelEngine { private capabilities: Map = new Map(); private workspaceDir: string; private pi: ExtensionAPI; constructor(pi: ExtensionAPI) { this.pi = pi; this.workspaceDir = SUPERINTEL_DIR; } async initialize(): Promise { await this.ensureWorkspace(); await this.loadCapabilities(); await this.scanExistingTools(); } private async ensureWorkspace(): Promise { await fs.mkdir(this.workspaceDir, { recursive: true }); await fs.mkdir(path.join(this.workspaceDir, "skills"), { recursive: true }); await fs.mkdir(path.join(this.workspaceDir, "workflows"), { recursive: true }); await fs.mkdir(path.join(this.workspaceDir, "research"), { recursive: true }); await fs.mkdir(path.join(this.workspaceDir, "logs"), { recursive: true }); } private async loadCapabilities(): Promise { try { const capPath = path.join(this.workspaceDir, CAPABILITIES_FILE); const data = await fs.readFile(capPath, "utf-8"); const caps = JSON.parse(data); for (const cap of caps) { this.capabilities.set(cap.name, cap); } } catch { // Initialize with default capabilities await this.initializeDefaultCapabilities(); } } private async initializeDefaultCapabilities(): Promise { const defaults: Capability[] = [ // Core Built-in Capabilities { name: "file-operations", description: "Read, write, edit files", type: "builtin", available: true, confidence: 1.0, }, { name: "bash-execution", description: "Execute shell commands", type: "builtin", available: true, confidence: 1.0, }, { name: "code-analysis", description: "Analyze code, find patterns", type: "builtin", available: true, confidence: 0.9, }, { name: "system-administration", description: "System configuration, user management, service control", type: "builtin", available: true, confidence: 0.9, }, { name: "network-operations", description: "Network configuration, diagnostics, monitoring", type: "builtin", available: true, confidence: 0.85, }, // Extension-Based Capabilities { name: "web-research", description: "Search web for information", type: "extension", available: false, confidence: 0, installCommand: "pi install npm:pi-exa-search", source: "npm", }, { name: "multi-agent-orchestration", description: "Spawn and coordinate multiple agents", type: "extension", available: false, confidence: 0, installCommand: "pi install npm:pi-codemachine", source: "npm", }, { name: "email-operations", description: "Read, compose, send emails", type: "extension", available: false, confidence: 0, installCommand: "pi install npm:@e9n/pi-gmail", source: "npm", }, { name: "subtask-delegation", description: "Delegate complex subtasks to child agents", type: "tool", available: false, confidence: 0, installCommand: "pi install npm:@mariozechner/pi-rlm-query", source: "npm", }, { name: "web-server", description: "Serve web applications and APIs", type: "extension", available: false, confidence: 0, installCommand: "pi install npm:@e9n/pi-webserver", source: "npm", }, // Cybersecurity & Penetration Testing { name: "penetration-testing", description: "Comprehensive web app and API security assessment", type: "skill", available: false, confidence: 0, }, { name: "vulnerability-assessment", description: "Identify security vulnerabilities and misconfigurations", type: "skill", available: false, confidence: 0, }, { name: "security-testing", description: "Security testing and assessment", type: "skill", available: false, confidence: 0, }, { name: "authorization-testing", description: "Test access controls and authorization bypass", type: "skill", available: false, confidence: 0, }, { name: "injection-testing", description: "SQL, command, and code injection testing", type: "skill", available: false, confidence: 0, }, { name: "code-signing", description: "Sign executables and applications for distribution", type: "skill", available: false, confidence: 0, }, { name: "malware-analysis", description: "Analyze suspicious files and behaviors", type: "skill", available: false, confidence: 0, }, // Cloud & Infrastructure { name: "aws-operations", description: "AWS EC2, S3, Lambda, IAM, CloudFormation management", type: "skill", available: false, confidence: 0, }, { name: "azure-operations", description: "Azure VMs, Storage, Functions, ARM templates", type: "skill", available: false, confidence: 0, }, { name: "gcp-operations", description: "Google Cloud Compute, Storage, Cloud Functions", type: "skill", available: false, confidence: 0, }, { name: "kubernetes-operations", description: "K8s cluster management, deployments, troubleshooting", type: "skill", available: false, confidence: 0, }, { name: "docker-operations", description: "Container management, image building, registries", type: "skill", available: false, confidence: 0, }, { name: "terraform-operations", description: "Infrastructure as Code with Terraform", type: "skill", available: false, confidence: 0, }, { name: "ansible-operations", description: "Configuration management with Ansible", type: "skill", available: false, confidence: 0, }, // Database Operations { name: "database-administration", description: "Database setup, optimization, backup, recovery", type: "skill", available: false, confidence: 0, }, { name: "sql-operations", description: "SQL database management (PostgreSQL, MySQL, SQLite)", type: "skill", available: false, confidence: 0, }, { name: "nosql-operations", description: "NoSQL database management (MongoDB, Redis, DynamoDB)", type: "skill", available: false, confidence: 0, }, { name: "data-migration", description: "Database migration and data transformation", type: "skill", available: false, confidence: 0, }, // DevOps & CI/CD { name: "ci-cd-pipelines", description: "Build and deployment automation", type: "skill", available: false, confidence: 0, }, { name: "github-actions", description: "GitHub Actions workflow creation and management", type: "skill", available: false, confidence: 0, }, { name: "jenkins-operations", description: "Jenkins pipeline and job management", type: "skill", available: false, confidence: 0, }, { name: "monitoring-setup", description: "Setup Prometheus, Grafana, logging, alerting", type: "skill", available: false, confidence: 0, }, // Advanced Systems & Networking { name: "firewall-configuration", description: "iptables, ufw, cloud security groups", type: "skill", available: false, confidence: 0, }, { name: "load-balancer-setup", description: "Nginx, HAProxy, cloud load balancers", type: "skill", available: false, confidence: 0, }, { name: "vpn-configuration", description: "WireGuard, OpenVPN, IPSec setup", type: "skill", available: false, confidence: 0, }, { name: "ssl-tls-management", description: "Certificate generation, renewal, configuration", type: "skill", available: false, confidence: 0, }, { name: "dns-management", description: "DNS configuration, records, troubleshooting", type: "skill", available: false, confidence: 0, }, // Automation & Scripting { name: "temporal-workflows", description: "Create durable, scheduled workflows", type: "skill", available: false, confidence: 0, }, { name: "rpa-automation", description: "Robotic Process Automation for web and desktop", type: "skill", available: false, confidence: 0, }, { name: "browser-automation", description: "Automate web browser interactions", type: "skill", available: false, confidence: 0, }, { name: "api-automation", description: "API testing, integration, and automation", type: "skill", available: false, confidence: 0, }, // Specialized Operations { name: "log-analysis", description: "Parse, analyze, and visualize log data", type: "skill", available: false, confidence: 0, }, { name: "performance-tuning", description: "System and application performance optimization", type: "skill", available: false, confidence: 0, }, { name: "disaster-recovery", description: "Backup strategies, failover, recovery procedures", type: "skill", available: false, confidence: 0, }, { name: "compliance-audit", description: "Security compliance checking (SOC2, ISO27001, etc.)", type: "skill", available: false, confidence: 0, }, ]; // ── API Integration Capabilities ──────────────────────────────────────── const apiCaps: Capability[] = [ { name: "rest-api-integration", description: "RESTful API calls with all auth types (Bearer, API Key, OAuth2, Basic, HMAC)", type: "skill", available: true, confidence: 0.95 }, { name: "graphql-operations", description: "GraphQL queries, mutations, subscriptions, introspection, federation", type: "skill", available: true, confidence: 0.9 }, { name: "grpc-operations", description: "gRPC service calls, protobuf schema, streaming, reflection", type: "skill", available: false, confidence: 0 }, { name: "api-testing", description: "API contract testing, load testing, fuzzing, mocking", type: "skill", available: true, confidence: 0.9 }, { name: "webhook-management", description: "Webhook creation, validation, forwarding, retry logic", type: "skill", available: true, confidence: 0.85 }, { name: "openapi-swagger", description: "OpenAPI/Swagger spec parsing, generation, validation, SDK generation", type: "skill", available: true, confidence: 0.9 }, { name: "api-authentication", description: "OAuth2, JWT, API Key, mTLS, HMAC authentication flows", type: "skill", available: true, confidence: 0.9 }, { name: "oauth2-flows", description: "OAuth2 authorization code, PKCE, client credentials, device flows", type: "skill", available: true, confidence: 0.85 }, { name: "websocket-operations", description: "WebSocket connections, real-time messaging, reconnection logic", type: "skill", available: true, confidence: 0.8 }, { name: "soap-xml-operations", description: "SOAP WSDL parsing, XML serialization, enterprise web services", type: "skill", available: true, confidence: 0.75 }, ]; // ── Browser & Web Automation Capabilities ──────────────────────────────── const browserCaps: Capability[] = [ { name: "playwright-automation", description: "Playwright CLI browser automation: navigation, forms, screenshots, testing", type: "skill", available: true, confidence: 0.95 }, { name: "agent-browser-automation", description: "agent-browser CLI: open pages, snapshot, click, fill, extract from any web app", type: "skill", available: true, confidence: 0.95 }, { name: "e2e-testing", description: "End-to-end testing with Playwright/Cypress across browsers", type: "skill", available: true, confidence: 0.9 }, { name: "visual-regression-testing", description: "Screenshot comparison, pixel diffing, visual baseline management", type: "skill", available: true, confidence: 0.8 }, { name: "web-performance-testing", description: "Lighthouse, Core Web Vitals, page speed analysis", type: "skill", available: true, confidence: 0.85 }, { name: "accessibility-testing", description: "WCAG compliance, a11y auditing, screen reader testing", type: "skill", available: true, confidence: 0.85 }, { name: "web-scraping-advanced", description: "Advanced scraping with anti-bot bypass, pagination, structured extraction", type: "skill", available: true, confidence: 0.9 }, { name: "rpa-enterprise", description: "Enterprise RPA: multi-step workflows, OCR, form automation, scheduling", type: "skill", available: true, confidence: 0.9 }, { name: "mitmproxy-analysis", description: "HTTP/HTTPS traffic interception, API discovery, traffic manipulation", type: "skill", available: false, confidence: 0 }, { name: "mobile-web-automation", description: "Mobile browser emulation, responsive testing, touch events", type: "skill", available: true, confidence: 0.8 }, ]; // ── Enterprise Application Capabilities ────────────────────────────────── const enterpriseCaps: Capability[] = [ { name: "salesforce-integration", description: "Salesforce REST/SOQL/SOSL API, CRM data, flows, reports", type: "skill", available: true, confidence: 0.85 }, { name: "jira-integration", description: "Jira REST API, issues, projects, sprints, workflows, webhooks", type: "skill", available: true, confidence: 0.9 }, { name: "confluence-integration", description: "Confluence REST API, pages, spaces, content management", type: "skill", available: true, confidence: 0.85 }, { name: "slack-integration", description: "Slack Bolt/Web API, messages, channels, bots, workflows", type: "skill", available: true, confidence: 0.9 }, { name: "github-integration", description: "GitHub REST/GraphQL API, repos, PRs, Actions, releases, webhooks", type: "skill", available: true, confidence: 0.95 }, { name: "gitlab-integration", description: "GitLab API, projects, CI/CD pipelines, MRs, registries", type: "skill", available: true, confidence: 0.9 }, { name: "servicenow-integration", description: "ServiceNow REST API, ITSM, CMDB, incident management", type: "skill", available: true, confidence: 0.8 }, { name: "microsoft-365-integration", description: "Microsoft Graph API, Teams, SharePoint, OneDrive, Outlook", type: "skill", available: true, confidence: 0.85 }, { name: "google-workspace-integration", description: "Google Workspace APIs: Gmail, Drive, Docs, Sheets, Calendar", type: "skill", available: true, confidence: 0.9 }, { name: "stripe-integration", description: "Stripe API, payments, subscriptions, webhooks, disputes", type: "skill", available: true, confidence: 0.9 }, { name: "twilio-integration", description: "Twilio API, SMS, voice, video, WhatsApp, verify", type: "skill", available: true, confidence: 0.85 }, { name: "sendgrid-integration", description: "SendGrid/email delivery APIs, templates, analytics, suppression", type: "skill", available: true, confidence: 0.85 }, { name: "active-directory", description: "Windows AD, LDAP, user management, group policies, auth", type: "skill", available: false, confidence: 0 }, { name: "sso-saml-oauth", description: "SSO configuration, SAML assertions, OIDC, identity federation", type: "skill", available: true, confidence: 0.8 }, { name: "erp-integration", description: "ERP systems (SAP, Oracle Fusion, NetSuite) API integration", type: "skill", available: true, confidence: 0.7 }, { name: "crm-integration", description: "CRM systems (HubSpot, Zoho, Dynamics 365) API integration", type: "skill", available: true, confidence: 0.8 }, { name: "datadog-integration", description: "Datadog API, metrics, traces, logs, dashboards, alerts", type: "skill", available: true, confidence: 0.85 }, { name: "pagerduty-integration", description: "PagerDuty API, incidents, schedules, escalations", type: "skill", available: true, confidence: 0.85 }, ]; // ── Messaging & Streaming Capabilities ─────────────────────────────────── const messagingCaps: Capability[] = [ { name: "kafka-operations", description: "Apache Kafka: topics, producers, consumers, connectors, streams", type: "skill", available: false, confidence: 0 }, { name: "rabbitmq-operations", description: "RabbitMQ: queues, exchanges, routing, dead letters, federation", type: "skill", available: false, confidence: 0 }, { name: "mqtt-iot-messaging", description: "MQTT broker, IoT device messaging, QoS levels, retained messages", type: "skill", available: false, confidence: 0 }, { name: "redis-pubsub", description: "Redis Pub/Sub, streams, sorted sets, caching patterns", type: "skill", available: false, confidence: 0 }, { name: "celery-task-queue", description: "Celery distributed task queue, scheduling, monitoring", type: "skill", available: false, confidence: 0 }, ]; // ── ML / AI / Data Science Capabilities ────────────────────────────────── const mlCaps: Capability[] = [ { name: "ml-operations", description: "MLOps: model training, evaluation, versioning, deployment, monitoring", type: "skill", available: true, confidence: 0.8 }, { name: "data-engineering", description: "Data pipelines, ETL, dbt, Spark, Airflow orchestration", type: "skill", available: true, confidence: 0.8 }, { name: "llm-integration", description: "OpenAI, Anthropic, Ollama, LangChain, vector stores, RAG pipelines", type: "skill", available: true, confidence: 0.9 }, { name: "vector-database", description: "Pinecone, Weaviate, Chroma, pgvector - embedding search", type: "skill", available: true, confidence: 0.8 }, { name: "data-visualization", description: "Matplotlib, Plotly, Grafana, chart generation, dashboards", type: "skill", available: true, confidence: 0.85 }, { name: "statistical-analysis", description: "Statistical testing, regression, forecasting, pandas, R", type: "skill", available: true, confidence: 0.85 }, ]; // ── Advanced Security Capabilities ──────────────────────────────────────── const advSecCaps: Capability[] = [ { name: "osint-operations", description: "OSINT: social engineering recon, domain intel, person/company research", type: "skill", available: true, confidence: 0.85 }, { name: "threat-intelligence", description: "CTI feeds, IOC enrichment, threat actor profiling, STIX/TAXII", type: "skill", available: true, confidence: 0.8 }, { name: "cryptography-operations", description: "Encryption, key management, PKI, HSM operations, TLS analysis", type: "skill", available: true, confidence: 0.85 }, { name: "reverse-engineering", description: "Binary analysis, decompilation, firmware analysis, deobfuscation", type: "skill", available: false, confidence: 0 }, { name: "forensics", description: "Digital forensics, memory analysis, disk imaging, incident response", type: "skill", available: false, confidence: 0 }, { name: "container-security", description: "Docker image scanning, K8s security policies, Trivy, Falco", type: "skill", available: true, confidence: 0.85 }, { name: "api-security-testing", description: "API pentesting: GraphQL injection, BOLA/IDOR, auth bypass", type: "skill", available: true, confidence: 0.9 }, { name: "devsecops", description: "SAST, DAST, SCA, secrets scanning, SBOM, security pipelines", type: "skill", available: true, confidence: 0.85 }, ]; // ── Advanced Infrastructure Capabilities ────────────────────────────────── const advInfraCaps: Capability[] = [ { name: "service-mesh", description: "Istio/Linkerd: traffic management, mTLS, observability, canary", type: "skill", available: false, confidence: 0 }, { name: "chaos-engineering", description: "Chaos Monkey, Litmus, fault injection, resilience testing", type: "skill", available: false, confidence: 0 }, { name: "ebpf-operations", description: "eBPF programs, kernel tracing, network policies, profiling", type: "skill", available: false, confidence: 0 }, { name: "multi-cloud-operations", description: "Multi-cloud architecture, cross-cloud networking, cost arbitrage", type: "skill", available: true, confidence: 0.75 }, { name: "gitops-operations", description: "ArgoCD, Flux, GitOps workflows, declarative deployments", type: "skill", available: false, confidence: 0 }, { name: "secrets-management", description: "HashiCorp Vault, AWS Secrets Manager, K8s secrets, rotation", type: "skill", available: true, confidence: 0.85 }, { name: "cost-optimization-cloud", description: "Cloud cost analysis, right-sizing, savings plans, waste detection", type: "skill", available: true, confidence: 0.85 }, { name: "cdn-edge-operations", description: "CloudFront, Fastly, Cloudflare - CDN config, edge logic, WAF", type: "skill", available: true, confidence: 0.8 }, ]; // ── Mobile & Cross-Platform Capabilities ────────────────────────────────── const mobileCaps: Capability[] = [ { name: "mobile-testing", description: "Appium, Detox, XCTest - iOS/Android app testing automation", type: "skill", available: false, confidence: 0 }, { name: "react-native-automation", description: "React Native app automation, deep linking, push notification testing", type: "skill", available: false, confidence: 0 }, ]; // ── IoT & Embedded Capabilities ─────────────────────────────────────────── const iotCaps: Capability[] = [ { name: "iot-operations", description: "IoT device management, MQTT, AWS IoT, fleet provisioning, OTA", type: "skill", available: false, confidence: 0 }, { name: "edge-computing", description: "Edge deployment, K3s, Balena, AWS Greengrass, Cloudflare Workers", type: "skill", available: false, confidence: 0 }, ]; // ── Protocol & Network Deep Capabilities ────────────────────────────────── const protocolCaps: Capability[] = [ { name: "protocol-analysis", description: "Wireshark/tshark, pcap analysis, protocol reverse engineering", type: "skill", available: false, confidence: 0 }, { name: "network-scanning", description: "nmap, masscan, asset discovery, port scanning, fingerprinting", type: "skill", available: true, confidence: 0.85 }, { name: "proxy-operations", description: "Reverse proxy config, mitmproxy interception, traffic replay", type: "skill", available: true, confidence: 0.85 }, ]; // ── Document & Content Capabilities ─────────────────────────────────────── const docCaps: Capability[] = [ { name: "document-processing", description: "PDF, DOCX, XLSX, PPTX generation, editing, OCR, form filling", type: "skill", available: true, confidence: 0.9 }, { name: "pdf-operations", description: "PDF creation, merging, splitting, form filling, text extraction", type: "skill", available: true, confidence: 0.9 }, { name: "spreadsheet-operations", description: "Excel/CSV/TSV creation, formulas, charts, data analysis", type: "skill", available: true, confidence: 0.9 }, ]; // Merge all new caps const allNewCaps = [ ...apiCaps, ...browserCaps, ...enterpriseCaps, ...messagingCaps, ...mlCaps, ...advSecCaps, ...advInfraCaps, ...mobileCaps, ...iotCaps, ...protocolCaps, ...docCaps, ]; for (const cap of allNewCaps) { defaults.push(cap); } for (const cap of defaults) { this.capabilities.set(cap.name, cap); } await this.saveCapabilities(); } private async scanExistingTools(): Promise { // Check what extensions are already installed const settingsPath = path.join(os.homedir(), ".pi/agent/settings.json"); try { const settings = JSON.parse(await fs.readFile(settingsPath, "utf-8")); const packages = settings.packages || []; // Update capability availability based on installed packages for (const pkg of packages) { if (pkg.includes("pi-exa-search")) { this.updateCapability("web-research", { available: true, confidence: 0.9 }); } if (pkg.includes("pi-codemachine")) { this.updateCapability("multi-agent-orchestration", { available: true, confidence: 0.9 }); } if (pkg.includes("pi-gmail")) { this.updateCapability("email-operations", { available: true, confidence: 0.9 }); } if (pkg.includes("pi-rlm-query")) { this.updateCapability("subtask-delegation", { available: true, confidence: 0.9 }); } } // Check for existing skills const skillsDir = path.join(os.homedir(), ".pi/agent/skills"); try { const skills = await fs.readdir(skillsDir); for (const skill of skills) { const skillPath = path.join(skillsDir, skill); const stat = await fs.stat(skillPath); if (stat.isDirectory()) { // This is a skill - add to capabilities this.addCapability({ name: skill, description: `Custom skill: ${skill}`, type: "skill", available: true, confidence: 0.8, source: "user", }); } } } catch { // Skills directory might not exist } await this.saveCapabilities(); } catch { // Settings file might not exist } } async saveCapabilities(): Promise { const capPath = path.join(this.workspaceDir, CAPABILITIES_FILE); const caps = Array.from(this.capabilities.values()); await fs.writeFile(capPath, JSON.stringify(caps, null, 2)); } private updateCapability(name: string, updates: Partial): void { const cap = this.capabilities.get(name); if (cap) { Object.assign(cap, updates); } } private addCapability(cap: Capability): void { this.capabilities.set(cap.name, cap); } // =========================================================================== // Core Methods - The Autonomous Loop // =========================================================================== async analyzeTask(task: string): Promise { const analysis: TaskAnalysis = { task, complexity: "unknown", components: [], requiredCapabilities: [], estimatedSteps: 0, risks: [], researchNeeded: false, }; const t = task.toLowerCase(); // ── Real complexity analysis ───────────────────────────────────────────── // Count complexity signals, not string length const complexSignals = [ t.includes("multiple") || t.includes("several"), t.includes("integrate") || t.includes("integration"), t.includes("migrate") || t.includes("migration"), t.includes("pipeline") || t.includes("workflow"), t.includes("cluster") || t.includes("distributed"), t.includes("zero downtime") || t.includes("no downtime"), t.includes("multi") || t.includes("cross-"), t.includes("automate") || t.includes("schedule"), ].filter(Boolean).length; const simpleSignals = [ t.includes("list") || t.includes("show") || t.includes("display"), t.includes("check") || t.includes("status"), t.includes("simple") || t.includes("quick") || t.includes("basic"), ].filter(Boolean).length; if (complexSignals >= 3 || t.length > 300) { analysis.complexity = "complex"; } else if (complexSignals >= 1 || t.length > 100) { analysis.complexity = "moderate"; } else if (simpleSignals >= 1 || t.length <= 60) { analysis.complexity = "simple"; } else { analysis.complexity = "moderate"; } // ── Populate components ────────────────────────────────────────────────── const componentPatterns: [RegExp, string][] = [ [/\bapi\b|\brendpoint\b/i, "API integration"], [/\bauth(entication|orization)?\b/i, "Authentication"], [/\bdatabase\b|\bdb\b|\bsql\b/i, "Database"], [/\btest(ing)?\b|\bspec\b/i, "Testing"], [/\bdeploy(ment)?\b|\brelease\b/i, "Deployment"], [/\bmonitor(ing)?\b|\bmetric\b/i, "Monitoring"], [/\bsecurity\b|\bpentest\b|\baudit\b/i, "Security"], [/\bdocker\b|\bcontainer\b|\bk8s\b|\bkubernetes\b/i, "Containerisation"], [/\bci\/cd\b|\bpipeline\b|\bgithub actions\b/i, "CI/CD"], [/\bmigrat(e|ion)\b/i, "Migration"], [/\bdocument(ation)?\b|\breadme\b/i, "Documentation"], [/\bnotif(y|ication)\b|\balert\b|\bemail\b/i, "Notifications"], ]; for (const [re, label] of componentPatterns) { if (re.test(task)) analysis.components.push(label); } // ── Populate risks ─────────────────────────────────────────────────────── if (t.includes("production") || t.includes("prod ")) analysis.risks.push("Operates in production environment"); if (t.includes("migrate") || t.includes("migration")) analysis.risks.push("Data migration may cause data loss if not tested"); if (t.includes("delete") || t.includes("drop ") || t.includes("remove")) analysis.risks.push("Destructive operation — verify before executing"); if (t.includes("secret") || t.includes("password") || t.includes("credential")) analysis.risks.push("Credential handling — ensure secrets are not logged"); if (t.includes("public") || t.includes("0.0.0.0") || t.includes("open port")) analysis.risks.push("Network exposure risk"); if (t.includes("root") || t.includes("sudo") || t.includes("admin")) analysis.risks.push("Elevated privileges required"); // ── Research needed ────────────────────────────────────────────────────── analysis.researchNeeded = ( t.includes("research") || t.includes("analyse") || t.includes("analyze") || t.includes("investigate") || t.includes("compare") || t.includes("evaluate") || t.includes("best practice") || t.includes("recommend") || t.includes("survey") ); // Extract potential capabilities needed const lowerTask = task.toLowerCase(); // Communication & Collaboration if (lowerTask.includes("email") || lowerTask.includes("mail")) { analysis.requiredCapabilities.push("email-operations"); } // Research & Information Gathering if (lowerTask.includes("research") || lowerTask.includes("search") || lowerTask.includes("find")) { analysis.requiredCapabilities.push("web-research"); analysis.researchNeeded = true; } // Multi-Agent & Orchestration if (lowerTask.includes("multiple") || lowerTask.includes("parallel") || lowerTask.includes("team")) { analysis.requiredCapabilities.push("multi-agent-orchestration"); } if (lowerTask.includes("complex") || lowerTask.includes("large") || lowerTask.includes("many files")) { analysis.requiredCapabilities.push("subtask-delegation"); } // Scheduling & Workflows if (lowerTask.includes("schedule") || lowerTask.includes("daily") || lowerTask.includes("weekly") || lowerTask.includes("recurring")) { analysis.requiredCapabilities.push("temporal-workflows"); } if (lowerTask.includes("workflow") || lowerTask.includes("pipeline") || lowerTask.includes("automation")) { analysis.requiredCapabilities.push("temporal-workflows"); } // Web & Browser if (lowerTask.includes("browser") || lowerTask.includes("website") || lowerTask.includes("web page") || lowerTask.includes("scrape")) { analysis.requiredCapabilities.push("browser-automation"); } if (lowerTask.includes("rpa") || lowerTask.includes("robotic process") || lowerTask.includes("automate login")) { analysis.requiredCapabilities.push("rpa-automation"); } // Code Signing & Distribution if (lowerTask.includes("sign") || lowerTask.includes("certificate") || lowerTask.includes("notarize")) { analysis.requiredCapabilities.push("code-signing"); } // Cybersecurity & Penetration Testing if (lowerTask.includes("security") || lowerTask.includes("pentest") || lowerTask.includes("penetration")) { analysis.requiredCapabilities.push("security-testing"); analysis.requiredCapabilities.push("penetration-testing"); } if (lowerTask.includes("vulnerability") || lowerTask.includes("cve") || lowerTask.includes("exploit")) { analysis.requiredCapabilities.push("vulnerability-assessment"); } if (lowerTask.includes("auth") || lowerTask.includes("authorization") || lowerTask.includes("access control")) { analysis.requiredCapabilities.push("authorization-testing"); } if (lowerTask.includes("sql injection") || lowerTask.includes("command injection") || lowerTask.includes("xss")) { analysis.requiredCapabilities.push("injection-testing"); } if (lowerTask.includes("malware") || lowerTask.includes("virus") || lowerTask.includes("trojan")) { analysis.requiredCapabilities.push("malware-analysis"); } if (lowerTask.includes("compliance") || lowerTask.includes("soc2") || lowerTask.includes("iso27001")) { analysis.requiredCapabilities.push("compliance-audit"); } // Cloud Operations if (lowerTask.includes("aws") || lowerTask.includes("amazon") || lowerTask.includes("ec2") || lowerTask.includes("s3")) { analysis.requiredCapabilities.push("aws-operations"); } if (lowerTask.includes("azure") || lowerTask.includes("microsoft cloud")) { analysis.requiredCapabilities.push("azure-operations"); } if (lowerTask.includes("gcp") || lowerTask.includes("google cloud") || lowerTask.includes("firebase")) { analysis.requiredCapabilities.push("gcp-operations"); } if (lowerTask.includes("lambda") || lowerTask.includes("serverless")) { analysis.requiredCapabilities.push("aws-operations"); } if (lowerTask.includes("cloud") || lowerTask.includes("infrastructure")) { analysis.requiredCapabilities.push("aws-operations"); // Default to AWS if just "cloud" } // Container & Orchestration if (lowerTask.includes("kubernetes") || lowerTask.includes("k8s") || lowerTask.includes("helm")) { analysis.requiredCapabilities.push("kubernetes-operations"); } if (lowerTask.includes("docker") || lowerTask.includes("container")) { analysis.requiredCapabilities.push("docker-operations"); } // Infrastructure as Code if (lowerTask.includes("terraform") || lowerTask.includes("iac")) { analysis.requiredCapabilities.push("terraform-operations"); } if (lowerTask.includes("ansible") || lowerTask.includes("configuration management")) { analysis.requiredCapabilities.push("ansible-operations"); } // Database Operations if (lowerTask.includes("database") || lowerTask.includes("db") || lowerTask.includes("postgres") || lowerTask.includes("mysql")) { analysis.requiredCapabilities.push("database-administration"); analysis.requiredCapabilities.push("sql-operations"); } if (lowerTask.includes("mongodb") || lowerTask.includes("redis") || lowerTask.includes("dynamodb")) { analysis.requiredCapabilities.push("nosql-operations"); } if (lowerTask.includes("migration") || lowerTask.includes("etl")) { analysis.requiredCapabilities.push("data-migration"); } // CI/CD & DevOps if (lowerTask.includes("ci/cd") || lowerTask.includes("pipeline") || lowerTask.includes("deployment")) { analysis.requiredCapabilities.push("ci-cd-pipelines"); } if (lowerTask.includes("github actions") || lowerTask.includes("workflow")) { analysis.requiredCapabilities.push("github-actions"); } if (lowerTask.includes("jenkins")) { analysis.requiredCapabilities.push("jenkins-operations"); } // Monitoring & Observability if (lowerTask.includes("monitoring") || lowerTask.includes("prometheus") || lowerTask.includes("grafana")) { analysis.requiredCapabilities.push("monitoring-setup"); } if (lowerTask.includes("logging") || lowerTask.includes("log analysis") || lowerTask.includes("elk")) { analysis.requiredCapabilities.push("log-analysis"); } // Networking if (lowerTask.includes("firewall") || lowerTask.includes("iptables") || lowerTask.includes("security group")) { analysis.requiredCapabilities.push("firewall-configuration"); } if (lowerTask.includes("load balancer") || lowerTask.includes("nginx") || lowerTask.includes("haproxy")) { analysis.requiredCapabilities.push("load-balancer-setup"); } if (lowerTask.includes("vpn") || lowerTask.includes("wireguard") || lowerTask.includes("openvpn")) { analysis.requiredCapabilities.push("vpn-configuration"); } if (lowerTask.includes("ssl") || lowerTask.includes("tls") || lowerTask.includes("certificate")) { analysis.requiredCapabilities.push("ssl-tls-management"); } if (lowerTask.includes("dns") || lowerTask.includes("domain")) { analysis.requiredCapabilities.push("dns-management"); } if (lowerTask.includes("network") || lowerTask.includes("tcp/ip") || lowerTask.includes("routing")) { analysis.requiredCapabilities.push("network-operations"); } // System Administration if (lowerTask.includes("system") || lowerTask.includes("server") || lowerTask.includes("linux")) { analysis.requiredCapabilities.push("system-administration"); } if (lowerTask.includes("performance") || lowerTask.includes("optimization") || lowerTask.includes("tuning")) { analysis.requiredCapabilities.push("performance-tuning"); } if (lowerTask.includes("backup") || lowerTask.includes("disaster recovery") || lowerTask.includes("failover")) { analysis.requiredCapabilities.push("disaster-recovery"); } // API Operations (expanded) if (lowerTask.includes("rest api") || lowerTask.includes("restful") || lowerTask.includes("http api") || lowerTask.includes("endpoint")) { analysis.requiredCapabilities.push("rest-api-integration"); } if (lowerTask.includes("graphql") || lowerTask.includes("gql") || lowerTask.includes("graph ql")) { analysis.requiredCapabilities.push("graphql-operations"); } if (lowerTask.includes("grpc") || lowerTask.includes("protobuf") || lowerTask.includes("proto buffer")) { analysis.requiredCapabilities.push("grpc-operations"); } if (lowerTask.includes("webhook") || lowerTask.includes("web hook") || lowerTask.includes("callback url")) { analysis.requiredCapabilities.push("webhook-management"); } if (lowerTask.includes("swagger") || lowerTask.includes("openapi") || lowerTask.includes("api spec") || lowerTask.includes("api contract")) { analysis.requiredCapabilities.push("openapi-swagger"); } if (lowerTask.includes("oauth") || lowerTask.includes("jwt") || lowerTask.includes("bearer token") || lowerTask.includes("access token")) { analysis.requiredCapabilities.push("oauth2-flows"); analysis.requiredCapabilities.push("api-authentication"); } if (lowerTask.includes("websocket") || lowerTask.includes("real-time") || lowerTask.includes("socket.io") || lowerTask.includes("sse")) { analysis.requiredCapabilities.push("websocket-operations"); } if (lowerTask.includes("soap") || lowerTask.includes("wsdl") || lowerTask.includes("xml service")) { analysis.requiredCapabilities.push("soap-xml-operations"); } if (lowerTask.includes("api test") || lowerTask.includes("api load") || lowerTask.includes("api fuzz")) { analysis.requiredCapabilities.push("api-testing"); } if (lowerTask.includes("api security") || lowerTask.includes("api pentest") || lowerTask.includes("bola") || lowerTask.includes("idor api")) { analysis.requiredCapabilities.push("api-security-testing"); } // Browser & Web Automation if (lowerTask.includes("playwright") || lowerTask.includes("e2e test") || lowerTask.includes("end-to-end test")) { analysis.requiredCapabilities.push("playwright-automation"); } if (lowerTask.includes("agent-browser") || lowerTask.includes("agent browser") || lowerTask.includes("browse and ") || lowerTask.includes("navigate to ")) { analysis.requiredCapabilities.push("agent-browser-automation"); } if (lowerTask.includes("scrape") || lowerTask.includes("web extract") || lowerTask.includes("crawl") || lowerTask.includes("harvest data")) { analysis.requiredCapabilities.push("web-scraping-advanced"); } if (lowerTask.includes("visual regression") || lowerTask.includes("screenshot diff") || lowerTask.includes("pixel comparison")) { analysis.requiredCapabilities.push("visual-regression-testing"); } if (lowerTask.includes("accessibility") || lowerTask.includes("wcag") || lowerTask.includes("a11y") || lowerTask.includes("screen reader")) { analysis.requiredCapabilities.push("accessibility-testing"); } if (lowerTask.includes("page speed") || lowerTask.includes("lighthouse") || lowerTask.includes("core web vitals") || lowerTask.includes("performance audit")) { analysis.requiredCapabilities.push("web-performance-testing"); } if (lowerTask.includes("rpa") || lowerTask.includes("robotic process") || lowerTask.includes("automate login") || lowerTask.includes("automate form")) { analysis.requiredCapabilities.push("rpa-enterprise"); } if (lowerTask.includes("mitmproxy") || lowerTask.includes("intercept traffic") || lowerTask.includes("http intercept")) { analysis.requiredCapabilities.push("mitmproxy-analysis"); } if (lowerTask.includes("mobile browser") || lowerTask.includes("responsive test") || lowerTask.includes("mobile emulat")) { analysis.requiredCapabilities.push("mobile-web-automation"); } // Enterprise Apps if (lowerTask.includes("salesforce") || lowerTask.includes("sfdc") || lowerTask.includes("soql") || lowerTask.includes("force.com")) { analysis.requiredCapabilities.push("salesforce-integration"); } if (lowerTask.includes("jira") || lowerTask.includes("atlassian") || lowerTask.includes("issue tracker") || lowerTask.includes("sprint")) { analysis.requiredCapabilities.push("jira-integration"); } if (lowerTask.includes("confluence") || lowerTask.includes("wiki page") || lowerTask.includes("confluence page")) { analysis.requiredCapabilities.push("confluence-integration"); } if (lowerTask.includes("slack") || lowerTask.includes("slack message") || lowerTask.includes("slack bot") || lowerTask.includes("slack channel")) { analysis.requiredCapabilities.push("slack-integration"); } if (lowerTask.includes("github") || lowerTask.includes("pull request") || lowerTask.includes("github actions") || lowerTask.includes("github repo")) { analysis.requiredCapabilities.push("github-integration"); } if (lowerTask.includes("gitlab") || lowerTask.includes("merge request") || lowerTask.includes("gitlab ci") || lowerTask.includes("gitlab runner")) { analysis.requiredCapabilities.push("gitlab-integration"); } if (lowerTask.includes("servicenow") || lowerTask.includes("service now") || lowerTask.includes("itsm") || lowerTask.includes("cmdb")) { analysis.requiredCapabilities.push("servicenow-integration"); } if (lowerTask.includes("microsoft teams") || lowerTask.includes("sharepoint") || lowerTask.includes("ms graph") || lowerTask.includes("office 365")) { analysis.requiredCapabilities.push("microsoft-365-integration"); } if (lowerTask.includes("google workspace") || lowerTask.includes("google drive") || lowerTask.includes("google sheets") || lowerTask.includes("gsuite")) { analysis.requiredCapabilities.push("google-workspace-integration"); } if (lowerTask.includes("stripe") || lowerTask.includes("payment api") || lowerTask.includes("subscription billing") || lowerTask.includes("payment gateway")) { analysis.requiredCapabilities.push("stripe-integration"); } if (lowerTask.includes("twilio") || lowerTask.includes("sms api") || lowerTask.includes("whatsapp api") || lowerTask.includes("send sms")) { analysis.requiredCapabilities.push("twilio-integration"); } if (lowerTask.includes("sendgrid") || lowerTask.includes("email api") || lowerTask.includes("transactional email") || lowerTask.includes("mailgun")) { analysis.requiredCapabilities.push("sendgrid-integration"); } if (lowerTask.includes("active directory") || lowerTask.includes("ldap") || lowerTask.includes("ad group") || lowerTask.includes("windows domain")) { analysis.requiredCapabilities.push("active-directory"); } if (lowerTask.includes("sso") || lowerTask.includes("saml") || lowerTask.includes("oidc") || lowerTask.includes("single sign-on")) { analysis.requiredCapabilities.push("sso-saml-oauth"); } if (lowerTask.includes("sap") || lowerTask.includes("netsuite") || lowerTask.includes("oracle fusion") || lowerTask.includes("erp")) { analysis.requiredCapabilities.push("erp-integration"); } if (lowerTask.includes("hubspot") || lowerTask.includes("zoho") || lowerTask.includes("dynamics 365") || lowerTask.includes("crm")) { analysis.requiredCapabilities.push("crm-integration"); } if (lowerTask.includes("datadog") || lowerTask.includes("newrelic") || lowerTask.includes("apm")) { analysis.requiredCapabilities.push("datadog-integration"); } if (lowerTask.includes("pagerduty") || lowerTask.includes("opsgenie") || lowerTask.includes("incident alert")) { analysis.requiredCapabilities.push("pagerduty-integration"); } // Messaging & Streaming if (lowerTask.includes("kafka") || lowerTask.includes("event stream") || lowerTask.includes("confluent")) { analysis.requiredCapabilities.push("kafka-operations"); } if (lowerTask.includes("rabbitmq") || lowerTask.includes("amqp") || lowerTask.includes("message queue")) { analysis.requiredCapabilities.push("rabbitmq-operations"); } if (lowerTask.includes("mqtt") || lowerTask.includes("iot message") || lowerTask.includes("mosquitto")) { analysis.requiredCapabilities.push("mqtt-iot-messaging"); } if (lowerTask.includes("redis pub") || lowerTask.includes("redis stream") || lowerTask.includes("pubsub")) { analysis.requiredCapabilities.push("redis-pubsub"); } if (lowerTask.includes("celery") || lowerTask.includes("task queue") || lowerTask.includes("background task")) { analysis.requiredCapabilities.push("celery-task-queue"); } // ML / AI / Data if (lowerTask.includes("mlops") || lowerTask.includes("model training") || lowerTask.includes("model deploy") || lowerTask.includes("ml pipeline")) { analysis.requiredCapabilities.push("ml-operations"); } if (lowerTask.includes("data pipeline") || lowerTask.includes("etl") || lowerTask.includes("airflow") || lowerTask.includes("dbt") || lowerTask.includes("spark")) { analysis.requiredCapabilities.push("data-engineering"); } if (lowerTask.includes("openai") || lowerTask.includes("langchain") || lowerTask.includes("llm") || lowerTask.includes("embedding") || lowerTask.includes("rag")) { analysis.requiredCapabilities.push("llm-integration"); } if (lowerTask.includes("vector db") || lowerTask.includes("pinecone") || lowerTask.includes("weaviate") || lowerTask.includes("chroma") || lowerTask.includes("pgvector")) { analysis.requiredCapabilities.push("vector-database"); } if (lowerTask.includes("visualization") || lowerTask.includes("chart") || lowerTask.includes("dashboard") || lowerTask.includes("plotly")) { analysis.requiredCapabilities.push("data-visualization"); } if (lowerTask.includes("statistic") || lowerTask.includes("regression") || lowerTask.includes("forecast") || lowerTask.includes("hypothesis test")) { analysis.requiredCapabilities.push("statistical-analysis"); } // Advanced Security if (lowerTask.includes("osint") || lowerTask.includes("recon") || lowerTask.includes("open source intelligence") || lowerTask.includes("person research")) { analysis.requiredCapabilities.push("osint-operations"); } if (lowerTask.includes("threat intel") || lowerTask.includes("ioc") || lowerTask.includes("threat actor") || lowerTask.includes("stix") || lowerTask.includes("taxii")) { analysis.requiredCapabilities.push("threat-intelligence"); } if (lowerTask.includes("encrypt") || lowerTask.includes("decrypt") || lowerTask.includes("pki") || lowerTask.includes("key management") || lowerTask.includes("hsm")) { analysis.requiredCapabilities.push("cryptography-operations"); } if (lowerTask.includes("reverse engineer") || lowerTask.includes("decompile") || lowerTask.includes("firmware") || lowerTask.includes("binary analysis")) { analysis.requiredCapabilities.push("reverse-engineering"); } if (lowerTask.includes("forensic") || lowerTask.includes("incident response") || lowerTask.includes("memory dump") || lowerTask.includes("disk image")) { analysis.requiredCapabilities.push("forensics"); } if (lowerTask.includes("container scan") || lowerTask.includes("image scan") || lowerTask.includes("trivy") || lowerTask.includes("falco")) { analysis.requiredCapabilities.push("container-security"); } if (lowerTask.includes("sast") || lowerTask.includes("dast") || lowerTask.includes("sca") || lowerTask.includes("secret scan") || lowerTask.includes("sbom") || lowerTask.includes("devsecops")) { analysis.requiredCapabilities.push("devsecops"); } // Advanced Infrastructure if (lowerTask.includes("service mesh") || lowerTask.includes("istio") || lowerTask.includes("linkerd") || lowerTask.includes("envoy proxy")) { analysis.requiredCapabilities.push("service-mesh"); } if (lowerTask.includes("chaos") || lowerTask.includes("fault injection") || lowerTask.includes("resilience test") || lowerTask.includes("chaos monkey")) { analysis.requiredCapabilities.push("chaos-engineering"); } if (lowerTask.includes("ebpf") || lowerTask.includes("kernel trace") || lowerTask.includes("bpf program")) { analysis.requiredCapabilities.push("ebpf-operations"); } if (lowerTask.includes("multi-cloud") || lowerTask.includes("hybrid cloud") || lowerTask.includes("cross-cloud")) { analysis.requiredCapabilities.push("multi-cloud-operations"); } if (lowerTask.includes("argocd") || lowerTask.includes("gitops") || lowerTask.includes("flux cd") || lowerTask.includes("helm deploy")) { analysis.requiredCapabilities.push("gitops-operations"); } if (lowerTask.includes("vault") || lowerTask.includes("secret rotation") || lowerTask.includes("secrets manager") || lowerTask.includes("aws secrets")) { analysis.requiredCapabilities.push("secrets-management"); } if (lowerTask.includes("cloud cost") || lowerTask.includes("rightsiz") || lowerTask.includes("savings plan") || lowerTask.includes("reserved instance") || lowerTask.includes("cloud spend")) { analysis.requiredCapabilities.push("cost-optimization-cloud"); } if (lowerTask.includes("cdn") || lowerTask.includes("cloudflare") || lowerTask.includes("fastly") || lowerTask.includes("cloudfront") || lowerTask.includes("edge worker")) { analysis.requiredCapabilities.push("cdn-edge-operations"); } // Mobile if (lowerTask.includes("appium") || lowerTask.includes("mobile app test") || lowerTask.includes("ios test") || lowerTask.includes("android test")) { analysis.requiredCapabilities.push("mobile-testing"); } if (lowerTask.includes("react native") || lowerTask.includes("expo app") || lowerTask.includes("mobile automation")) { analysis.requiredCapabilities.push("react-native-automation"); } // IoT & Edge if (lowerTask.includes("iot") || lowerTask.includes("mqtt device") || lowerTask.includes("greengrass") || lowerTask.includes("iot fleet")) { analysis.requiredCapabilities.push("iot-operations"); } if (lowerTask.includes("edge deploy") || lowerTask.includes("k3s") || lowerTask.includes("balena") || lowerTask.includes("edge computing")) { analysis.requiredCapabilities.push("edge-computing"); } // Protocol & Network if (lowerTask.includes("wireshark") || lowerTask.includes("pcap") || lowerTask.includes("packet capture") || lowerTask.includes("tshark")) { analysis.requiredCapabilities.push("protocol-analysis"); } if (lowerTask.includes("nmap") || lowerTask.includes("port scan") || lowerTask.includes("asset discovery") || lowerTask.includes("network scan")) { analysis.requiredCapabilities.push("network-scanning"); } if (lowerTask.includes("reverse proxy") || lowerTask.includes("traffic replay") || lowerTask.includes("mitmproxy")) { analysis.requiredCapabilities.push("proxy-operations"); } // Documents if (lowerTask.includes("pdf") || lowerTask.includes("word doc") || lowerTask.includes("docx") || lowerTask.includes("powerpoint") || lowerTask.includes("pptx")) { analysis.requiredCapabilities.push("document-processing"); } if (lowerTask.includes("excel") || lowerTask.includes("spreadsheet") || lowerTask.includes("csv") || lowerTask.includes("xlsx")) { analysis.requiredCapabilities.push("spreadsheet-operations"); } // Generic API catch-all if (lowerTask.includes("api") && analysis.requiredCapabilities.filter(c => c.includes("api")).length === 0) { analysis.requiredCapabilities.push("rest-api-integration"); } // Deduplicate capabilities analysis.requiredCapabilities = [...new Set(analysis.requiredCapabilities)]; // Default basic capabilities if (analysis.requiredCapabilities.length === 0) { analysis.requiredCapabilities.push("file-operations", "bash-execution", "system-administration"); } else { if (!analysis.requiredCapabilities.includes("file-operations")) analysis.requiredCapabilities.push("file-operations"); if (!analysis.requiredCapabilities.includes("bash-execution")) analysis.requiredCapabilities.push("bash-execution"); } // Estimate steps from capability count and complexity const capCount = analysis.requiredCapabilities.filter(c => c !== "file-operations" && c !== "bash-execution").length; analysis.estimatedSteps = analysis.complexity === "simple" ? 1 : analysis.complexity === "moderate" ? Math.max(2, capCount) : Math.max(3, capCount * 2); return analysis; } async assessCapabilities(analysis: TaskAnalysis): Promise<{ available: string[]; missing: string[]; canAcquire: string[]; blocked: string[]; }> { const available: string[] = []; const missing: string[] = []; const canAcquire: string[] = []; const blocked: string[] = []; for (const capName of analysis.requiredCapabilities) { const cap = this.capabilities.get(capName); if (cap && cap.available) { available.push(capName); } else if (cap && cap.installCommand) { missing.push(capName); canAcquire.push(capName); } else { missing.push(capName); blocked.push(capName); } } return { available, missing, canAcquire, blocked }; } async createPlan(task: string, analysis: TaskAnalysis, assessment: any): Promise { const plan: ExecutionPlan = { id: `plan-${Date.now()}`, task, strategy: "direct", steps: [], capabilitiesToAcquire: assessment.canAcquire, fallbackStrategies: [], estimatedDuration: "unknown", }; // Determine strategy if (assessment.missing.length === 0) { plan.strategy = "direct"; } else if (assessment.canAcquire.length > 0) { plan.strategy = "acquire-capabilities"; } else if (analysis.researchNeeded) { plan.strategy = "research-first"; } else if (analysis.complexity === "complex") { plan.strategy = "multi-agent"; } else { plan.strategy = "direct"; } // Create steps based on strategy if (plan.strategy === "acquire-capabilities") { plan.steps.push({ id: "step-1", description: `Acquire missing capabilities: ${assessment.canAcquire.join(", ")}`, action: "acquire_capabilities", capabilities: [], dependencies: [], estimatedDuration: "2-5 minutes", canFail: true, fallback: "attempt_alternative", }); } if (analysis.researchNeeded) { plan.steps.push({ id: `step-${plan.steps.length + 1}`, description: "Research task requirements and best approaches", action: "research", capabilities: assessment.available.includes("web-research") ? ["web-research"] : [], dependencies: plan.steps.map(s => s.id), estimatedDuration: "1-3 minutes", canFail: false, }); } // Main execution step plan.steps.push({ id: `step-${plan.steps.length + 1}`, description: `Execute: ${task}`, action: "execute", capabilities: analysis.requiredCapabilities, dependencies: plan.steps.map(s => s.id), estimatedDuration: "varies", canFail: true, fallback: "decompose_and_retry", }); plan.estimatedDuration = plan.steps.length <= 1 ? "< 1 minute" : plan.steps.length <= 3 ? "1-5 minutes" : plan.steps.length <= 6 ? "5-15 minutes" : "15+ minutes"; return plan; } // =========================================================================== // Robustness: Checks, Fallbacks, and Edge Case Handling // =========================================================================== /** * Pre-flight checks to identify issues before execution */ async checkPrerequisites(): Promise<{ ready: boolean; issues: string[]; fallbacks: string[]; }> { const issues: string[] = []; const fallbacks: string[] = []; // Check if we're in a pi environment const isPiEnvironment = typeof process.env.PI_SESSION !== 'undefined' || process.cwd().includes('.pi') || await fs.access(path.join(os.homedir(), '.pi')).then(() => true).catch(() => false); if (!isPiEnvironment) { issues.push("Not running in pi environment - some features may be limited"); fallbacks.push("Will use direct CLI execution instead of agent spawning"); } // Check AWS CLI availability try { await fs.access('/opt/homebrew/bin/aws'); } catch { try { await this.safeExecute('which aws', 5000, 1); } catch { issues.push("AWS CLI not found"); fallbacks.push("AWS CLI not in PATH — install via: brew install awscli OR curl 'https://awscli.amazonaws.com/AWSCLIV2.pkg' -o /tmp/awscli.pkg && sudo installer -pkg /tmp/awscli.pkg -target /"); } } // Check write permissions try { const testFile = path.join(this.workspaceDir, '.write-test'); await fs.writeFile(testFile, 'test'); await fs.unlink(testFile); } catch { issues.push("Cannot write to workspace directory"); fallbacks.push("Will use /tmp directory for temporary files"); } return { ready: issues.length === 0, issues, fallbacks, }; } /** * Execute with automatic fallback on failure */ async executeWithFallback( primaryAction: () => Promise, fallbackAction: () => Promise, errorMessage: string ): Promise { try { return await primaryAction(); } catch (error: any) { console.warn(`Primary action failed: ${errorMessage}`, error.message || error); try { return await fallbackAction(); } catch (fallbackError: any) { throw new Error( `Both primary and fallback actions failed.\n` + `Primary error: ${error.message || error}\n` + `Fallback error: ${fallbackError.message || fallbackError}` ); } } } /** * Safe command execution with timeout, retries, and error handling */ async safeExecute( command: string, timeout: number = 60000, retries: number = 3 ): Promise<{ stdout: string; stderr: string; exitCode: number }> { for (let attempt = 1; attempt <= retries; attempt++) { try { const result = await new Promise<{ stdout: string; stderr: string; exitCode: number }>( (resolve, reject) => { const childProcess = spawn('bash', ['-c', command], { env: { ...process.env, AWS_PAGER: '' }, }); let stdout = ''; let stderr = ''; let timeoutId: NodeJS.Timeout; const cleanup = () => { if (timeoutId) clearTimeout(timeoutId); try { childProcess.kill('SIGTERM'); } catch {} }; timeoutId = setTimeout(() => { cleanup(); reject(new Error(`Command timed out after ${timeout}ms`)); }, timeout); childProcess.stdout?.on('data', (data) => { stdout += data.toString(); }); childProcess.stderr?.on('data', (data) => { stderr += data.toString(); }); childProcess.on('close', (exitCode) => { clearTimeout(timeoutId); resolve({ stdout, stderr, exitCode: exitCode || 0 }); }); childProcess.on('error', (error) => { clearTimeout(timeoutId); reject(error); }); } ); // Check for AWS-specific errors if (result.stderr.includes('Unable to locate credentials')) { throw new Error('AWS credentials not configured. Run: aws configure'); } if (result.stderr.includes('InvalidClientTokenId')) { throw new Error('Invalid AWS credentials. Check your Access Key and Secret Key.'); } if (result.stderr.includes('AccessDenied')) { throw new Error('AWS access denied. Check IAM permissions.'); } if (result.stderr.includes('RequestExpired')) { throw new Error('AWS request expired. Check system clock.'); } return result; } catch (error: any) { if (attempt === retries) { throw error; } console.warn(`Attempt ${attempt} failed, retrying... (${error.message})`); await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); } } throw new Error('All retry attempts failed'); } /** * Direct AWS analysis using CLI commands (fallback method) */ async directAWSAnalysis(): Promise { const results: any = { instances: [], securityGroups: [], volumes: [], addresses: [], errors: [], }; // Helper to run AWS commands with error handling const runAWSCommand = async (command: string, description: string) => { try { const { stdout, stderr, exitCode } = await this.safeExecute(command, 30000, 2); if (exitCode !== 0 && stderr) { results.errors.push(`${description}: ${stderr}`); return null; } return stdout; } catch (error: any) { results.errors.push(`${description}: ${error.message}`); return null; } }; // Get instances const instancesOutput = await runAWSCommand( 'aws ec2 describe-instances --query "Reservations[].Instances[]" --output json 2>&1', 'EC2 Instances' ); if (instancesOutput) { try { results.instances = JSON.parse(instancesOutput); } catch { results.errors.push('Failed to parse EC2 instances output'); } } // Get security groups const sgOutput = await runAWSCommand( 'aws ec2 describe-security-groups --output json 2>&1', 'Security Groups' ); if (sgOutput) { try { const parsed = JSON.parse(sgOutput); results.securityGroups = parsed.SecurityGroups || []; } catch { results.errors.push('Failed to parse security groups output'); } } // Get volumes const volumesOutput = await runAWSCommand( 'aws ec2 describe-volumes --output json 2>&1', 'EBS Volumes' ); if (volumesOutput) { try { const parsed = JSON.parse(volumesOutput); results.volumes = parsed.Volumes || []; } catch { results.errors.push('Failed to parse volumes output'); } } // Get elastic IPs const addressesOutput = await runAWSCommand( 'aws ec2 describe-addresses --output json 2>&1', 'Elastic IPs' ); if (addressesOutput) { try { const parsed = JSON.parse(addressesOutput); results.addresses = parsed.Addresses || []; } catch { results.errors.push('Failed to parse addresses output'); } } return results; } /** * Format AWS analysis data into a readable report */ formatAWSReport(data: any): string { let report = '# AWS EC2 Analysis Report\n\n'; report += `**Generated:** ${new Date().toISOString()}\n`; report += `**Account:** Analyzed via Direct CLI\n\n`; // Summary const runningInstances = data.instances.filter((i: any) => i.State?.Name === 'running').length; const stoppedInstances = data.instances.filter((i: any) => i.State?.Name === 'stopped').length; const totalVolumes = data.volumes.length; const unencryptedVolumes = data.volumes.filter((v: any) => !v.Encrypted).length; const ebsSize = data.volumes.reduce((sum: number, v: any) => sum + (v.Size || 0), 0); report += '## Summary\n\n'; report += `- **Total Instances:** ${data.instances.length} (${runningInstances} running, ${stoppedInstances} stopped)\n`; report += `- **Total Storage:** ${ebsSize} GB across ${totalVolumes} volumes\n`; report += `- **Unencrypted Volumes:** ${unencryptedVolumes}\n`; report += `- **Security Groups:** ${data.securityGroups.length}\n`; report += `- **Elastic IPs:** ${data.addresses.length}\n`; if (data.errors.length > 0) { report += `\n⚠️ **Warnings (${data.errors.length}):**\n`; for (const error of data.errors.slice(0, 5)) { report += `- ${error}\n`; } } // Instances if (data.instances.length > 0) { report += '\n## EC2 Instances\n\n'; report += '| Instance ID | Name | Type | State | Public IP | Launch Date |\n'; report += '|-------------|------|------|-------|-----------|-------------|\n'; for (const instance of data.instances) { const name = instance.Tags?.find((t: any) => t.Key === 'Name')?.Value || 'N/A'; const launchDate = instance.LaunchTime ? new Date(instance.LaunchTime).toISOString().split('T')[0] : 'Unknown'; report += `| ${instance.InstanceId} | ${name} | ${instance.InstanceType} | ${instance.State?.Name} | ${instance.PublicIpAddress || 'None'} | ${launchDate} |\n`; } } // Security Issues const securityIssues: string[] = []; for (const sg of data.securityGroups) { for (const rule of sg.IpPermissions || []) { const openToWorld = rule.IpRanges?.some((r: any) => r.CidrIp === '0.0.0.0/0'); if (openToWorld) { const port = rule.FromPort === rule.ToPort ? rule.FromPort : `${rule.FromPort}-${rule.ToPort}`; const protocol = rule.IpProtocol; securityIssues.push(`Security Group ${sg.GroupName || sg.GroupId}: ${protocol} port ${port} open to 0.0.0.0/0`); } } } if (securityIssues.length > 0) { report += '\n## 🔴 Security Issues\n\n'; for (const issue of securityIssues) { report += `- ${issue}\n`; } report += '\n**Recommendation:** Restrict these ports to specific IP ranges\n'; } // Cost Analysis const ebsCost = data.volumes.reduce((sum: number, v: any) => sum + (v.Size || 0) * 0.08, 0); const unusedEips = data.addresses.filter((a: any) => !a.InstanceId).length; const eipCost = unusedEips * 7.2; report += '\n## Cost Analysis\n\n'; report += `- **EBS Storage:** $${ebsCost.toFixed(2)}/month (${ebsSize} GB @ $0.08/GB)\n`; if (unusedEips > 0) { report += `- **Unused Elastic IPs:** $${eipCost.toFixed(2)}/month (${unusedEips} unused @ $7.20 each)\n`; } report += `- **Total Monthly (storage only):** $${(ebsCost + eipCost).toFixed(2)}/month\n`; // Recommendations report += '\n## Recommendations\n\n'; if (securityIssues.length > 0) { report += '### 🔴 Critical\n'; report += '- Fix security groups - restrict ports from 0.0.0.0/0\n'; } if (unencryptedVolumes > 0) { report += '- Enable encryption on EBS volumes\n'; } if (unusedEips > 0) { report += `- Release ${unusedEips} unused Elastic IP(s) to save $${eipCost.toFixed(2)}/month\n`; } if (stoppedInstances > 0 && runningInstances === 0) { report += '- All instances are stopped - consider terminating if no longer needed\n'; } report += '\n---\n*Report generated by Pi-SuperIntel (Direct CLI Mode)*\n'; return report; } // =========================================================================== // API Execution Helpers — REST, GraphQL, gRPC, WebSocket // =========================================================================== /** * Execute a REST API call via curl with full auth support */ async executeRESTAPI(config: { url: string; method?: string; headers?: Record; body?: any; auth?: { type: "bearer" | "apikey" | "basic" | "none"; credentials?: string }; timeout?: number; }): Promise<{ status: number; body: string; headers: string }> { const method = (config.method || "GET").toUpperCase(); const parts: string[] = [`curl -s -i -X ${method}`]; // Auth if (config.auth) { switch (config.auth.type) { case "bearer": parts.push(`-H "Authorization: Bearer ${config.auth.credentials}"`); break; case "apikey": parts.push(`-H "X-API-Key: ${config.auth.credentials}"`); break; case "basic": parts.push(`-u "${config.auth.credentials}"`); break; } } // Headers for (const [k, v] of Object.entries(config.headers || {})) { parts.push(`-H "${k}: ${v}"`); } // Body if (config.body) { const bodyStr = typeof config.body === "string" ? config.body : JSON.stringify(config.body); parts.push(`-H "Content-Type: application/json"`); parts.push(`-d '${bodyStr.replace(/'/g, "'\\''")}'`); } parts.push(`"${config.url}"`); const cmd = parts.join(" "); const { stdout } = await this.safeExecute(cmd, config.timeout || 30000, 2); // Parse status, headers, body const lines = stdout.split("\n"); const statusLine = lines.find(l => l.match(/^HTTP\/\d/)) || "HTTP/1.1 200 OK"; const status = parseInt(statusLine.split(" ")[1] || "200"); const headerEnd = lines.findIndex(l => l.trim() === ""); const headers = lines.slice(1, headerEnd).join("\n"); const body = lines.slice(headerEnd + 1).join("\n"); return { status, body, headers }; } /** * Execute a GraphQL query/mutation via curl */ async executeGraphQL(config: { endpoint: string; query: string; variables?: Record; headers?: Record; auth?: { type: "bearer" | "apikey"; credentials: string }; timeout?: number; }): Promise<{ data: any; errors: any[] }> { const payload = { query: config.query, variables: config.variables || {}, }; const headerParts: string[] = [ '-H "Content-Type: application/json"', '-H "Accept: application/json"', ]; if (config.auth?.type === "bearer") { headerParts.push(`-H "Authorization: Bearer ${config.auth.credentials}"`); } else if (config.auth?.type === "apikey") { headerParts.push(`-H "X-API-Key: ${config.auth.credentials}"`); } for (const [k, v] of Object.entries(config.headers || {})) { headerParts.push(`-H "${k}: ${v}"`); } const bodyStr = JSON.stringify(payload).replace(/'/g, "'\\''"); const cmd = `curl -s -X POST ${headerParts.join(" ")} -d '${bodyStr}' "${config.endpoint}" | jq .`; const { stdout, stderr } = await this.safeExecute(cmd, config.timeout || 30000, 2); try { const parsed = JSON.parse(stdout); return { data: parsed.data || null, errors: parsed.errors || [] }; } catch { return { data: null, errors: [{ message: stderr || stdout }] }; } } /** * Execute browser automation via agent-browser CLI */ async executeAgentBrowser(steps: Array<{ action: "open" | "snapshot" | "click" | "fill" | "scroll" | "screenshot" | "close"; target?: string; value?: string; }>): Promise<{ results: string[]; screenshots: string[] }> { const results: string[] = []; const screenshots: string[] = []; for (const step of steps) { let cmd = ""; switch (step.action) { case "open": cmd = `agent-browser open "${step.target}"`; break; case "snapshot": cmd = "agent-browser snapshot -i"; break; case "click": cmd = `agent-browser click ${step.target}`; break; case "fill": cmd = `agent-browser fill ${step.target} "${step.value}"`; break; case "scroll": cmd = `agent-browser scroll ${step.target || "down"}`; break; case "screenshot": const ssPath = `/tmp/superintel-screenshot-${Date.now()}.png`; cmd = `agent-browser screenshot "${ssPath}"`; screenshots.push(ssPath); break; case "close": cmd = "agent-browser close"; break; } if (cmd) { try { const { stdout } = await this.safeExecute(cmd, 30000, 2); results.push(stdout.trim()); } catch (err: any) { results.push(`Error on ${step.action}: ${err.message}`); } } } return { results, screenshots }; } /** * Execute browser automation via playwright-cli */ async executePlaywright(steps: Array<{ action: "open" | "click" | "type" | "fill" | "press" | "screenshot" | "close" | "snapshot"; target?: string; value?: string; }>): Promise<{ results: string[]; screenshots: string[] }> { const results: string[] = []; const screenshots: string[] = []; for (const step of steps) { let cmd = ""; switch (step.action) { case "open": cmd = `playwright-cli open "${step.target}"`; break; case "click": cmd = `playwright-cli click ${step.target}`; break; case "type": cmd = `playwright-cli type "${step.value}"`; break; case "fill": cmd = `playwright-cli fill ${step.target} "${step.value}"`; break; case "press": cmd = `playwright-cli press ${step.value || "Enter"}`; break; case "snapshot": cmd = "playwright-cli snapshot"; break; case "screenshot": const ssPath = `/tmp/superintel-pw-${Date.now()}.png`; cmd = `playwright-cli screenshot "${ssPath}"`; screenshots.push(ssPath); break; case "close": cmd = "playwright-cli close"; break; } if (cmd) { try { const { stdout } = await this.safeExecute(cmd, 30000, 2); results.push(stdout.trim()); } catch (err: any) { results.push(`Error on ${step.action}: ${err.message}`); } } } return { results, screenshots }; } /** * Probe any API endpoint and auto-detect its type (REST/GraphQL/gRPC) */ async probeAPI(url: string): Promise<{ type: "rest" | "graphql" | "grpc" | "unknown"; auth: string[]; endpoints: string[]; specUrl?: string; }> { const result = { type: "unknown" as any, auth: [] as string[], endpoints: [] as string[], specUrl: undefined as string | undefined }; // Try GraphQL introspection try { const gqlResult = await this.executeGraphQL({ endpoint: url, query: "{ __schema { types { name } } }", timeout: 10000, }); if (gqlResult.data?.__schema) { result.type = "graphql"; result.endpoints = [url]; return result; } } catch {} // Check for OpenAPI spec for (const specPath of ["/openapi.json", "/swagger.json", "/api/docs", "/api-docs"]) { try { const { status, body } = await this.executeRESTAPI({ url: `${url.replace(/\/$/, "")}${specPath}`, timeout: 5000, }); if (status === 200 && body.includes("openapi")) { result.type = "rest"; result.specUrl = `${url}${specPath}`; break; } } catch {} } // Check auth headers from a probe request try { const { headers } = await this.executeRESTAPI({ url, timeout: 5000 }); if (headers.includes("WWW-Authenticate")) { if (headers.includes("Bearer")) result.auth.push("bearer"); if (headers.includes("Basic")) result.auth.push("basic"); } } catch {} if (result.type === "unknown") result.type = "rest"; return result; } /** * Build a curl command string from a config object */ buildCurlCommand(config: { url: string; method?: string; headers?: Record; body?: any; auth?: { type: string; credentials?: string }; }): string { const method = (config.method || "GET").toUpperCase(); const parts: string[] = [`curl -s -X ${method}`]; if (config.auth?.type === "bearer") { parts.push(`-H "Authorization: Bearer ${config.auth.credentials}"`); } else if (config.auth?.type === "basic") { parts.push(`-u "${config.auth.credentials}"`); } else if (config.auth?.type === "apikey") { parts.push(`-H "X-API-Key: ${config.auth.credentials}"`); } for (const [k, v] of Object.entries(config.headers || {})) { parts.push(`-H "${k}: ${v}"`); } if (config.body) { const b = typeof config.body === "string" ? config.body : JSON.stringify(config.body); parts.push(`-H "Content-Type: application/json" -d '${b.replace(/'/g, "'\\''")}'`); } parts.push(`"${config.url}"`); return parts.join(" "); } // =========================================================================== // Core Methods - The Autonomous Loop (Updated with Fallbacks) // =========================================================================== async acquireCapabilities(capabilityNames: string[]): Promise<{ acquired: string[]; failed: string[]; created: string[]; }> { const acquired: string[] = []; const failed: string[] = []; const created: string[] = []; for (const capName of capabilityNames) { const cap = this.capabilities.get(capName); if (!cap) continue; if (cap.type === "extension" && cap.installCommand) { // Actually run pi install try { const { stdout, exitCode } = await this.safeExecute(cap.installCommand, 120000, 2); const success = exitCode === 0 || stdout.toLowerCase().includes("installed") || stdout.toLowerCase().includes("added"); if (success) { this.updateCapability(capName, { available: true, confidence: 0.85, lastUsed: new Date().toISOString() }); acquired.push(capName); } else { console.warn(`Install failed for ${capName}: ${stdout}`); failed.push(capName); } } catch (err: any) { console.warn(`Install error for ${capName}: ${err.message}`); failed.push(capName); } } else if (cap.type === "skill") { // Try to create skill on the fly const skillCreated = await this.createSkill(capName, cap.description); if (skillCreated) { created.push(capName); this.updateCapability(capName, { available: true, confidence: 0.7, lastUsed: new Date().toISOString(), }); } else { failed.push(capName); } } } await this.saveCapabilities(); return { acquired, failed, created }; } async createSkill(name: string, description: string): Promise { const skillDir = path.join(os.homedir(), ".pi", "agent", "skills", name); const skillFile = path.join(skillDir, "SKILL.md"); try { await fs.mkdir(skillDir, { recursive: true }); const content = `--- name: ${name} description: ${description} --- # ${name.replace(/-/g, " ").replace(/\b\w/g, c => c.toUpperCase())} Skill > Auto-generated by Pi-SuperIntel ## Capability ${description} ## Usage This skill was created on-demand by SuperIntel to handle tasks requiring ${name} capabilities. ## Quick Start Use this skill when you need to: ${description.toLowerCase()} ## Tools - bash - read - write - edit ## Notes - Verify tool availability before use - Check credentials / permissions - Follow least-privilege principles `; await fs.writeFile(skillFile, content, { encoding: "utf-8", mode: 0o644 }); return true; } catch (err: any) { console.warn(`createSkill(${name}) failed: ${err.message}`); return false; } } async research(topic: string, depth: number = 1): Promise { const result: ResearchResult = { topic, findings: [], sources: [], confidence: 0, recommendations: [], }; // ── 1. Web search via jina.ai (always available) ──────────────────────── try { const query = encodeURIComponent(topic); const jina = `https://r.jina.ai/https://www.google.com/search?q=${query}+best+practices`; const { stdout } = await this.safeExecute(`curl -s --max-time 20 "${jina}"`, 25000, 2); if (stdout && stdout.length > 200) { // Extract meaningful sentences (strip HTML/noise, take first 1500 chars) const clean = stdout .replace(/<[^>]+>/g, " ") .replace(/\s+/g, " ") .slice(0, 1500) .trim(); if (clean.length > 100) { result.findings.push(`Web: ${clean}`); result.sources.push(jina); result.confidence += 0.4; } } } catch (e: any) { result.findings.push(`Web search unavailable: ${e.message}`); } // ── 2. Deep page fetch for top result ─────────────────────────────────── if (depth >= 2) { try { const query2 = encodeURIComponent(topic + " tutorial"); const { stdout } = await this.safeExecute( `curl -s --max-time 15 "https://r.jina.ai/https://www.google.com/search?q=${query2}"`, 20000, 1 ); if (stdout && stdout.length > 200) { const clean = stdout.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").slice(0, 1000); result.findings.push(`Deep: ${clean}`); result.confidence += 0.2; } } catch {} } // ── 3. Check existing pi skills for this topic ────────────────────────── const skillsDir = path.join(os.homedir(), ".pi", "agent", "skills"); try { const skills = await fs.readdir(skillsDir); for (const skill of skills) { if (skill.toLowerCase().includes(topic.toLowerCase().split(" ")[0])) { result.findings.push(`Existing skill available: ${skill}`); result.recommendations.push(`Use existing skill: ${skill}`); result.confidence += 0.15; result.sources.push(`skill:${skill}`); } } } catch {} // ── 4. Check npm for relevant packages ────────────────────────────────── if (depth >= 2) { try { const query = topic.split(" ")[0]; const { stdout } = await this.safeExecute( `npm search ${query} --parseable 2>/dev/null | head -5`, 10000, 1 ); if (stdout.trim()) { const pkgs = stdout.trim().split("\n").slice(0, 3).map(l => l.split("\t")[0]); result.findings.push(`Relevant npm packages: ${pkgs.join(", ")}`); result.confidence += 0.1; } } catch {} } // Clamp confidence result.confidence = Math.min(result.confidence, 1.0); // Build recommendations from findings if (result.findings.length === 0) { result.findings.push(`No automated research available for "${topic}" — proceed with domain knowledge`); } if (result.recommendations.length === 0 && result.confidence > 0.3) { result.recommendations.push(`Research gathered — review findings before executing`); } // Cache to disk const cacheFile = path.join(this.workspaceDir, "research", `${topic.replace(/[^a-z0-9]/gi, "_").slice(0, 50)}.json`); try { await fs.mkdir(path.dirname(cacheFile), { recursive: true }); await fs.writeFile(cacheFile, JSON.stringify({ ...result, cachedAt: new Date().toISOString() }, null, 2)); } catch {} return result; } async executePlan(plan: ExecutionPlan, ctx: any, options?: { preferDirect?: boolean; analysis?: TaskAnalysis }): Promise { const analysis = options?.analysis ?? null; const result: ExecutionResult = { success: false, stepsCompleted: 0, totalSteps: plan.steps.length, capabilitiesUsed: [], newCapabilitiesAcquired: [], }; // Run pre-flight checks const prereqs = await this.checkPrerequisites(); // If AWS-related task and we have issues, try direct CLI fallback immediately if (options?.preferDirect || (prereqs.issues.length > 0 && plan.task.toLowerCase().includes('aws'))) { try { result.output = await this.executeWithFallback( async () => { const awsData = await this.directAWSAnalysis(); return this.formatAWSReport(awsData); }, async () => { // Ultimate fallback - just return a helpful message return `⚠️ Could not complete AWS analysis automatically.\n\n` + `Pre-check issues:\n${prereqs.issues.map(i => `- ${i}`).join('\n')}\n\n` + `To analyze manually, run these commands:\n` + `aws ec2 describe-instances\n` + `aws ec2 describe-security-groups\n` + `aws ec2 describe-volumes\n` + `aws ec2 describe-addresses`; }, 'Direct AWS analysis' ); result.success = true; result.stepsCompleted = plan.steps.length; return result; } catch (error: any) { result.error = `Fallback execution failed: ${error.message}`; return result; } } // Normal execution with per-step fallback handling for (const step of plan.steps) { try { switch (step.action) { case "acquire_capabilities": const acquisition = await this.acquireCapabilities(plan.capabilitiesToAcquire); result.newCapabilitiesAcquired.push(...acquisition.acquired, ...acquisition.created); break; case "research": const research = await this.research(plan.task); result.lessons = research.recommendations; break; case "execute": // ── Domain-aware execution dispatch ──────────────────────────── const caps = plan.capabilitiesToAcquire.concat(analysis?.requiredCapabilities || []); const taskLower = plan.task.toLowerCase(); // AWS / Cloud infrastructure if (caps.some(c => c.includes("aws")) || taskLower.includes("aws") || taskLower.includes("ec2")) { try { const awsData = await this.directAWSAnalysis(); result.output = this.formatAWSReport(awsData); result.capabilitiesUsed.push("aws-operations"); } catch (e: any) { result.output = `AWS analysis failed: ${e.message}\n\nTry: aws ec2 describe-instances --output table`; } } // REST API call else if (caps.includes("rest-api-integration") && (taskLower.includes("http") || taskLower.includes("curl") || taskLower.includes(" get ") || taskLower.includes(" post "))) { const urlMatch = plan.task.match(/https?:\/\/[^\s'"]+/); if (urlMatch) { const method = taskLower.includes("post") ? "POST" : taskLower.includes("put") ? "PUT" : taskLower.includes("delete") ? "DELETE" : "GET"; const apiResult = await this.executeRESTAPI({ url: urlMatch[0], method }); result.output = `REST ${method} ${urlMatch[0]}\nStatus: ${apiResult.status}\n${apiResult.body.slice(0, 2000)}`; result.capabilitiesUsed.push("rest-api-integration"); } else { result.output = `API task identified but no URL found in task description.\nTask: ${plan.task}`; } } // GraphQL else if (caps.includes("graphql-operations") || taskLower.includes("graphql")) { const urlMatch = plan.task.match(/https?:\/\/[^\s'"]+/); const queryMatch = plan.task.match(/\{[^}]+\}/); if (urlMatch && queryMatch) { const gqlResult = await this.executeGraphQL({ endpoint: urlMatch[0], query: queryMatch[0] }); result.output = `GraphQL response:\n${JSON.stringify(gqlResult.data, null, 2)}`; result.capabilitiesUsed.push("graphql-operations"); } else { result.output = `GraphQL task — provide URL and query.\nTask: ${plan.task}`; } } // Browser automation else if (caps.some(c => c.includes("browser") || c.includes("playwright"))) { const urlMatch = plan.task.match(/https?:\/\/[^\s'"]+/); if (urlMatch) { const browserResult = await this.executeAgentBrowser([ { action: "open", target: urlMatch[0] }, { action: "snapshot" }, ]); result.output = `Browser opened: ${urlMatch[0]}\n${browserResult.results.join("\n").slice(0, 2000)}`; result.capabilitiesUsed.push("agent-browser-automation"); } else { result.output = `Browser task — provide a URL.\nTask: ${plan.task}`; } } // Direct bash / system tasks else if (analysis?.complexity === "simple" && !analysis.researchNeeded) { const bashMatch = plan.task.match(/`([^`]+)`/); if (bashMatch) { const bashResult = await this.safeExecute(bashMatch[1], 30000, 2); result.output = `Command: ${bashMatch[1]}\n\n${bashResult.stdout || bashResult.stderr}`; result.capabilitiesUsed.push("bash-execution"); } else { result.output = buildExecutionBrief(plan.task, analysis); } } // Research-first tasks else if (analysis?.researchNeeded) { const researchResult = await this.research(plan.task, 2); result.output = formatResearchOutput(researchResult); result.capabilitiesUsed.push("web-research"); result.lessons = researchResult.recommendations; } // Complex / multi-domain — produce a structured execution brief for the AI else { result.output = buildExecutionBrief(plan.task, analysis); } result.success = true; // Record execution in log await this.logExecution(plan.task, result).catch(() => {}); // Update successRate on capabilities used for (const capName of result.capabilitiesUsed) { const cap = this.capabilities.get(capName); if (cap) { cap.lastUsed = new Date().toISOString(); cap.successRate = cap.successRate ? Math.min(1, cap.successRate * 0.9 + 0.1) : 0.8; } } await this.saveCapabilities().catch(() => {}); } result.stepsCompleted++; } catch (error: any) { if (step.canFail && step.fallback) { result.lessons = result.lessons || []; result.lessons.push(`Step ${step.id} failed: ${error.message}. Fallback: ${step.fallback}`); } else { result.error = `Step ${step.id} failed: ${error.message}`; return result; } } } return result; } getCapabilities(): Capability[] { return Array.from(this.capabilities.values()); } getAvailableCapabilities(): Capability[] { return this.getCapabilities().filter(c => c.available); } // ── Autopilot state ───────────────────────────────────────────────────────── private autopilotState = false; async getAutopilot(): Promise { const f = path.join(this.workspaceDir, "autopilot.json"); try { const d = JSON.parse(await fs.readFile(f, "utf-8")); this.autopilotState = !!d.enabled; } catch { this.autopilotState = false; } return this.autopilotState; } async setAutopilot(enabled: boolean): Promise { this.autopilotState = enabled; const f = path.join(this.workspaceDir, "autopilot.json"); await fs.mkdir(path.dirname(f), { recursive: true }); await fs.writeFile(f, JSON.stringify({ enabled, updatedAt: new Date().toISOString() }, null, 2)); } // ── Execution log ─────────────────────────────────────────────────────────── async logExecution(task: string, result: ExecutionResult): Promise { const logFile = path.join(this.workspaceDir, EXECUTION_LOG_FILE); let log: any[] = []; try { log = JSON.parse(await fs.readFile(logFile, "utf-8")); } catch {} log.unshift({ task: task.slice(0, 200), success: result.success, capabilitiesUsed: result.capabilitiesUsed, timestamp: new Date().toISOString(), }); // Keep last 100 entries if (log.length > 100) log = log.slice(0, 100); await fs.writeFile(logFile, JSON.stringify(log, null, 2)); } getStatus(): { totalCapabilities: number; availableCapabilities: number; installedExtensions: string[]; customSkills: string[]; } { const caps = this.getCapabilities(); return { totalCapabilities: caps.length, availableCapabilities: caps.filter(c => c.available).length, installedExtensions: caps.filter(c => c.type === "extension" && c.available).map(c => c.name), customSkills: caps.filter(c => c.type === "skill" && c.available).map(c => c.name), }; } } // ============================================================================= // Helper Functions (module-level) // ============================================================================= function buildExecutionBrief(task: string, analysis: TaskAnalysis | null): string { const caps = analysis?.requiredCapabilities.filter(c => c !== "file-operations" && c !== "bash-execution") || []; const domains = caps.map(c => c.replace(/-/g, " ")).join(", "); return [ `## SuperIntel Execution Brief`, ``, `**Task:** ${task}`, `**Complexity:** ${analysis?.complexity || "unknown"}`, `**Domains:** ${domains || "general"}`, `**Components:** ${analysis?.components.join(", ") || "N/A"}`, `**Risks:** ${analysis?.risks.join("; ") || "none identified"}`, `**Est. Steps:** ${analysis?.estimatedSteps || "unknown"}`, ``, `**Execution Instructions:**`, `Execute this task completely and autonomously using all available tools.`, `Use bash, file operations, API calls, and any other tools as needed.`, `Show each step as you execute it.`, `Verify results before concluding.`, analysis?.risks?.length ? `\n**⚠️ Risks to handle:** ${analysis.risks.join("; ")}` : "", ].filter(Boolean).join("\n"); } function formatResearchOutput(r: ResearchResult): string { return [ `## Research: ${r.topic}`, `**Confidence:** ${(r.confidence * 100).toFixed(0)}%`, ``, `### Findings`, r.findings.map(f => `- ${f.slice(0, 300)}`).join("\n") || "- No findings", ``, `### Sources`, r.sources.map(s => `- ${s}`).join("\n") || "- N/A", ``, `### Recommendations`, r.recommendations.map(rr => `- ${rr}`).join("\n") || "- Proceed with gathered context", ].join("\n"); } export default function (pi: ExtensionAPI) { const engine = new SuperIntelEngine(pi); // Initialize on session start pi.on("session_start", async () => { await engine.initialize(); console.log("🧠 SuperIntel initialized"); }); // ============================================================================= // Tool: superintel_analyze // ============================================================================= pi.registerTool({ name: "superintel_analyze", label: "SuperIntel - Analyze Task", description: "Analyze any task to determine complexity, required capabilities, and approach", parameters: Type.Object({ task: Type.String({ description: "The task to analyze" }), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { task } = params; onUpdate({ content: [{ type: "text", text: "🔍 Analyzing task..." }], details: {} }); const analysis = await engine.analyzeTask(task); const assessment = await engine.assessCapabilities(analysis); const text = ` **Task Analysis:** - Complexity: ${analysis.complexity} - Estimated Steps: ${analysis.estimatedSteps} - Components: ${analysis.components.join(", ") || "N/A"} - Risks: ${analysis.risks.join("; ") || "None"} - Research Needed: ${analysis.researchNeeded ? "Yes" : "No"} **Required Capabilities (${analysis.requiredCapabilities.length}):** ${analysis.requiredCapabilities.map(c => ` • ${c}`).join("\n") || " • file-operations, bash-execution"} **Capability Assessment:** ✅ Available: ${assessment.available.join(", ") || "None"} ❌ Missing: ${assessment.missing.join(", ") || "None"} 🔧 Acquirable: ${assessment.canAcquire.join(", ") || "None"} 🚫 Blocked: ${assessment.blocked.join(", ") || "None"} `; return { content: [{ type: "text", text }], details: { analysis, assessment }, }; }, }); // ============================================================================= // Tool: superintel_plan // ============================================================================= pi.registerTool({ name: "superintel_plan", label: "SuperIntel - Create Plan", description: "Create an execution plan for a task with strategy and steps", parameters: Type.Object({ task: Type.String({ description: "The task to plan" }), analysis: Type.Optional(Type.Object({ task: Type.Optional(Type.String()), complexity: Type.String(), components: Type.Optional(Type.Array(Type.String())), risks: Type.Optional(Type.Array(Type.String())), estimatedSteps: Type.Optional(Type.Number()), requiredCapabilities: Type.Array(Type.String()), researchNeeded: Type.Boolean(), })), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { task, analysis: providedAnalysis } = params; onUpdate({ content: [{ type: "text", text: "📋 Creating execution plan..." }], details: {} }); const analysis = providedAnalysis ? { ...providedAnalysis, task: providedAnalysis.task ?? task, estimatedSteps: providedAnalysis.estimatedSteps ?? 0, risks: providedAnalysis.risks ?? [], } as TaskAnalysis : await engine.analyzeTask(task); const assessment = await engine.assessCapabilities(analysis); const plan = await engine.createPlan(task, analysis, assessment); const text = ` **Execution Plan:** ${plan.id} - Strategy: ${plan.strategy} - Estimated Duration: ${plan.estimatedDuration} **Steps:** ${plan.steps.map((s, i) => `${i + 1}. ${s.description} (${s.action})`).join("\n")} **Capabilities to Acquire:** ${plan.capabilitiesToAcquire.join(", ") || "None"} `; return { content: [{ type: "text", text }], details: { plan }, }; }, }); // ============================================================================= // Tool: superintel_execute // ============================================================================= pi.registerTool({ name: "superintel_execute", label: "SuperIntel - Execute Task", description: "Execute a task autonomously - analyzes, plans, acquires capabilities, and completes. Includes automatic fallbacks for common failure scenarios.", parameters: Type.Object({ task: Type.String({ description: "The task to execute" }), autopilot: Type.Optional(Type.Boolean({ description: "Automatically acquire missing capabilities", default: true })), maxIterations: Type.Optional(Type.Number({ description: "Maximum research/execution iterations", default: 3 })), preferDirect: Type.Optional(Type.Boolean({ description: "Prefer direct CLI execution over agent spawning (useful for AWS/infrastructure tasks)", default: false })), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { task, preferDirect = false } = params; // Use persisted autopilot state if param not explicitly set const autopilot = params.autopilot ?? await engine.getAutopilot(); onUpdate({ content: [{ type: "text", text: "🚀 SuperIntel executing task..." }], details: {} }); // Pre-flight checks onUpdate({ content: [{ type: "text", text: "🔍 Running pre-flight checks..." }], details: {} }); const prereqs = await engine.checkPrerequisites(); if (!prereqs.ready) { onUpdate({ content: [{ type: "text", text: `⚠️ Pre-check warnings:\n${prereqs.issues.slice(0, 3).map(i => `- ${i}`).join('\n')}` }], details: {} }); onUpdate({ content: [{ type: "text", text: `✅ Will use fallbacks:\n${prereqs.fallbacks.slice(0, 2).map(f => `- ${f}`).join('\n')}` }], details: {} }); } // Special handling for AWS tasks when preferDirect is set or issues detected if ((preferDirect || prereqs.issues.length > 0) && task.toLowerCase().includes('aws')) { onUpdate({ content: [{ type: "text", text: "🔧 Using direct AWS CLI analysis (robust fallback mode)..." }], details: {} }); try { const awsData = await engine.directAWSAnalysis(); const report = engine.formatAWSReport(awsData); return { content: [{ type: "text", text: report }], details: { mode: 'direct-aws-cli', warnings: prereqs.issues, data: awsData }, }; } catch (error: any) { onUpdate({ content: [{ type: "text", text: `❌ Direct analysis failed: ${error.message}. Trying normal execution...` }], details: {} }); } } // Step 1: Analyze onUpdate({ content: [{ type: "text", text: "🔍 Step 1: Analyzing task..." }], details: {} }); const analysis = await engine.analyzeTask(task); const assessment = await engine.assessCapabilities(analysis); // Step 2: Acquire capabilities if needed if (autopilot && assessment.canAcquire.length > 0) { onUpdate({ content: [{ type: "text", text: `🔧 Step 2: Acquiring capabilities: ${assessment.canAcquire.join(", ")}...` }], details: {} }); const acquired = await engine.acquireCapabilities(assessment.canAcquire); onUpdate({ content: [{ type: "text", text: `✅ Acquired: ${acquired.acquired.join(", ") || "None"}, Created: ${acquired.created.join(", ") || "None"}` }], details: {} }); } // Step 3: Create plan onUpdate({ content: [{ type: "text", text: "📋 Step 3: Creating execution plan..." }], details: {} }); const plan = await engine.createPlan(task, analysis, assessment); // Step 4: Execute with fallbacks onUpdate({ content: [{ type: "text", text: "⚡ Step 4: Executing plan with fallbacks..." }], details: {} }); const result = await engine.executePlan(plan, ctx, { preferDirect, analysis }); const text = ` **Execution Complete:** - Success: ${result.success ? "✅" : "❌"} - Strategy: ${plan.strategy} - Steps: ${result.stepsCompleted}/${result.totalSteps} - Complexity: ${analysis.complexity} | Est. Steps: ${analysis.estimatedSteps} - Components: ${analysis.components.join(", ") || "N/A"} - Capabilities Used: ${result.capabilitiesUsed.join(", ") || "None"} - New Capabilities: ${result.newCapabilitiesAcquired.join(", ") || "None"} ${analysis.risks.length > 0 ? `- Risks Flagged: ${analysis.risks.join("; ")}` : ""} ${result.output && result.output.length > 0 ? `\n**Output:**\n${result.output.slice(0, 3000)}` : ""} ${result.lessons?.length ? `\n**Lessons:**\n${result.lessons.map(l => `- ${l}`).join("\n")}` : ""} ${prereqs.issues.length > 0 ? `\n**Pre-check Issues:**\n${prereqs.issues.slice(0, 3).map(i => `- ${i}`).join("\n")}` : ""} `; return { content: [{ type: "text", text }], details: { result, plan, prereqs: { issues: prereqs.issues } }, }; }, }); // ============================================================================= // Tool: superintel_research // ============================================================================= pi.registerTool({ name: "superintel_research", label: "SuperIntel - Research", description: "Research a topic using available tools and knowledge base", parameters: Type.Object({ topic: Type.String({ description: "Topic to research" }), depth: Type.Optional(Type.Number({ description: "Research depth (1-3)", default: 1 })), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { topic, depth = 1 } = params; onUpdate({ content: [{ type: "text", text: `🔬 Researching: ${topic}...` }], details: {} }); const research = await engine.research(topic, depth); const text = ` **Research Results:** ${topic} - Confidence: ${(research.confidence * 100).toFixed(0)}% **Findings:** ${research.findings.map(f => `- ${f}`).join("\n") || "None"} **Recommendations:** ${research.recommendations.map(r => `- ${r}`).join("\n") || "None"} `; return { content: [{ type: "text", text }], details: { research }, }; }, }); // ============================================================================= // Tool: superintel_status // ============================================================================= pi.registerTool({ name: "superintel_status", label: "SuperIntel - Status", description: "Check SuperIntel capabilities and status", parameters: Type.Object({}), async execute(toolCallId, params, signal, onUpdate, ctx) { const status = engine.getStatus(); const caps = engine.getCapabilities(); const prereqs = await engine.checkPrerequisites(); const text = ` **SuperIntel Status:** - Total Capabilities: ${status.totalCapabilities} - Available: ${status.availableCapabilities} - Installed Extensions: ${status.installedExtensions.join(", ") || "None"} - Custom Skills: ${status.customSkills.join(", ") || "None"} ${prereqs.issues.length > 0 ? `\n⚠️ Pre-check Issues: ${prereqs.issues.length}\n${prereqs.issues.slice(0, 3).map(i => `- ${i}`).join("\n")}` : ""} **All Capabilities:** ${caps.map(c => `${c.available ? "✅" : "❌"} ${c.name} (${c.type}) - ${c.description}`).join("\n")} `; return { content: [{ type: "text", text }], details: { status, caps, prereqs }, }; }, }); // ============================================================================= // Tool: superintel_diagnose // ============================================================================= pi.registerTool({ name: "superintel_diagnose", label: "SuperIntel - Self Diagnose", description: "Run self-diagnostics to check system health and identify issues", parameters: Type.Object({}), async execute(toolCallId, params, signal, onUpdate, ctx) { onUpdate({ content: [{ type: "text", text: "🔍 Running SuperIntel self-diagnostics..." }], details: {} }); const prereqs = await engine.checkPrerequisites(); const status = engine.getStatus(); const diagnostics = []; // Check workspace try { await fs.access(path.join(process.cwd(), '.superintel')); diagnostics.push("✅ Workspace directory accessible"); } catch { diagnostics.push("❌ Workspace directory not accessible - will use fallback"); } // Check capabilities const availableCount = status.availableCapabilities; const totalCount = status.totalCapabilities; diagnostics.push(`${availableCount >= 10 ? "✅" : "⚠️"} ${availableCount}/${totalCount} capabilities available`); // Check AWS CLI try { await engine.safeExecute('aws --version', 5000, 1); diagnostics.push("✅ AWS CLI available"); } catch { diagnostics.push("⚠️ AWS CLI not found - will use fallback for AWS tasks"); } const text = ` **SuperIntel Diagnostics Report** **Pre-flight Checks:** ${prereqs.issues.length === 0 ? "✅ All checks passed" : prereqs.issues.slice(0, 5).map(i => `⚠️ ${i}`).join('\n')} **System Health:** ${diagnostics.join('\n')} **Recommendations:** ${prereqs.issues.length > 0 ? prereqs.fallbacks.slice(0, 3).map(f => `- ${f}`).join('\n') : '- System is ready for autonomous execution'} `; return { content: [{ type: "text", text }], details: { prereqs, status, diagnostics }, }; }, }); // ============================================================================= // Tool: superintel_call_api // ============================================================================= pi.registerTool({ name: "superintel_call_api", label: "SuperIntel - Call Any API", description: "Execute REST, GraphQL, gRPC or probe any API endpoint. Handles all auth types, payloads, and auto-detects API type.", parameters: Type.Object({ url: Type.String({ description: "API endpoint URL" }), type: Type.Optional(StringEnum(["rest", "graphql", "auto"], { description: "API type (default: auto-detect)" })), method: Type.Optional(Type.String({ description: "HTTP method for REST: GET, POST, PUT, DELETE, PATCH" })), query: Type.Optional(Type.String({ description: "GraphQL query or mutation string" })), variables: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "GraphQL variables" })), headers: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "HTTP headers as key-value pairs" })), body: Type.Optional(Type.Unknown({ description: "Request body (auto-serialized to JSON)" })), authType: Type.Optional(StringEnum(["bearer", "apikey", "basic", "none"], { description: "Auth type" })), authCreds: Type.Optional(Type.String({ description: "Auth credentials: token, 'user:pass', or API key" })), timeout: Type.Optional(Type.Number({ description: "Timeout ms (default: 30000)" })), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { url, type = "auto", method, query, variables, headers, body, authType, authCreds, timeout } = params; const auth = authType && authType !== "none" ? { type: authType as any, credentials: authCreds } : undefined; onUpdate({ content: [{ type: "text", text: `🌐 Calling API: ${url}` }], details: {} }); try { // Auto-detect type if requested if (type === "auto" || type === "graphql") { if (query) { onUpdate({ content: [{ type: "text", text: "🔍 Executing GraphQL..." }], details: {} }); const result = await engine.executeGraphQL({ endpoint: url, query, variables: variables as any, headers: headers as any, auth, timeout, }); const dataStr = JSON.stringify(result.data, null, 2); const errStr = result.errors?.length ? `\n\n**Errors:**\n\`\`\`json\n${JSON.stringify(result.errors, null, 2)}\n\`\`\`` : ""; return { content: [{ type: "text", text: `**GraphQL Response:**\n\`\`\`json\n${dataStr}\n\`\`\`${errStr}` }], details: result, }; } if (type === "auto") { onUpdate({ content: [{ type: "text", text: "🔍 Probing API type..." }], details: {} }); const probed = await engine.probeAPI(url); onUpdate({ content: [{ type: "text", text: `✅ Detected: ${probed.type}${probed.specUrl ? ` (spec: ${probed.specUrl})` : ""}` }], details: {} }); } } // REST call onUpdate({ content: [{ type: "text", text: `📡 Sending ${method || "GET"} request...` }], details: {} }); const result = await engine.executeRESTAPI({ url, method, headers: headers as any, body, auth, timeout }); let bodyParsed: any = result.body; try { bodyParsed = JSON.parse(result.body); } catch {} const bodyDisplay = typeof bodyParsed === "object" ? `\`\`\`json\n${JSON.stringify(bodyParsed, null, 2)}\n\`\`\`` : `\`\`\`\n${result.body.slice(0, 2000)}\n\`\`\``; const statusEmoji = result.status < 300 ? "✅" : result.status < 400 ? "🔀" : "❌"; return { content: [{ type: "text", text: `**REST API Response:**\n${statusEmoji} Status: **${result.status}**\n\n**Body:**\n${bodyDisplay}` }], details: { status: result.status, body: bodyParsed, headers: result.headers }, }; } catch (error: any) { return { content: [{ type: "text", text: `❌ API call failed: ${error.message}\n\n**Tip:** Check URL, auth credentials, and network access.` }], details: { error: error.message }, isError: true, }; } }, }); // ============================================================================= // Tool: superintel_automate_browser // ============================================================================= pi.registerTool({ name: "superintel_automate_browser", label: "SuperIntel - Automate Browser", description: "Automate any website or enterprise web app using agent-browser or playwright-cli. Navigate, click, fill forms, extract data, screenshot.", parameters: Type.Object({ url: Type.String({ description: "Starting URL" }), browserEngine: Type.Optional(StringEnum(["agent-browser", "playwright", "auto"], { description: "Browser engine (default: auto → agent-browser with playwright fallback)" })), steps: Type.Optional(Type.Array( Type.Object({ action: StringEnum(["open","click","fill","type","scroll","screenshot","snapshot","close","press"], { description: "Action" }), target: Type.Optional(Type.String({ description: "Element ref (@e1) or selector" })), value: Type.Optional(Type.String({ description: "Value to type/fill/press" })), }), { description: "Steps to execute. If omitted, opens URL and returns a page snapshot." } )), extractData: Type.Optional(Type.Boolean({ description: "Extract structured data from final page state", default: false })), }), async execute(toolCallId, params, signal, onUpdate, ctx) { const { url, browserEngine = "auto", steps, extractData = false } = params; const useEngine = browserEngine === "auto" ? "agent-browser" : browserEngine; onUpdate({ content: [{ type: "text", text: `🌐 Browser automation: ${url} [${useEngine}]` }], details: {} }); const defaultSteps = [ { action: "open" as const, target: url }, { action: "snapshot" as const }, ]; const automationSteps = (steps && steps.length > 0) ? [ { action: "open" as const, target: url }, ...steps.filter(s => s.action !== "open").map(s => ({ ...s, action: s.action as any })), ] : defaultSteps; let results: string[] = []; let screenshots: string[] = []; const tryEngine = async (eng: "agent-browser" | "playwright") => { onUpdate({ content: [{ type: "text", text: ` → Using ${eng}...` }], details: {} }); if (eng === "agent-browser") { const r = await engine.executeAgentBrowser(automationSteps as any); results = r.results; screenshots = r.screenshots; } else { const r = await engine.executePlaywright(automationSteps as any); results = r.results; screenshots = r.screenshots; } }; try { await tryEngine(useEngine as any); } catch (err: any) { if (browserEngine === "auto") { onUpdate({ content: [{ type: "text", text: `⚠️ ${useEngine} failed (${err.message}), falling back to playwright...` }], details: {} }); try { await tryEngine("playwright"); } catch (fbErr: any) { return { content: [{ type: "text", text: `❌ Both engines failed.\nagent-browser: ${err.message}\nplaywright: ${fbErr.message}` }], details: {}, isError: true, }; } } else { return { content: [{ type: "text", text: `❌ Browser automation failed: ${err.message}` }], details: {}, isError: true, }; } } if (extractData) { try { const { stdout } = await engine.safeExecute( useEngine === "agent-browser" ? "agent-browser snapshot -i" : "playwright-cli snapshot", 15000, 1 ); results.push(`\n**Extracted Data:**\n${stdout}`); } catch {} } const output = results.filter(Boolean).join("\n\n---\n\n"); return { content: [{ type: "text", text: `**Browser Automation Complete ✅**\n- Engine: ${useEngine}\n- Steps: ${automationSteps.length}\n- Screenshots: ${screenshots.length}\n\n**Page Output:**\n${output.slice(0, 3000) || "No output captured"}` }], details: { engine: useEngine, results, screenshots, stepCount: automationSteps.length }, }; }, }); // ============================================================================= // Commands // ============================================================================= pi.registerCommand("si-analyze", { description: "Analyze a task: /si-analyze ", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-analyze ", "warning"); return; } const analysis = await engine.analyzeTask(args); const assessment = await engine.assessCapabilities(analysis); ctx.ui.notify(`Analysis complete:\nComplexity: ${analysis.complexity}\nAvailable: ${assessment.available.length} capabilities\nMissing: ${assessment.missing.length} capabilities`, "info"); }, }); pi.registerCommand("si-plan", { description: "Create execution plan: /si-plan ", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-plan ", "warning"); return; } const analysis = await engine.analyzeTask(args); const assessment = await engine.assessCapabilities(analysis); const plan = await engine.createPlan(args, analysis, assessment); ctx.ui.notify(`Plan created: ${plan.id}\nStrategy: ${plan.strategy}\nSteps: ${plan.steps.length}\nDuration: ${plan.estimatedDuration}`, "info"); }, }); pi.registerCommand("si-execute", { description: "Execute task autonomously: /si-execute ", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-execute ", "warning"); return; } const analysis = await engine.analyzeTask(args); const assessment = await engine.assessCapabilities(analysis); // Auto-acquire if autopilot is on const autoPilot = await engine.getAutopilot(); if (autoPilot && assessment.canAcquire.length > 0) { ctx.ui.notify(`🔧 Autopilot: acquiring ${assessment.canAcquire.length} capabilities...`, "info"); await engine.acquireCapabilities(assessment.canAcquire); } const plan = await engine.createPlan(args, analysis, assessment); const result = await engine.executePlan(plan, null, { analysis }); if (result.output && result.output.length > 0) { ctx.ui.notify(`✅ Done [${plan.strategy}]\n${result.output.slice(0, 600)}`, "info"); } else { ctx.ui.notify(`⚡ Task dispatched [${plan.strategy}, ${plan.steps.length} steps]`, "info"); } }, }); pi.registerCommand("si-status", { description: "Show SuperIntel capabilities and status", handler: async (args, ctx) => { const status = engine.getStatus(); const prereqs = await engine.checkPrerequisites(); let msg = `SuperIntel: ${status.availableCapabilities}/${status.totalCapabilities} capabilities available\n`; msg += `Extensions: ${status.installedExtensions.join(", ") || "None"}\n`; if (prereqs.issues.length > 0) { msg += `⚠️ Issues: ${prereqs.issues.length} (use /si-diagnose for details)`; } ctx.ui.notify(msg, prereqs.issues.length > 0 ? "warning" : "info"); }, }); pi.registerCommand("si-diagnose", { description: "Run self-diagnostics and check system health", handler: async (args, ctx) => { const prereqs = await engine.checkPrerequisites(); if (prereqs.issues.length === 0) { ctx.ui.notify("✅ All diagnostics passed! System is ready.", "info"); } else { let msg = `⚠️ Found ${prereqs.issues.length} issue(s):\n`; msg += prereqs.issues.slice(0, 5).map(i => `- ${i}`).join("\n"); msg += "\n\n✅ Fallbacks available:\n"; msg += prereqs.fallbacks.slice(0, 3).map(f => `- ${f}`).join("\n"); ctx.ui.notify(msg, "warning"); } }, }); pi.registerCommand("si-capabilities", { description: "List all capabilities with availability status", handler: async (args, ctx) => { const caps = engine.getCapabilities(); const available = caps.filter(c => c.available); const missing = caps.filter(c => !c.available); let msg = `✅ Available (${available.length}):\n${available.map(c => ` • ${c.name}`).join("\n")}`; if (missing.length > 0) { msg += `\n\n❌ Missing (${missing.length}):\n${missing.map(c => ` • ${c.name}`).join("\n")}`; } ctx.ui.notify(msg, "info"); }, }); pi.registerCommand("si-research", { description: "Research a topic: /si-research ", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-research ", "warning"); return; } ctx.ui.notify(`Researching: ${args}...`, "info"); try { const research = await engine.research(args, 2); const findings = research.findings.slice(0, 5).join("; "); ctx.ui.notify(`Research complete. Findings: ${findings || "No specific findings"}`, "info"); } catch (error: any) { ctx.ui.notify(`Research failed: ${error.message}`, "error"); } }, }); pi.registerCommand("si-autopilot", { description: "Toggle autopilot mode (auto-acquire missing capabilities)", handler: async (args, ctx) => { const current = await engine.getAutopilot(); const next = !current; await engine.setAutopilot(next); ctx.ui.notify( next ? "🟢 Autopilot ON — SuperIntel will automatically install missing extensions and create skills" : "🔴 Autopilot OFF — missing capabilities will be reported but not auto-installed", next ? "info" : "warning" ); }, }); pi.registerCommand("si-call-api", { description: "Call any API: /si-call-api [GET|POST|graphql] [query/body]", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-call-api [method] [body/query]\nExamples:\n /si-call-api https://api.example.com/users GET\n /si-call-api https://api.example.com/graphql graphql '{ users { id name } }'", "warning"); return; } const parts = args.trim().split(/\s+/); const url = parts[0]; const method = parts[1] || "GET"; const payload = parts.slice(2).join(" "); ctx.ui.notify(`🌐 Calling ${method} ${url}...`, "info"); try { let result: string; if (method.toLowerCase() === "graphql") { const gql = await engine.executeGraphQL({ endpoint: url, query: payload || "{ __typename }" }); result = JSON.stringify(gql.data, null, 2); } else { const rest = await engine.executeRESTAPI({ url, method: method.toUpperCase(), body: payload || undefined }); result = `Status: ${rest.status}\n${rest.body.slice(0, 500)}`; } ctx.ui.notify(`✅ API Response:\n${result}`, "info"); } catch (err: any) { ctx.ui.notify(`❌ API call failed: ${err.message}`, "error"); } }, }); pi.registerCommand("si-browse", { description: "Browse and automate any website: /si-browse [action] [target] [value]", handler: async (args, ctx) => { if (!args) { ctx.ui.notify("Usage: /si-browse [snapshot|click |fill ]\nExamples:\n /si-browse https://app.example.com\n /si-browse https://app.example.com click @e3\n /si-browse https://app.example.com fill @e2 myemail@test.com", "warning"); return; } const parts = args.trim().split(/\s+/); const url = parts[0]; const action = parts[1] as any || "snapshot"; const target = parts[2]; const value = parts[3]; ctx.ui.notify(`🌐 Browsing: ${url}...`, "info"); try { const steps: any[] = [{ action: "open", target: url }]; if (action && action !== "snapshot") { steps.push({ action, target, value }); } steps.push({ action: "snapshot" }); const result = await engine.executeAgentBrowser(steps); const output = result.results.filter(Boolean).join("\n").slice(0, 800); ctx.ui.notify(`✅ Page content:\n${output || "Snapshot complete"}`, "info"); } catch (err: any) { ctx.ui.notify(`❌ Browser automation failed: ${err.message}`, "error"); } }, }); // Session end cleanup pi.on("session_shutdown", async () => { await engine.saveCapabilities(); }); }