Commit ·
20f108c
0
Parent(s):
Duplicate from teddyoas/PHANTOM-v2
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+13
- .editorconfigAdded+12
- .gitattributesAdded+12
- .github/workflows/ci.ymlAdded+49
- .gitignoreAdded+13
- .npmignoreAdded+12
- .prettierrcAdded+13
- CONTEXT.mdAdded+232
- DockerfileAdded+23
- LICENSEAdded+21
- README.mdAdded+246
- chat.mjsAdded+200
- guides/hackersploit_fundamentals.mdAdded+51
- lib/config.mjsAdded+15
- lib/dashboard.mjsAdded+846
- lib/env.mjsAdded+231
- lib/evolve.mjsAdded+867
- lib/logger.mjsAdded+17
- lib/mission.mjsAdded+181
- lib/playwright-tool.mjsAdded+122
- lib/recon-analysis.mjsAdded+350
- lib/recon-intelligence.mjsAdded+388
- lib/recon-learning.mjsAdded+294
- lib/recon-planner.mjsAdded+397
- lib/recon.mjsAdded+425
- lib/runtime.mjsAdded+250
- lib/self_improve.mjsAdded+2548
- lib/server.mjsAdded+394
- lib/session.mjsAdded+125
- lib/tools.mjsAdded
- lib/tui.mjsAdded+159
- lib/visual.mjsAdded+131
- package-lock.jsonAdded+597
- package.jsonAdded+49
- phantom-logo.htmlAdded+294
- phantom.mjsAdded
- run.shAdded+110
- src/agents/agent.tsAdded+397
- src/agents/manager.tsAdded+126
- src/agents/types.tsAdded+74
- src/core/config.tsAdded+155
- src/core/eventbus.tsAdded+41
- src/core/hacker-tools.tsAdded
- src/core/persistence.tsAdded+62
- src/core/tools.tsAdded+79
- src/gui/server.tsAdded+1012
- src/index.tsAdded+23
- src/providers/openai.tsAdded+318
- src/ui/panels.tsAdded+153
- src/ui/terminal.tsAdded+275
12345678910111213node_modules/dist/.env*.log.git/.gitattributes.gitignore.github/test/tmp/.tmp/.DS_Store*.tsbuildinfo123456789101112root = true
[*]indent_style = spaceindent_size = 2end_of_line = lfcharset = utf-8trim_trailing_whitespace = trueinsert_final_newline = true
[*.md]trim_trailing_whitespace = false123456789101112* text=auto eol=lf*.mjs text eol=lf*.ts text eol=lf*.json text eol=lf*.md text eol=lf*.sh text eol=lf*.yml text eol=lfDockerfile text eol=lf.gitattributes text eol=lf.gitignore text eol=lf.editorconfig text eol=lfLICENSE text eol=lf12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849name: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: quality: runs-on: ubuntu-latest strategy: matrix: node-version: [20, 22]
steps: - uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: 'npm'
- name: Install dependencies run: npm ci
- name: Check JS syntax run: | node --check phantom.mjs node --check lib/tools.mjs node --check lib/config.mjs node --check lib/runtime.mjs node --check lib/visual.mjs
- name: TypeScript build run: npm run build
- name: Verify CLI starts run: timeout 5 node phantom.mjs --list 2>&1 | grep -q '🔧' || true
- name: Run tests run: npm test
- name: Verify tool count run: | COUNT=$(timeout 5 node phantom.mjs --list 2>&1 | wc -l) echo "Tools: $COUNT" test "$COUNT" -gt 100 || (echo "Too few tools ($COUNT)" && exit 1)12345678910111213node_modules/dist/.env*.tsbuildinfo*.log.tmp/tmp/config.jsonlib/generated/lib/learned/.config/phantom/*.vtt*.srt123456789101112node_modules/dist/test/src/.git/.github/.gitignore.gitattributes.prettierrc.editorconfig*.logtsconfig.json12345678910111213# Phantom — formatting conventionsroot = true
[*]indent_style = spaceindent_size = 2end_of_line = lfcharset = utf-8trim_trailing_whitespace = trueinsert_final_newline = true
[*.md]trim_trailing_whitespace = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232# Phantom — Development Context
## What is Phantom?
**Phantom** is a multi-agent terminal AI turned **cybersecurity assistant** — zero-dependency on any system with Node.js 18+ (desktop, Termux on Android, CI). It spawns AI agents that use tools autonomously to perform recon, vulnerability research, scanning, and exploitation tasks.
## Current State (as of latest commit: `ea7bc25`)
**100+ hacker tools** in dual runtime (`.mjs` zero-dep + `src/` TypeScript):
| Category | Tools | Count ||----------|-------|-------|| Core | shell, web_fetch, decode, file_analyze, dns_lookup, hash | 6 || Advanced | whois, port_scan, http_headers, ssl_check, sub_enum, crawl, vt_check, yara | 8 || Workflow | recon, cve_search, searchsploit, bruteforce | 4 || File ops | file_read, file_write, file_edit, file_search, file_list | 5 || Self | self_info, self_read, self_edit | 3 || Auto-scan | vuln_scan, report_save | 2 || Sessions | session_save, session_load | 2 || Knowledge | knowledge_add, knowledge_search | 2 || Playbook | playbook_create, playbook_list, playbook_run, playbook_edit | 4 || Recon | geoip, dns_zone, http_methods, robots_txt, email_verify | 5 || Utility | reverse_dns, wayback, cert_expiry, cors_test, jwt_decode, hash_crack | 6 || Web sec | dir_bruteforce, xss_scan, sql_detect, open_redirect | 4 || OSINT | shodan_search, email_breach, github_dork, sub_takeover | 4 || Plugin | plugin_load, plugin_create | 2 || Reporting | report_export | 1 || LLM config | llm_config | 1 || Distro | distro (PRoot env mgmt) | 1 || Code gen | code_gen | 1 || Self-build | self_add_tool | 1 || GUI | dashboard | 1 || Bug bounty | hackerone (programs, scope, reports, submit) | 1 |
## Project Structure
```/root/phantom/├── phantom.mjs ← MAIN: Zero-dep standalone entry (what actually runs)├── run.sh ← Zero-setup bootstrap launcher├── package.json ← NPM metadata (optional deps)├── tsconfig.json ← TypeScript config├── src/ ← TypeScript source (refactored version)│ ├── agents/│ │ ├── agent.ts ← Agent class with capabilities + persistence│ │ ├── manager.ts ← Agent orchestrator│ │ └── types.ts ← Types│ ├── core/│ │ ├── config.ts ← Configuration│ │ ├── eventbus.ts ← Pub/sub event bus│ │ ├── persistence.ts ← Memory/knowledge save/load│ │ ├── tools.ts ← Dynamic tool system│ │ └── hacker-tools.ts ← 18 cybersecurity tool implementations│ ├── providers/│ │ └── openai.ts ← OpenAI + Ollama provider│ ├── ui/│ │ ├── panels.ts ← Desktop terminal UI│ │ └── ... ← Terminal, Termux, Theme│ └── index.ts ← Entry point├── gui/│ └── server.ts ← Web dashboard server└── CONTEXT.md ← THIS FILE```
## How to Run
### Quick install (zero-setup)```bashbash <(curl -s https://raw.githubusercontent.com/Njap-png/Phantom/main/run.sh)```
### Clone the full repo```bashgit clone https://github.com/Njap-png/Phantom.gitcd Phantomphantom # if symlinked, or:node phantom.mjs # zero-dep fallback```
### One command (after symlink)```bashphantom # conversational REPL (default)phantom --recon example.com # full recon + reportphantom --tool cve_search "nginx" # run one toolphantom --tool port_scan scanme.org # port scanphantom --list # list all 62 toolsphantom --gui # web dashboard (port 8080)phantom --api # REST API server (port 9090)phantom --help # show help```
### With LLM```bashOPENAI_API_KEY=sk-... phantom # with AI agentsOLLAMA_HOST=http://localhost:11434 phantom # local LLM (offline)```
### No PATH symlink```bashnode phantom.mjs # same as above```
## Conversational REPL
Default mode is a **Hermes/Claude Code** style interactive shell. Features:- `❯` prompt with arrow-key history, cursor movement, multi-line (`\` continuation)- `/help`, `/tools`, `/model`, `/clear`, `/save`, `/load`, `/quit` commands- Code blocks rendered with `┌─` / `│` / `└─` box-drawing- Tool calls shown with `⚡ @tool|args`- Auto-detects LLM provider; falls back to tools-only mode if no key set
## REST API (`--api`)
Start on port 9090 (or `PHANTOM_API_PORT`):```bashphantom --api```
All responses are JSON `{ ok: true, data }` or `{ ok: false, error }`.
| Method | Endpoint | Description ||--------|----------|-------------|| `GET` | `/api` | API overview, tool list, version || `GET` | `/api/tools` | List all 62 tools || `GET` | `/api/info` | Tool metadata || `GET` | `/api/tool/:name` | Specific tool info || `GET` / `POST` | `/api/run?tool=X&args=Y` or POST `{tool, args}` | Execute any tool || `GET` | `/api/playbooks` | List playbooks || `GET` / `POST` | `/api/playbook/run?name=X&vars=Y` | Run a playbook || `GET` | `/api/reports` | List reports || `GET` | `/api/report/:name` | View a report || `GET` | `/api/health` | Health check (status, pid, uptime, tool count) |
## Web Dashboard (`--gui`)
Zero-dep web UI at **http://localhost:8080** (or `PHANTOM_PORT`):```bashphantom --gui```
**Tabs:** Tools grid (search + run), Playbooks (list + run with vars), Reports (view saved).
Built with vanilla JS/HTML/CSS. No npm, no CDN, no build step. Works in any browser including mobile Termux.
## Offline / Local LLM
Ollama fully supported:```bashOLLAMA_HOST=http://localhost:11434 phantom```
Phantom will use Ollama for AI features (agent mode, code gen, playbook creation) instead of OpenAI. No internet needed.
## Multi-Provider LLM
**8 providers** at runtime — no restart. Switch with `@llm_config|<provider>` or `llm_config|<provider>`.
| Provider | Env Var | Default Model ||----------|---------|---------------|| OpenAI | `OPENAI_API_KEY` | gpt-4o || Anthropic | `ANTHROPIC_API_KEY` | claude-sonnet-4 || Google Gemini | `GEMINI_API_KEY` | gemini-2.0-flash || Groq | `GROQ_API_KEY` | llama-3.3-70b || DeepSeek | `DEEPSEEK_API_KEY` | deepseek-chat || Mistral | `MISTRAL_API_KEY` | mistral-large || OpenRouter | `OPENROUTER_API_KEY` | claude-sonnet-4 || Ollama | `OLLAMA_HOST` (base URL) | llama3 |
Set key at runtime (persisted to `~/.config/phantom/config.json`):```@llm_config|set ANTHROPIC_API_KEY sk-ant-...```
Switch at runtime:```@llm_config|anthropic@llm_config|ollama@llm_config|list```
## Config System
Auto-loads from `~/.config/phantom/config.json`:```json{ "VT_API_KEY": "your-key-here", "report_dir": "/path/to/reports", "default_provider": "anthropic"}```
## Tool Calling Format (for LLM agents)```@tool_name|argument```
## What's Left To Do
- [x] **Web UI / dashboard** — `phantom --gui` or `npm run dashboard`- [x] **Web app security scanning** — dir bruteforce, XSS, SQLi, open redirect- [x] **OSINT & recon tools** — Shodan, email breach, GitHub dork, subdomain takeover- [x] **Plugin system** — Extend Phantom with external plugins- [x] **Report export** — HTML/PDF report generation- [x] **Local model support** — Offline LLM via Ollama- [x] **Conversational REPL** — Hermes/Claude Code style interactive shell- [x] **PRoot/Termux detection** — Distro management + env-aware- [x] **HackerOne bug bounty integration** — programs, scope, reports, submit, test auth- [x] **Git credentials auto-config** — Auto-push evolution improvements- [x] **Config case-sensitivity** — Preserve token case for API credentials- [ ] **Autonomous agent chaining** — Multi-agent parallel playbook runs- [ ] **Distributed scanning** — Phantom runs across multiple hosts- [ ] **Self-healing tools** — Auto-detect broken deps, suggest install- [ ] **Session memory across restarts** — Persistent agent memory
## External Deps (optional)- `OPENAI_API_KEY` — enables code_gen, self_add_tool, playbook_create via LLM- `VT_API_KEY` — VirusTotal hash lookups- `HACKERONE_API_USERNAME` — HackerOne API token identifier (Basic Auth username)- `HACKERONE_API_TOKEN` — HackerOne API token value (Basic Auth password)- `yara` CLI — YARA scanning (`apt install yara`)- `whois` CLI — WHOIS lookups (`apt install whois`)- `sshpass` CLI — SSH brute force (`apt install sshpass`)- `mysql` CLI — MySQL brute force (`apt install mysql-client`)- `searchsploit` CLI — exploit-db queries (`apt install exploitdb`)- `openssl` — cert_expiry tool (usually pre-installed)
## Git Config- User: `Njap-png`- Email: `teddy.njagi.w@gmail.com`- Remote: `https://github.com/Njap-png/Phantom.git`- Auth: Token stored in config (`@config|set GIT_TOKEN <token>`)- Latest: 4 commits ahead (HackerOne auth fix, config case-sensitivity, test auth, CONTEXT update)1234567891011121314151617181920212223FROM node:22-alpine
WORKDIR /app
# Install dependencies needed by tools# which: for external binary detection# curl, wget, git: for web-fetch, recon, install tools# ca-certificates: for HTTPSRUN apk add --no-cache which curl wget git ca-certificates
# Copy manifest + install TS deps (devDep for type-checking)COPY package.json package-lock.json* ./RUN npm ci --omit=dev || npm i --omit=dev
# Copy sourceCOPY . .
# Build TypeScript stubsRUN npm run build
# Default entry: REPL modeENTRYPOINT ["node", "phantom.mjs"]CMD []123456789101112131415161718192021MIT License
Copyright (c) 2025 Njap-png
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246# 👻 PHANTOM
[](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml)
**Multi-agent cybersecurity AI assistant** — autonomous penetration testing, reconnaissance, vulnerability analysis, and AI-powered security operations, all from your terminal.
```· · · · · · ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ █ ═══ ═══ ═══ ═══ █▐█ · · · · █▌▐█ ╔═══════════╗ █▌▐█ ║ ◈ ◈ ║ █▌▐█ ║ ╲ ╱ ╲ ╱ ║ █▌▐█ ╚═══════════╝ █▌▐█ ● █▌ ▀▄ ═══════════ ▄▀ P H A N T O M cybersecurity AI · v0.2.0```
## Quick Start
```bash# Clonegit clone https://github.com/Njap-png/Phantom.gitcd Phantom
# Run (no install needed — zero-dep ESM)node phantom.mjs
# Or Dockerdocker build -t phantom .docker run -it phantom```
## Features
### 🔧 108 Built-in Tools
| Category | Tools ||---|---|| **Core** | shell, web_fetch, decode, encode, hash, file_analyze, batch, code_analyze, code_gen, yara || **Recon** | dns_lookup, whois, sub_enum, subfinder (ext), port_scan, http_headers, ssl_check, crawl, geoip, dns_zone, reverse_dns, wayback, robots_txt, amass (ext), dnsx (ext), httpx (ext), naabu (ext), katana (ext), sub_takeover || **Web** | dir_bruteforce, xss_scan, sql_detect, open_redirect, cors_test, http_methods, ffuf (ext), arjun (ext) || **CVE/Exploit** | cve_search, searchsploit, shodan_search, nuclei (ext) || **Auth** | bruteforce, jwt_decode, hash_crack, hashcat (ext) || **OSINT** | email_verify, email_breach, github_dork, vt_check, cloud_enum, wayback || **Network** | netcat (ext), nmap (ext), masscan (ext), dig, ping, traceroute, netstat || **Crypto** | ssl_check, cert_expiry, encrypt, decrypt, random || **File** | file_read, file_write, file_edit, file_search, file_list || **Self** | self_info, self_read, self_edit, self_add_tool, distro || **Knowledge** | knowledge_add, knowledge_search || **Automation** | playbook_create, playbook_list, playbook_run, playbook_edit, recon, vuln_scan, report_save, report_export, session_save, session_load, schedule |
> Type `node phantom.mjs --list` for the full list. External tools (marked `ext`) require installation — Phantom detects them at runtime.
### 🚀 New in v0.2.0
| Feature | Description ||---|---|| **`--json` output** | `phantom --tool --json <name> <input>` — structured `{ok, data}` JSON || **Tool piping** | `phantom --tool --pipe "subfinder\|dom\|httpx"` — chain output→input || **Scheduled scanning** | `@schedule\|daily\|recon\|target` — recurring automated scans || **Scope management** | `@scope\|add\|domain.com` — target scoping for batch ops || **Shell audit trail** | Every command logged, dangerous patterns blocked || **`--quiet` mode** | `PHANTOM_QUIET=1` or `--quiet` — suppress banner/status || **`--version`** | `phantom --version` — prints version and exits || **Docker** | `docker build -t phantom .` — Alpine-based container || **TAB autocomplete** | `@tool_name|` completion in REPL |
### 🤖 Multi-Agent Team
4 specialized agents working in parallel:
| Agent | Role | Specialty ||---|---|---|| **Lyra** | Coordinator | Breaks down tasks, delegates, synthesizes results || **Nova** | Recon | DNS, OSINT, scanning, surface mapping || **Orion** | Exploit | Vulnerability research, pentesting, brute force || **Vega** | Defense | SSL, CORS, JWT, hardening, monitoring |
Use `@delegate|name|task` for agent-to-agent delegation.
### 🎯 One-Shot Commands
```bashphantom --recon example.com # Full recon (7 steps + report)phantom --tool port_scan scanme.org # Run a single toolphantom --tool --json cve_search "apache 2.4.49" # JSON outputphantom --tool --pipe "subfinder|dom|httpx|nuclei" # Tool chainphantom --list # List all 108 toolsphantom --list --json # List as JSONphantom --gui # Web dashboard (port 8080)phantom --api # REST API (port 9090)phantom --quiet # Suppress bannerphantom --version # Show versionphantom --help # Full usage```
### 💬 Interactive REPL
```bashphantom👻 recon example.com👻 /model groq # Switch LLM👻 @schedule|daily|recon|example.com # Schedule daily scan👻 @scope|add|example.com # Add to target scope👻 @pipe|subfinder|example.com|httpx # Chain tools inline```
| Command | Description ||---|---|| `/help` | Show all commands || `/tools` | List available tools || `/model` | Show/switch LLM provider || `/delegate <agent> <task>` | Delegate to a specialist || `/talk <agent> <message>` | Chat directly with an agent || `/agents` | List agent team with status || `/gui` | Start web dashboard || `/api` | Start REST API || `/save <name>` | Save session || `/load <name>` | Load session || `/clear` | Clear screen || `/quit` | Exit |
REPL also supports:- `@tool_name|args` — run any tool inline- `@pipe|tool1|input|tool2` — chain tools- `@schedule|interval|tool|target` — schedule recurring scans- `@scope|add|domain` — manage target scope- `@workspace_write|key|value` — save findings- `TAB` — autocomplete tool names
## CI
Every push runs across Node.js 20 and 22:
- JS syntax check- TypeScript build (`tsc --noEmit`)- CLI verification (`--list` with tool count > 100)- **34 test cases** (core runtime + features)
[](https://github.com/Njap-png/Phantom/actions/workflows/ci.yml)
## LLM Providers
Phantom auto-detects available providers on startup. Supported:
| Provider | Config ||---|---|| **Ollama** (local, default) | Auto-detected if running || **OpenAI** | `OPENAI_API_KEY` env or `@llm_config\|set\|openai_api_key\|sk-...` || **OpenCode** (via Hermes) | `@llm_config\|opencode\|deepseek-v4-flash-free` || **Groq** | `GROQ_API_KEY` env || **Anthropic** | `ANTHROPIC_API_KEY` env || **Gemini** | `GEMINI_API_KEY` env || **DeepSeek** | `DEEPSEEK_API_KEY` env || **Mistral** | `MISTRAL_API_KEY` env || **OpenRouter** | `OPENROUTER_API_KEY` env |
Set API keys via interactive prompt on first run, or directly in `~/.config/phantom/config.json`.
### Example: Hermes Agent / OpenCode provider
Phantom works with Hermes Agent's OpenCode provider chain:
```bash# Via @llm_config interactive👻 @llm_config|opencode|deepseek-v4-flash-free
# Or set env varsexport PHANTOM_LLM_PROVIDER=opencodeexport HERMES_OPCODE_API_KEY=sk-your-key-here # <-- REPLACE with your keyphantom```
> ⚠ Never commit real API keys to Git. Use environment variables or the interactive `@llm_config` prompt instead.
## Configuration
All config lives in `~/.config/phantom/`:
- `config.json` — LLM provider settings, API keys, defaults- `memories/` — Per-agent persistent memory- `tools/` — Custom tool definitions- `reports/` — Generated security reports- `knowledge/` — Persistent knowledge base entries- `scope.json` — Target scope definitions- `projects/` — Per-project workspace data- `schedules.json` — Scheduled scan definitions
## Environment Variables
| Variable | Default | Description ||---|---|---|| `PHANTOM_MAX_ITER` | `8` | Max ReAct loop iterations per request || `PHANTOM_TOOL_TIMEOUT` | `30000` | Shell command timeout (ms) || `PHANTOM_LLM_PROVIDER` | `openai` | Default LLM provider || `PHANTOM_PROVIDERS_READY` | — | Comma-separated ready providers || `PHANTOM_QUIET` | — | Suppress banner/status output || `HERMES_OPCODE_API_KEY` | — | Hermes Agent / OpenCode provider API key |
## Architecture
```User Input │ ▼ Lyra (Coordinator) │ ├── Nova (Recon) — DNS, ports, OSINT ├── Orion (Exploit) — CVEs, brute force, SQLi └── Vega (Defense) — SSL, CORS, hardening │ ▼ Shared Workspace (agent-to-agent data) │ ▼ Synthesized Response```
- **Zero dependencies** — runs on vanilla Node.js ESM- **EventBus** pattern for decoupled agent communication- **ReAct loop** with 8 configurable tool iterations- **Persistent memory** for each agent- **Auto-save** conversations across sessions
## Requirements
- **Node.js** 20+ (ESM support)- **Termux** / **Linux** / **macOS** / **WSL**- LLM provider (Ollama recommended for local use)- Docker (optional, for containerized use)
## Known Issues
- System tool detection runs once at startup — tools installed later won't show until restart- Agent delegation requires an LLM provider (not available in tools-only mode)- Some tools (vt_check, shodan_search) require API keys in environment- Dashboard requires `blessed` for terminal split-panel UI (optional dep)
## License
MIT# test123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200#!/usr/bin/env node// Chat — Phantom conversational CLI// Zero deps. Run: node chat.mjs
import { createRequire } from "module";const $r = createRequire(import.meta.url);import fs from "fs";import { resolve } from "path";
const R = "\x1b[0m";const _B = "\x1b[1m";const _D = "\x1b[2m";function c(n) { const colors = { green: "32", cyan: "36", dim: "2", yellow: "33", magenta: "35", red: "31", blue: "34" }; return colors[n] ? `\x1b[${colors[n]}m` : "";}
// ── Provider (from phantom.mjs) ──export function createProvider() { const PROVIDERS = { openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: o => ({ model: o.model, messages: o.messages, max_tokens: 4096 }), parse: d => d.content?.[0]?.text || "...", auth: k => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, openrouter:{ url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: o => ({ model: o.model, messages: o.messages, stream: false }), parse: d => d.message?.content?.trim() || "...", auth: () => ({}) }, opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "nemotron-3-ultra-free", chatPath: "/chat/completions", fmt: o => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 256 }), parse: d => d.choices?.[0]?.message?.content?.trim() || "...", auth: k => ({ Authorization: `Bearer ${k}` }) }, };
const providerName = process.env.PHANTOM_LLM_PROVIDER || "openai"; function getProvider() { return PROVIDERS[providerName] || PROVIDERS.openai; } function getKey(p) { if (!p.keyEnv) return ""; const k = process.env[p.keyEnv]; if (k) return k; // Check project root config (for USB portability) try { const projectRoot = resolve(new URL(".", import.meta.url).pathname, ".."); const projectConfigPath = resolve(projectRoot, "config.json"); const cfg = JSON.parse(fs.readFileSync(projectConfigPath, "utf8")); if (cfg[p.keyEnv]) return cfg[p.keyEnv]; } catch {} // Check user config try { const cfg = JSON.parse(fs.readFileSync(resolve(process.env.HOME || "/root", ".config", "phantom", "config.json"), "utf8")); return cfg[p.keyEnv] || ""; } catch { return ""; } }
return { get provider() { return providerName; }, get hasLLM() { const p = getProvider(); return !!(p.keyEnv ? getKey(p) : true); }, async chat(messages, opts = {}) { const p = getProvider(); const key = getKey(p); if (p.keyEnv && !key) return `[${providerName}] No API key. Set ${p.keyEnv} env var.`; const model = opts.model || p.defaultModel; try { let url = `${p.url}${p.chatPath.replace("{model}", model)}`; const h = { "Content-Type": "application/json", ...p.auth(key) }; const body = JSON.stringify(p.fmt({ model, messages })); const r = await fetch(url, { method: "POST", headers: h, body, signal: AbortSignal.timeout(60000) }); if (!r.ok) { const t = await r.text().catch(() => ""); return `[${r.status}] ${t.substring(0, 200)}`; } const d = await r.json(); return p.parse(d) || "..."; } catch (e) { return `[err] ${e.message}`; } } };}
// ── Spinner ──function spinner(start) { const frames = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]; let i = 0, timer; const fmt = ts => { const s = Math.floor((Date.now() - ts) / 1000); return s > 60 ? `${Math.floor(s/60)}m ${s%60}s` : `${s}s`; }; return { start() { timer = setInterval(() => { process.stdout.write(`\r${c("dim")}${frames[i]} ${fmt(start)}${R}`); i = (i + 1) % frames.length; }, 120); }, stop() { clearInterval(timer); process.stdout.write("\r\x1b[K\n"); }, };}
// ── CLI Chat ──export async function runChat(llm) { const version = "0.1.0"; const history = []; const maxHistory = 20;
// Use provided LLM or create one const provider = llm || createProvider(); if (!provider.hasLLM) { console.error(`${c("red")}No LLM provider configured.${R}`); console.error(`${c("dim")}Set PHANTOM_LLM_PROVIDER and the corresponding API key env var.${R}`); process.exit(1); }
console.log(`${c("green")}${_B}PHANTOM Chat${R} ${c("dim")}v${version} · ${provider.provider}${R}`); console.log(`${c("dim")}Type /help for commands, /exit to quit${R}\n`);
const rl = $r("readline").createInterface({ input: process.stdin, output: process.stdout, terminal: true });
function ask() { rl.question(`${c("green")}>> ${R}`, async (input) => { const trimmed = input.trim(); if (!trimmed) { ask(); return; }
// Commands if (trimmed.startsWith("/")) { const cmd = trimmed.slice(1).toLowerCase(); if (cmd === "exit" || cmd === "quit" || cmd === "q") { rl.close(); return; } if (cmd === "help") { console.log(`\n${c("dim")}Commands:${R}`); console.log(` ${c("green")}/exit${R} Exit chat`); console.log(` ${c("green")}/clear${R} Clear conversation history`); console.log(` ${c("green")}/model <n>${R} Show/set model`); console.log(` ${c("green")}/help${R} This help\n`); ask(); return; } if (cmd === "clear") { history.length = 0; console.log(`${c("dim")}History cleared${R}\n`); ask(); return; } if (cmd.startsWith("model ")) { // Could set model, but for now just show current console.log(`${c("dim")}Model: ${provider.provider}${R}\n`); ask(); return; } console.log(`${c("yellow")}Unknown: ${trimmed}${R}\n`); ask(); return; }
// Show user input process.stdout.write(`${c("green")}>${R} ${trimmed}\n`);
// Build context const messages = [ { role: "system", content: "You are Phantom, a helpful AI assistant. You are concise, knowledgeable, and direct. Answer clearly and accurately." }, ...history.slice(-maxHistory), { role: "user", content: trimmed }, ];
// Streaming spinner - DISABLED // const s = spinner(Date.now()); // s.start();
// Streaming spinner const s = spinner(Date.now()); s.start();
const start = Date.now(); console.error("DEBUG chat.mjs: BEFORE provider.chat"); let response; try { response = await provider.chat(messages); } catch (e) { console.error("DEBUG chat.mjs: EXCEPTION in provider.chat:", e.message); response = "[error] " + e.message; } console.error("DEBUG chat.mjs: AFTER provider.chat, response:", response?.substring(0, 50)); s.stop();
if (response.startsWith("[") && response.includes("] ")) { console.log(`${c("red")}${response}${R}\n`); ask(); return; }
// Show response process.stdout.write("\n"); process.stdout.write(response + "\n"); process.stdout.write("\n"); console.error("DEBUG chat.mjs: wrote response:", response.substring(0, 50)); const elapsed = Math.floor((Date.now() - start) / 1000); console.log(`${c("dim")}✓ ${elapsed}s${R}\n`);
// Store in history history.push({ role: "user", content: trimmed }); history.push({ role: "assistant", content: response });
ask(); }); }
rl.on("close", () => { console.log(`\n${c("dim")}Bye.${R}`); process.exit(0); });
ask();}
// ── Entry ──// Only run if executed directly (not imported)if (import.meta.url === `file://${process.argv[1]}`) { const llm = createProvider(); if (!llm.hasLLM) { console.error(`${c("red")}No LLM provider configured.${R}`); console.error(`${c("dim")}Set PHANTOM_LLM_PROVIDER and the corresponding API key env var.${R}`); process.exit(1); }
runChat(llm).catch(e => { console.error(`${c("red")}${e.message}${R}`); process.exit(1); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Cybersecurity Fundamentals — HackerSploit Study Guide
Source: HackerSploit — "Top 5 Skills to Learn to Get Into Cybersecurity"URL: https://youtube.com/watch?v=Kx4y9c7w2JQ
## Top 5 Skills
### 1. Building and Using Virtual Machines- VMs run on top of existing "host" OS via a "hypervisor"- Hypervisors: Hyper-V (Microsoft), VirtualBox (Oracle), VMware, KVM- "Cloud" = thousands of VMs on specialized hypervisors in datacenters- Key: be platform-agnostic, comfortable with ALL operating systems- Use VMs for: training, sandboxing, analyzing suspect files, exploit testing- Snapshots let you restore to an earlier state
### 2. Learn the Command Line- CLI = Shell = most efficient way to interact with an OS- Shell wraps around the Kernel (the core of the OS)- Bash = Bourne-again Shell, default on most Linux distros- Zsh = Z-Shell (macOS default, nicer features)- PowerShell = go-to native shell for Windows- WSL (Windows Subsystem for Linux) runs Linux shells natively on Windows- CLI enables scripting, automation, and tool access without GUIs
### 3. System Administration- Configuring and maintaining computers (personal devices to servers)- Know your platform and tools inside and out- Push limits: delete + recover files, analyze malware in VMs, extract passwords- Learn by doing: read guides, follow along, practice daily
### 4. Computer Networking- The "laws of physics" for cyberspace- Two models: TCP/IP (4 layers) and OSI (7 layers) - TCP/IP: network access, internet, transport, application - OSI: physical, datalink, network, transport, session, presentation, application- Layers help describe "what's happening where" — like postal service logistics- Strong networking = rockstar troubleshooting in red, blue, or IT ops
### 5. Personal Digital Security- Passwords, encryption, secure communications- Stay current with security news and best practices- Cybercrime industry is booming — IoT expands attack surface- Practice what you preach: many breaches originate from IT/SOC staff- Be the subject-matter expert others turn to for advice
## Key Takeaways- Skills > Certs. What you can DO > what you KNOW- Be versatile across platforms, not locked into one- Automation via CLI makes you valuable- Networking knowledge lets you "see the matrix"- Security starts with yourself123456789101112131415// Phantom — shared directory constants// Zero-dep ESM. Imported by phantom.mjs and lib modules.import { homedir } from "os";import { resolve } from "path";
export const BASE_DIR = resolve(homedir(), ".config", "phantom");export const MEMORY_DIR = resolve(BASE_DIR, "memory");export const KNOWLEDGE_DIR = resolve(BASE_DIR, "knowledge");export const BOOKS_DIR = resolve(BASE_DIR, "books");export const TOOLS_DIR = resolve(BASE_DIR, "tools");export const REPORTS_DIR = resolve(BASE_DIR, "reports");export const PLAYBOOKS_DIR = resolve(BASE_DIR, "playbooks");export const HACKBOOK_DIR = resolve(BASE_DIR, "hackbook");export const MISSIONS_DIR = resolve(BASE_DIR, "missions");export const PHANTOM_VERSION = "0.2.0";123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846// Phantom — Dashboard embedded HTML/CSS/JS// VS Code-style IDE layout with sidebar, activity bar, bottom panel// Dark neon hacker theme — violet/cyan
export const DASHBOARD_HTML = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Phantom Dashboard</title><style>*{margin:0;padding:0;box-sizing:border-box}body{background:#0a0a0f;color:#c8d6e5;font-family:'Cascadia Code','Fira Code','JetBrains Mono',monospace;font-size:13px;height:100vh;overflow:hidden;display:flex;flex-direction:column}::selection{background:#a855f766;color:#fff}::-webkit-scrollbar{width:4px;background:#0a0a0f}::-webkit-scrollbar-thumb{background:#a855f744;border-radius:2px}::-webkit-scrollbar-thumb:hover{background:#a855f788}
/* ── Activity Bar ── */.activity-bar{width:48px;background:#0a0a14;border-right:1px solid #1a1a2e;display:flex;flex-direction:column;align-items:center;padding:8px 0;gap:4px;flex-shrink:0}.activity-btn{width:36px;height:36px;display:flex;align-items:center;justify-content:center;color:#3a4a5a;cursor:pointer;border-radius:6px;transition:all .15s;font-size:16px;position:relative}.activity-btn:hover{color:#c084fc;background:#a855f711}.activity-btn.active{color:#c084fc;background:#a855f722}.activity-btn.active::before{content:'';position:absolute;left:-6px;top:6px;bottom:6px;width:2px;background:#c084fc;border-radius:1px}
/* ── Monitoring Panel Styles ── */.monitor-panel{display:flex;flex-direction:column;height:100%;padding:16px;overflow-y:auto}.monitor-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}.monitor-card{background:#0c0c18;border:1px solid #1a1a2e;border-radius:8px;padding:16px}.monitor-card h3{color:#c084fc;font-size:13px;margin-bottom:12px;border-bottom:1px solid #1a1a2e;padding-bottom:8px;display:flex;align-items:center;gap:8px}.monitor-card .stat{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #141424;font-size:12px}.monitor-card .stat:last-child{border-bottom:none}.monitor-card .stat-label{color:#5a6a7a}.monitor-card .stat-value{color:#c8d6e5;font-weight:500}.monitor-card .stat-value.ok{color:#34d399}.monitor-card .stat-value.warn{color:#fbbf24}.monitor-card .stat-value.error{color:#f87171}.monitor-card .stat-value.running{color:#22d3ee}
.mission-list{max-height:400px;overflow:auto}.mission-item{background:#0c0c18;border:1px solid #1a1a2e;border-radius:6px;padding:12px;margin-bottom:8px;cursor:pointer;transition:all .15s}.mission-item:hover{border-color:#a855f744;background:#a855f70a}.mission-item .header{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}.mission-item .name{color:#c084fc;font-size:12px;font-weight:700;word-break:break-all}.mission-item .status{font-size:10px;padding:2px 8px;border-radius:3px;white-space:nowrap}.mission-item .status.planning{background:#a855f722;color:#c084fc}.mission-item .status.ready{background:#fbbf2422;color:#fbbf24}.mission-item .status.reconnaissance{background:#22d3ee22;color:#22d3ee}.mission-item .status.paused{background:#f8717122;color:#f87171}.mission-item .status.completed{background:#34d39922;color:#34d399}.mission-item .status.cancelled{background:#f8717122;color:#f87171}.mission-item .status.failed{background:#ef444422;color:#ef4444}.mission-item .status.invalid_state{background:#5a6a7a22;color:#5a6a7a}.mission-item .meta{color:#5a6a7a;font-size:10px;margin-bottom:4px}.mission-item .scope{color:#3a4a5a;font-size:10px}
.schedule-item{background:#0c0c18;border:1px solid #1a1a2e;border-radius:6px;padding:12px;margin-bottom:8px}.schedule-item .header{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}.schedule-item .tool{color:#fbbf24;font-size:12px;font-weight:700}.schedule-item .next{color:#5a6a7a;font-size:10px}.schedule-item .target{color:#c8d6e5;font-size:11px;margin:4px 0;word-break:break-all}.schedule-item .interval{color:#3a4a5a;font-size:10px}
.task-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:8px;max-height:400px;overflow:auto}.task-card{background:#0c0c18;border:1px solid #1a1a2e;border-radius:6px;padding:10px 12px;cursor:pointer;transition:all .15s}.task-card:hover{border-color:#a855f744;background:#a855f70a}.task-card .name{color:#22d3ee;font-size:11px;font-weight:700;word-break:break-all}.task-card .category{color:#3a4a5a;font-size:9px;text-transform:uppercase;margin-top:2px}
.health-indicator{display:inline-flex;align-items:center;gap:6px}.health-dot{width:8px;height:8px;border-radius:50%}.health-dot.ok{background:#34d399;box-shadow:0 0 6px #34d399}.health-dot.warn{background:#fbbf24;box-shadow:0 0 6px #fbbf24}.health-dot.error{background:#f87171;box-shadow:0 0 6px #f87171}
.search-box{width:100%;padding:8px 12px;background:#050510;border:1px solid #1a1a3e;border-radius:6px;color:#c8d6e5;font-family:inherit;font-size:12px;margin-bottom:12px;outline:none;transition:border-color .15s}.search-box:focus{border-color:#a855f766}
@media(max-width:768px){.monitor-grid{grid-template-columns:1fr}.task-grid{grid-template-columns:repeat(auto-fill,minmax(140px,1fr))}}
/* ── Main Layout ── */.main-wrap{display:flex;flex:1;overflow:hidden}.sidebar{width:260px;background:#0c0c18;border-right:1px solid #1a1a2e;display:flex;flex-direction:column;flex-shrink:0;overflow:hidden}.sidebar.hidden{display:none}.sidebar.collapsed{width:0;min-width:0;overflow:hidden;border:none;transition:width .2s;flex-shrink:1;flex-grow:0}.sidebar.collapsed+.editor{border-left:none}.sidebar-toggle{cursor:pointer;color:#3a4a5a;font-size:10px;padding:2px 6px;border-radius:3px;transition:all .15s}.sidebar-toggle:hover{color:#c084fc;background:#a855f711}.sidebar-header{padding:10px 14px;font-size:11px;color:#5a6a7a;text-transform:uppercase;letter-spacing:1px;border-bottom:1px solid #1a1a2e;display:flex;justify-content:space-between;align-items:center}.sidebar-header .count{color:#a855f7;font-size:10px}.sidebar-search{padding:8px 10px}.sidebar-search input{width:100%;padding:6px 10px;background:#050510;border:1px solid #1a1a3e;border-radius:4px;color:#c8d6e5;font-family:inherit;font-size:12px;outline:none;transition:border-color .15s}.sidebar-search input:focus{border-color:#a855f766}.sidebar-content{flex:1;overflow-y:auto;padding:4px 0}.sidebar-empty{padding:20px;color:#3a4a5a;text-align:center;font-size:12px}
/* ── Tool tree ── */.category-group{margin-bottom:2px}.category-label{padding:6px 14px;font-size:10px;color:#5a6a7a;text-transform:uppercase;letter-spacing:1px;cursor:pointer;display:flex;align-items:center;gap:6px;transition:color .15s}.category-label:hover{color:#c084fc}.category-label .arrow{font-size:8px;transition:transform .15s;display:inline-block}.category-label .arrow.open{transform:rotate(90deg)}.category-label .badge{font-size:9px;color:#3a4a5a;margin-left:auto}.category-items{overflow:hidden}.category-items.collapsed{display:none}.tool-item{display:flex;align-items:center;padding:4px 14px 4px 24px;cursor:pointer;transition:all .1s;font-size:12px;gap:8px;border-left:2px solid transparent}.tool-item:hover{background:#a855f70a;border-left-color:#a855f744}.tool-item.active{background:#a855f714;border-left-color:#c084fc;color:#c084fc}.tool-item .name{flex:1}.tool-item .run-btn{font-size:10px;color:#3a4a5a;cursor:pointer;padding:1px 5px;border-radius:3px;transition:all .15s;opacity:0}.tool-item:hover .run-btn{opacity:1}.tool-item .run-btn:hover{background:#22d3ee22;color:#22d3ee}.tool-icon{font-size:10px;width:16px;text-align:center}
/* ── Editor Area ── */.editor{flex:1;display:flex;flex-direction:column;overflow:hidden;background:#0a0a0f}.editor-tabs{display:flex;background:#0c0c18;border-bottom:1px solid #1a1a2e;min-height:32px;overflow-x:auto}.editor-tab{display:flex;align-items:center;gap:6px;padding:6px 14px;font-size:11px;color:#5a6a7a;border-right:1px solid #1a1a2e;cursor:pointer;transition:color .15s;white-space:nowrap}.editor-tab:hover{color:#c8d6e5}.editor-tab.active{color:#c8d6e5;background:#0a0a0f;border-bottom:2px solid #c084fc}.editor-tab .close{font-size:10px;color:#3a4a5a;cursor:pointer;padding:0 3px;border-radius:2px}.editor-tab .close:hover{color:#f87171;background:#ef444422}.editor-content{flex:1;display:flex;flex-direction:column;overflow:hidden}.editor-welcome{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:#3a4a5a;gap:16px;padding:40px}.editor-welcome pre{color:#22d3ee;font-size:9px;line-height:1.15;text-shadow:0 0 10px #22d3ee11}.editor-welcome h2{color:#a855f7;font-size:16px;letter-spacing:2px}.editor-welcome p{font-size:12px;max-width:400px;text-align:center;color:#5a6a7a}
/* ── Bottom Panel ── */.bottom-panel{height:200px;background:#0c0c18;border-top:1px solid #1a1a2e;display:flex;flex-direction:column;flex-shrink:0}.bottom-panel.collapsed{height:28px}.bottom-panel.collapsed .panel-body{display:none}.panel-tabs{display:flex;align-items:center;background:#080810;border-bottom:1px solid #1a1a2e;min-height:28px;padding:0 4px;gap:0}.panel-tab{padding:4px 12px;font-size:10px;color:#5a6a7a;cursor:pointer;border-bottom:2px solid transparent;transition:all .15s}.panel-tab:hover{color:#c8d6e5}.panel-tab.active{color:#22d3ee;border-bottom-color:#22d3ee}.panel-actions{margin-left:auto;display:flex;gap:4px;padding:0 4px}.panel-btn{font-size:10px;color:#3a4a5a;cursor:pointer;padding:2px 6px;border-radius:3px;transition:color .15s}.panel-btn:hover{color:#c8d6e5}.panel-body{flex:1;overflow:auto;padding:8px 12px;font-size:11px;white-space:pre-wrap;font-family:inherit;line-height:1.4}.panel-body .prompt{color:#22d3ee88}.panel-body .ok{color:#34d399}.panel-body .err{color:#f87171}.panel-body .info{color:#5a6a7a}.panel-body .dim{color:#3a4a5a}
/* ── Status Bar ── */.status-bar{height:22px;background:#0a0a14;border-top:1px solid #1a1a2e;display:flex;align-items:center;padding:0 12px;font-size:10px;color:#3a4a5a;gap:16px;flex-shrink:0}.status-bar .left{display:flex;align-items:center;gap:12px}.status-bar .right{margin-left:auto;display:flex;align-items:center;gap:12px}.status-dot{width:6px;height:6px;border-radius:50%;display:inline-block}.status-dot.on{background:#22d3ee;box-shadow:0 0 6px #22d3ee}.status-dot.off{background:#3a4a5a}.status-bar .item{display:flex;align-items:center;gap:4px;cursor:default}.status-bar .item:hover{color:#5a6a7a}
/* ── Modal / Command Palette ── */.palette-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:#00000088;display:none;align-items:flex-start;justify-content:center;padding-top:10vh;z-index:100}.palette-overlay.show{display:flex}.palette{background:#0c0c18;border:1px solid #1a1a3e;border-radius:8px;width:500px;max-width:90vw;box-shadow:0 20px 60px #00000088;overflow:hidden}.palette input{width:100%;padding:12px 16px;background:#050510;border:none;color:#c8d6e5;font-family:inherit;font-size:14px;outline:none;border-bottom:1px solid #1a1a3e}.palette-results{max-height:300px;overflow-y:auto}.palette-item{padding:8px 16px;cursor:pointer;display:flex;align-items:center;gap:10px;font-size:12px;transition:background .1s;border-left:2px solid transparent}.palette-item:hover,.palette-item.active{background:#a855f714;border-left-color:#c084fc}.palette-item .desc{color:#5a6a7a;font-size:11px;margin-left:auto}
@keyframes fadeIn{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}
/* ── Mobile responsive ── */@media(max-width:768px){.activity-bar{width:40px}.activity-btn{width:28px;height:28px;font-size:12px}.sidebar{width:200px}.sidebar-header{font-size:10px;padding:6px 10px}.sidebar-search{padding:4px 8px}.sidebar-search input{font-size:11px;padding:4px 8px}.category-label{font-size:9px;padding:4px 10px}.tool-item{font-size:11px;padding:3px 10px 3px 18px}.editor-welcome{padding:20px;gap:10px}.editor-welcome h2{font-size:14px}.editor-welcome pre{font-size:7px}.bottom-panel{height:140px}.panel-body{font-size:10px;padding:4px 8px}.panel-tab{font-size:9px;padding:3px 8px}.status-bar{font-size:9px;gap:8px;padding:0 8px}.palette{width:95vw}.palette input{font-size:13px;padding:10px 12px}.palette-item{font-size:11px;padding:6px 12px}}@media(max-width:480px){.activity-bar{width:36px}.activity-btn{width:24px;height:24px;font-size:10px}.activity-btn.active::before{left:-5px;top:4px;bottom:4px}.sidebar{width:160px}.sidebar-header{font-size:9px}.category-label{font-size:8px;padding:3px 8px}.tool-item{font-size:10px;padding:2px 8px 2px 14px}.editor-welcome{padding:12px}.editor-welcome h2{font-size:12px}.editor-welcome p{font-size:10px}.bottom-panel{height:120px}.panel-body{font-size:9px}.status-bar{font-size:8px;gap:4px;padding:0 4px}.editor-welcome pre{display:none}}
/* ── Chat Panel ── */.chat-panel{display:flex;flex-direction:column;height:100%}.chat-messages{flex:1;overflow-y:auto;padding:12px 16px}.chat-msg{margin-bottom:10px;animation:fadeIn .15s}.chat-msg.user{text-align:right}.chat-msg.user .chat-bubble{background:#a855f722;border:1px solid #a855f744;color:#e2d5f7}.chat-msg.agent .chat-bubble{background:#22d3ee11;border:1px solid #22d3ee33;color:#b8eef7}.chat-msg.system .chat-bubble{background:#0a0a0f;border:1px solid #3a4a5a;color:#5a6a7a;font-size:10px;text-align:center}.chat-bubble{display:inline-block;max-width:80%;padding:8px 14px;border-radius:8px;font-size:12px;line-height:1.5;text-align:left;white-space:pre-wrap;word-break:break-word}.chat-bubble .chat-code{display:block;background:#050510;border:1px solid #1a1a3e;border-radius:4px;padding:6px 10px;margin:4px 0;font-size:11px;overflow-x:auto;color:#c8d6e5}.chat-bubble .chat-code-header{font-size:9px;color:#5a6a7a;margin-bottom:2px}.chat-input-bar{display:flex;align-items:center;padding:8px 12px;border-top:1px solid #1a1a2e;background:#0c0c18;gap:8px}.chat-input-bar textarea{flex:1;padding:8px 12px;background:#050510;border:1px solid #1a1a3e;border-radius:6px;color:#c8d6e5;font-family:inherit;font-size:12px;outline:none;resize:none;min-height:36px;max-height:120px;line-height:1.4;transition:border-color .15s}.chat-input-bar textarea:focus{border-color:#a855f766}.chat-input-bar .chat-send{background:linear-gradient(135deg,#a855f744,#22d3ee44);color:#c084fc;border:1px solid #a855f755;padding:6px 16px;border-radius:5px;cursor:pointer;font-family:inherit;font-size:12px;transition:all .15s}.chat-input-bar .chat-send:hover{background:linear-gradient(135deg,#a855f766,#22d3ee66);color:#d8b4fe}.chat-input-bar .chat-send:disabled{opacity:.4;cursor:default}.chat-typing{text-align:center;color:#5a6a7a;font-size:11px;padding:4px}.chat-emoji{font-size:11px}.chat-status{font-size:10px;color:#3a4a5a;padding:2px 0}.chat-status .dot{display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:4px;animation:pulse 1.5s infinite}@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}</style></head><body>
<div style="display:flex;flex-direction:column;height:100vh"> <div class="main-wrap"> <div class="activity-bar"> <div class="activity-btn active" onclick="switchActivity('chat')" title="Chat">💬</div> <div class="activity-btn" onclick="switchActivity('tools')" title="Tools">◈</div> <div class="activity-btn" onclick="switchActivity('playbooks')" title="Playbooks">◆</div> <div class="activity-btn" onclick="switchActivity('reports')" title="Reports">■</div> <div class="activity-btn" onclick="switchActivity('monitor')" title="Monitor">📊</div> <div style="margin-top:auto" class="activity-btn" onclick="showPalette()" title="Commands">⌘</div> </div>
<div class="sidebar" id="sidebar"> <div class="sidebar-header"> <span id="sidebarTitle">TOOLS</span> <span style="display:flex;gap:4px;align-items:center"> <span class="count" id="toolCount">—</span> <span class="sidebar-toggle" onclick="toggleSidebar()" title="Collapse sidebar">◀</span> </span> </div> <div class="sidebar-search"><input id="search" placeholder="filter..." oninput="filterTools(this.value)"></div> <div class="sidebar-content" id="sidebarContent"><div class="sidebar-empty">loading...</div></div> </div>
<div class="editor"> <div class="editor-content" id="editorContent"> <div class="editor-welcome" id="welcomeScreen"> <pre id="logoAscii"></pre> <h2>⋊ PHANTOM ⋉</h2> <p>Select a tool from the sidebar or press <span style="color:#a855f7">⌘</span> to open the command palette</p> </div> <div class="editor-welcome" id="toolEditor" style="display:none"> <div style="width:100%;max-width:600px;margin:0 auto;padding:40px 20px"> <div style="display:flex;gap:12px;align-items:center;margin-bottom:16px"> <span id="editToolIcon" style="font-size:20px">🔧</span> <h2 id="editToolName" style="color:#c084fc;margin:0">@tool</h2> </div> <input id="toolArgs" placeholder="arguments..." style="width:100%;padding:10px 14px;background:#050510;border:1px solid #1a1a3e;border-radius:6px;color:#c8d6e5;font-family:inherit;font-size:13px;outline:none;margin-bottom:10px" onkeydown="if(event.key==='Enter')runTool()"> <button onclick="runTool()" style="background:linear-gradient(135deg,#a855f722,#22d3ee22);color:#c084fc;border:1px solid #a855f744;padding:6px 20px;border-radius:5px;cursor:pointer;font-family:inherit;font-size:12px">▶ Run</button> </div> </div> <div class="chat-panel" id="chatPanel" style="display:none;flex:1"> <div class="chat-messages" id="chatMessages"> <div class="chat-msg system"><div class="chat-bubble">🕷️ Phantom agent ready — ask me anything or give me a hacking target</div></div> </div> <div class="chat-status" id="chatStatus" style="display:none"><span class="dot" style="background:#22d3ee"></span>thinking...</div> <div class="chat-input-bar"> <textarea id="chatInput" rows="1" placeholder="Type a command, target, or question..." onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendChat()}"></textarea> <button class="chat-send" id="chatSend" onclick="sendChat()">▶ Send</button> </div> </div> <div class="monitor-panel" id="monitorPanel" style="display:none"> <div class="monitor-grid"> <div class="monitor-card"> <h3>🖥 System Health</h3> <div class="stat"><span class="stat-label">Status</span><span class="stat-value ok" id="sysStatus"><span class="health-dot ok"></span> OK</span></div> <div class="stat"><span class="stat-label">Uptime</span><span class="stat-value" id="sysUptime">—</span></div> <div class="stat"><span class="stat-label">Memory</span><span class="stat-value" id="sysMemory">—</span></div> <div class="stat"><span class="stat-label">CPU Load</span><span class="stat-value" id="sysLoad">—</span></div> <div class="stat"><span class="stat-label">Disk (USB)</span><span class="stat-value" id="sysDisk">—</span></div> <div class="stat"><span class="stat-label">Node</span><span class="stat-value" id="sysNode">—</span></div> <div class="stat"><span class="stat-label">PID</span><span class="stat-value" id="sysPid">—</span></div> <div class="stat"><span class="stat-label">USB Mount</span><span class="stat-value ok" id="sysUsb">✓ Mounted</span></div> </div>
<div class="monitor-card"> <h3>🎯 Active Missions</h3> <input class="search-box" id="missionSearch" placeholder="Filter missions..." oninput="filterMissions(this.value)"> <div class="mission-list" id="missionList"><div class="sidebar-empty">Loading missions...</div></div> </div>
<div class="monitor-card"> <h3>⏰ Active Schedules</h3> <div id="scheduleList"><div class="sidebar-empty">Loading schedules...</div></div> </div>
<div class="monitor-card"> <h3>📋 All Tasks (Searchable)</h3> <input class="search-box" id="taskSearch" placeholder="Search tasks..." oninput="filterTasks(this.value)"> <div class="task-grid" id="taskGrid"><div class="sidebar-empty">Loading tasks...</div></div> </div> </div> </div> </div> </div> </div>
<div class="bottom-panel" id="bottomPanel"> <div class="panel-tabs"> <div class="panel-tab active" onclick="switchPanel('output')">OUTPUT</div> <div class="panel-tab" onclick="switchPanel('info')">INFO</div> <div class="panel-actions"> <span class="panel-btn" onclick="clearPanel()" title="Clear">⊘</span> <span class="panel-btn" onclick="togglePanel()" title="Toggle panel">_</span> </div> </div> <div class="panel-body" id="panelOutput"><span class="dim">⧩ ready</span></div> </div>
<div class="status-bar"> <div class="left"> <span class="item"><span class="status-dot on"></span><span id="statusConnected">connected</span></span> <span class="item" id="statusToolCount">— tools</span> <span class="item" id="statusBarLevel" style="color:#a855f7">lv1</span> </div> <div class="right"> <span class="item">⋉ phantom v0.2.0 ⋊</span> </div> </div></div>
<div class="palette-overlay" id="palette" onclick="if(event.target===this)hidePalette()"> <div class="palette" style="animation:fadeIn .15s"> <input id="paletteInput" placeholder="Type a command..." oninput="filterPalette(this.value)" onkeydown="if(event.key==='Enter')execPalette();if(event.key==='Escape')hidePalette()" autofocus> <div class="palette-results" id="paletteResults"></div> </div></div>
<script>const HOODIE = [ ' ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄', ' █ ═══ ═══ ═══ ═══ ═══ █', '▐█ · · · · · █▌', '▐█ ╔═══════════╗ █▌', '▐█ ║ ◈ ◈ ║ █▌', '▐█ ║ ╔═══╗ ║ █▌', '▐█ ╚═══════════╝ █▌', ' █ ┊ ║ ║ ┊ █', ' █ ┊ ║ ● ║ ┊ █', ' ▀▄ ║ ═══ ║ ▄▀', ' P H A N T O M'].join('\\n');document.getElementById('logoAscii').textContent = HOODIE;
let tools = [];let activeTab = 'tools';let paletteItems = [];let paletteIdx = -1;
// APIasync function api(p,o){const r=await fetch(p,o);if(!r.ok)throw new Error(r.statusText);return r.json()}
// ── Chat ──let chatBusy = false;function addChatMsg(role, text) { const el = document.getElementById('chatMessages'); const div = document.createElement('div'); div.className = 'chat-msg ' + role; // Format code blocks const formatted = text.replace(/\`\`\`(\w*)\n?([\s\S]*?)\`\`\`/g, (_, lang, code) => { return '<div class=\"chat-code-header\">' + (lang || 'code') + '</div><pre class=\"chat-code\">' + code.trim() + '</pre>'; }); div.innerHTML = '<div class="chat-bubble">' + formatted + '</div>'; el.appendChild(div); el.scrollTop = el.scrollHeight;}async function sendChat() { if (chatBusy) return; const input = document.getElementById('chatInput'); const msg = input.value.trim(); if (!msg) return; input.value = ''; input.style.height = 'auto'; addChatMsg('user', msg); chatBusy = true; document.getElementById('chatSend').disabled = true; document.getElementById('chatStatus').style.display = 'block'; try { const r = await api('/api/chat', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({message:msg}) }); if (r.ok) { addChatMsg('agent', r.response); if (r.level) { document.getElementById('statusBarLevel').textContent = 'lv' + r.level; } } else { addChatMsg('system', '⛔ ' + (r.error || 'request failed')); } } catch(e) { addChatMsg('system', '⛔ Error: ' + e.message); } chatBusy = false; document.getElementById('chatSend').disabled = false; document.getElementById('chatStatus').style.display = 'none'; document.getElementById('chatInput').focus();}document.addEventListener('DOMContentLoaded', () => { document.getElementById('chatInput').focus(); // Auto-resize textarea document.getElementById('chatInput').addEventListener('input', function() { this.style.height = 'auto'; this.style.height = Math.min(this.scrollHeight, 120) + 'px'; });});
// Categorize toolfunction toolCat(t){ const n=t.toLowerCase(); if(['shell','web_fetch','decode','encode','hash','file_analyze','batch','code_analyze','code_gen','yara','random'].some(x=>n.includes(x)))return{cat:'core',icon:'⚡',color:'#22d3ee'}; if(['dns','whois','sub_enum','subfinder','port_scan','http_headers','ssl_check','crawl','geoip','dns_zone','reverse_dns','wayback','robots_txt','amass','dnsx','httpx','naabu','katana','sub_takeover','cloud_enum','dns_lookup','cert_expiry','dig','ping','traceroute','netstat'].some(x=>n.includes(x)))return{cat:'recon',icon:'🔍',color:'#c084fc'}; if(['dir_brute','xss','sql','open_redirect','cors_test','http_methods','ffuf','arjun','nuclei'].some(x=>n.includes(x)))return{cat:'web',icon:'🌐',color:'#fbbf24'}; if(['cve','searchsploit','shodan','bruteforce','jwt_decode','hash_crack','hashcat','nmap','masscan'].some(x=>n.includes(x)))return{cat:'exploit',icon:'💥',color:'#f87171'}; if(['email','github_dork','vt_check','cloud_enum','geoip'].some(x=>n.includes(x)))return{cat:'osint',icon:'📡',color:'#34d399'}; if(['file_read','file_write','file_edit','file_search','file_list','file_analyze'].some(x=>n.includes(x)))return{cat:'file',icon:'📁',color:'#818cf8'}; if(['self_','knowledge_','playbook_','session_','report_','schedule','batch'].some(x=>n.includes(x)))return{cat:'system',icon:'⚙',color:'#5a6a7a'}; return{cat:'other',icon:'🔧',color:'#5a6a7a'};}
// Load toolsasync function loadTools(){ try{ const resp=await api('/api/tools'); tools=resp.tools||[]; if(!tools.length){document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>⛔ no tools from API</div>';return} const cats={}; tools.forEach(t=>{const c=toolCat(t).cat;if(!cats[c])cats[c]=[];cats[c].push(t)}); renderSidebar(cats); document.getElementById('toolCount').textContent=tools.length; document.getElementById('statusToolCount').textContent=tools.length+' tools'; buildPalette(); }catch(e){ document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>⛔ '+e.message+'<br><br><button onclick="loadTools()" style="background:#a855f722;color:#c084fc;border:1px solid #a855f744;padding:6px 16px;border-radius:4px;cursor:pointer;font:inherit;font-size:11px">↻ retry</button></div>'; }}
// Render sidebarfunction renderSidebar(cats){ const order=['core','recon','web','exploit','osint','file','system','other']; const labels={core:'CORE',recon:'RECON',web:'WEB',exploit:'EXPLOIT',osint:'OSINT',file:'FILE',system:'SYSTEM',other:'OTHER'}; const expanded=JSON.parse(localStorage.getItem('phantom_cats')||'{}'); let html=''; order.forEach(c=>{ if(!cats[c]||!cats[c].length)return; const open=expanded[c]!==false; const icon={core:'⚡',recon:'🔍',web:'🌐',exploit:'💥',osint:'📡',file:'📁',system:'⚙',other:'🔧'}[c]; html+='<div class=category-group>'; html+='<div class=category-label onclick="toggleCat(\\''+c+'\\')"><span class="arrow '+(open?'open':'')+'">▶</span>'+icon+' '+labels[c]+' <span class=badge>'+cats[c].length+'</span></div>'; html+='<div class="category-items'+(open?'':' collapsed')+'" id="cat_'+c+'">'; cats[c].forEach(t=>{ const info=toolCat(t); html+='<div class=tool-item onclick="selectTool(\\''+t+'\\')"><span class=tool-icon style=color:'+info.color+'>'+info.icon+'</span><span class=name>'+t+'</span><span class=run-btn onclick="event.stopPropagation();quickRun(\\''+t+'\\')">▶</span></div>'; }); html+='</div></div>'; }); document.getElementById('sidebarContent').innerHTML=html;}
function toggleCat(c){ const el=document.getElementById('cat_'+c); const label=el.previousElementSibling.querySelector('.arrow'); const collapsed=el.classList.toggle('collapsed'); label.classList.toggle('open'); const stored=JSON.parse(localStorage.getItem('phantom_cats')||'{}'); stored[c]=!collapsed; localStorage.setItem('phantom_cats',JSON.stringify(stored));}
// Select toollet currentTool=null;function selectTool(t){ currentTool=t; document.querySelectorAll('.tool-item').forEach(i=>i.classList.remove('active')); event.currentTarget.classList.add('active'); document.getElementById('welcomeScreen').style.display='none'; document.getElementById('toolEditor').style.display='block'; const info=toolCat(t); document.getElementById('editToolIcon').textContent=info.icon; document.getElementById('editToolName').textContent='@'+t; document.getElementById('toolArgs').value=''; document.getElementById('toolArgs').focus();}
function quickRun(t){ currentTool=t; document.getElementById('welcomeScreen').style.display='none'; document.getElementById('toolEditor').style.display='block'; const info=toolCat(t); document.getElementById('editToolIcon').textContent=info.icon; document.getElementById('editToolName').textContent='@'+t; document.getElementById('toolArgs').value=''; setTimeout(()=>runTool(),50);}
async function runTool(){ if(!currentTool)return; const args=document.getElementById('toolArgs').value; const out=document.getElementById('panelOutput'); document.getElementById('bottomPanel').classList.remove('collapsed'); out.innerHTML+='\\n<span class=prompt>⧩</span> @'+currentTool+'|'+args+'\\n'; out.scrollTop=out.scrollHeight; switchPanel('output'); try{ const r=await api('/api/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({tool:currentTool,args})}); out.innerHTML+='<span class=ok>'+r.result+'</span>\\n\\n'; }catch(e){ out.innerHTML+='<span class=err>⛔ '+e.message+'</span>\\n\\n'; } out.scrollTop=out.scrollHeight;}
// Filter toolsfunction filterTools(q){ const f=q.toLowerCase(); document.querySelectorAll('.tool-item').forEach(el=>{ el.style.display=el.querySelector('.name').textContent.includes(f)?'':'none'; }); document.querySelectorAll('.category-group').forEach(g=>{ const visible=Array.from(g.querySelectorAll('.tool-item')).some(i=>i.style.display!=='none'); g.style.display=visible?'':'none'; });}
// Command palettefunction buildPalette(){ paletteItems=[]; tools.forEach(t=>{ const info=toolCat(t); paletteItems.push({label:'@'+t,desc:info.cat.toUpperCase(),action:()=>selectTool(t)}); }); ['Help','Tools','Model','Clear','Quit','GUI','API'].forEach(c=>{ paletteItems.push({label:'/'+c.toLowerCase(),desc:'COMMAND',action:()=>{ document.getElementById('panelOutput').innerHTML+='<span class=prompt>⧩</span> /'+c.toLowerCase()+'\\n'; }}); });}
function showPalette(){ document.getElementById('palette').classList.add('show'); document.getElementById('paletteInput').value=''; document.getElementById('paletteInput').focus(); filterPalette('');}
function hidePalette(){ document.getElementById('palette').classList.remove('show');}
function filterPalette(q){ const f=q.toLowerCase(); const results=paletteItems.filter(p=>p.label.toLowerCase().includes(f)||p.desc.toLowerCase().includes(f)); const container=document.getElementById('paletteResults'); container.innerHTML=results.map((p,i)=>'<div class="palette-item'+(i===0?' active':'')+'" onclick="execPaletteItem('+i+')" data-idx="'+i+'"><span>'+p.label+'</span><span class=desc>'+p.desc+'</span></div>').join(''); paletteIdx=0;}
// Sidebar togglelet sidebarOpen=true;function toggleSidebar(){ sidebarOpen=!sidebarOpen; document.getElementById('sidebar').classList.toggle('collapsed'); document.querySelector('.sidebar-toggle').textContent=sidebarOpen?'◀':'▶'; document.querySelector('.sidebar-toggle').title=sidebarOpen?'Collapse sidebar':'Expand sidebar';}
// Keyboard shortcuts const active=document.querySelector('.palette-item.active'); if(active)execPaletteItem(parseInt(active.dataset.idx));}
function execPaletteItem(idx){ hidePalette(); if(paletteItems[idx])paletteItems[idx].action();}
// Panel controlsfunction switchPanel(name){ document.querySelectorAll('.panel-tab').forEach(t=>t.classList.remove('active')); const idx=name==='output'?0:1; document.querySelectorAll('.panel-tab')[idx].classList.add('active');}
function clearPanel(){ document.getElementById('panelOutput').innerHTML='<span class=dim>⧩ cleared</span>';}
function togglePanel(){ document.getElementById('bottomPanel').classList.toggle('collapsed');}
// Activity switchingfunction switchActivity(name){ document.querySelectorAll('.activity-btn').forEach(b=>b.classList.remove('active')); event.currentTarget.classList.add('active'); activeTab=name; // Hide chat panel / tools / welcome / monitor when switching document.getElementById('chatPanel').style.display='none'; document.getElementById('welcomeScreen').style.display='none'; document.getElementById('toolEditor').style.display='none'; document.getElementById('monitorPanel').style.display='none'; if(name==='chat'){ document.getElementById('sidebarTitle').textContent='CHAT'; document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty style="font-size:10px">💬 Chat with Phantom<br><span style="color:#3a4a5a">Send commands, targets, or questions</span></div>'; document.getElementById('sidebar').classList.remove('hidden'); document.getElementById('chatPanel').style.display='flex'; setTimeout(()=>document.getElementById('chatInput').focus(),100); }else if(name==='tools'){ document.getElementById('sidebarTitle').textContent='TOOLS'; document.getElementById('sidebarContent').querySelector('.sidebar-empty')||loadTools(); document.getElementById('sidebar').classList.remove('hidden'); }else if(name==='playbooks'){ document.getElementById('sidebarTitle').textContent='PLAYBOOKS'; document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>loading...</div>'; document.getElementById('sidebar').classList.remove('hidden'); loadPlaybooks(); }else if(name==='reports'){ document.getElementById('sidebarTitle').textContent='REPORTS'; document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>loading...</div>'; document.getElementById('sidebar').classList.remove('hidden'); loadReports(); }else if(name==='monitor'){ document.getElementById('sidebarTitle').textContent='MONITOR'; document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty style="font-size:10px">📊 System monitoring<br><span style="color:#3a4a5a">Real-time status, missions, schedules & tasks</span></div>'; document.getElementById('sidebar').classList.remove('hidden'); document.getElementById('monitorPanel').style.display='flex'; loadMonitorData(); }}
async function loadPlaybooks(){ try{ const resp=await api('/api/playbooks'); const l=resp.playbooks||[]; const c=document.getElementById('sidebarContent'); if(!l.length){c.innerHTML='<div class=sidebar-empty>◆ no playbooks</div>';return} c.innerHTML=l.map(p=>'<div class="tool-item" onclick="runPlaybook(\\''+p.name+'\\')"><span class=tool-icon>◆</span><span class=name>'+p.name+'</span></div>').join(''); }catch(e){ document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>⛔ '+e.message+'</div>'; }}
async function runPlaybook(n){ const out=document.getElementById('panelOutput'); document.getElementById('bottomPanel').classList.remove('collapsed'); out.innerHTML+='\\n<span class=prompt>⧩</span> ◆ '+n+'\\n'; switchPanel('output'); try{ const r=await api('/api/playbook/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:n,vars:'target='})}); out.innerHTML+='<span class=ok>'+r.result+'</span>\\n\\n'; }catch(e){ out.innerHTML+='<span class=err>⛔ '+e.message+'</span>\\n\\n'; } out.scrollTop=out.scrollHeight;}
async function loadReports(){ try{ const resp=await api('/api/reports'); const l=resp.reports||[]; const c=document.getElementById('sidebarContent'); if(!l.length){c.innerHTML='<div class=sidebar-empty>■ no reports</div>';return} c.innerHTML=l.map(r=>'<div class="tool-item" onclick="viewReport(\\''+r.name+'\\')"><span class=tool-icon>■</span><span class=name>'+r.name+'<span style=color:#3a4a5a;font-size:10px;margin-left:8px>'+r.size+'</span></div>').join(''); }catch(e){ document.getElementById('sidebarContent').innerHTML='<div class=sidebar-empty>⛔ '+e.message+'</div>'; }}
async function viewReport(n){ try{ const r=await api('/api/report/'+encodeURIComponent(n)); const out=document.getElementById('panelOutput'); document.getElementById('bottomPanel').classList.remove('collapsed'); out.innerHTML+='\\n<span class=prompt>⧩</span> ■ '+n+'\\n<span class=info>'+r.content+'</span>\\n\\n'; out.scrollTop=out.scrollHeight; switchPanel('output'); }catch(e){}}
// ── Monitoring Functions ──let monitorRefreshInterval = null;
async function loadMonitorData() { await Promise.all([loadMissions(), loadSchedules(), loadTasks(), loadHealth(), loadSystem()]); // Set up periodic refresh if (monitorRefreshInterval) clearInterval(monitorRefreshInterval); monitorRefreshInterval = setInterval(() => { loadHealth(); loadSystem(); loadSchedules(); }, 10000); setInterval(loadMissions, 30000); setInterval(loadTasks, 60000);}
async function loadMissions() { try { const resp = await api('/api/missions'); const missions = resp.missions || []; renderMissions(missions); } catch(e) { document.getElementById('missionList').innerHTML = '<div class=sidebar-empty>⛔ ' + e.message + '</div>'; }}
function renderMissions(list) { const div = document.getElementById('missionList'); if (!list.length) { div.innerHTML = '<div class=sidebar-empty>No missions found</div>'; return; } div.innerHTML = list.map(m => '<div class="mission-item">' + '<div class="header">' + '<span class="name">' + m.id + '</span>' + '<span class="status ' + m.status + '">' + m.status.toUpperCase() + '</span>' + '</div>' + '<div class="meta">' + m.programName + ' (' + m.programHandle + ') • Updated: ' + new Date(m.updatedAt).toLocaleString() + '</div>' + '<div class="scope">In-scope: ' + m.inScopeCount + ' assets • Objectives: ' + m.objectives + '</div>' + '</div>' ).join('');}
function filterMissions(q) { const items = document.querySelectorAll('.mission-item'); items.forEach(item => { const text = item.textContent.toLowerCase(); item.style.display = text.includes(q.toLowerCase()) ? '' : 'none'; });}
async function loadSchedules() { try { const resp = await api('/api/schedules'); const list = resp.schedules || []; renderSchedules(list); } catch(e) { document.getElementById('scheduleList').innerHTML = '<div class=sidebar-empty>⛔ ' + e.message + '</div>'; }}
function renderSchedules(list) { const div = document.getElementById('scheduleList'); if (!list.length) { div.innerHTML = '<div class=sidebar-empty>No active schedules. Use @schedule|daily|tool|target to create one.</div>'; return; } div.innerHTML = list.map(s => '<div class="schedule-item">' + '<div class="header">' + '<span class="tool">@' + s.tool + '</span>' + '<span class="next">Next: ' + s.nextAtHuman + '</span>' + '</div>' + '<div class="target">Target: ' + s.target + '</div>' + '<div class="interval">Interval: ' + s.interval + ' • ID: ' + s.id + '</div>' + '</div>' ).join('');}
async function loadTasks() { try { const resp = await api('/api/tasks'); const tasks = resp.tasks || []; renderTasks(tasks); } catch(e) { document.getElementById('taskGrid').innerHTML = '<div class=sidebar-empty>⛔ ' + e.message + '</div>'; }}
function renderTasks(list) { const grid = document.getElementById('taskGrid'); grid.innerHTML = list.map(t => '<div class="task-card" onclick="runTaskFromMonitor(\'' + t.name + '\')">' + '<div class="name">@' + t.name + '</div>' + '<div class="category">' + t.category + '</div>' + '</div>' ).join('');}
function filterTasks(q) { const cards = document.querySelectorAll('.task-card'); cards.forEach(c => { const name = c.querySelector('.name').textContent.toLowerCase(); const cat = c.querySelector('.category').textContent.toLowerCase(); c.style.display = (name.includes(q.toLowerCase()) || cat.includes(q.toLowerCase())) ? '' : 'none'; });}
async function runTaskFromMonitor(name) { const input = prompt('Enter arguments for @' + name + ':'); if (input === null) return; const out = document.getElementById('panelOutput'); document.getElementById('bottomPanel').classList.remove('collapsed'); out.innerHTML += '\n<span class=prompt>⧩</span> @' + name + '|' + input + '\n'; out.scrollTop = out.scrollHeight; switchPanel('output'); try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:name, args:input}) }); out.innerHTML += '<span class=ok>' + r.result + '</span>\n\n'; } catch(e) { out.innerHTML += '<span class=err>⛔ ' + e.message + '</span>\n\n'; } out.scrollTop = out.scrollHeight;}
async function loadHealth() { try { const h = await api('/api/health'); updateHealth(h); } catch(e) {}}
function updateHealth(h) { document.getElementById('sysUptime').textContent = h.uptimeHuman; document.getElementById('sysMemory').textContent = h.memory.heapUsed + ' / ' + h.memory.heapTotal + ' (RSS: ' + h.memory.rss + ')'; document.getElementById('sysNode').textContent = h.nodeVersion; document.getElementById('sysPid').textContent = h.pid; document.getElementById('sysUsb').textContent = h.usbMounted ? '✓ Mounted' : '✗ Not mounted'; document.getElementById('sysUsb').className = 'stat-value ' + (h.usbMounted ? 'ok' : 'error');}
async function loadSystem() { try { const s = await api('/api/system'); document.getElementById('sysLoad').textContent = s.loadAvg || '—'; document.getElementById('sysDisk').textContent = s.disk ? s.disk.split('\n')[1]?.trim() || '—' : '—'; } catch(e) {}}
// Keyboard shortcutsdocument.addEventListener('keydown',e=>{ if((e.metaKey||e.ctrlKey)&&e.key==='p'){e.preventDefault();showPalette()} if(e.key==='Escape')hidePalette();});
loadTools();</script></body></html>`;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231// Phantom — Environment auto-detection// Lazy singleton: fast checks on first access, cached in __r.ENV
import { execFileSync, spawn } from "child_process";
// ── Cache ──let _populated = false;
// ── Quick binary check (which, cached) ──const _binCache = {};function hasBin(name) { if (name in _binCache) return _binCache[name]; try { execFileSync("which", [name], { timeout: 2000, stdio: "pipe" }); _binCache[name] = true; } catch { _binCache[name] = false; } return _binCache[name];}
// ── Security/network tool categories ──const RECON_BINS = ["nmap","masscan","subfinder","amass","whois","dig","nslookup","dnsx","shuffledns"];const EXPLOIT_BINS = ["sqlmap","metasploit","searchsploit","hydra","john","hashcat","nuclei","ffuf","gobuster"];const DEV_BINS = ["python3","python","go","rustc","gcc","make","git","curl","wget","jq"];const NET_BINS = ["ping","traceroute","netstat","ss","iptables","ufw"];const BROWSER_BINS = ["google-chrome","chromium","firefox","chromium-browser"];const ALL_BINS = [...RECON_BINS, ...EXPLOIT_BINS, ...DEV_BINS, ...NET_BINS, ...BROWSER_BINS];
// Binary name → apt package name mappingconst PKG_MAP = { nmap:"nmap", masscan:"masscan", whois:"whois", dig:"dnsutils", hydra:"hydra", john:"john", hashcat:"hashcat", traceroute:"traceroute", netstat:"net-tools", ss:"iproute2", nikto:"nikto", dirb:"dirb", whatweb:"whatweb", wafw00f:"wafw00f", aircrack:"aircrack-ng", tshark:"tshark", sqlmap:"sqlmap", dnsrecon:"dnsrecon",};// Estimated installed size in KB (from apt-cache show). hashcat=145MB is excluded.const PKG_SIZE = { nmap:4156, masscan:464, whois:300, dig:1200, hydra:1006, john:403, hashcat:148553, traceroute:216, netstat:1072, ss:3703, nikto:1862, dirb:1594, whatweb:19206, wafw00f:260, aircrack:2491, tshark:398, sqlmap:15000, dnsrecon:200,};
function detectTools() { const tools = {}; try { const script = ALL_BINS.map(t => `command -v ${t} 2>/dev/null && echo BIN:${t}`).join(";"); let out; try { out = execFileSync("sh", ["-c", script], { timeout: 5000, stdio: ["pipe","pipe","pipe"] }).toString(); } catch (e) { // Some commands fail (tools not found) — still read partial stdout out = e.stdout?.toString() || ""; } const found = new Set(out.trim().split("\n").filter(l => l.startsWith("BIN:")).map(l => l.slice(4))); for (const t of ALL_BINS) tools[t] = found.has(t); } catch { for (const t of ALL_BINS) tools[t] = false; } return tools;}
// ── Package manager ──function detectPkgManager() { if (hasBin("apt")) return "apt"; if (hasBin("apk")) return "apk"; if (hasBin("yum")) return "yum"; if (hasBin("dnf")) return "dnf"; if (hasBin("pacman")) return "pacman"; if (hasBin("brew")) return "brew"; if (hasBin("pkg")) return "pkg"; return null;}
// ── Shell ──function detectShell() { return process.env.SHELL?.split("/").pop() || "sh"; }
// ── Network ──function detectNetwork() { const info = { online: false, publicIP: null, dns: null, proxy: null }; try { execFileSync("sh", ["-c", "timeout 3 curl -s --max-time 3 https://1.1.1.1 >/dev/null 2>&1 || timeout 3 ping -c 1 -W 2 8.8.8.8 2>/dev/null"], { timeout: 5000 }); info.online = true; } catch {} try { const out = execFileSync("sh", ["-c", "timeout 3 dig +short myip.opendns.com @resolver1.opendns.com 2>/dev/null || timeout 3 curl -s --max-time 3 ifconfig.me 2>/dev/null || timeout 3 curl -s --max-time 3 icanhazip.com 2>/dev/null"], { timeout: 5000, stdio: ["pipe","pipe","pipe"] }); const ip = out.toString().trim(); if (ip) { info.publicIP = ip; info.online = true; } } catch {} if (process.env.HTTP_PROXY || process.env.https_proxy) info.proxy = process.env.HTTP_PROXY || process.env.https_proxy; if (process.env.HTTPS_PROXY || process.env.https_proxy) info.proxy = info.proxy || process.env.HTTPS_PROXY; try { const out = execFileSync("sh", ["-c", "grep '^nameserver' /etc/resolv.conf 2>/dev/null | head -1 | awk '{print $2}'"], { timeout: 2000 }); const dns = out.toString().trim(); if (dns) info.dns = dns; } catch {} return info;}
// ── System resources ──function detectResources() { const r = { cpu: 0, mem: 0, memFree: 0, diskFree: 0, arch: process.arch }; try { r.cpu = parseInt(execFileSync("nproc",[],{timeout:2000}).toString().trim()) || 0; } catch { try { r.cpu = parseInt(execFileSync("sh",["-c","grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 1"],{timeout:2000}).toString().trim()) || 1; } catch { r.cpu = 1; } } try { const out1 = execFileSync("sh",["-c","grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo 0"],{timeout:2000}); r.mem = parseInt(out1.toString().trim()) || 0; const out2 = execFileSync("sh",["-c","grep MemAvailable /proc/meminfo 2>/dev/null | awk '{print $2}' || grep MemFree /proc/meminfo 2>/dev/null | awk '{print $2}' || echo 0"],{timeout:2000}); r.memFree = parseInt(out2.toString().trim()) || 0; } catch {} try { const df = execFileSync("sh",["-c","df / 2>/dev/null | tail -1 | awk '{print $4}'"],{timeout:2000}); const kb = parseInt(df.toString().trim()); if (!isNaN(kb)) r.diskFree = kb; } catch {} return r;}
const CORE_TOOLS = ["curl","wget","git","jq","python3"];
// Auto-install core missing tools (skips if disk < 50MB).// Returns: >0 installed, 0 nothing needed, -1 install failed, -2 disk too lowexport function autoInstallCore(envTools) { if (!envTools?.pkgMgr || envTools.pkgMgr !== "apt") return 0; if (envTools.resources?.diskFree < 50*1024) return -2; if (!envTools.tools) return 0; const missing = CORE_TOOLS.filter(t => envTools.tools[t] === false); if (!missing.length) return 0; try { execFileSync("apt",["install","-y",...missing],{timeout:120000,stdio:"pipe"}); for (const t of missing) { try { execFileSync("which",[t],{timeout:2000,stdio:"pipe"}); envTools.tools[t] = true; } catch {} } return missing.length; } catch { return -1; }}
// Auto-install missing security tools (background, non-blocking).// Picks smallest tools first, skips hashcat (145MB). Runs at most once.let _autoSecurityStarted = false;export function autoInstallSecurity(envTools, logFn) { if (_autoSecurityStarted) return; if (!envTools?.pkgMgr || envTools.pkgMgr !== "apt") return; if (envTools.resources?.diskFree < 200*1024) return; // need 200MB+ free if (!envTools.tools) return;
const missingBins = Object.entries(envTools.tools) .filter(([k,v]) => !v && PKG_MAP[k]) .map(([k]) => k);
// Skip hashcat (145MB), sort remaining by size (smallest first) const targets = missingBins .filter(t => t !== "hashcat" && t !== "sqlmap") // skip biggest .sort((a, b) => (PKG_SIZE[a] || 999999) - (PKG_SIZE[b] || 999999)) .slice(0, 15); // max 15 packages
if (!targets.length) return; _autoSecurityStarted = true;
const pkgs = targets.map(t => PKG_MAP[t]); const totalEst = targets.reduce((s, t) => s + (PKG_SIZE[t] || 0), 0); const neededKb = totalEst + 50000; // +50MB margin for deps
if (envTools.resources.diskFree < neededKb) { if (logFn) logFn(`[env] Need ~${Math.round(neededKb/1024)}MB for security tools, only ${Math.round(envTools.resources.diskFree/1024)}MB free — skipping auto-install`); _autoSecurityStarted = false; return; }
if (logFn) logFn(`[env] Auto-installing ${targets.length} security tools (${Math.round(totalEst/1024)}MB)...`);
const proc = spawn("apt", ["install", "-y", ...pkgs], { stdio: ["pipe", "pipe", "pipe"], timeout: 300000 }); let output = ""; proc.stdout.on("data", d => { output += d.toString(); }); proc.stderr.on("data", d => { output += d.toString(); });
proc.on("close", (code) => { if (code === 0 && logFn) { // Refresh tool detection const freshTools = detectTools(); Object.assign(envTools.tools, freshTools); const now = Object.entries(freshTools).filter(([,v]) => v).length; if (logFn) logFn(`[env] ✓ ${targets.length} tools installed (${now}/${Object.keys(freshTools).length} available)`); } else { if (logFn) logFn(`[env] ✗ apt install exited code ${code} — will retry next startup`); _autoSecurityStarted = false; // allow retry } }); proc.on("error", (e) => { if (logFn) logFn(`[env] ✗ apt install error: ${e.message}`); _autoSecurityStarted = false; });}
// ── Public API ──export function populateEnv(existingEnv = {}) { if (_populated) return; _populated = true;
const tools = detectTools(); const pkgMgr = detectPkgManager(); const shell = detectShell(); const network = detectNetwork(); const resources = detectResources();
// Auto-install core missing tools const installed = autoInstallCore({ pkgMgr, tools, resources }); if (installed > 0) { const freshTools = detectTools(); Object.assign(tools, freshTools); }
const availableCount = Object.values(tools).filter(Boolean).length; const totalChecked = Object.keys(tools).length;
Object.assign(existingEnv, { tools, pkgMgr, shell, network, resources, availableTools: availableCount, totalChecked });}
export function getEnvSummary(env) { const lines = []; lines.push(`Platform: ${env.platform || "?"}`); lines.push(`Shell: ${env.shell || "?"}`); lines.push(`Terminal: ${env.terminal || "?"}`); lines.push(`Colors: ${env.hasTrueColor ? "truecolor" : env.has256 ? "256" : "16"}`); lines.push(`Screen: ${env.cols}x${env.rows} (${env.screenSize})`); lines.push(`Package manager: ${env.pkgMgr || "none"}`); lines.push(`Network: ${env.network?.online ? "online" : "offline"}${env.network?.publicIP ? " · IP: " + env.network.publicIP : ""}${env.network?.dns ? " · DNS: " + env.network.dns : ""}`); lines.push(`CPU: ${env.resources?.cpu || "?"} cores · RAM: ${Math.round((env.resources?.mem||0)/1024)}MB (${Math.round((env.resources?.memFree||0)/1024)}MB free) · Disk: ${Math.round((env.resources?.diskFree||0)/1024)}MB free`);
const { tools } = env; if (tools) { const avail = Object.entries(tools).filter(([,v]) => v).map(([k]) => k); const missing = Object.entries(tools).filter(([,v]) => !v).map(([k]) => k); lines.push(`Tools: ${avail.length}/${Object.keys(tools).length} available`); lines.push(` Present: ${avail.join(", ")}`); if (missing.length < 60) lines.push(` Missing: ${missing.join(", ")}`); } return lines.join("\n");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867// Phantom — Auto-Evolution Engine// Self-healing, self-optimizing, self-growing.// Runs automatically on startup and after tasks.
import fs from "fs";import { execFileSync, execSync } from "child_process";import { resolve, join } from "path";import { homedir } from "os";import { BASE_DIR, TOOLS_DIR, PHANTOM_VERSION } from "./config.mjs";import { __r } from "./runtime.mjs";
// ── Constants ──────────────────────────────────────────────const PHANTOM_DIR = resolve(import.meta.dirname, ".."); // project rootconst EVOLVE_LOG = resolve(BASE_DIR, "evolve.json");const AUTO_TOOLS_DIR = resolve(PHANTOM_DIR, "lib", "auto_tools"); // in-repo so git-tracked
// ── Git helpers ────────────────────────────────────────────function gitRoot() { try { const r = execSync("git rev-parse --show-toplevel 2>/dev/null", { encoding: "utf-8", timeout: 5000 }).trim(); return r || null; } catch { return null; }}
export function gitCommit(files, msg) { const root = gitRoot(); if (!root) return false; try { // Stage specific files or all changes if (files && files.length > 0) { for (const f of files) { const abs = f.startsWith("/") ? f : resolve(PHANTOM_DIR, f); if (fs.existsSync(abs)) execSync(`git add "${abs}"`, { cwd: root, encoding: "utf-8", timeout: 10000 }); } } else { execSync("git add -A", { cwd: root, encoding: "utf-8", timeout: 10000 }); } // Check if anything staged const staged = execSync("git diff --cached --stat", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); if (!staged) return false; execSync(`git commit -m "${msg}"`, { cwd: root, encoding: "utf-8", timeout: 15000 }); return true; } catch { return false; }}
export function gitPush() { const root = gitRoot(); if (!root) return { pushed: false, reason: "no git root" }; // Check if remote exists try { const remotes = execSync("git remote", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); if (!remotes) return { pushed: false, reason: "no remote configured" }; } catch { return { pushed: false, reason: "no remote" }; }
// Fetch and check for upstream divergence (misalignment) try { const upstream = execSync("git rev-parse --symbolic-full-name @{upstream} 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); if (upstream) { execSync("git fetch origin 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 30000 }); const behind = execSync("git rev-list --count HEAD..@{upstream} 2>/dev/null", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); if (parseInt(behind) > 0) return { pushed: false, reason: `${behind} commit(s) behind upstream — pull first` }; } } catch { /* no upstream tracking, push anyway */ }
// Alignment check on the diff const alignment = verifyDiffAlignment(root); if (!alignment.ok) return { pushed: false, reason: `alignment: ${alignment.errors[0]}`, alignment };
// Push try { execSync("git push 2>&1", { cwd: root, encoding: "utf-8", timeout: 60000 }); return { pushed: true }; } catch (e) { return { pushed: false, reason: e.stderr?.slice(0, 200) || e.message }; }}
// ── Diff misalignment check ──// Scans staged changes for regressions before push.export function verifyDiffAlignment(root) { const result = { ok: true, errors: [], warnings: [] };
let diffStat; try { diffStat = execSync("git diff --cached --stat", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); } catch { return result; } if (!diffStat) { result.warnings.push("no staged changes"); return result; }
// Extract changed .mjs files const changedMjs = diffStat.split("\n") .map(l => l.split("|")[0]?.trim()) .filter(f => f && f.endsWith(".mjs"));
// 1. Syntax check every changed .mjs file for (const f of changedMjs) { const abs = f.startsWith("/") ? f : resolve(root, f); if (fs.existsSync(abs)) { try { execSync(`node --check "${abs}"`, { encoding: "utf-8", timeout: 10000 }); } catch (e) { const err = (e.stderr || e.message || "").slice(0, 200); result.errors.push(`${f}: syntax error — ${err}`); result.ok = false; } } }
// 2. Forbid debug artifacts in changed files const diffContent = execSync("git diff --cached -U0", { cwd: root, encoding: "utf-8", timeout: 5000 }); if (diffContent) { // Added lines that are debug artifacts const additions = diffContent.split("\n").filter(l => l.startsWith("+") && !l.startsWith("+++") && !l.startsWith("+ ")); const debugPatterns = [/^\+.*console\.(log|debug)\s*\(/m, /^\+.*debugger\s*;?$/m, /^\+.*process\.env\.PHANTOM_GIT_PUSH/m]; for (const pat of debugPatterns) { const matches = additions.filter(l => pat.test(l)); if (matches.length > 0) { result.warnings.push(`${matches.length} line(s) match ${pat.source} — verify intentional`); // Don't block for debug warnings, just flag } }
// 3. Check for hardcoded secrets (API keys, tokens, passwords) const secretPatterns = [/^\+.*(?:api.?key|secret|password|token|passwd)\s*[:=]\s*['\"][^'\"]{8,}['\"]/im]; for (const pat of secretPatterns) { if (additions.some(l => pat.test(l))) { result.errors.push("hardcoded secret detected in staged diff — blocking push"); result.ok = false; } }
// 4. Check file sizes (no binaries >100KB staged) try { const binaryCheck = execSync("git diff --cached --numstat | awk '{sum+=$1} END {print sum+0}'", { cwd: root, encoding: "utf-8", timeout: 5000 }).trim(); const totalAdditions = parseInt(binaryCheck); if (totalAdditions > 5000) result.warnings.push(`large diff: ${totalAdditions} additions — verify`); } catch { /* numstat unavailable */ } }
// 5. Run core tests to verify nothing regressed try { const testOut = execSync("node test/core.test.mjs 2>&1", { cwd: root, encoding: "utf-8", timeout: 45000 }); const failMatch = testOut.match(/fail\s+(\d+)/); if (failMatch && parseInt(failMatch[1]) > 0) { result.errors.push(`${failMatch[1]} test(s) failing — blocking push`); result.ok = false; } } catch (e) { result.warnings.push("test runner unavailable — skipping test gate"); }
return result;}
// ── Known external binaries & their wrapper boilerplate ──const WRAP_BLUEPRINTS = { naabu: { install: "go install github.com/projectdiscovery/naabu/v2/cmd/naabu@latest", generate: (bin) => `naabu: async (input) => { try { const { execSync } = await import("child_process"); const { resolve } = await import("path"); const target = input.trim() || ""; if (!target) return "[naabu] Usage: @naabu|<target> [options]\\nFast port scanner by ProjectDiscovery.\\nExamples:\\n naabu|scanme.org\\n naabu|scanme.org -p 80,443,8443\\n naabu|scanme.org -top-ports 1000"; const r = execSync(\`naabu \${target}\`, { encoding: "utf-8", timeout: 120000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no results)"; } catch (e) { return \`[naabu Error] \${e.stderr?.slice(0, 500) || e.message}\`; } },` }, notify: { install: "go install github.com/projectdiscovery/notify/cmd/notify@latest", generate: (bin) => `notify: async (input) => { try { const { execSync } = await import("child_process"); const msg = input.trim(); if (!msg) return "[notify] Usage: @notify|<message>\\nSend notifications to Slack/Telegram/Discord/etc.\\nRequires ~/.config/notify/provider-config.yaml"; execSync(\`notify -data <(echo "\${msg}")\`, { encoding: "utf-8", timeout: 15000 }); return "[notify] Sent"; } catch (e) { return \`[notify Error] \${e.message}\`; } },` }, puredns: { install: "go install github.com/d3mondev/puredns/v2@latest", generate: (bin) => `puredns: async (input) => { try { const { execSync } = await import("child_process"); const args = input.trim(); if (!args) return "[puredns] Usage: @puredns|<args>\\nFast DNS resolver by d3mondev.\\nExamples:\\n puredns|resolve domains.txt\\n puredns|bruteforce wordlist.txt example.com"; const r = execSync(\`puredns \${args}\`, { encoding: "utf-8", timeout: 120000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no results)"; } catch (e) { return \`[puredns Error] \${e.stderr?.slice(0, 500) || e.message}\`; } },` }, httprobe: { install: "go install github.com/tomnomnom/httprobe@latest", generate: (bin) => `httprobe: async (input) => { try { const { execSync } = await import("child_process"); const targets = input.trim(); if (!targets) return "[httprobe] Usage: @httprobe|<targets>\\nProbe for alive HTTP/HTTPS servers. Takes list of hosts.\\nExamples:\\n httprobe|example.com:443\\n httprobe|subs.txt"; const r = execSync(\`echo "\${targets}" | httprobe\`, { encoding: "utf-8", timeout: 60000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no alive hosts)"; } catch (e) { return \`[httprobe Error] \${e.message}\`; } },` }, chaos: { install: "go install github.com/projectdiscovery/chaos-client/cmd/chaos@latest", generate: (bin) => `chaos: async (input) => { try { const { execSync } = await import("child_process"); const domain = input.trim(); if (!domain) return "[chaos] Usage: @chaos|<domain>\\nProjectDiscovery Chaos - subdomain enumeration from passive sources.\\nRequires CHAOS_API_KEY env var."; const r = execSync(\`chaos -d \${domain} -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no subs from Chaos)"; } catch (e) { return \`[chaos Error] \${e.message}\`; } },` }, uncover: { install: "go install github.com/projectdiscovery/uncover/cmd/uncover@latest", generate: (bin) => `uncover: async (input) => { try { const { execSync } = await import("child_process"); const query = input.trim(); if (!query) return "[uncover] Usage: @uncover|<query>\\nSearch Shodan/Censys/Fofa/Publicwww for hosts.\\nRequires API keys configured in ~/.config/uncover/"; const r = execSync(\`uncover -q "\${query}" -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no results)"; } catch (e) { return \`[uncover Error] \${e.message}\`; } },` }, mapcidr: { install: "go install github.com/projectdiscovery/mapcidr/cmd/mapcidr@latest", generate: (bin) => `mapcidr: async (input) => { try { const { execSync } = await import("child_process"); const cidr = input.trim(); if (!cidr) return "[mapcidr] Usage: @mapcidr|<cidr>\\nCIDR expansion utility by ProjectDiscovery.\\nExamples:\\n mapcidr|192.168.1.0/24\\n mapcidr|-a 2a00:1450:4000::/48"; const r = execSync(\`mapcidr -cidr \${cidr} -silent\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024 }); return r.trim() || "(no results)"; } catch (e) { return \`[mapcidr Error] \${e.message}\`; } },` }, "subfinder": null, // already wrapped "httpx": null, // already wrapped "nuclei": null, // already wrapped "nmap": null, // already wrapped "ffuf": null, // already wrapped "gobuster": null, // already wrapped "hydra": null, // already wrapped "masscan": null, // already wrapped "nikto": null, // already wrapped "whatweb": null, // already wrapped "sqlmap": null, // already wrapped "amass": null, // already wrapped "dnsx": null, // already wrapped "gau": null, // already wrapped "katana": null, // already wrapped "gitleaks": null, // already wrapped "s3scanner": null, // already wrapped "trufflehog": null, // already wrapped "wafw00f": null, // already wrapped "arjun": null, // already wrapped "gospider": null, // already wrapped "interactsh": null, // already wrapped};
// ── Tools Phantom already wraps (skip) ──const EXISTING_TOOLS = new Set(Object.keys(WRAP_BLUEPRINTS).filter(k => WRAP_BLUEPRINTS[k] === null));
// ── Load evolve state ──function loadState() { try { if (fs.existsSync(EVOLVE_LOG)) return JSON.parse(fs.readFileSync(EVOLVE_LOG, "utf-8")); } catch {} return { generation: 1, patches: [], wrappers: [], errors_fixed: 0, last_evolve: null, auto_fixes: [] };}
function saveState(st) { try { if (!fs.existsSync(BASE_DIR)) fs.mkdirSync(BASE_DIR, { recursive: true }); fs.writeFileSync(EVOLVE_LOG, JSON.stringify(st, null, 2), "utf-8"); } catch {}}
// ── 1. Auto-detect missing wrappers ──// Scan PATH for installed security tools Phantom doesn't wrap yet.export function detectMissingWrappers() { const existing = new Set([ "nmap","sqlmap","searchsploit","ffuf","gobuster","hydra","john","hashcat", "aircrack-ng","tshark","masscan","nikto","wpscan","dirb","enum4linux", "smbclient","nc","ncat","socat","curl","wget","git","python3","node", "docker","kubectl","terraform","yara","clamscan","sslyze","testssl", "whois","dig","nslookup","host","tcpdump","sqlite3","jq","yt-dlp","ffmpeg", "subfinder","httpx","nuclei","amass","gau","dnsx","katana","gitleaks", "s3scanner","gobuster","nmap","sqlmap","whatweb","wafw00f","trufflehog", "hydra","masscan","nikto","arjun","gospider","cloud_enum","notify", "interactsh","burpsuite","metasploit","naabu","puredns","httprobe", "chaos","uncover","mapcidr","crtsh", ]);
const found = []; const candidates = Object.entries(WRAP_BLUEPRINTS).filter(([, v]) => v !== null);
for (const [bin, blueprint] of candidates) { if (existing.has(bin)) continue; try { execFileSync("which", [bin], { encoding: "utf-8", timeout: 3000 }); found.push({ bin, blueprint }); } catch {} } return found;}
// Generate wrapper code and save it as a proper ESM moduleexport function generateWrapper(bin, blueprint) { let code = blueprint.generate(bin); const dir = AUTO_TOOLS_DIR; if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); // Strip the "name: async (input) => {" prefix and trailing "},\n" suffix // The blueprints include object-literal formatting we don't need in standalone modules code = code.replace(/^\w+:\s*async\s*\(\s*input\s*\)\s*=>\s*{/, "").replace(/},\s*$/, "").trim(); // Wrap in a proper ESM default export const moduleCode = `// Auto-generated wrapper for ${bin}// Created by Phantom auto-evolution
export default async function(input) {${code}}\n`; const filePath = resolve(dir, `${bin}.mjs`); fs.writeFileSync(filePath, moduleCode, "utf-8"); return filePath;}
// Load all auto-generated tools and return as {name: executeFn}export async function loadAutoTools() { const tools = {}; if (!fs.existsSync(AUTO_TOOLS_DIR)) return tools; const files = fs.readdirSync(AUTO_TOOLS_DIR).filter(f => f.endsWith(".mjs")); for (const file of files) { try { const name = file.replace(/\.mjs$/, ""); const mod = await import(resolve(AUTO_TOOLS_DIR, file) + `?t=${Date.now()}`); const fn = mod.default || mod.execute; if (typeof fn === "function") tools[name] = fn; } catch {} } return tools;}
// ── 2. Auto-fix common tool errors ──// Patterns that can be auto-patchedfunction autoInstall(bin) { // Try to auto-install a missing binary try { // Check if npm package exists execSync(`which npm 2>/dev/null`, { timeout: 3000 }); execSync(`npm list -g ${bin} 2>/dev/null || npm install -g ${bin} 2>/dev/null`, { timeout: 60000 }); return { fixed: true, message: `Auto-installed ${bin} via npm` }; } catch {} try { execSync(`which apt 2>/dev/null && apt install -y ${bin} 2>/dev/null`, { timeout: 60000 }); return { fixed: true, message: `Auto-installed ${bin} via apt` }; } catch {} try { execSync(`which pkg 2>/dev/null && pkg install -y ${bin} 2>/dev/null`, { timeout: 60000 }); return { fixed: true, message: `Auto-installed ${bin} via pkg` }; } catch {} return { fixed: false, message: `${bin} not installed and auto-install failed` };}
const FIX_PATTERNS = [ { match: /command not found/i, fix: async (tool, err) => { const bin = tool || err.match(/'([^']+)'/)?.[1]; if (bin) return autoInstall(bin); return { fixed: false, message: `Tool not installed. Install it and try again.` }; } }, { match: /Cannot find module/i, fix: async (tool, err) => { const mod = err.match(/'([^']+)'/)?.[1]; if (mod) { try { execSync(`npm install ${mod} 2>/dev/null`, { timeout: 60000, cwd: PHANTOM_DIR }); return { fixed: true, message: `Auto-installed module ${mod}` }; } catch { try { execSync(`npm install ${mod} 2>/dev/null`, { timeout: 60000 }); return { fixed: true, message: `Auto-installed module ${mod} globally` }; } catch {} } } return { fixed: false, message: `Missing module ${mod || tool} — could not auto-install` }; } }, { match: /EACCES|EPERM/i, fix: async (tool, err) => { const file = err.match(/'([^']+)'/)?.[1]; if (file) { try { execSync(`chmod +x "${file}" 2>/dev/null`, { timeout: 5000 }); return { fixed: true, message: `Made ${file} executable` }; } catch {} } return { fixed: false, message: `Permission denied — run with elevated privileges` }; } }, { match: /ETIMEOUT|ENOTFOUND|fetch.*failed/i, fix: async (tool, err) => { return { fixed: false, message: `Network issue — check connectivity and try again` }; } }, { match: /ENOENT/i, fix: async (tool, err) => { return { fixed: false, message: `File/directory not found — verify path exists` }; } }, { match: /Syntax error.*backquote|EOF in backquote|unclosed.*backtick/i, fix: async (tool, err) => { return { fixed: false, message: `Check for unescaped backticks or $() in command` }; } }, { match: /Shell Error/i, fix: async (tool, err) => { return { fixed: false, message: `Shell command failed — check syntax and retry` }; } },];
// Analyze a tool error and attempt auto-fixexport async function analyzeError(tool, errorMessage) { for (const pattern of FIX_PATTERNS) { if (pattern.match.test(errorMessage)) { const result = await pattern.fix(tool, errorMessage); if (result) { const st = loadState(); st.errors_fixed++; st.auto_fixes.push({ ts: new Date().toISOString(), tool, error: errorMessage.slice(0, 100), fix: result.message }); saveState(st); return result; } } } return null;}
// ── 3. Auto-syntax heal — actually fix common issues ──// Auto-fix common syntax/errors in Phantom's own sourceexport async function autoHealSyntax() { const results = []; const files = [ "phantom.mjs", ...fs.readdirSync(resolve(PHANTOM_DIR, "lib")).filter(f => f.endsWith(".mjs")).map(f => `lib/${f}`), ];
for (const file of files) { const fp = resolve(PHANTOM_DIR, file); if (!fs.existsSync(fp)) continue;
try { execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); continue; // syntax OK } catch (e) { // Syntax error — try to fix common issues try { const content = fs.readFileSync(fp, "utf-8"); const stderr = e.stderr || e.message || ""; let fixed = false;
// Fix 1: trailing commas in non-module context (common in object literals) if (stderr.includes("trailing comma") || stderr.includes("nexpected token")) { const newContent = content.replace(/,(\s*[\n\r]+\s*[}\]])/g, '$1'); if (newContent !== content) { fs.writeFileSync(fp, newContent, "utf-8"); try { execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); fixed = true; results.push({ file, fixed: true, error: "Fixed trailing commas" }); continue; } catch {} } }
// Fix 2: unclosed string — look for unterminated string error if (stderr.includes("Unterminated string") || stderr.includes("unterminated string")) { const newContent = content.replace(/('''|"""|````)/g, (m) => m.slice(0, 3)); if (newContent !== content) { fs.writeFileSync(fp, newContent, "utf-8"); try { execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); fixed = true; results.push({ file, fixed: true, error: "Fixed unterminated string" }); continue; } catch {} } }
// Fix 3: missing closing brace or paren if (stderr.includes("Unexpected end of input") || stderr.includes("missing )") || stderr.includes("missing }")) { // Try adding closing braces let newContent = content; const opens = (content.match(/{/g) || []).length; const closes = (content.match(/}/g) || []).length; const opensP = (content.match(/\(/g) || []).length; const closesP = (content.match(/\)/g) || []).length; if (opens > closes) { newContent += "\n" + "}".repeat(opens - closes); } if (opensP > closesP) { newContent += "\n" + ")".repeat(opensP - closesP); } if (newContent !== content) { fs.writeFileSync(fp, newContent, "utf-8"); try { execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); fixed = true; results.push({ file, fixed: true, error: `Fixed unbalanced braces/parens` }); continue; } catch {} } }
if (!fixed) { results.push({ file, fixed: false, error: stderr.trim().slice(0, 100) || "Unknown syntax error" }); } } catch { results.push({ file, fixed: false, error: "Cannot read file" }); } } }
return results;}
// ── 4. Auto-optimization scanner ──// Scan Phantom source for optimization opportunitiesexport function scanOptimizations() { const issues = []; const mainPath = resolve(PHANTOM_DIR, "phantom.mjs"); if (!fs.existsSync(mainPath)) return issues;
const src = fs.readFileSync(mainPath, "utf-8"); const lines = src.split("\n");
// Check for oversized functions let fnStart = 0; let braceCount = 0; let inFn = false; for (let i = 0; i < lines.length; i++) { const l = lines[i]; if (!inFn && l.match(/async\s+\w+\s*\(/)) { fnStart = i; inFn = true; braceCount = (l.match(/{/g) || []).length - (l.match(/}/g) || []).length; } else if (inFn) { braceCount += (l.match(/{/g) || []).length - (l.match(/}/g) || []).length; if (braceCount <= 0) { const len = i - fnStart; if (len > 100) { issues.push({ line: fnStart + 1, type: "long_fn", detail: `Function at line ${fnStart + 1} is ${len} lines — consider splitting` }); } inFn = false; } } }
// Check for repeated patterns const dynamicImportCount = (src.match(/import\("child_process"\)/g) || []).length; if (dynamicImportCount > 3) { issues.push({ line: 0, type: "repeated_import", detail: `Dynamic import("child_process") used ${dynamicImportCount} times — hoist to module scope` }); }
// Check for console.log vs structured logging const consoleCount = (src.match(/console\.(log|error|warn)\(/g) || []).length; if (consoleCount > 60) { issues.push({ line: 0, type: "console_spam", detail: `${consoleCount} console.* calls — use structured logging` }); }
return issues;}
// ── 5. Run full evolution cycle ──export async function autoEvolve() { const st = loadState(); const results = [];
// Phase 1: Auto-detect missing wrappers try { const missing = detectMissingWrappers(); if (missing.length > 0) { const created = []; for (const { bin, blueprint } of missing) { try { const path = generateWrapper(bin, blueprint); st.wrappers.push({ bin, path, ts: new Date().toISOString() }); created.push(bin); results.push({ phase: "wrapper", bin, status: "created", path }); } catch (e) { results.push({ phase: "wrapper", bin, status: "error", error: e.message }); } } // ── Git commit auto-generated wrappers ── if (created.length > 0) { const committed = gitCommit( created.map(b => `lib/auto_tools/${b}.mjs`), `🧬 auto-evolve: add ${created.length} tool wrapper(s): ${created.join(", ")}` ); if (committed) { results.push({ phase: "git", status: "committed", files: created.length }); } } } } catch (e) { results.push({ phase: "wrapper", status: "error", error: e.message }); }
// Phase 2: Syntax check and auto-heal try { const healResults = await autoHealSyntax(); for (const r of healResults) { results.push({ phase: "heal", file: r.file, status: r.fixed ? "fixed" : "failed", error: r.error }); } } catch (e) { results.push({ phase: "heal", status: "error", error: e.message }); }
// Phase 3: Scan for optimizations try { const opts = scanOptimizations(); for (const o of opts) { results.push({ phase: "optimize", type: o.type, detail: o.detail, line: o.line }); } } catch (e) { results.push({ phase: "optimize", status: "error", error: e.message }); }
// Phase 4: Self-syntax validation try { const { execSync } = await import("child_process"); execSync(`node --check "${resolve(PHANTOM_DIR, "phantom.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); results.push({ phase: "validate", file: "phantom.mjs", status: "ok" }); execSync(`node --check "${resolve(PHANTOM_DIR, "lib/tools.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); results.push({ phase: "validate", file: "lib/tools.mjs", status: "ok" }); execSync(`node --check "${resolve(PHANTOM_DIR, "lib/runtime.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); results.push({ phase: "validate", file: "lib/runtime.mjs", status: "ok" }); execSync(`node --check "${resolve(PHANTOM_DIR, "lib/evolve.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); results.push({ phase: "validate", file: "lib/evolve.mjs", status: "ok" }); } catch (e) { results.push({ phase: "validate", status: "error", error: e.stderr?.slice(0, 200) || e.message }); }
// Phase 5: Test gate — only suggest push if tests pass try { const { execSync } = await import("child_process"); const testOut = execSync("node test/core.test.mjs", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 30000 }).trim(); const passMatch = testOut.match(/pass\s+(\d+)/); const failMatch = testOut.match(/fail\s+(\d+)/); const passed = passMatch ? parseInt(passMatch[1]) : 0; const failed = failMatch ? parseInt(failMatch[1]) : 0; results.push({ phase: "test", status: failed > 0 ? "failed" : "passed", passed, failed });
if (failed > 0) { // Attempt auto-heal on test failures try { const { autoHealSyntax } = await import("./evolve.mjs"); const healed = await autoHealSyntax(); for (const h of healed) { results.push({ phase: "heal_retry", file: h.file, status: h.fixed ? "fixed" : "failed", error: h.error }); } if (healed.some(h => h.fixed)) { // Re-run tests after heal const retryOut = execSync("node test/core.test.mjs", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 30000 }).trim(); const retryPass = retryOut.match(/pass\s+(\d+)/); const retryFail = retryOut.match(/fail\s+(\d+)/); const rPassed = retryPass ? parseInt(retryPass[1]) : 0; const rFailed = retryFail ? parseInt(retryFail[1]) : 0; results.push({ phase: "test_retry", status: rFailed > 0 ? "failed" : "passed", passed: rPassed, failed: rFailed }); } } catch { /* heal attempt failed */ } } } catch (e) { results.push({ phase: "test", status: "error", error: e.stderr?.slice(0, 200) || e.message }); }
// Check readiness: have committed wrappers AND all tests passed? const hasCommits = results.some(r => r.phase === "git" && r.status === "committed"); const testsPassed = results.some(r => r.phase === "test" && r.status === "passed"); const finalTestsOk = results.some(r => r.phase === "test_retry" && r.status === "passed") || testsPassed;
if (hasCommits && finalTestsOk) { const pushResult = gitPush(); if (pushResult.pushed) { results.push({ phase: "git", status: "pushed", summary: "✅ Auto-pushed to remote" }); } else { results.push({ phase: "git", status: pushResult.reason?.startsWith("alignment") ? "blocked" : "push_failed", reason: pushResult.reason, summary: `⚠ Push skipped: ${pushResult.reason}` }); } } else if (hasCommits && !finalTestsOk) { results.push({ phase: "git", status: "tests_failed", summary: "⚠ Not pushing — tests failing after changes" }); }
// Update state st.generation++; st.last_evolve = new Date().toISOString(); st.patches = [...(st.patches || []), ...results.filter(r => r.phase === "heal")]; saveState(st);
return { generation: st.generation, results, wrappers_created: st.wrappers.length, errors_fixed: st.errors_fixed };}
// ── Quick startup evolution check ──export async function startupEvolve() { const st = loadState(); const results = { wrappers_checked: 0, wrappers_created: 0, issues: [] };
// Only run full evolution if more than 6 hours since last, or never run const last = st.last_evolve ? new Date(st.last_evolve).getTime() : 0; const sixHours = 6 * 60 * 60 * 1000; if (Date.now() - last < sixHours && st.generation > 1) { results.issues.push("skipped — recently evolved"); return results; }
// Quick wrapper check try { const missing = detectMissingWrappers(); results.wrappers_checked = missing.length; const created = []; for (const { bin, blueprint } of missing) { try { generateWrapper(bin, blueprint); st.wrappers.push({ bin, path: resolve(AUTO_TOOLS_DIR, `${bin}.mjs`), ts: new Date().toISOString() }); created.push(bin); results.wrappers_created++; } catch {} } // Git commit wrappers created at startup if (created.length > 0) { gitCommit(created.map(b => `lib/auto_tools/${b}.mjs`), "🧬 startup: add new auto-generated wrappers"); const pushResult = gitPush(); if (pushResult.pushed) results.push("auto-pushed"); else if (pushResult.reason) results.push(`push: ${pushResult.reason}`); } } catch {}
// Quick syntax check try { execSync(`node --check "${resolve(PHANTOM_DIR, "phantom.mjs")}"`, { encoding: "utf-8", timeout: 10000 }); } catch (e) { results.issues.push("syntax error in phantom.mjs"); }
// Ensure generated modules directory exists const generatedDir = resolve(PHANTOM_DIR, "lib", "generated"); if (!fs.existsSync(generatedDir)) fs.mkdirSync(generatedDir, { recursive: true });
if (results.wrappers_created > 0 || results.issues.length > 0) { st.last_evolve = new Date().toISOString(); st.generation++; saveState(st); }
return results;}
export function getEvolveStatus() { const st = loadState(); return { generation: st.generation, wrappers_created: st.wrappers.length, errors_fixed: st.errors_fixed, patches_applied: st.patches.length, last_evolve: st.last_evolve, wrapper_list: st.wrappers, recent_fixes: st.auto_fixes?.slice(-5), };}
// ── 7. SELF-HEAL: full auto-diagnose → fix → test → iterate ──// Runs until clean or max attempts reached.export async function selfHeal(options = {}) { const maxAttempts = options.maxAttempts || 5; const log = []; const startTime = Date.now();
for (let attempt = 1; attempt <= maxAttempts; attempt++) { const round = { attempt, checks: [], fixes: [], tests: [] };
// Phase 1: Syntax check all .mjs files const mjsFiles = ["phantom.mjs", ...fs.readdirSync(resolve(PHANTOM_DIR, "lib")).filter(f => f.endsWith(".mjs")).map(f => `lib/${f}`)]; let allClean = true; for (const file of mjsFiles) { const fp = resolve(PHANTOM_DIR, file); if (!fs.existsSync(fp)) continue; try { execSync(`node --check "${fp}" 2>/dev/null`, { encoding: "utf-8", timeout: 10000 }); round.checks.push({ file, status: "ok" }); } catch { allClean = false; round.checks.push({ file, status: "error" }); } }
// Phase 2: Auto-fix syntax issues if (!allClean) { const healResults = await autoHealSyntax(); for (const r of healResults) { round.fixes.push(r); if (r.fixed) { const st = loadState(); st.patches.push(r); st.errors_fixed = (st.errors_fixed || 0) + 1; saveState(st); } } // If nothing was fixed, break — can't heal further if (!healResults.some(r => r.fixed)) { log.push(round); break; } }
// Phase 3: Run tests try { const testOut = execSync("node test/core.test.mjs 2>/dev/null && echo 'TESTS_PASSED'", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 60000 }).trim(); const passed = testOut.includes("TESTS_PASSED"); round.tests.push({ status: passed ? "passed" : "failed" }); if (passed) { log.push(round); // If all clean and tests pass, commit and push try { const staged = execSync("git diff --cached --stat", { cwd: PHANTOM_DIR, encoding: "utf-8", timeout: 5000 }).trim(); if (staged) { const committed = gitCommit([], `🧬 self-heal: auto-fix ${round.fixes.filter(f => f.fixed).length} issue(s)`); if (committed) { const pushResult = gitPush(); round.push = pushResult.pushed ? "pushed" : pushResult.reason || "push_failed"; } } } catch {} break; // done } } catch (e) { round.tests.push({ status: "error", error: e.stderr?.slice(0, 200) || e.message }); }
log.push(round); }
// Update state const st = loadState(); st.last_evolve = new Date().toISOString(); st.generation++; saveState(st);
return { elapsed: Date.now() - startTime, attempts: log.length, clean: log[log.length - 1]?.tests?.some(t => t.status === "passed") || false, log, };}1234567891011121314151617// Phantom — structured logger// Provides log.output, log.ok, log.warn, log.error, log.info, log.art, log.cli// Respects --quiet / PHANTOM_QUIET for info/art/debug suppression.
const quiet = !!(process.env.PHANTOM_QUIET || process.argv.includes("--quiet") || process.argv.includes("-q"));
export const log = { art: quiet ? ()=>{} : console.log, info: quiet ? ()=>{} : console.log, ok: console.log, warn: console.warn, error: console.error, debug: ()=>{}, output: console.log, raw: console.log, cli: console.log,};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import fs from "fs";import { resolve } from "path";import { homedir } from "os";
const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions");
export function createMission(program, scope) { const id = `mission-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const now = new Date().toISOString(); return { id, programName: program.name || program.handle, programHandle: program.handle, programUrl: program.url, scope, status: "planning", objectives: [ "Passive reconnaissance of in-scope assets", "Active HTTP probing and technology detection", "Vulnerability validation and reporting" ], restrictions: [], createdAt: now, updatedAt: now, activityLog: [{ timestamp: now, action: "created", details: `Mission created for ${program.name || program.handle} (${program.handle})` }] };}
export function saveMission(mission) { if (!fs.existsSync(MISSIONS_DIR)) fs.mkdirSync(MISSIONS_DIR, { recursive: true }); const f = resolve(MISSIONS_DIR, `${mission.id}.json`); fs.writeFileSync(f, JSON.stringify(mission, null, 2), "utf-8");}
export function loadMission(missionId) { const f = resolve(MISSIONS_DIR, `${missionId}.json`); if (!fs.existsSync(f)) return null; return JSON.parse(fs.readFileSync(f, "utf-8"));}
export function listMissions() { if (!fs.existsSync(MISSIONS_DIR)) return []; return fs.readdirSync(MISSIONS_DIR) .filter(f => f.endsWith(".json")) .map(f => { const m = JSON.parse(fs.readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); return { id: m.id, programName: m.programName, programHandle: m.programHandle, status: m.status, createdAt: m.createdAt, updatedAt: m.updatedAt }; });}
export function updateMissionStatus(missionId, status) { const mission = loadMission(missionId); if (!mission) return null; mission.status = status; mission.updatedAt = new Date().toISOString(); saveMission(mission); return mission;}
export function addMissionActivity(missionId, activity) { const mission = loadMission(missionId); if (!mission) return; mission.activityLog = mission.activityLog || []; mission.activityLog.push({ timestamp: new Date().toISOString(), ...activity }); saveMission(mission);}
export function isInScope(target, mission) { const normalized = normalizeTarget(target); for (const scopeEntry of mission.scope.inScope) { if (scopeEntry.isWildcard) { const base = scopeEntry.normalized.replace(/^\*\./, ""); if (normalized === base || normalized.endsWith("." + base)) { return { allowed: true, reason: "Matches wildcard scope", matchingScopeEntry: scopeEntry }; } } else if (normalized === scopeEntry.normalized) { return { allowed: true, reason: "Exact match", matchingScopeEntry: scopeEntry }; } } return { allowed: false, reason: "Not in scope", matchingScopeEntry: null };}
export function normalizeTarget(target) { return target .replace(/^https?:\/\//, "") .replace(/\/.*$/, "") .toLowerCase() .trim();}
export function generateReconPlan(mission) { const targets = mission.scope.inScope.map(s => s.normalized); return { phases: [ { phase: 1, name: "Passive Reconnaissance", description: "Subdomain enumeration, DNS resolution", targets, tools: ["subfinder", "dnsx"] }, { phase: 2, name: "Active HTTP Probing", description: "HTTP probing, technology detection", targets, tools: ["httpx"] }, { phase: 3, name: "Validation & Reporting", description: "Validate findings, generate report", targets, tools: ["nuclei", "custom"] } ], notes: [ "Stage 1 only — NO active exploitation", "Default deny for all targets not in scope", "All findings saved per-target per-phase" ] };}
export async function fetchProgramAndScope(handle) { const { hackerTools } = await import("./tools.mjs"); const result = await hackerTools.hackerone(`scope ${handle}`); const inScope = []; const outScope = []; // The result has literal \n (backslash-n) as line separators between scope entries, // and actual newlines within multi-line descriptions. // First split by literal \n to get the logical lines. const lines = result.split("\\n"); let current = "in"; for (const line of lines) { const trimmed = line.trim(); // Check for section headers on the trimmed line if (trimmed.includes("IN SCOPE")) current = "in"; else if (trimmed.includes("OUT OF SCOPE")) current = "out"; // Check for scope entries on the raw line (which preserves leading spaces) else if (line.startsWith(" ") && trimmed.includes("(")) { // Match: "identifier (TYPE) — description" (trimmed has no leading spaces) const match = trimmed.match(/([^\s]+)\s+\(([^)]+)\)/); if (match) { const [, identifier, assetType] = match; const entry = { identifier, normalized: identifier.replace(/^\*\./, "").toLowerCase(), assetType, isWildcard: identifier.startsWith("*."), maxSeverity: "critical", instruction: current === "out" ? "Not eligible" : "" }; if (current === "in") inScope.push(entry); else outScope.push(entry); } } } return { program: { handle, name: handle, url: `https://hackerone.com/${handle}` }, scope: { inScope, exclusions: outScope, restrictions: [] } };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import { chromium } from 'playwright';
/** * Perform browser automation actions on a given URL. * @param {string} url - The URL to navigate to. * @param {Array} actions - List of action objects: {type, selector, value, code}. * Supported types: click, type, screenshot, evaluate. * @returns {Object} Result object with overall success, navigation error, and per-action results. */export default async function runTool(url, actions) { // --- Input Validation --- if (typeof url !== 'string' || url.trim() === '') { throw new Error('A valid URL string is required'); } if (!Array.isArray(actions)) { throw new Error('Actions must be an array'); }
// --- Launch Browser --- const browser = await chromium.launch({ headless: true }); const context = await browser.newContext(); const page = await context.newPage();
// Set default timeout for all page operations (navigation, clicks, etc.) const DEFAULT_TIMEOUT = 30000; page.setDefaultTimeout(DEFAULT_TIMEOUT);
const results = []; let navigationError = null;
try { // --- Navigation --- await page.goto(url, { waitUntil: 'networkidle', timeout: DEFAULT_TIMEOUT }); } catch (err) { navigationError = err.message; }
// --- Process each action (even if navigation failed) --- for (const action of actions) { const { type, selector, value, code } = action; const actionResult = { type, selector: selector || null, value: value || null, code: code || null, success: false, data: null, error: null, };
// Skip action execution if navigation failed if (navigationError) { actionResult.error = 'Navigation failed, action skipped'; results.push(actionResult); continue; }
try { switch (type) { case 'click': { if (!selector) throw new Error('Selector is required for click'); await page.click(selector); actionResult.success = true; actionResult.data = `Clicked on "${selector}"`; break; }
case 'type': { if (!selector) throw new Error('Selector is required for type'); if (value === undefined || value === null) throw new Error('Value is required for type'); await page.fill(selector, String(value)); actionResult.success = true; actionResult.data = `Typed "${value}" into "${selector}"`; break; }
case 'screenshot': { const buffer = await page.screenshot({ fullPage: true }); actionResult.data = buffer.toString('base64'); actionResult.success = true; break; }
case 'evaluate': { if (typeof code !== 'string' || code.trim() === '') { throw new Error('Valid JavaScript code string is required for evaluate'); } const evalResult = await page.evaluate(code); // Ensure serializable result (basic handling for common cases) actionResult.data = evalResult !== undefined && evalResult !== null ? typeof evalResult === 'object' ? JSON.parse(JSON.stringify(evalResult)) : evalResult : null; actionResult.success = true; break; }
default: { throw new Error(`Unsupported action type: "${type}"`); } } } catch (err) { actionResult.success = false; actionResult.error = err.message; }
results.push(actionResult); }
// --- Cleanup --- await browser.close();
// --- Build final response --- const overallSuccess = !navigationError && results.every((r) => r.success); return { success: overallSuccess, navigationError: navigationError, results: results, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350import fs from "fs";import { resolve } from "path";import { homedir } from "os";
const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions");
function parseSubfinderOutput(output, target, phase) { const results = []; if (!output || typeof output !== "string") return results; for (const line of output.split("\n")) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("[") || trimmed.startsWith("Error")) continue; const subdomain = trimmed.toLowerCase().replace(/^https?:\/\//, "").split("/")[0]; if (subdomain && subdomain.includes(".")) { results.push({ type: "subdomain", value: subdomain, target, phase, source: "subfinder", timestamp: new Date().toISOString(), status: "success" }); } } return results;}
function parseDnsxOutput(output, target, phase) { const results = []; if (!output || typeof output !== "string") return results; for (const line of output.split("\n")) { const trimmed = line.trim(); if (!trimmed) continue; try { const parsed = JSON.parse(trimmed); if (parsed.host) { results.push({ type: "dns_record", name: parsed.host, recordType: parsed.a ? "A" : parsed.aaaa ? "AAAA" : parsed.cname ? "CNAME" : parsed.txt ? "TXT" : parsed.mx ? "MX" : parsed.ns ? "NS" : "UNKNOWN", value: parsed.a || parsed.aaaa || parsed.cname || parsed.txt || parsed.mx || parsed.ns || "", target, phase, source: "dnsx", timestamp: new Date().toISOString(), status: "success" }); } } catch { const parts = trimmed.split(/\s+/); if (parts.length >= 3) { results.push({ type: "dns_record", name: parts[0], recordType: parts[1].toUpperCase(), value: parts.slice(2).join(" "), target, phase, source: "dnsx", timestamp: new Date().toISOString(), status: "success" }); } } } return results;}
function parseHttpxOutput(output, target, phase) { const results = []; if (!output || typeof output !== "string") return results; for (const line of output.split("\n")) { const trimmed = line.trim(); if (!trimmed) continue; try { const parsed = JSON.parse(trimmed); if (parsed.url) { results.push({ type: "http_service", url: parsed.url, statusCode: parsed.status_code, contentLength: parsed.content_length, technology: parsed.tech ? parsed.tech.map(t => t.toLowerCase()) : [], title: parsed.title || "", webServer: parsed.webserver || "", target, phase, source: "httpx", timestamp: new Date().toISOString(), status: "success" }); } } catch { const urlMatch = trimmed.match(/https?:\/\/[^\s]+/); if (urlMatch) { results.push({ type: "http_service", url: urlMatch[0], target, phase, source: "httpx", timestamp: new Date().toISOString(), status: "success" }); } } } return results;}
function parseNucleiOutput(output, target, phase) { const results = []; if (!output || typeof output !== "string") return results; for (const line of output.split("\n")) { const trimmed = line.trim(); if (!trimmed) continue; try { const parsed = JSON.parse(trimmed); if (parsed.template_id) { results.push({ type: "security_metadata", templateId: parsed.template_id, severity: parsed.info?.severity || "info", name: parsed.info?.name || "", description: parsed.info?.description || "", matchedAt: parsed.matched_at, target, phase, source: "nuclei", timestamp: new Date().toISOString(), status: "success" }); } } catch { const sevMatch = trimmed.match(/\[(critical|high|medium|low|info)\]/i); if (sevMatch) { results.push({ type: "security_metadata", raw: trimmed, severity: sevMatch[1].toLowerCase(), target, phase, source: "nuclei", timestamp: new Date().toISOString(), status: "success" }); } } } return results;}
function parseTLSOutput(output, target, phase) { const results = []; if (!output || typeof output !== "string") return results; try { const parsed = JSON.parse(output); if (parsed.subject || parsed.issuer || parsed.notAfter || parsed.notBefore || parsed.sans) { results.push({ type: "tls_certificate", subject: parsed.subject || "", issuer: parsed.issuer || "", notBefore: parsed.notBefore || "", notAfter: parsed.notAfter || "", sans: parsed.sans || [], fingerprint: parsed.fingerprint || "", target, phase, source: "tlsx", timestamp: new Date().toISOString(), status: "success" }); } } catch { // Text format - minimal parsing const certMatch = output.match(/subject=(.+)/i) || output.match(/issuer=(.+)/i); if (certMatch) { results.push({ type: "tls_certificate", raw: output, target, phase, source: "tlsx", timestamp: new Date().toISOString(), status: "success" }); } } return results;}
function parseTechnologyOutput(output, target, phase, source) { const results = []; if (!output || typeof output !== "string") return results; const techPatterns = [ /nginx\/[\d.]+/gi, /apache\/[\d.]+/gi, /iis\/[\d.]+/gi, /openresty\/[\d.]+/gi, /cloudflare/gi, /aws/gi, /google/gi, /microsoft/gi, /cloudfront/gi, /akamai/gi, /wordpress/gi, /drupal/gi, /joomla/gi, /magento/gi, /php\/[\d.]+/gi, /python\/[\d.]+/gi, /node\.js/gi, /express/gi, /django/gi, /rails/gi, /laravel/gi, /react/gi, /vue/gi, /angular/gi, /next\.js/gi, /nuxt/gi, /kubernetes/gi, /docker/gi, /traefik/gi, /envoy/gi, /haproxy/gi, /postgresql/gi, /mysql/gi, /mongodb/gi, /redis/gi, /grafana/gi, /prometheus/gi, /kibana/gi, /jenkins/gi, /gitlab/gi, /github/gi, /bitbucket/gi, /ssh/gi, /ftp/gi, /smtp/gi, /imap/gi ]; for (const pattern of techPatterns) { const matches = output.match(pattern); if (matches) { for (const match of matches) { results.push({ type: "technology", name: match.toLowerCase(), source, target, phase, timestamp: new Date().toISOString(), status: "success" }); } } } return results;}
export function normalizeObservations(missionId) { const missionDir = resolve(MISSIONS_DIR, missionId); if (!fs.existsSync(missionDir)) { return { observations: [], errors: ["Mission directory not found"] }; } const observations = []; const errors = []; const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation"]; for (const phaseDir of phaseDirs) { const dir = resolve(missionDir, phaseDir); if (!fs.existsSync(dir)) continue; const files = fs.readdirSync(dir).filter(f => f.endsWith(".json")); for (const file of files) { try { const content = JSON.parse(fs.readFileSync(resolve(dir, file), "utf-8")); const result = content.result; const tool = content.tool; const target = content.target; const phase = content.phase; const savedAt = content.savedAt; if (!result) continue; let parsed = []; switch (tool) { case "subfinder": parsed = parseSubfinderOutput(result, target, phase); break; case "dnsx": parsed = parseDnsxOutput(result, target, phase); break; case "httpx": parsed = parseHttpxOutput(result, target, phase); break; case "nuclei": parsed = parseNucleiOutput(result, target, phase); break; case "tlsx": parsed = parseTLSOutput(result, target, phase); break; case "whatweb": case "wappalyzer": case "techdetect": parsed = parseTechnologyOutput(result, target, phase, tool); break; } // Extract technologies from any tool output if (typeof result === "string") { parsed.push(...parseTechnologyOutput(result, target, phase, tool)); } // Add savedAt timestamp if available for (const obs of parsed) { if (savedAt) obs.savedAt = savedAt; } observations.push(...parsed); } catch (e) { errors.push({ file, error: e.message }); } } } // Also parse error files to capture failed tool status const errorsDir = resolve(missionDir, "errors"); if (fs.existsSync(errorsDir)) { const errorFiles = fs.readdirSync(errorsDir); for (const file of errorFiles) { try { const content = JSON.parse(fs.readFileSync(resolve(errorsDir, file), "utf-8")); observations.push({ type: "error", tool: content.tool, target: content.target, phase: content.phase, error: content.error, timestamp: content.timestamp, status: "error" }); } catch { // Ignore parse errors in error files } } } return { observations, errors };}
export function loadMissionResults(missionId) { const { observations, errors } = normalizeObservations(missionId); return observations;}
export function loadMissionErrors(missionId) { const { observations } = normalizeObservations(missionId); return observations.filter(o => o.status === "error");}
export function getObservationsByType(missionId, type) { const { observations } = normalizeObservations(missionId); return observations.filter(o => o.type === type && o.status === "success");}
export function getObservationsByPhase(missionId, phase) { const { observations } = normalizeObservations(missionId); return observations.filter(o => o.phase === phase && o.status === "success");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388import { normalizeObservations, getObservationsByType, getObservationsByPhase, loadMissionResults, loadMissionErrors } from "./recon-analysis.mjs";import { loadLearning, getLearningStats, getSuccessfulTechniques, getToolFailureRates, getDiscoveryMethods, getFalsePositivePatterns, getMissionLearning, sanitize } from "./recon-learning.mjs";
export function getMissionObservationSummary(missionId) { const { observations } = normalizeObservations(missionId); const summary = { missionId, timestamp: new Date().toISOString(), counts: { subdomains: 0, dnsRecords: 0, httpServices: 0, tlsCertificates: 0, technologies: 0, securityMetadata: 0, errors: 0 }, byPhase: { 1: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 }, 2: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 }, 3: { subdomains: 0, dnsRecords: 0, httpServices: 0, technologies: 0, securityMetadata: 0, errors: 0 } } }; for (const obs of observations) { if (obs.status === "success") { if (summary.counts[obs.type + "s"] !== undefined) { summary.counts[obs.type + "s"]++; } else if (summary.counts[obs.type] !== undefined) { summary.counts[obs.type]++; } if (obs.phase && summary.byPhase[obs.phase]) { if (summary.byPhase[obs.phase][obs.type + "s"] !== undefined) { summary.byPhase[obs.phase][obs.type + "s"]++; } else if (summary.byPhase[obs.phase][obs.type] !== undefined) { summary.byPhase[obs.phase][obs.type]++; } } } else if (obs.status === "error") { summary.counts.errors++; if (obs.phase && summary.byPhase[obs.phase]) { summary.byPhase[obs.phase].errors++; } } } return summary;}
export function getTechnologySummary(missionId) { const technologies = getObservationsByType(missionId, "technology"); const techCounts = new Map(); for (const tech of technologies) { const name = tech.name || tech.value; if (name) { techCounts.set(name, (techCounts.get(name) || 0) + 1); } } return { missionId, timestamp: new Date().toISOString(), uniqueTechnologies: techCounts.size, totalObservations: technologies.length, technologies: Array.from(techCounts.entries()) .sort((a, b) => b[1] - a[1]) .map(([name, count]) => ({ name, count })) };}
export function getHttpSummary(missionId) { const httpServices = getObservationsByType(missionId, "http_service"); const statusCodes = new Map(); const webServers = new Map(); const titles = new Map(); const withTech = 0; let withTechCount = 0; for (const svc of httpServices) { if (svc.statusCode) { statusCodes.set(svc.statusCode, (statusCodes.get(svc.statusCode) || 0) + 1); } if (svc.webServer) { webServers.set(svc.webServer, (webServers.get(svc.webServer) || 0) + 1); } if (svc.title) { titles.set(svc.title, (titles.get(svc.title) || 0) + 1); } if (svc.technology && svc.technology.length > 0) { withTechCount++; } } return { missionId, timestamp: new Date().toISOString(), totalServices: httpServices.length, statusCodes: Object.fromEntries(statusCodes), webServers: Object.fromEntries(webServers), uniqueTitles: titles.size, servicesWithTech: withTechCount };}
export function getDnsSummary(missionId) { const dnsRecords = getObservationsByType(missionId, "dns_record"); const recordTypes = new Map(); const uniqueNames = new Set(); for (const dns of dnsRecords) { recordTypes.set(dns.recordType, (recordTypes.get(dns.recordType) || 0) + 1); uniqueNames.add(dns.name); } return { missionId, timestamp: new Date().toISOString(), totalRecords: dnsRecords.length, uniqueNames: uniqueNames.size, recordTypes: Object.fromEntries(recordTypes) };}
export function getSecurityMetadataSummary(missionId) { const securityMeta = getObservationsByType(missionId, "security_metadata"); const severities = new Map(); const templates = new Map(); for (const meta of securityMeta) { if (meta.severity) { severities.set(meta.severity, (severities.get(meta.severity) || 0) + 1); } if (meta.templateId) { templates.set(meta.templateId, (templates.get(meta.templateId) || 0) + 1); } } return { missionId, timestamp: new Date().toISOString(), totalFindings: securityMeta.length, note: "Security metadata are informational observations from passive scanning templates. They are NOT vulnerability confirmations.", severities: Object.fromEntries(severities), templates: Object.fromEntries(templates) };}
export function getLearnedSummary(missionId) { const learning = getMissionLearning(missionId); if (learning.length === 0) { return { missionId, timestamp: new Date().toISOString(), hasLearning: false, message: "No learning recorded for this mission" }; } const latest = learning[learning.length - 1]; return { missionId, timestamp: new Date().toISOString(), hasLearning: true, successfulTechniques: latest.successfulTechniques || [], toolFailures: latest.toolFailures || [], duration: latest.duration, discoveryMethods: latest.discoveryMethods || [], falsePositivePatterns: latest.falsePositivePatterns || [], targetCount: latest.targetCount || 0, phaseResults: latest.phaseResults || {} };}
export function getGlobalLearningStats() { return getLearningStats();}
export function getRecommendedNextActions(missionId) { const { observations } = normalizeObservations(missionId); const learning = getMissionLearning(missionId); const actions = []; const subdomains = observations.filter(o => o.type === "subdomain" && o.status === "success"); const httpServices = observations.filter(o => o.type === "http_service" && o.status === "success"); const dnsRecords = observations.filter(o => o.type === "dns_record" && o.status === "success"); const errors = observations.filter(o => o.status === "error"); // Only passive, advisory recommendations if (subdomains.length > 0 && httpServices.length === 0) { actions.push({ priority: "high", action: "Probe discovered subdomains with HTTP/HTTPS", rationale: `${subdomains.length} subdomains found but no HTTP probing yet. Consider running httpx against subdomain list.`, tools: ["httpx"], passive: true }); } if (dnsRecords.length > 0 && subdomains.length === 0) { actions.push({ priority: "medium", action: "Enumerate subdomains for resolved domains", rationale: `${dnsRecords.length} DNS records found but no subdomain enumeration yet. Consider running subfinder.`, tools: ["subfinder"], passive: true }); } if (httpServices.length > 0) { const techObs = observations.filter(o => o.type === "technology" && o.status === "success"); if (techObs.length === 0) { actions.push({ priority: "medium", action: "Deep technology fingerprinting on live services", rationale: `${httpServices.length} HTTP services probed but no technology details captured. Consider running whatweb/wappalyzer.`, tools: ["whatweb", "wappalyzer"], passive: true }); } } if (errors.length > 0) { const failedTools = [...new Set(errors.map(e => e.tool))]; actions.push({ priority: "low", action: "Investigate and fix tool failures", rationale: `${errors.length} errors from tools: ${failedTools.join(", ")}. Check installation and permissions.`, tools: failedTools, passive: true }); } // Learning-based recommendations if (learning.length > 0) { const latest = learning[learning.length - 1]; if (latest.falsePositivePatterns && latest.falsePositivePatterns.length > 0) { actions.push({ priority: "low", action: "Review false-positive patterns in nuclei results", rationale: latest.falsePositivePatterns.join("; "), tools: ["nuclei"], passive: true }); } const successfulTechs = latest.successfulTechniques || []; if (successfulTechs.includes("subfinder") && !successfulTechs.includes("dnsx")) { actions.push({ priority: "medium", action: "Run DNS resolution on discovered subdomains", rationale: "Subfinder succeeded but DNS resolution (dnsx) not recorded. Validate subdomains exist.", tools: ["dnsx"], passive: true }); } } // TLS certificate analysis const tlsCerts = observations.filter(o => o.type === "tls_certificate" && o.status === "success"); if (tlsCerts.length === 0 && httpServices.length > 0) { actions.push({ priority: "low", action: "Collect TLS certificate details from HTTPS services", rationale: `${httpServices.length} HTTPS services probed but no TLS certificate data. Consider running tlsx.`, tools: ["tlsx"], passive: true }); } return { missionId, timestamp: new Date().toISOString(), actions: actions.sort((a, b) => { const priority = { high: 3, medium: 2, low: 1 }; return priority[b.priority] - priority[a.priority]; }) };}
export function getMissionIntelligence(missionId) { return { missionId, timestamp: new Date().toISOString(), observationSummary: getMissionObservationSummary(missionId), technologySummary: getTechnologySummary(missionId), httpSummary: getHttpSummary(missionId), dnsSummary: getDnsSummary(missionId), securityMetadataSummary: getSecurityMetadataSummary(missionId), learnedSummary: getLearnedSummary(missionId), recommendedActions: getRecommendedNextActions(missionId), globalLearning: getGlobalLearningStats() };}
export function formatIntelligenceReport(missionId) { const intel = getMissionIntelligence(missionId); let report = `\n🧠 MISSION INTELLIGENCE — ${intel.missionId}\n`; report += `════════════════════════════════════════\n`; report += `Generated: ${intel.timestamp}\n\n`; // Observation Summary const obs = intel.observationSummary; report += `📊 OBSERVATION SUMMARY\n`; report += ` Subdomains: ${obs.counts.subdomains}\n`; report += ` DNS Records: ${obs.counts.dnsRecords}\n`; report += ` HTTP Services: ${obs.counts.httpServices}\n`; report += ` TLS Certificates: ${obs.counts.tlsCertificates}\n`; report += ` Technologies: ${obs.counts.technologies}\n`; report += ` Security Metadata: ${obs.counts.securityMetadata}\n`; report += ` Errors: ${obs.counts.errors}\n\n`; // Technology Summary const tech = intel.technologySummary; if (tech.uniqueTechnologies > 0) { report += `🔧 TECHNOLOGIES (${tech.uniqueTechnologies} unique)\n`; for (const t of tech.technologies.slice(0, 10)) { report += ` ${t.name}: ${t.count}\n`; } report += `\n`; } // HTTP Summary const http = intel.httpSummary; if (http.totalServices > 0) { report += `🌐 HTTP SERVICES (${http.totalServices})\n`; report += ` Status Codes: ${Object.entries(http.statusCodes).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\n`; report += ` Web Servers: ${Object.entries(http.webServers).map(([k,v]) => `${k}:${v}`).join(", ") || "none"}\n`; report += ` With Tech: ${http.servicesWithTech}/${http.totalServices}\n\n`; } // DNS Summary const dns = intel.dnsSummary; if (dns.totalRecords > 0) { report += `🔍 DNS RECORDS (${dns.totalRecords} across ${dns.uniqueNames} names)\n`; report += ` Types: ${Object.entries(dns.recordTypes).map(([k,v]) => `${k}:${v}`).join(", ")}\n\n`; } // Security Metadata const sec = intel.securityMetadataSummary; if (sec.totalFindings > 0) { report += `🛡️ SECURITY METADATA (${sec.totalFindings}) [INFORMATIONAL ONLY]\n`; report += ` ${sec.note}\n`; report += ` Severities: ${Object.entries(sec.severities).map(([k,v]) => `${k}:${v}`).join(", ")}\n\n`; } // Learned Summary const learned = intel.learnedSummary; if (learned.hasLearning) { report += `📚 LEARNED FROM THIS MISSION\n`; report += ` Successful: ${learned.successfulTechniques.join(", ") || "none"}\n`; report += ` Failed: ${learned.toolFailures.map(f => `${f.tool}(${f.target})`).join(", ") || "none"}\n`; report += ` Methods: ${learned.discoveryMethods.join(", ") || "none"}\n`; if (learned.falsePositivePatterns.length > 0) { report += ` ⚠️ ${learned.falsePositivePatterns.join("; ")}\n`; } report += `\n`; } // Recommended Actions const actions = intel.recommendedActions.actions; if (actions.length > 0) { report += `🎯 RECOMMENDED NEXT PASSIVE ACTIONS\n`; for (const a of actions) { report += ` [${a.priority.toUpperCase()}] ${a.action}\n`; report += ` Rationale: ${a.rationale}\n`; report += ` Tools: ${a.tools.join(", ")} (passive)\n\n`; } } else { report += `✅ No immediate passive actions recommended\n\n`; } report += `════════════════════════════════════════\n`; report += `Read-only intelligence. No targets authorized. No exploitation.\n`; return report;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294import fs from "fs";import { resolve } from "path";import { homedir } from "os";
const LEARNING_DIR = resolve(homedir(), ".config", "phantom", "learning");const LEARNING_FILE = resolve(LEARNING_DIR, "recon.jsonl");
if (!fs.existsSync(LEARNING_DIR)) fs.mkdirSync(LEARNING_DIR, { recursive: true });
const SECRET_PATTERNS = [ /api[_-]?key/i, /token/i, /password/i, /secret/i, /credential/i, /authorization/i, /bearer/i, /cookie/i, /session/i, /jwt/i, /private[_-]?key/i, /access[_-]?key/i, /aws[_-]?secret/i, /x-api-key/i, /client[_-]?secret/i, /ssh[_-]?key/i];
function containsSecret(text) { if (!text) return false; const str = String(text).toLowerCase(); return SECRET_PATTERNS.some(p => p.test(str));}
function sanitize(text) { if (!text) return text; let result = String(text); // Patterns for secret values (key=value, key: value, etc.) const valuePatterns = [ /(api[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, /(token\s*[=:]?\s*)[^\s,}]+/gi, /(password\s*[=:]?\s*)[^\s,}]+/gi, /(secret\s*[=:]?\s*)[^\s,}]+/gi, /(credential\s*[=:]?\s*)[^\s,}]+/gi, /(authorization\s*[=:]?\s*)[^\s,}]+/gi, /(bearer\s+)[^\s,}]+/gi, /(cookie\s*[=:]?\s*)[^\s,}]+/gi, /(session\s*[=:]?\s*)[^\s,}]+/gi, /(jwt\s*[=:]?\s*)[^\s,}]+/gi, /(private[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, /(access[_-]?key\s*[=:]?\s*)[^\s,}]+/gi, /(aws[_-]?secret\s*[=:]?\s*)[^\s,}]+/gi, /(x-api-key\s*[=:]?\s*)[^\s,}]+/gi, /(client[_-]?secret\s*[=:]?\s*)[^\s,}]+/gi, /(ssh[_-]?key\s*[=:]?\s*)[^\s,}]+/gi ]; for (const pattern of valuePatterns) { result = result.replace(pattern, "$1[REDACTED]"); } // Additional pass for "Bearer token123" format (token after space) result = result.replace(/(bearer\s+)[^\s]+\s+[^\s,}]+/gi, "$1[REDACTED] [REDACTED]"); result = result.replace(/(authorization:\s*bearer\s+)[^\s]+\s+[^\s,}]+/gi, "$1[REDACTED] [REDACTED]"); return result;}
function sanitizeObject(obj) { if (!obj || typeof obj !== "object") return sanitize(obj); const result = Array.isArray(obj) ? [] : {}; for (const [key, value] of Object.entries(obj)) { if (containsSecret(key)) { result[key] = "[REDACTED]"; } else if (typeof value === "string") { result[key] = sanitize(value); } else if (typeof value === "object" && value !== null) { result[key] = sanitizeObject(value); } else { result[key] = value; } } return result;}
export function recordLearning(entry) { const timestamp = new Date().toISOString(); const learningEntry = { timestamp, ...sanitizeObject(entry) }; try { fs.appendFileSync(LEARNING_FILE, JSON.stringify(learningEntry) + "\n", "utf-8"); return { success: true }; } catch (e) { return { success: false, error: e.message }; }}
export function recordReconLearning(missionId, data) { const entry = { type: "recon_learning", missionId, successfulTechniques: data.successfulTechniques || [], toolFailures: data.toolFailures || [], duration: data.duration || null, discoveryMethods: data.discoveryMethods || [], falsePositivePatterns: data.falsePositivePatterns || [], targetCount: data.targetCount || 0, phaseResults: data.phaseResults || {} }; return recordLearning(entry);}
export function recordToolFailure(tool, target, phase, error) { return recordLearning({ type: "tool_failure", tool, target: sanitize(target), phase, error: sanitize(String(error)), timestamp: new Date().toISOString() });}
export function recordTechniqueSuccess(technique, missionId, targetCount) { return recordLearning({ type: "technique_success", technique, missionId, targetCount, timestamp: new Date().toISOString() });}
export function loadLearning(options = {}) { const { type, missionId, since, limit } = options; if (!fs.existsSync(LEARNING_FILE)) return []; const content = fs.readFileSync(LEARNING_FILE, "utf-8"); const lines = content.trim().split("\n").filter(Boolean); const results = []; for (const line of lines) { try { const entry = JSON.parse(line); if (type && entry.type !== type) continue; if (missionId && entry.missionId !== missionId) continue; if (since && entry.timestamp < since) continue; results.push(entry); } catch { // Skip malformed entries - recoverable continue; } } if (limit && results.length > limit) { return results.slice(-limit); } return results;}
export function getLearningStats() { const entries = loadLearning(); const stats = { totalEntries: entries.length, byType: {}, successfulTechniques: new Map(), toolFailures: new Map(), totalDuration: 0, missionsAnalyzed: new Set() }; for (const entry of entries) { stats.byType[entry.type] = (stats.byType[entry.type] || 0) + 1; if (entry.missionId) stats.missionsAnalyzed.add(entry.missionId); if (entry.successfulTechniques) { for (const tech of entry.successfulTechniques) { stats.successfulTechniques.set(tech, (stats.successfulTechniques.get(tech) || 0) + 1); } } if (entry.toolFailures) { for (const tf of entry.toolFailures) { const key = `${tf.tool}:${tf.target || "unknown"}`; stats.toolFailures.set(key, (stats.toolFailures.get(key) || 0) + 1); } } if (entry.duration) { stats.totalDuration += entry.duration; } } return { totalEntries: stats.totalEntries, byType: stats.byType, successfulTechniques: Object.fromEntries(stats.successfulTechniques), toolFailures: Object.fromEntries(stats.toolFailures), averageDuration: stats.missionsAnalyzed.size > 0 ? stats.totalDuration / stats.missionsAnalyzed.size : 0, missionsAnalyzed: stats.missionsAnalyzed.size };}
export function getSuccessfulTechniques() { const entries = loadLearning({ type: "recon_learning" }); const techCounts = new Map(); for (const entry of entries) { if (entry.successfulTechniques) { for (const tech of entry.successfulTechniques) { techCounts.set(tech, (techCounts.get(tech) || 0) + 1); } } } return Array.from(techCounts.entries()) .sort((a, b) => b[1] - a[1]) .map(([technique, count]) => ({ technique, count }));}
export function getToolFailureRates() { const entries = loadLearning({ type: "recon_learning" }); const failureCounts = new Map(); const totalCounts = new Map(); for (const entry of entries) { if (entry.toolFailures) { for (const tf of entry.toolFailures) { const key = tf.tool; failureCounts.set(key, (failureCounts.get(key) || 0) + 1); } } // Also count successes to calculate rate if (entry.successfulTechniques) { for (const tech of entry.successfulTechniques) { totalCounts.set(tech, (totalCounts.get(tech) || 0) + 1); } } } return Array.from(failureCounts.entries()) .map(([tool, failures]) => ({ tool, failures, totalRuns: (totalCounts.get(tool) || 0) + failures, failureRate: (totalCounts.get(tool) || 0) + failures > 0 ? failures / ((totalCounts.get(tool) || 0) + failures) : 0 })) .sort((a, b) => b.failureRate - a.failureRate);}
export function getDiscoveryMethods() { const entries = loadLearning({ type: "recon_learning" }); const methodCounts = new Map(); for (const entry of entries) { if (entry.discoveryMethods) { for (const method of entry.discoveryMethods) { methodCounts.set(method, (methodCounts.get(method) || 0) + 1); } } } return Array.from(methodCounts.entries()) .sort((a, b) => b[1] - a[1]) .map(([method, count]) => ({ method, count }));}
export function getFalsePositivePatterns() { const entries = loadLearning({ type: "recon_learning" }); const patterns = []; for (const entry of entries) { if (entry.falsePositivePatterns) { patterns.push(...entry.falsePositivePatterns); } } return [...new Set(patterns)];}
export function getMissionLearning(missionId) { return loadLearning({ missionId, type: "recon_learning" });}
export function clearLearning() { if (fs.existsSync(LEARNING_FILE)) { fs.unlinkSync(LEARNING_FILE); }}
export function getLearningFilePath() { return LEARNING_FILE;}
export { sanitize, containsSecret, SECRET_PATTERNS };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397import { normalizeObservations, getObservationsByType, getObservationsByPhase } from "./recon-analysis.mjs";import { getMissionLearning, getSuccessfulTechniques, getToolFailureRates } from "./recon-learning.mjs";import { isInScope, normalizeTarget, loadMission as loadMissionFromMission } from "./mission.mjs";import { getRecommendedNextActions } from "./recon-intelligence.mjs";
const PASSIVE_TOOLS = [ "subfinder", "dnsx", "httpx", "nuclei", "whatweb", "wappalyzer", "tlsx", "katana", "gau", "waybackurls", "crt", "amass", "findomain", "assetfinder", "chaos", "dnsrecon", "massdns", "shuffledns"];
function getCompletedActions(missionId) { const { observations } = normalizeObservations(missionId); const completed = new Set(); for (const obs of observations) { // Observations may have 'tool' or 'source' field depending on parser const tool = obs.tool || obs.source; if (obs.status === "success" && tool) { const key = `${tool}:${obs.target}:${obs.phase}`; completed.add(key); } } return completed;}
function getInScopeTargets(missionId) { const mission = loadMissionFromMission(missionId); if (!mission || !mission.scope || !mission.scope.inScope) { return []; } return mission.scope.inScope.map(s => ({ identifier: s.identifier, normalized: s.normalized, isWildcard: s.isWildcard, assetType: s.assetType }));}
function filterTargetsByScope(targets, mission) { const allowed = []; const denied = []; for (const target of targets) { // Check if target is in scope const inScopeCheck = isInScope(target, mission); if (!inScopeCheck.allowed) { denied.push({ target, scopeReason: inScopeCheck.reason }); continue; } // Check if target is in exclusions const normalized = normalizeTarget(target); let isExcluded = false; if (mission.scope && mission.scope.exclusions) { for (const exclusion of mission.scope.exclusions) { const exclusionCheck = isInScope(target, { scope: { inScope: [exclusion] } }); if (exclusionCheck.allowed) { isExcluded = true; break; } } } if (isExcluded) { denied.push({ target, scopeReason: "Excluded by scope policy" }); } else { allowed.push({ target, scopeReason: inScopeCheck.reason }); } } return { allowed, denied };}
function getNextActionsForTarget(target, missionId, observations, learning) { if (!target) { return []; } const actions = []; const normalized = normalizeTarget(target); const completed = getCompletedActions(missionId); // Check if subfinder already done for this target const subfinderDone = completed.has(`subfinder:${normalized}:1`); const dnsxDone = completed.has(`dnsx:${normalized}:1`); const httpxDone = completed.has(`httpx:${normalized}:2`); const nucleiDone = completed.has(`nuclei:${normalized}:3`); const tlsxDone = completed.has(`tlsx:${normalized}:2`); const whatwebDone = completed.has(`whatweb:${normalized}:2`); const subdomains = getObservationsByType(missionId, "subdomain"); const targetSubdomains = subdomains.filter(s => s.target === normalized); const httpServices = getObservationsByType(missionId, "http_service"); const targetHttp = httpServices.filter(h => h.target === normalized); // Priority 1: Subdomain enumeration (if not done) if (!subfinderDone) { actions.push({ id: `subfinder:${normalized}:1`, target: normalized, technique: "passive_subdomain_enum", tool: "subfinder", phase: 1, reason: "No subdomain enumeration recorded for this target", priority: "high", evidence: { subdomainsFound: targetSubdomains.length, dnsRecords: getObservationsByType(missionId, "dns_record").filter(d => d.target === normalized).length }, safety: { scopeChecked: true, passive: true } }); } // Priority 2: DNS resolution on discovered subdomains if (subfinderDone && !dnsxDone && targetSubdomains.length > 0) { actions.push({ id: `dnsx:${normalized}:1`, target: normalized, technique: "dns_resolution", tool: "dnsx", phase: 1, reason: `${targetSubdomains.length} subdomains found but DNS resolution not recorded`, priority: "high", evidence: { subdomains: targetSubdomains.map(s => s.value) }, safety: { scopeChecked: true, passive: true } }); } // Priority 3: HTTP probing on resolved domains if (dnsxDone && !httpxDone) { const dnsRecords = getObservationsByType(missionId, "dns_record"); const targetDns = dnsRecords.filter(d => d.target === normalized); if (targetDns.length > 0) { actions.push({ id: `httpx:${normalized}:2`, target: normalized, technique: "http_probing", tool: "httpx", phase: 2, reason: `${targetDns.length} DNS records resolved but HTTP probing not recorded`, priority: "high", evidence: { dnsRecords: targetDns.map(d => `${d.name} ${d.recordType}`) }, safety: { scopeChecked: true, passive: true } }); } } // Priority 4: Technology fingerprinting on live HTTP services if (httpxDone && !whatwebDone && targetHttp.length > 0) { const techObs = getObservationsByType(missionId, "technology"); const targetTech = techObs.filter(t => t.target === normalized); if (targetTech.length === 0) { actions.push({ id: `whatweb:${normalized}:2`, target: normalized, technique: "technology_fingerprinting", tool: "whatweb", phase: 2, reason: `${targetHttp.length} HTTP services probed but no technology fingerprinting recorded`, priority: "medium", evidence: { httpServices: targetHttp.map(h => h.url) }, safety: { scopeChecked: true, passive: true } }); } } // Priority 5: TLS certificate collection on HTTPS services const tlsCerts = getObservationsByType(missionId, "tls_certificate"); const targetTls = tlsCerts.filter(t => t.target === normalized); if (httpxDone && !tlsxDone && targetHttp.length > 0 && targetTls.length === 0) { const httpsServices = targetHttp.filter(h => h.url.startsWith("https://")); if (httpsServices.length > 0) { actions.push({ id: `tlsx:${normalized}:2`, target: normalized, technique: "tls_certificate_collection", tool: "tlsx", phase: 2, reason: `${httpsServices.length} HTTPS services probed but no TLS certificate data recorded`, priority: "medium", evidence: { httpsServices: httpsServices.map(h => h.url) }, safety: { scopeChecked: true, passive: true } }); } } // Priority 6: Nuclei scanning (passive templates only) on HTTP services if (httpxDone && !nucleiDone && targetHttp.length > 0) { actions.push({ id: `nuclei:${normalized}:3`, target: normalized, technique: "passive_security_metadata_collection", tool: "nuclei", phase: 3, reason: `${targetHttp.length} HTTP services available for passive template matching (informational only)`, priority: "low", evidence: { httpServices: targetHttp.map(h => h.url) }, safety: { scopeChecked: true, passive: true, informationalOnly: true } }); } // Priority 7: Deep crawling on web applications if (httpxDone && targetHttp.length > 0) { const webServices = targetHttp.filter(h => h.url.includes(":80") || h.url.includes(":443") || h.url.includes(":8080") || h.url.includes(":8443") ); if (webServices.length > 0) { const katanaDone = completed.has(`katana:${normalized}:3`); if (!katanaDone) { actions.push({ id: `katana:${normalized}:3`, target: normalized, technique: "passive_endpoint_discovery", tool: "katana", phase: 3, reason: `${webServices.length} web services available for passive endpoint discovery`, priority: "low", evidence: { webServices: webServices.map(h => h.url) }, safety: { scopeChecked: true, passive: true } }); } } } return actions;}
export function getMissionPlan(missionId) { const mission = loadMissionFromMission(missionId); if (!mission) { return { missionId, timestamp: new Date().toISOString(), actions: [], error: "Mission not found", safety: { scopeValid: false } }; } const inScopeTargets = getInScopeTargets(missionId); if (inScopeTargets.length === 0) { return { missionId, timestamp: new Date().toISOString(), actions: [], error: "No in-scope targets found. Mission scope is empty.", safety: { scopeValid: false, reason: "Empty scope" } }; } // Filter to only domain-like targets (containing dot or wildcard) // Exclude URLs (starting with http:// or https://) const domainTargets = inScopeTargets.filter(t => { const id = t.identifier; if (id.startsWith('http://') || id.startsWith('https://')) return false; return id.includes('.') || id.startsWith('*.'); }); if (domainTargets.length === 0) { return { missionId, timestamp: new Date().toISOString(), actions: [], error: "No domain-like targets in scope. Only non-domain entries (e.g., 'Pages', 'CDNJS') found.", safety: { scopeValid: false, reason: "No actionable domains in scope" } }; } const { observations } = normalizeObservations(missionId); const learning = getMissionLearning(missionId); // Filter targets by scope guard - use original identifiers for scope checking const { allowed, denied } = filterTargetsByScope( domainTargets.map(t => t.identifier), mission ); if (allowed.length === 0) { return { missionId, timestamp: new Date().toISOString(), actions: [], error: "All targets denied by scope guard", safety: { scopeValid: false, deniedTargets: denied.map(d => ({ target: d.target, reason: d.scopeReason })), reason: "Stage 1 scope guard rejected all targets" } }; } // Get successful techniques and tool failure rates from learning const successfulTechs = getSuccessfulTechniques(); const toolFailures = getToolFailureRates(); // Build ranked action plan const allActions = []; for (const allowedTarget of allowed) { // Find the original domain target object to get full properties const domainTarget = domainTargets.find(t => t.identifier === allowedTarget.target); if (!domainTarget) continue; const targetActions = getNextActionsForTarget(allowedTarget.target, missionId, observations, learning); // Add scope context and learning-based priority adjustment for (const action of targetActions) { action.target = domainTarget.normalized; action.targetOriginal = domainTarget.identifier; action.targetIsWildcard = domainTarget.isWildcard; action.assetType = domainTarget.assetType; action.scopeReason = allowedTarget.scopeReason; // Adjust priority based on learning const toolFailure = toolFailures.find(f => f.tool === action.tool); if (toolFailure && toolFailure.failureRate > 0.5) { action.priority = "low"; action.reason += ` (Note: ${action.tool} has high failure rate: ${Math.round(toolFailure.failureRate * 100)}%)`; } const techSuccess = successfulTechs.find(t => t.technique === action.tool); if (techSuccess && techSuccess.count > 2) { if (action.priority !== "high") action.priority = "high"; action.reason += ` (${action.tool} has ${techSuccess.count} prior successes)`; } // Add learning-based technique suggestions if (learning.length > 0) { const latest = learning[learning.length - 1]; if (latest.discoveryMethods?.includes("passive_subdomain_enum") && action.technique === "passive_subdomain_enum") { action.reason += " (Learning: passive subdomain enumeration previously successful)"; } } } allActions.push(...targetActions); } // Sort by priority (high > medium > low) then by phase (1 > 2 > 3) const priorityOrder = { high: 3, medium: 2, low: 1 }; allActions.sort((a, b) => { const pDiff = priorityOrder[b.priority] - priorityOrder[a.priority]; if (pDiff !== 0) return pDiff; return a.phase - b.phase; }); // Remove duplicates (same tool+target+phase) const seen = new Set(); const uniqueActions = allActions.filter(a => { const key = `${a.tool}:${a.target}:${a.phase}`; if (seen.has(key)) return false; seen.add(key); return true; }); return { missionId, timestamp: new Date().toISOString(), actions: uniqueActions, deniedTargets: denied.map(d => ({ target: d.target, reason: d.scopeReason })), scopeValid: true, safety: { scopeGuard: "Stage 1 scope guard applied", allActionsPassive: true, noExploitation: true, informationalOnly: true } };}
export function getNextAction(missionId) { const plan = getMissionPlan(missionId); if (!plan.scopeValid || plan.actions.length === 0) { return { missionId, action: null, reason: plan.error || "No valid actions available", safety: plan.safety }; } return { missionId, action: plan.actions[0], alternatives: plan.actions.slice(1, 3), reason: `Selected highest-priority passive action`, safety: plan.safety };}
export function getAllPlannedActions(missionId) { return getMissionPlan(missionId);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425import fs from "fs";import { resolve } from "path";import { homedir } from "os";import { execFileSync } from "child_process";import { BASE_DIR, REPORTS_DIR, MISSIONS_DIR } from "./config.mjs";import { isInScope, createMission, saveMission, loadMission, listMissions, updateMissionStatus, addMissionActivity, generateReconPlan, fetchProgramAndScope } from "./mission.mjs";
const EXEC_STATES = { PLANNING: "planning", READY: "ready", RECONNAISSANCE: "reconnaissance", PAUSED: "paused", FAILED: "failed", COMPLETED: "completed", CANCELLED: "cancelled"};
const VALID_TRANSITIONS = { [EXEC_STATES.PLANNING]: [EXEC_STATES.READY], [EXEC_STATES.READY]: [EXEC_STATES.RECONNAISSANCE], [EXEC_STATES.RECONNAISSANCE]: [EXEC_STATES.PAUSED, EXEC_STATES.FAILED, EXEC_STATES.COMPLETED, EXEC_STATES.CANCELLED], [EXEC_STATES.PAUSED]: [EXEC_STATES.RECONNAISSANCE, EXEC_STATES.CANCELLED], [EXEC_STATES.FAILED]: [EXEC_STATES.RECONNAISSANCE, EXEC_STATES.CANCELLED], [EXEC_STATES.COMPLETED]: [], [EXEC_STATES.CANCELLED]: []};
function getMissionDir(missionId) { return resolve(MISSIONS_DIR, missionId);}
function getExecutionStateFile(missionId) { return resolve(getMissionDir(missionId), "state.json");}
function getExecutionState(missionId) { const f = getExecutionStateFile(missionId); if (!fs.existsSync(f)) return null; try { return JSON.parse(fs.readFileSync(f, "utf-8")).state; } catch { return null; }}
function setExecutionState(missionId, state) { const dir = getMissionDir(missionId); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(getExecutionStateFile(missionId), JSON.stringify({ state, updatedAt: new Date().toISOString() }), "utf-8");}
function transitionState(missionId, newState) { const current = getExecutionState(missionId); if (!current) throw new Error(`Mission ${missionId} has no execution state`); const allowed = VALID_TRANSITIONS[current] || []; if (!allowed.includes(newState)) throw new Error(`Invalid transition: ${current} → ${newState}`); setExecutionState(missionId, newState); return { state: newState, previous: current };}
function ensureMissionDirs(missionId) { const dir = getMissionDir(missionId); const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation", "errors"]; if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); for (const d of phaseDirs) { if (!fs.existsSync(resolve(dir, d))) fs.mkdirSync(resolve(dir, d), { recursive: true }); } return dir;}
function getResultKey(phase, tool, target) { return `${phase}_${tool}_${target.replace(/[^a-zA-Z0-9.-]/g, "_")}`;}
function resultExists(missionId, key) { const dir = getMissionDir(missionId); const files = fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json")); return files.some(f => f.includes(key));}
function saveResult(missionId, key, data) { const dir = getMissionDir(missionId); fs.writeFileSync(resolve(dir, `${key}.json`), JSON.stringify({ ...data, savedAt: new Date().toISOString() }, null, 2), "utf-8");}
function loadExistingResult(missionId, key) { const dir = getMissionDir(missionId); const f = resolve(dir, `${key}.json`); if (!fs.existsSync(f)) return null; return JSON.parse(fs.readFileSync(f, "utf-8"));}
function saveError(missionId, phase, tool, target, error) { const dir = resolve(getMissionDir(missionId), "errors"); if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); const key = `${phase}_${tool}_${target.replace(/[^a-zA-Z0-9.-]/g, "_")}_error.json`; fs.writeFileSync(resolve(dir, key), JSON.stringify({ phase, tool, target, error: String(error), timestamp: new Date().toISOString() }, null, 2), "utf-8");}
function appendActivity(missionId, activity) { const dir = getMissionDir(missionId); const f = resolve(dir, "activity.jsonl"); const entry = { timestamp: new Date().toISOString(), ...activity }; fs.appendFileSync(f, JSON.stringify(entry) + "\n", "utf-8");}
async function startRecon(missionId) { const mission = loadMission(missionId); if (!mission) throw new Error(`Mission not found: ${missionId}`); ensureMissionDirs(missionId); // Initialize execution state if not exists const currentState = getExecutionState(missionId); if (!currentState) { setExecutionState(missionId, EXEC_STATES.READY); } // If already completed, allow re-run by resetting to READY first else if (currentState === EXEC_STATES.COMPLETED) { setExecutionState(missionId, EXEC_STATES.READY); } transitionState(missionId, EXEC_STATES.RECONNAISSANCE); updateMissionStatus(missionId, "reconnaissance"); appendActivity(missionId, { action: "recon_start", phase: 1 }); // Phase 1: Passive recon const findings = []; const inScopeTargets = mission.scope.inScope.map(s => s.normalized); for (const target of inScopeTargets) { if (getExecutionState(missionId) !== EXEC_STATES.RECONNAISSANCE) break; try { const { subfinder, dnsx, httpx } = await import("./tools.mjs"); const subResult = await subfinder(target); saveResult(missionId, getResultKey(1, "subfinder", target), { target, tool: "subfinder", result: subResult, phase: 1 }); appendActivity(missionId, { action: "tool_complete", phase: 1, tool: "subfinder", target }); // Extract subdomains and run dnsx const subs = subResult.split("\n").filter(l => l.trim() && !l.startsWith("[")).slice(0, 50); if (subs.length > 0) { const dnsResult = await dnsx(subs.join(" ")); saveResult(missionId, getResultKey(1, "dnsx", target), { target, tool: "dnsx", result: dnsResult, phase: 1 }); appendActivity(missionId, { action: "tool_complete", phase: 1, tool: "dnsx", target }); } findings.push({ target, phase: 1, status: "success", tools: ["subfinder", "dnsx"] }); } catch (e) { saveError(missionId, 1, "subfinder", target, e); findings.push({ target, phase: 1, status: "error", error: String(e) }); } } // Phase 2: Active recon (httpx) if (getExecutionState(missionId) === EXEC_STATES.RECONNAISSANCE) { appendActivity(missionId, { action: "phase_start", phase: 2 }); for (const target of inScopeTargets) { if (getExecutionState(missionId) !== EXEC_STATES.RECONNAISSANCE) break; try { const { httpx } = await import("./tools.mjs"); const httpResult = await httpx(target); saveResult(missionId, getResultKey(2, "httpx", target), { target, tool: "httpx", result: httpResult, phase: 2 }); appendActivity(missionId, { action: "tool_complete", phase: 2, tool: "httpx", target }); findings.push({ target, phase: 2, status: "success", tools: ["httpx"] }); } catch (e) { saveError(missionId, 2, "httpx", target, e); findings.push({ target, phase: 2, status: "error", error: String(e) }); } } } // Phase 3: Validation if (getExecutionState(missionId) === EXEC_STATES.RECONNAISSANCE) { appendActivity(missionId, { action: "phase_start", phase: 3 }); transitionState(missionId, EXEC_STATES.COMPLETED); updateMissionStatus(missionId, "completed"); appendActivity(missionId, { action: "recon_complete" }); // Generate learning from completed mission (non-blocking, best-effort) try { const { recordReconLearning, loadLearning } = await import("./recon-learning.mjs"); // Check if learning already exists for this mission (deduplication) const existing = loadLearning({ missionId, type: "recon_learning" }); if (existing.length === 0) { const mission = loadMission(missionId); if (mission) { // Calculate duration from activity log const activityFile = resolve(getMissionDir(missionId), "activity.jsonl"); let duration = null; if (fs.existsSync(activityFile)) { const lines = fs.readFileSync(activityFile, "utf-8").trim().split("\n").filter(Boolean); if (lines.length >= 2) { const first = JSON.parse(lines[0]); const last = JSON.parse(lines[lines.length - 1]); duration = new Date(last.timestamp) - new Date(first.timestamp); } } // Collect successful techniques from phase directories const successfulTechniques = []; const toolFailures = []; const discoveryMethods = []; const phaseResults = {}; const phaseDirs = ["phase1_passive", "phase2_active", "phase3_validation"]; for (const phaseDir of phaseDirs) { const dir = resolve(getMissionDir(missionId), phaseDir); if (fs.existsSync(dir)) { const files = fs.readdirSync(dir).filter(f => f.endsWith(".json")); const phaseNum = parseInt(phaseDir.match(/\d+/)?.[0] || "0"); phaseResults[`phase${phaseNum}`] = files.length; for (const file of files) { try { const content = JSON.parse(fs.readFileSync(resolve(dir, file), "utf-8")); if (content.tool && !successfulTechniques.includes(content.tool)) { successfulTechniques.push(content.tool); } // Map tools to discovery methods if (content.tool === "subfinder" && !discoveryMethods.includes("passive_subdomain_enum")) { discoveryMethods.push("passive_subdomain_enum"); } if (content.tool === "dnsx" && !discoveryMethods.includes("dns_resolution")) { discoveryMethods.push("dns_resolution"); } if (content.tool === "httpx" && !discoveryMethods.includes("http_probing")) { discoveryMethods.push("http_probing"); } if (content.tool === "nuclei" && !discoveryMethods.includes("technology_fingerprinting")) { discoveryMethods.push("technology_fingerprinting"); } } catch {} } } } // Collect tool failures from errors directory const errorsDir = resolve(getMissionDir(missionId), "errors"); if (fs.existsSync(errorsDir)) { const errorFiles = fs.readdirSync(errorsDir); for (const file of errorFiles) { try { const content = JSON.parse(fs.readFileSync(resolve(errorsDir, file), "utf-8")); if (content.tool && content.target) { toolFailures.push({ tool: content.tool, target: content.target, error: content.error }); } } catch {} } } // Detect false positive patterns const falsePositivePatterns = []; const nucleiFiles = fs.readdirSync(resolve(getMissionDir(missionId), "phase3_validation") || "") .filter(f => f.includes("nuclei") && f.endsWith(".json")); if (nucleiFiles.length > 0 && discoveryMethods.includes("http_probing")) { const httpFiles = fs.readdirSync(resolve(getMissionDir(missionId), "phase2_active") || "") .filter(f => f.includes("httpx") && f.endsWith(".json")); if (nucleiFiles.length > httpFiles.length * 2) { falsePositivePatterns.push("High nuclei findings relative to live HTTP services"); } } recordReconLearning(missionId, { successfulTechniques, toolFailures, duration, discoveryMethods, falsePositivePatterns, targetCount: mission.scope.inScope.length, phaseResults }); } } } catch (e) { // Non-blocking - learning failure should never affect recon appendActivity(missionId, { action: "learning_error", error: String(e) }); } } return findings;}
function pauseRecon(missionId) { const state = getExecutionState(missionId); if (state !== EXEC_STATES.RECONNAISSANCE) throw new Error(`Cannot pause: current state is ${state}`); transitionState(missionId, EXEC_STATES.PAUSED); updateMissionStatus(missionId, "paused"); appendActivity(missionId, { action: "recon_pause" }); return { success: true, state: EXEC_STATES.PAUSED };}
async function resumeRecon(missionId) { const state = getExecutionState(missionId); if (state !== EXEC_STATES.PAUSED && state !== EXEC_STATES.FAILED) { throw new Error(`Cannot resume: current state is ${state}`); } return await startRecon(missionId);}
function cancelMission(missionId) { const state = getExecutionState(missionId); if (state === EXEC_STATES.COMPLETED || state === EXEC_STATES.CANCELLED) { throw new Error(`Mission already ${state}`); } transitionState(missionId, EXEC_STATES.CANCELLED); updateMissionStatus(missionId, "cancelled"); appendActivity(missionId, { action: "mission_cancel" }); return { success: true, state: EXEC_STATES.CANCELLED };}
function stopRecon(missionId) { const state = getExecutionState(missionId); if (state !== EXEC_STATES.RECONNAISSANCE) { return { success: false, message: `No active recon to stop (state: ${state})`, state }; } transitionState(missionId, EXEC_STATES.PAUSED); updateMissionStatus(missionId, "paused"); appendActivity(missionId, { action: "recon_stop" }); return { success: true, message: "Reconnaissance stopped, can resume", state: EXEC_STATES.PAUSED };}
function getExecutionSummary(missionId) { const state = getExecutionState(missionId); if (!state) return { error: "No execution state" }; const dir = getMissionDir(missionId); if (!fs.existsSync(dir)) return { state, findings: 0, errors: 0 }; const files = fs.readdirSync(dir, { recursive: true }); const results = files.filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json").length; const errors = files.filter(f => f.includes("error")).length; const activityFile = resolve(dir, "activity.jsonl"); const activity = fs.existsSync(activityFile) ? fs.readFileSync(activityFile, "utf-8").trim().split("\n").filter(Boolean).length : 0; return { state, findings: results, errors, activity };}
function generateReconSummary(missionId) { const mission = loadMission(missionId); if (!mission) return null; const summary = getExecutionSummary(missionId); const findings = getMissionFindings(missionId); let out = `📋 RECON COMPLETE — ${mission.programName} (${missionId})\n`; out += `State: ${summary.state}\n`; out += `Findings: ${summary.findings} | Errors: ${summary.errors} | Activity: ${summary.activity}\n\n`; out += `📊 PHASE 1 — Passive Reconnaissance\n`; const phase1 = findings.filter(f => f.phase === 1); out += ` Targets processed: ${phase1.length}\n`; out += ` Successful: ${phase1.filter(f => f.status === "success").length}\n`; out += ` Errors: ${phase1.filter(f => f.status === "error").length}\n\n`; out += `📊 PHASE 2 — Active HTTP Probing\n`; const phase2 = findings.filter(f => f.phase === 2); out += ` Targets processed: ${phase2.length}\n`; out += ` Successful: ${phase2.filter(f => f.status === "success").length}\n\n`; out += `📊 PHASE 3 — Validation\n`; out += ` Completed: ${summary.state === "completed" ? "Yes" : "Pending"}\n\n`; out += `💾 Results saved in: ${getMissionDir(missionId)}`; return out;}
function getMissionFindings(missionId) { const dir = getMissionDir(missionId); if (!fs.existsSync(dir)) return []; const findings = []; const files = fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json"); for (const f of files) { try { const data = JSON.parse(fs.readFileSync(resolve(dir, f), "utf-8")); if (data.phase) findings.push(data); } catch {} } return findings;}
function loadMissionResults(missionId) { const dir = getMissionDir(missionId); if (!fs.existsSync(dir)) return []; return fs.readdirSync(dir, { recursive: true }).filter(f => f.endsWith(".json") && !f.includes("error") && f !== "state.json");}
function loadMissionErrors(missionId) { const dir = resolve(getMissionDir(missionId), "errors"); if (!fs.existsSync(dir)) return []; return fs.readdirSync(dir).filter(f => f.endsWith(".json"));}
function loadMissionActivity(missionId) { const f = resolve(getMissionDir(missionId), "activity.jsonl"); if (!fs.existsSync(f)) return []; return fs.readFileSync(f, "utf-8").trim().split("\n").filter(Boolean).map(JSON.parse);}
export { EXEC_STATES, VALID_TRANSITIONS, startRecon, pauseRecon, resumeRecon, cancelMission, stopRecon, getExecutionState, setExecutionState, transitionState, getExecutionSummary, generateReconSummary, getMissionFindings, loadMissionResults, loadMissionErrors, loadMissionActivity, ensureMissionDirs, getResultKey, resultExists, saveResult, loadExistingResult, saveError, appendActivity};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250// Phantom — shared runtime state// Mutable exports set by phantom.mjs, read by lib modules.// ESM live bindings ensure imports see the latest values.
import { execFileSync } from "child_process";import { resolve } from "path";
// Lazy import for evolve — avoid circular dep at module load timelet _evolve = null;async function getEvolve() { if (!_evolve) _evolve = await import("./evolve.mjs"); return _evolve;}
export const __r = { llmInstance: null, _config: {}, setProvider: null, PROVIDERS: null, PHANTOM_LLM_PROVIDER: "openai", ENV: null,};
// ── Async shell exec helper ──────────────────────────────// Replaces execSync throughout tools.mjs so the event loop stays// responsive during long-running commands (stdin keeps working).export function execAsync(cmd, opts = {}) { const timeout = opts.timeout ?? 30000; const maxBuffer = opts.maxBuffer ?? 1024 * 1024; return new Promise((resolve, reject) => { // Dynamic import to avoid top-level require import("child_process").then(({ exec }) => { exec(cmd, { encoding: "utf-8", timeout, maxBuffer }, (err, stdout, stderr) => { if (err) { err.stderr = (stderr || "").substring(0, 500); return reject(err); } resolve(stdout); }); }).catch(reject); });}
// ── External tool helper ─────────────────────────────────// DRY wrapper for all external-binary tools.// Handles dynamic import caching, which-check, error formatting.// Returns trimmed stdout lines array. Throws on error.const _cp = /* lazily cached */ null;function _ensureChildProcess() { // execFileSync is already statically imported; this is a no-op // but kept for symmetry with tools that imported dynamically return { execFileSync };}
/** * Run an external binary and return its trimmed stdout lines. * * @param {string} tool Binary name (e.g. "nmap", "subfinder") * @param {string[]} args CLI arguments * @param {object} [opts] * @param {number} [opts.timeout=60000] * @param {number} [opts.maxBuffer=1024*1024] * @param {string} [opts.input] stdin content * @param {string} [opts.installGuide] shown if binary missing * @returns {string[]} non-empty stdout lines */export function runExternal(tool, args, opts = {}) { const { execFileSync } = _ensureChildProcess(); const timeout = opts.timeout ?? 60000; const maxBuffer = opts.maxBuffer ?? 1024 * 1024; const input = opts.input; const guide = opts.installGuide || `go install ...${tool}@latest`;
// which check — prefer cached env.tools, fallback to which const cached = __r.ENV?.tools?.[tool]; if (cached === false) { throw new Error(`[${tool}] NOT INSTALLED — ${guide}`); } if (cached !== true) { try { execFileSync("which", [tool], { encoding: "utf-8", timeout: 5000 }); } catch { throw new Error(`[${tool}] NOT INSTALLED — ${guide}`); } }
const execOpts = { encoding: "utf-8", timeout, maxBuffer }; if (input !== undefined) execOpts.input = input;
const out = execFileSync(tool, args, execOpts); return out.trim().split("\n").filter(Boolean);}
/** * Format external tool output for display. * @param {string} toolName * @param {string} target * @param {string[]} lines * @param {number} [maxLines=50] * @returns {string} formatted output */export function formatExternal(toolName, target, lines, maxLines = 50) { if (!lines.length) return `[${toolName}] No results for ${target}`; const result = [`🔎 ${toolName}: ${target}`, `Results: ${lines.length}`]; result.push(...lines.slice(0, maxLines).map(l => ` ${l}`)); if (lines.length > maxLines) result.push(` ... and ${lines.length - maxLines} more`); return result.join("\n");}
// ── Tool execution wrapper ───────────────────────────────// Handles JSON output, tool chaining/piping, error wrapping.
/** * Run a tool from the hackerTools registry with optional flags. * * @param {object} tools - hackerTools object * @param {string} toolName * @param {string} input * @param {object} [opts] * @param {boolean} [opts.json=false] Return JSON string instead of formatted text * @returns {Promise<string>} Formatted text or JSON string */export async function runTool(tools, toolName, input, opts = {}) { const fn = tools[toolName]; if (!fn) { const msg = `[${toolName}] Unknown tool. Use --list to see available tools.`; return opts.json ? JSON.stringify({ ok: false, error: msg, tool: toolName }) : msg; } // Built-in --help for any tool const trimmed = (input || "").trim().toLowerCase(); if (trimmed === "--help" || trimmed === "-h") { const help = `[${toolName}] Usage: @${toolName}|<args> Run "${toolName}" with empty input for built-in usage. Available tools: ${Object.keys(tools).length}`; return opts.json ? JSON.stringify({ ok: true, tool: toolName, help: true, data: help }) : help; } // Show spinner for slow tools (non-CLI mode — REPL handles its own feedback) const timer = setTimeout(() => process.stdout.write(`[*] ${toolName} running...\r`), 2000); try { const result = await fn(input); clearTimeout(timer); if (opts.json) { return JSON.stringify({ ok: true, tool: toolName, input, data: result, length: result.length }); } return result; } catch (e) { clearTimeout(timer); // Auto-heal: try to fix the error and retry once try { const evolve = await getEvolve(); const fix = await evolve.analyzeError(toolName, e.message); if (fix && fix.fixed) { // Retry the tool after successful fix const retryResult = await fn(input); if (opts.json) { return JSON.stringify({ ok: true, tool: toolName, input, data: retryResult, length: retryResult.length, auto_healed: true, fix: fix.message }); } return `[auto-heal] ${fix.message}\n${retryResult}`; } } catch {} const msg = `[${toolName} Error] ${e.message}`; return opts.json ? JSON.stringify({ ok: false, error: e.message, tool: toolName, input }) : msg; }}
/** * Parse and execute a piped tool chain. * Format: tool1|args | tool2 | tool3|more_args * * @param {object} tools - hackerTools object * @param {string} chain - e.g. "subfinder|example.com | httpx | nuclei|https://x.com" * @param {object} [opts] * @returns {Promise<string>} */export async function runPipe(tools, chain, opts = {}) { // Chain separator = " | " (space-pipe-space) // Tool/args separator = "|" (no spaces needed) // This avoids conflict between "shell|echo hi" and "subfinder|x.com | httpx" const segments = chain.split(/\s+\|\s+/).filter(Boolean); if (segments.length === 0) return opts.json ? JSON.stringify({ ok: false, error: "Empty pipe chain" }) : "[pipe] Empty chain"; if (segments.length === 1) { // Single tool, no piping const [toolName, ...args] = segments[0].split("|"); const input = args.join("|").trim(); return runTool(tools, toolName, input, opts); }
// Multi-segment pipe: output of each tool becomes input of the next let pipeInput = ""; let lastResult = "";
for (let i = 0; i < segments.length; i++) { const seg = segments[i].trim(); const [toolName, ...args] = seg.split("|"); let input = args.join("|").trim();
// If there's piped input from previous tool, prepend it // Format: previous output lines become part of the argument if (pipeInput && input) { // Both piped input and explicit args — append piped data input = input + " " + pipeInput; } else if (pipeInput && !input) { input = pipeInput; }
// Last segment gets the opts as-is; intermediate segments are not JSON const segOpts = (i === segments.length - 1) ? opts : {}; const result = await runTool(tools, toolName, input, segOpts);
if (i === segments.length - 1) { lastResult = result; } else { // Intermediate output: take the last line or the whole thing const lines = result.split("\n").filter(Boolean); // Try to find the most relevant data lines (skip header/count) const dataLines = lines.filter(l => !l.startsWith("🔎") && !l.startsWith("Results:") && !l.startsWith("[") && l.trim()); pipeInput = dataLines.length > 0 ? dataLines.join("\n") : lines.slice(-10).join("\n"); } }
return lastResult;}
/** * Run a scheduled scan: executes a tool on each scope target. * @param {object} tools - hackerTools object * @param {string} toolName - tool to run * @param {string} [extra] - extra options * @param {number} [concurrency=1] * @returns {Promise<string>} */export async function runScheduledScan(tools, toolName, extra = "", concurrency = 1) { // Load scope const scopeResult = await tools.scope("export"); const targets = scopeResult.split("\n").filter(l => l.trim() && !l.includes("(empty") && !l.includes("Commands")); if (targets.length === 0) return "[schedule] No scope targets defined. Use scope add <target> first.";
const fn = tools[toolName]; if (!fn) return `[schedule] Unknown tool: ${toolName}`;
const results = []; for (const target of targets) { try { const r = await fn(`${target} ${extra}`.trim()); results.push(`=== ${target} ===\n${r}`); } catch (e) { results.push(`=== ${target} ===\n[${toolName} Error] ${e.message}`); } } return results.join("\n\n");}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548// Phantom — Self-Improvement Engine// Reads other projects' source code, analyzes what Phantom lacks,// and generates code to fill those gaps autonomously.//// Capabilities:// 1. Project Scanner — Clone/read any git repo, parse file structure// 2. Feature Extractor — Discover what features other projects have// 3. Gap Analyzer — Compare features against Phantom's own tools// 4. Pattern Learner — Extract architectural patterns from other projects// 5. Code Generator — Generate new Phantom modules from learned patterns// 6. Auto-Applier — Write, validate, test, and commit improvements
import fs from "fs";import { execFileSync, execSync } from "child_process";import { resolve, join, dirname, basename, extname, relative } from "path";import { homedir } from "os";import { BASE_DIR, TOOLS_DIR, PHANTOM_VERSION } from "./config.mjs";import { __r } from "./runtime.mjs";
// ── Constants ──────────────────────────────────────────────const PHANTOM_DIR = resolve(homedir(), "Phantom");const LEARN_DIR = resolve(BASE_DIR, "learned");const BLUEPRINTS_DIR = resolve(BASE_DIR, "blueprints");const EVOLVE_LOG = resolve(BASE_DIR, "evolve.json");const GENERATED_DIR = resolve(PHANTOM_DIR, "lib", "generated");const LEARNED_MODULES_DIR = resolve(PHANTOM_DIR, "lib", "learned");
// ── Helpers ────────────────────────────────────────────────
function loadState() { const defaults = { generation: 1, self_improve: [], imported_features: [], learned_patterns: [], patches: [], wrappers: [], errors_fixed: 0, last_evolve: null, auto_fixes: [] }; try { if (fs.existsSync(EVOLVE_LOG)) { const existing = JSON.parse(fs.readFileSync(EVOLVE_LOG, "utf-8")); // Merge with defaults so new keys are present even on old state files for (const [k, v] of Object.entries(defaults)) { if (!(k in existing)) existing[k] = v; } return existing; } } catch {} return { ...defaults };}
function saveState(st) { try { if (!fs.existsSync(BASE_DIR)) fs.mkdirSync(BASE_DIR, { recursive: true }); fs.writeFileSync(EVOLVE_LOG, JSON.stringify(st, null, 2), "utf-8"); } catch {}}
function ensureDir(p) { if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });}
function gitRoot() { try { const r = execSync("git rev-parse --show-toplevel 2>/dev/null", { encoding: "utf-8", timeout: 5000 }).trim(); return r || null; } catch { return null; }}
function safeReadFile(path) { try { if (!fs.existsSync(path)) return null; const stat = fs.statSync(path); if (stat.size > 500000) return null; // skip >500KB files return fs.readFileSync(path, "utf-8"); } catch { return null; }}
// ── 1. PROJECT SCANNER ────────────────────────────────────// Given a local path or remote git URL, scan and return project structure.
/** * Clone a remote git repo to a temp dir, or validate a local path. * Returns { path, name, isRemote, tempDir } */export function cloneOrLocate(target) { const cleaned = target.trim();
// Already a local directory? if (fs.existsSync(cleaned) && fs.statSync(cleaned).isDirectory()) { return { path: resolve(cleaned), name: basename(resolve(cleaned)), isRemote: false, tempDir: null }; }
// Try git clone if (cleaned.match(/^https?:\/\/.+\.git$/) || cleaned.match(/^git@/)) { const name = cleaned.split("/").pop().replace(/\.git$/, "") || `repo_${Date.now()}`; const dest = resolve(BASE_DIR, "cloned", name); ensureDir(dirname(dest)); if (!fs.existsSync(dest)) { try { execSync(`git clone --depth 1 "${cleaned}" "${dest}"`, { encoding: "utf-8", timeout: 60000 }); } catch (e) { throw new Error(`Git clone failed: ${e.stderr?.slice(0, 200) || e.message}`); } } return { path: dest, name, isRemote: true, tempDir: dest }; }
// Could be a repo URL without .git — try to clone anyway if (cleaned.startsWith("http") || cleaned.startsWith("git@")) { const url = cleaned.endsWith(".git") ? cleaned : `${cleaned}.git`; const name = url.split("/").pop().replace(/\.git$/, "") || `repo_${Date.now()}`; const dest = resolve(BASE_DIR, "cloned", name); ensureDir(dirname(dest)); if (!fs.existsSync(dest)) { try { execSync(`git clone --depth 1 "${url}" "${dest}"`, { encoding: "utf-8", timeout: 60000 }); } catch (e) { throw new Error(`Git clone failed: ${e.stderr?.slice(0, 200) || e.message}`); } } return { path: dest, name, isRemote: true, tempDir: dest }; }
throw new Error(`Cannot locate project: ${cleaned}. Provide a local path or git URL.`);}
/** * Scan a project directory and return a structured summary: * { name, fileCount, languages, entryPoints, exports, tools, features, structure } */export function scanProject(projectPath) { const result = { name: basename(projectPath), path: projectPath, fileCount: 0, languages: {}, fileTree: [], entryPoints: [], exports: [], features: [], tools: [], patterns: { moduleSystem: "unknown", hasTests: false, hasCli: false, hasHttpServer: false, hasConfig: false, hasPluginSystem: false, }, structure: {}, };
if (!fs.existsSync(projectPath)) return result;
const entries = fs.readdirSync(projectPath, { withFileTypes: true });
// Quick file tree (depth 1) const dirs = []; const files = []; for (const e of entries) { if (e.name.startsWith(".")) continue; if (e.isDirectory()) dirs.push(e.name); else files.push(e.name); }
result.structure = { dirs, files };
// Detect entry points for (const f of ["package.json", "index.mjs", "index.js", "app.mjs", "app.js", "main.mjs", "main.js", "cli.mjs", "cli.js"]) { if (files.includes(f)) result.entryPoints.push(f); }
// Parse package.json if present let pkg = null; const pkgPath = resolve(projectPath, "package.json"); if (fs.existsSync(pkgPath)) { try { pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); if (pkg.name) result.name = pkg.name; if (pkg.bin) { result.patterns.hasCli = true; const bins = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin); result.entryPoints.push(...bins.filter(b => !result.entryPoints.includes(b))); } } catch {} }
// Recursively walk JS files to extract patterns walkProjectFiles(projectPath, result);
// Detect module system if (result.languages["mjs"] || pkg?.type === "module") { result.patterns.moduleSystem = "esm"; } else if (result.languages["cjs"] || result.languages["js"]) { result.patterns.moduleSystem = "cjs"; }
// Test detection result.patterns.hasTests = result.languages["test.mjs"] > 0 || result.languages["spec.mjs"] > 0 || result.languages["test.js"] > 0 || result.features.some(f => f.includes("test"));
// HTTP server detection result.patterns.hasHttpServer = result.features.some(f => f.includes("http") || f.includes("server") || f.includes("express") || f.includes("fastify") );
// Config detection result.patterns.hasConfig = files.some(f => f.includes("config") || f.endsWith("rc") || f === ".env" );
// Plugin detection result.patterns.hasPluginSystem = result.features.some(f => f.includes("plugin") || f.includes("extension") || f.includes("module") );
return result;}
function walkProjectFiles(basePath, result) { try { const entries = fs.readdirSync(basePath, { withFileTypes: true }); for (const e of entries) { if (e.name.startsWith(".")) continue; if (e.name === "node_modules") continue; if (e.name === "dist") continue; if (e.name === "build") continue; if (e.name === ".git") continue;
const fullPath = resolve(basePath, e.name);
if (e.isDirectory()) { walkProjectFiles(fullPath, result); } else if (e.isFile()) { result.fileCount++;
// Track languages const ext = extname(e.name).replace(/^\./, ""); if (ext) { result.languages[ext] = (result.languages[ext] || 0) + 1; }
// Analyze JS/TS source files if (e.name.endsWith(".mjs") || e.name.endsWith(".js") || e.name.endsWith(".ts")) { analyzeJSFile(fullPath, result); }
// Analyze Python source if (e.name.endsWith(".py")) { analyzePythonFile(fullPath, result); }
// Analyze Go source if (e.name.endsWith(".go")) { analyzeGoFile(fullPath, result); } } } } catch {}}
// ── Language-specific file analyzers ─────────────────────────
function analyzeJSFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return;
const exports = content.match(/(?:export\s+(?:async\s+)?function\s+(\w+)|export\s+const\s+(\w+)|export\s+default\s+(?:async\s+)?function\s*[*(]\s*[^)]*\s*\)(?:.*{)?|module\.exports\s*=\s*{(?:[\s\S]*?)}|module\.exports\s*=\s*{)/g); if (exports) { for (const ex of exports) { const name = ex.match(/(?:function\s+|const\s+)(\w+)/)?.[1]; if (name) result.exports.push({ name, file: relative(result.path, fullPath) }); } }
const toolPatterns = content.matchAll(/(\w+):\s*(?:async\s*)?\(?\s*(input|args|cmd|query|target|url|domain|path|text|data|name)\s*\)?\s*=>\s*{/g); for (const m of toolPatterns) { result.tools.push({ name: m[1], param: m[2], file: relative(result.path, fullPath) }); }
const imports = content.matchAll(/from\s+["']([^"']+)["']/g); for (const m of imports) { const module = m[1]; if (module.startsWith("http") || module.startsWith("express") || module.startsWith("fastify")) { result.patterns.hasHttpServer = true; } if (!result.features.includes(module)) result.features.push(module); }
if (content.includes("commander") || content.includes("yargs") || content.includes("arg parse") || content.includes("process.argv") || (content.includes("command") && content.includes("description"))) { result.patterns.hasCli = true; }
for (const feature of [ ["websocket", /websocket|ws:\/\/|wss:\/\//i], ["database", /sqlite|mongo|postgres|mysql|knex|prisma|typeorm/i], ["graphql", /graphql|gql`/i], ["auth", /jwt|oauth|bcrypt|passport|session/i], ["cache", /redis|memcached|cache/i], ["logging", /winston|pino|log4js|bunyan/i], ["sse", /EventSource|Server-Sent Events|text\/event-stream/i], ["streaming", /pipe|stream|Transform|Readable|Writable/i], ["ipc", /child_process|fork|spawn|Worker|parentPort/i], ]) { if (feature[1].test(content) && !result.features.includes(feature[0])) { result.features.push(feature[0]); } }}
function analyzePythonFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return;
// Detect module system result.patterns.moduleSystem = "python";
// Extract function definitions as exports const funcs = content.matchAll(/^\s*(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)\s*:/gm); for (const m of funcs) { const name = m[1]; const params = m[2].trim(); result.exports.push({ name, file: relative(result.path, fullPath) });
// Classify as tool if param matches known patterns const toolParams = ["query", "target", "url", "domain", "path", "text", "data", "name", "input", "args", "cmd", "username", "email", "host", "port"]; const hasToolParam = toolParams.some(p => params.includes(p)); if (hasToolParam || !params) { result.tools.push({ name, param: params.split(",")[0]?.trim() || "input", file: relative(result.path, fullPath) }); } }
// Extract class definitions const classes = content.matchAll(/^\s*class\s+(\w+)\s*[:\(]/gm); for (const m of classes) { result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); }
// Extract imports as features const imports = content.matchAll(/(?:from\s+(\S+)\s+import|import\s+(\S+))/g); for (const m of imports) { const mod = m[1] || m[2]; if (mod && !result.features.includes(mod)) { result.features.push(mod.startsWith(".") ? mod.slice(1) : mod); } }
// Detect CLI frameworks if (content.includes("argparse") || content.includes("click") || content.includes("typer") || content.includes("fire.Fire") || content.includes("def main")) { result.patterns.hasCli = true; }
// Detect HTTP if (content.includes("from flask") || content.includes("from fastapi") || content.includes("import requests") || content.includes("aiohttp") || content.includes("django")) { result.patterns.hasHttpServer = true; }
// Feature detection if (/(sqlite|mongo(engine|db)?|postgres|mysql|psycopg|sqlalchemy)/i.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(jwt|oauth|bcrypt|passlib|hashlib)/i.test(content) && !result.features.includes("auth")) result.features.push("auth"); if (/(redis|memcached|cache)/i.test(content) && !result.features.includes("cache")) result.features.push("cache"); if (/(websocket|wss?:\/\/)/i.test(content) && !result.features.includes("websocket")) result.features.push("websocket"); if (/(thread|multiprocess|subprocess|concurrent)/i.test(content) && !result.features.includes("ipc")) result.features.push("ipc"); if (/(logging|loguru)/i.test(content) && !result.features.includes("logging")) result.features.push("logging");}
function analyzeGoFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return;
// Detect module system result.patterns.moduleSystem = "go";
// Extract function definitions const funcs = content.matchAll(/^\s*func\s+(?:\([^)]*\)\s+)?([A-Z]\w+)\s*\(([^)]*)\)(?:\s*\(?[^)]*\)?)?\s*\{/gm); for (const m of funcs) { const name = m[1]; const params = m[2].trim(); result.exports.push({ name, file: relative(result.path, fullPath) });
const toolParams = ["query", "target", "url", "domain", "path", "text", "data", "name", "input", "args", "cmd", "host", "port", "addr"]; const hasToolParam = toolParams.some(p => params.includes(p)); if (hasToolParam && name[0] >= 'A' && name[0] <= 'Z') { result.tools.push({ name, param: params.split(",")[0]?.trim() || "input", file: relative(result.path, fullPath) }); } }
// Detect main function if (content.includes("func main()")) result.patterns.hasCli = true;
// Detect HTTP if (/(http\.ListenAndServe|gin\.|fiber\.|echo\.|chi\.|net\/http)/.test(content)) { result.patterns.hasHttpServer = true; }
// Imports const imports = content.matchAll(/(?:"([^"]+)"|`([^`]+)`)/g); for (const m of imports) { const imp = (m[1] || m[2]).trim(); if (imp.includes("/") && !result.features.includes(imp)) { result.features.push(imp); } }
// Feature detection if (/(sqlite|mongo|postgres|mysql|database\/sql)/i.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(jwt|oauth|bcrypt|golang-jwt)/i.test(content) && !result.features.includes("auth")) result.features.push("auth"); if (/(websocket|gorilla\/websocket|nhooyr\.io\/websocket)/i.test(content) && !result.features.includes("websocket")) result.features.push("websocket"); if (/(redis|memcached)/i.test(content) && !result.features.includes("cache")) result.features.push("cache");}
// ── 2. SELF-ANALYSIS ──────────────────────────────────────// Analyze Phantom's own codebase to understand current capabilities.
export function analyzeSelf() { const toolsPath = resolve(PHANTOM_DIR, "lib", "tools.mjs"); const configPath = resolve(PHANTOM_DIR, "lib", "config.mjs"); const runtimePath = resolve(PHANTOM_DIR, "lib", "runtime.mjs"); const evolvePath = resolve(PHANTOM_DIR, "lib", "evolve.mjs"); const dashboardPath = resolve(PHANTOM_DIR, "lib", "dashboard.mjs"); const serverPath = resolve(PHANTOM_DIR, "lib", "server.mjs");
const self = { version: PHANTOM_VERSION, files: [], tools: [], exports: [], features: [], gaps: [], architecture: { moduleCount: 0, hasMultiAgent: false, hasRepl: false, hasApi: false, hasGui: false, hasPluginSystem: false, hasTestSuite: false, hasConfigManagement: false, }, };
// Analyze each source file for (const [label, fp] of [ ["phantom.mjs", resolve(PHANTOM_DIR, "phantom.mjs")], ["lib/tools.mjs", toolsPath], ["lib/config.mjs", configPath], ["lib/runtime.mjs", runtimePath], ["lib/evolve.mjs", evolvePath], ["lib/env.mjs", resolve(PHANTOM_DIR, "lib/env.mjs")], ["lib/session.mjs", resolve(PHANTOM_DIR, "lib/session.mjs")], ["lib/dashboard.mjs", dashboardPath], ["lib/server.mjs", serverPath], ]) { const content = safeReadFile(fp); if (!content) continue; self.files.push({ name: label, size: content.length, lines: content.split("\n").length });
// Extract exports const exports = content.match(/(?:export\s+(?:async\s+)?function\s+(\w+)|export\s+const\s+(\w+))/g); if (exports) { for (const ex of exports) { const name = ex.match(/(?:function\s+|const\s+)(\w+)/)?.[1]; if (name) self.exports.push(name); } } } self.architecture.moduleCount = self.files.length;
// Extract tools from tools.mjs const toolsContent = safeReadFile(toolsPath); if (toolsContent) { const toolNames = toolsContent.matchAll(/(\w+):\s*async\s*\(/g); for (const m of toolNames) { if (m[1] !== "export") self.tools.push(m[1]); } }
// Detect architecture features const mainSrc = safeReadFile(resolve(PHANTOM_DIR, "phantom.mjs")) || ""; self.architecture.hasMultiAgent = mainSrc.includes("AgentManager") && mainSrc.includes("spawn"); self.architecture.hasRepl = mainSrc.includes("readline") || mainSrc.includes("REPL"); self.architecture.hasApi = mainSrc.includes("startApiServer") || mainSrc.includes("REST"); self.architecture.hasGui = mainSrc.includes("startGuiDashboard") || mainSrc.includes("Dashboard"); self.architecture.hasTestSuite = fs.existsSync(resolve(PHANTOM_DIR, "test")) && fs.readdirSync(resolve(PHANTOM_DIR, "test")).length > 0; self.architecture.hasConfigManagement = mainSrc.includes("config") || mainSrc.includes("_config");
// Detect plugin system const allSrc = (safeReadFile(toolsPath) || "") + (safeReadFile(evolvePath) || "") + mainSrc; self.architecture.hasPluginSystem = allSrc.includes("plugin") && allSrc.includes("load");
// Identify categories of tools Phantom has self.features = [ { name: "dns_lookup", present: self.tools.includes("dns_lookup") }, { name: "port_scanning", present: self.tools.includes("port_scan") }, { name: "subdomain_enum", present: self.tools.includes("sub_enum") }, { name: "http_requests", present: self.tools.includes("web_fetch") }, { name: "ssl_check", present: self.tools.includes("ssl_check") }, { name: "whois", present: self.tools.includes("whois") }, { name: "cve_search", present: self.tools.includes("cve_search") }, { name: "exploit_search", present: self.tools.includes("searchsploit") }, { name: "vuln_scan", present: self.tools.includes("vuln_scan") }, { name: "bruteforce", present: self.tools.includes("bruteforce") }, { name: "file_analysis", present: self.tools.includes("file_analyze") }, { name: "hash", present: self.tools.includes("hash") }, { name: "encoding/decoding", present: self.tools.includes("decode") }, { name: "crawler", present: self.tools.includes("crawl") }, { name: "http_headers", present: self.tools.includes("http_headers") }, { name: "yara", present: self.tools.includes("yara") }, { name: "virustotal", present: self.tools.includes("vt_check") }, { name: "shell_execution", present: self.tools.includes("shell") }, { name: "code_generation", present: self.tools.includes("code_gen") }, { name: "self_modification", present: self.tools.includes("self_edit") }, { name: "knowledge_base", present: self.tools.includes("knowledge_add") }, { name: "playbooks", present: self.tools.includes("playbook_list") }, { name: "scheduling", present: self.tools.includes("schedule") || allSrc.includes("@schedule") }, { name: "scope_management", present: self.tools.includes("scope") }, { name: "pipeline/pipe", present: mainSrc.includes("runPipe") }, { name: "dashboard/gui", present: self.architecture.hasGui }, { name: "rest_api", present: self.architecture.hasApi }, { name: "multi_agent", present: self.architecture.hasMultiAgent }, ];
return self;}
// ── 3. GAP ANALYSIS ───────────────────────────────────────// Compare a scanned project against Phantom to find missing features.
/** * Compare project scan against Phantom's current capabilities. * Returns an array of gaps: { priority, category, feature, description, source, suggestedApproach } */export function gapAnalysis(projectScan, selfScan) { const gaps = []; const selfTools = new Set(selfScan.tools); const projectTools = projectScan.tools || []; const projectFeatures = projectScan.features || [];
// 1. Missing external tool wrappers const projectToolNames = new Set(projectTools.map(t => t.name)); for (const tool of projectTools) { if (!selfTools.has(tool.name) && !tool.name.match(/^[A-Z]/)) { gaps.push({ priority: "medium", category: "missing_tool", feature: tool.name, description: `Project has a tool/function "${tool.name}" that Phantom doesn't wrap`, source: `${projectScan.name}/${tool.file}`, suggestedApproach: "generate_wrapper", }); } }
// 2. Missing feature categories const selfFeaturesSet = new Set(selfScan.features.filter(f => f.present).map(f => f.name)); const featureMapping = { "websocket": { priority: "high", category: "protocol", description: "WebSocket client for real-time communication" }, "database": { priority: "high", category: "data", description: "Database integration (SQLite, PostgreSQL, etc.)" }, "graphql": { priority: "medium", category: "api", description: "GraphQL queries and schema introspection" }, "auth": { priority: "high", category: "security", description: "Authentication/authorization tools" }, "cache": { priority: "low", category: "performance", description: "Caching layer for repeated queries" }, "logging": { priority: "low", category: "devops", description: "Structured logging" }, "sse": { priority: "medium", category: "protocol", description: "Server-Sent Events streaming" }, "streaming": { priority: "medium", category: "protocol", description: "Stream processing for large data" }, "ipc": { priority: "medium", category: "system", description: "Inter-process communication" }, };
for (const [featureName, mapping] of Object.entries(featureMapping)) { if (projectFeatures.includes(featureName) && !selfFeaturesSet.has(featureName)) { gaps.push({ priority: mapping.priority, category: mapping.category, feature: featureName, description: `${mapping.description} — present in ${projectScan.name} but missing from Phantom`, source: projectScan.name, suggestedApproach: "generate_module", }); } }
// 3. Architecture gaps const proj = projectScan.patterns; const arch = selfScan.architecture;
if (proj.hasPluginSystem && !arch.hasPluginSystem) { gaps.push({ priority: "high", category: "architecture", feature: "plugin_system", description: `${projectScan.name} uses a plugin system — Phantom could support hot-loadable plugins`, source: projectScan.name, suggestedApproach: "generate_module", }); }
// 4. File structure patterns worth adopting if (projectScan.languages["mjs"] && projectScan.languages["mjs"] > 3) { // Another ESM project may have useful patterns gaps.push({ priority: "low", category: "pattern", feature: "esm_patterns", description: `${projectScan.name} uses modular ESM patterns worth studying`, source: projectScan.name, suggestedApproach: "learn_pattern", }); }
// 5. Detect if project has a README/docs system Phantom lacks const hasDocs = projectScan.fileTree.some(f => f.toLowerCase().includes("readme") || f.toLowerCase().includes("docs") || f.endsWith(".md") ); // Phantom already has --help, but structured docs are worth checking
return gaps;}
// ── 4. PATTERN LEARNER ────────────────────────────────────// Extract reusable patterns from other projects.
/** * Extract coding patterns from a project's source files. * Returns { modulePattern, errorHandling, toolPattern, cliPattern, middlewarePattern, ... } */export function extractPatterns(projectPath) { const patterns = { moduleExports: "named", errorStyle: "catch_return", toolInterface: "async_single_param", configStyle: "flat_object", eventStyle: "none", validatedBy: null, samples: [], };
// Count export styles let namedExports = 0, defaultExports = 0, moduleExports = 0;
// Walk all JS/MJS files try { const entries = fs.readdirSync(projectPath, { withFileTypes: true }); for (const e of entries) { if (e.name.startsWith(".") || e.isDirectory()) continue; if (!e.name.endsWith(".mjs") && !e.name.endsWith(".js")) continue;
const content = safeReadFile(resolve(projectPath, e.name)); if (!content) continue;
if ((content.match(/^export\s+(async\s+)?function/gm) || []).length > 0) namedExports++; if ((content.match(/export\s+default/g) || []).length > 0) defaultExports++; if ((content.match(/module\.exports/g) || []).length > 0) moduleExports++;
// Error handling pattern if (content.includes("try {") && content.includes("catch (e)")) { if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}return\s/)) { patterns.errorStyle = "catch_return"; } else if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}(?:reject|throw)/)) { patterns.errorStyle = "catch_throw"; } else if (content.match(/catch\s*\([^)]*\)\s*{[\s\S]{0,100}(?:console|log|warn)/)) { patterns.errorStyle = "catch_log"; } }
// Tool interface pattern if (content.match(/(\w+):\s*async\s*\(\s*(input|args|cmd)\s*\)/)) { patterns.toolInterface = "async_single_param"; } else if (content.match(/(\w+):\s*async\s*\(\s*\)/)) { patterns.toolInterface = "async_no_param"; }
// Config pattern if (content.includes("config") && content.includes("from")) { patterns.configStyle = "module_import"; }
// Extract a sample module as reference if (namedExports + defaultExports + moduleExports > 0 && !patterns.samples.length) { const lines = content.split("\n"); const sample = lines.slice(0, 40).map(l => l.trim()).filter(Boolean).slice(0, 20).join("\n"); if (sample.length > 80) { patterns.samples.push({ file: e.name, code: sample }); } } } } catch {}
return patterns;}
/** * Save learned patterns to disk for reference during code generation. */export function savePatterns(projectName, patterns) { ensureDir(LEARN_DIR); const fp = resolve(LEARN_DIR, `${projectName.replace(/[^a-z0-9_-]/gi, "_")}_patterns.json`); const data = { project: projectName, learned: new Date().toISOString(), patterns, }; fs.writeFileSync(fp, JSON.stringify(data, null, 2), "utf-8"); return fp;}
/** * Load all saved patterns for use in code generation. */export function loadAllPatterns() { const results = {}; ensureDir(LEARN_DIR); const files = fs.readdirSync(LEARN_DIR).filter(f => f.endsWith("_patterns.json")); for (const f of files) { try { const data = JSON.parse(fs.readFileSync(resolve(LEARN_DIR, f), "utf-8")); results[data.project] = data.patterns; } catch {} } return results;}
// ── 5a. TECHNIQUE EXTRACTOR ────────────────────────────────// Extract actual payloads/techniques from Markdown-heavy repos (PayloadsAllTheThings, etc.)
const IGNORE_DIRS = new Set([".git", "node_modules", "dist", "build", ".github", "images", "assets", ".env"]);const IGNORE_FILES = new Set(["README.md", "CONTRIBUTING.md", "LICENSE.md", "LICENSE", "CHANGELOG.md"]);
/** * Recursively find all .md files in a project. */function findMarkdownFiles(dirPath, maxFiles = 500) { const results = []; try { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (const e of entries) { if (e.name.startsWith(".") || IGNORE_DIRS.has(e.name)) continue; if (results.length >= maxFiles) break; const fullPath = resolve(dirPath, e.name); if (e.isDirectory()) { results.push(...findMarkdownFiles(fullPath, maxFiles - results.length)); } else if (e.isFile() && e.name.endsWith(".md") && !IGNORE_FILES.has(e.name)) { results.push(fullPath); } } } catch {} return results;}
/** * Parse a single markdown file into techniques: heading, code blocks, descriptions. */function parseMarkdownFile(filePath) { const content = safeReadFile(filePath); if (!content || content.length < 50) return null;
const techniques = []; const lines = content.split("\n"); let currentHeading = ""; let currentDesc = "";
for (let i = 0; i < lines.length; i++) { const line = lines[i];
// Track headings as technique categories const headingMatch = line.match(/^(#{1,4})\s+(.+)/); if (headingMatch) { currentHeading = headingMatch[2].trim(); currentDesc = ""; continue; }
// Capture description text (non-code, non-empty lines before a code block) const trimmed = line.trim(); if (trimmed && !trimmed.startsWith("```") && !trimmed.startsWith("`") && trimmed.length > 20) { currentDesc = trimmed.substring(0, 300); }
// Extract code blocks (payloads) if (trimmed.startsWith("```") && i + 1 < lines.length) { const lang = trimmed.slice(3).trim().split(/\s/)[0]; const blockLines = []; let j = i + 1; while (j < lines.length && !lines[j].trim().startsWith("```")) { blockLines.push(lines[j]); j++; } const code = blockLines.join("\n").trim(); if (code.length > 10 && code.length < 10000) { techniques.push({ heading: currentHeading || basename(dirname(filePath)), language: lang || "text", code: code.substring(0, 2000), description: currentDesc.substring(0, 200), source: filePath, }); } i = j; // skip past closing ``` continue; } }
return techniques.length > 0 ? techniques : null;}
/** * Extract payloads and techniques from a project's markdown files. * Saves them as knowledge entries and technique books. * Returns { totalFiles, totalTechniques, categories, bookFiles } */export function extractTechniques(projectPath, projectName) { const result = { totalFiles: 0, totalTechniques: 0, categories: {}, bookFiles: [], };
// Ensure books dir const booksDir = resolve(BASE_DIR, "books"); ensureDir(booksDir); const knowledgeDir = resolve(BASE_DIR, "knowledge"); ensureDir(knowledgeDir);
// Find all markdown files const mdFiles = findMarkdownFiles(projectPath); result.totalFiles = mdFiles.length;
// Category from directory structure const categoryMap = {}; // category -> [techniques]
for (const filePath of mdFiles) { // Determine category from relative path const relPath = relative(projectPath, filePath); const parts = relPath.split(/[\\/]/); const category = parts.length > 1 ? parts.slice(0, -1).join(" > ") : "root"; const fileName = parts[parts.length - 1].replace(/\.md$/, "");
const techs = parseMarkdownFile(filePath); if (!techs) continue;
for (const tech of techs) { tech.category = category; tech.fileName = fileName; const catKey = category || "uncategorized"; if (!categoryMap[catKey]) categoryMap[catKey] = []; categoryMap[catKey].push(tech); } result.totalTechniques += techs.length; }
// Save per-category technique books for (const [category, techs] of Object.entries(categoryMap)) { const safeName = `${projectName}_${category}`.replace(/[^a-z0-9_-]/gi, "_").substring(0, 50).toLowerCase(); const bookPath = resolve(booksDir, `${safeName}.txt`);
let bookContent = `## Techniques from ${projectName} — ${category}\n\n`; for (const tech of techs.slice(0, 100)) { // cap per category bookContent += `### ${tech.heading}\n`; if (tech.description) bookContent += `${tech.description}\n\n`; if (tech.code) { bookContent += `\`\`\`${tech.language}\n${tech.code}\n\`\`\`\n\n`; } } fs.writeFileSync(bookPath, bookContent, "utf-8"); result.bookFiles.push(bookPath); result.categories[category] = techs.length;
// Also save a knowledge entry const knowledgeEntry = { tags: ["auto-learned", "technique", projectName, category], content: `Learned ${techs.length} techniques from ${projectName}/${category}. Saved to ${safeName}.txt. Categories: ${[...new Set(techs.map(t => t.heading))].slice(0, 10).join(", ")}`, created: new Date().toISOString(), }; const kfPath = resolve(knowledgeDir, `technique_${safeName}.json`); fs.writeFileSync(kfPath, JSON.stringify(knowledgeEntry, null, 2), "utf-8"); }
return result;}
// ── 5. CODE GENERATOR ─────────────────────────────────────// Generate new Phantom code based on gaps and learned patterns.
/** * Generate a new tool wrapper for Phantom. * Takes a gap description and produces { filePath, code } */export function generateTool(feature, description) { const toolName = camelCase(feature); const ext = ".mjs";
const code = `// Auto-generated tool: ${toolName}// Source: Learned from "${feature}" — ${description}// Generated by Phantom self-improvement engine
export default async function(input) { try { const { execSync } = await import("child_process"); const { resolve } = await import("path"); const args = (input || "").trim(); if (!args) { return \`[${toolName}] Usage: @${toolName}|<args>Feature: ${description}Examples: ${toolName}|--help ${toolName}|<target>\`; } const result = execSync(\`${toolName} \${args}\`, { encoding: "utf-8", timeout: 60000, maxBuffer: 1024 * 1024, }); return result.trim() || "(no output)"; } catch (e) { return \`[${toolName} Error] \${e.stderr?.slice(0, 500) || e.message}\`; }}`;
ensureDir(GENERATED_DIR); const filePath = resolve(GENERATED_DIR, `${toolName}${ext}`); fs.writeFileSync(filePath, code, "utf-8");
return { filePath, toolName, code };}
/** * Generate a full new module based on a gap analysis result. * Can generate: tool wrappers, utility modules, feature modules, middleware */export function generateModule(gap, patterns) { const category = gap.category; const feature = gap.feature;
switch (gap.suggestedApproach) { case "generate_wrapper": return generateTool(feature, gap.description);
case "generate_module": { return generateFeatureModule(feature, gap.description, patterns); }
case "learn_pattern": return { note: `Pattern learning queued for ${feature}`, filePath: null };
default: return { note: `No generator for ${feature} (${gap.suggestedApproach})`, filePath: null }; }}
/** * Generate a new feature module (e.g., websocket client, database layer). */function generateFeatureModule(feature, description, patterns) { const moduleName = camelCase(feature); const ext = ".mjs"; const toolStyle = patterns?.toolInterface === "async_no_param" ? "async ()" : "async (input)";
// Generate appropriate module based on feature type let code = "";
switch (feature) { case "websocket": code = generateWebSocketModule(moduleName, description); break; case "database": code = generateDatabaseModule(moduleName, description); break; case "plugin_system": code = generatePluginModule(moduleName, description); break; case "graphql": code = generateGraphQLModule(moduleName, description); break; case "sse": code = generateSSEModule(moduleName, description); break; case "streaming": code = generateStreamingModule(moduleName, description); break; case "auth": code = generateAuthModule(moduleName, description); break; case "cache": code = generateCacheModule(moduleName, description); break; case "ipc": code = generateIPCModule(moduleName, description); break; default: // Generic module template code = `// Auto-generated module: ${moduleName}// Feature: ${feature} — ${description}// Generated by Phantom self-improvement engine
/** * ${description} * @param {string} input - Command/query input * @returns {Promise<string>} Formatted result */export default ${toolStyle} { try { const args = (input || "").trim(); if (!args) { return \`[${moduleName}] Usage: @${moduleName}|<args>Feature: ${description}This module was auto-generated from pattern analysis.Examples: ${moduleName}|--help\`; }
// TODO: Implement ${feature} logic // This module was auto-generated as a placeholder from gap analysis return \`[${moduleName}] Module scaffold generated for: \${args}Feature "${feature}" requires implementation.Pattern source: ${description}\`; } catch (e) { return \`[${moduleName} Error] \${e.message}\`; }};`; break; }
ensureDir(GENERATED_DIR); const filePath = resolve(GENERATED_DIR, `${moduleName}${ext}`); fs.writeFileSync(filePath, code, "utf-8");
return { filePath, moduleName, code };}
function generateWebSocketModule(name, description) { return `// Auto-generated module: ${name}// Feature: WebSocket client for real-time communication// Generated by Phantom self-improvement engine
/** * WebSocket client tool. * Usage: @${name}|<url> [--send=<message>] [--listen=<timeout_ms>] */export default async function(input) { try { const args = (input || "").trim(); if (!args) { return \`[${name}] WebSocket ClientUsage: @${name}|<url> [--send=<message>]Examples: ${name}|wss://echo.websocket.org --send=hello ${name}|wss://stream.binance.com:9443/ws/btcusdt --listen=5000
Sends an optional message and prints responses.Requires Node.js native WebSocket (Node 22+) or 'ws' package.\`; }
const urlMatch = args.match(/https?:\\/\\/[^\\s]+|wss?:\\/\\/[^\\s]+/); if (!urlMatch) return \`[${name}] No WebSocket URL found in: \${args}\`;
const url = urlMatch[0]; const sendMatch = args.match(/--send=([^\\s]+)/); const listenMatch = args.match(/--listen=(\\d+)/); const listenMs = listenMatch ? parseInt(listenMatch[1]) : 3000;
// Try native WebSocket (Node 22+) if (typeof WebSocket !== "undefined") { return await new Promise((resolve, reject) => { const ws = new WebSocket(url); const messages = []; const timeout = setTimeout(() => { ws.close(); if (messages.length === 0) resolve(\`[${name}] Connected to \${url} (no messages in \${listenMs}ms)\`); else resolve(\`[${name}] \${url}\\nMessages (\${messages.length}):\\n\${messages.join("\\n")}\`); }, listenMs);
ws.onopen = () => { if (sendMatch) ws.send(sendMatch[1]); }; ws.onmessage = (event) => { try { const parsed = JSON.parse(event.data); messages.push(typeof parsed === "object" ? JSON.stringify(parsed, null, 2).slice(0, 500) : event.data); } catch { messages.push(event.data.slice(0, 500)); } }; ws.onerror = (err) => { clearTimeout(timeout); resolve(\`[${name} Error] \${err.message || "Connection failed"}\`); }; ws.onclose = () => clearTimeout(timeout); }); }
return \`[${name}] WebSocket not available in this Node.js version. Install 'ws' package or upgrade to Node 22+.\`; } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateDatabaseModule(name, description) { return `// Auto-generated module: ${name}// Feature: Database integration (SQLite)// Generated by Phantom self-improvement engine
import { execSync } from "child_process";import { resolve } from "path";
/** * SQLite database query tool. * Usage: @${name}|<path>|<query> * Uses sqlite3 CLI. Install: apt install sqlite3 */export default async function(input) { try { const parts = (input || "").split("|").map(s => s.trim()); if (parts.length < 2) { return \`[${name}] SQLite Database ToolUsage: @${name}|<db_path>|<sql_query>Examples: ${name}|test.db|SELECT * FROM users LIMIT 10; ${name}|/tmp/data.db|.tables ${name}|--tables|test.db List tables
Requires: sqlite3 CLI (apt install sqlite3)\`; }
const dbPath = parts[0]; const query = parts.slice(1).join("|");
// Check sqlite3 availability try { execSync("which sqlite3", { encoding: "utf-8", timeout: 3000 }); } catch { return \`[${name}] sqlite3 not found. Install: apt install sqlite3\`; }
const escapedQuery = query.replace(/'/g, "'\\\\''"); const result = execSync(\`sqlite3 -header -column "\${dbPath}" '\${escapedQuery}'\`, { encoding: "utf-8", timeout: 30000, maxBuffer: 1024 * 1024, }).trim();
return result || "(empty result)"; } catch (e) { return \`[${name} Error] \${e.stderr?.slice(0, 500) || e.message}\`; }};`;}
function generatePluginModule(name, description) { return `// Auto-generated module: ${name}// Feature: Hot-loadable plugin system for Phantom// Generated by Phantom self-improvement engine
import fs from "fs";import { resolve } from "path";import { homedir } from "os";
const PLUGIN_DIRS = [ resolve(homedir(), ".config", "phantom", "plugins"), resolve(homedir(), "Phantom", "plugins"),];
/** * Plugin system — load, list, enable, disable plugins at runtime. * Usage: @${name}|list * @${name}|load|<path> * @${name}|enable|<name> * @${name}|disable|<name> */export default async function(input) { try { const args = (input || "").trim().split("|").map(s => s.trim()); const command = args[0] || "";
if (!command || command === "--help") { return \`[${name}] Plugin SystemCommands: @${name}|list List registered plugins @${name}|load|<path> Load a plugin from file @${name}|enable|<name> Enable a plugin @${name}|disable|<name> Disable a plugin @${name}|reload Reload all plugins @${name}|scan Scan PLUGIN_DIRS for plugins\`; }
// Ensure plugin dirs exist for (const d of PLUGIN_DIRS) { if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true }); }
const registryPath = resolve(PLUGIN_DIRS[0], "registry.json"); let registry = { enabled: {}, disabled: {}, manifest: {} }; try { if (fs.existsSync(registryPath)) registry = JSON.parse(fs.readFileSync(registryPath, "utf-8")); } catch {}
switch (command) { case "list": { const enabled = Object.keys(registry.enabled); const disabled = Object.keys(registry.disabled); const lines = [\`[${name}] Plugin Registry (\${enabled.length} enabled, \${disabled.length} disabled)\`]; for (const p of enabled) { const info = registry.manifest[p] || {}; lines.push(\` ✅ \${p} — \${info.description || "no description"}\`); } for (const p of disabled) { const info = registry.manifest[p] || {}; lines.push(\` ⏸ \${p} — \${info.description || "no description"} [disabled]\`); } if (!enabled.length && !disabled.length) lines.push(" (no plugins registered)"); return lines.join("\\n"); }
case "load": { const pluginPath = args[1]; if (!pluginPath) return \`[${name}] Usage: @${name}|load|<path>\`; if (!fs.existsSync(pluginPath)) return \`[${name}] Plugin not found: \${pluginPath}\`; try { const mod = await import(resolve(pluginPath) + \`?t=\${Date.now()}\`); const name = mod.name || basename(pluginPath).replace(/\\.mjs$/, ""); const description = mod.description || ""; const version = mod.version || "1.0.0"; registry.enabled[name] = { path: pluginPath, loaded: new Date().toISOString(), version }; registry.manifest[name] = { description, version, path: pluginPath }; fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] ✅ Loaded plugin: \${name} v\${version}\`; } catch (e) { return \`[${name}] Failed to load plugin: \${e.message}\`; } }
case "enable": { const pname = args[1]; if (!pname || !registry.disabled[pname]) return \`[${name}] Plugin not found in disabled list: \${pname}\`; registry.enabled[pname] = registry.disabled[pname]; delete registry.disabled[pname]; fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] ✅ Enabled plugin: \${pname}\`; }
case "disable": { const dname = args[1]; if (!dname || !registry.enabled[dname]) return \`[${name}] Plugin not found in enabled list: \${dname}\`; registry.disabled[dname] = registry.enabled[dname]; delete registry.enabled[dname]; fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] ⏸ Disabled plugin: \${dname}\`; }
case "scan": { let found = 0; for (const dir of PLUGIN_DIRS) { if (!fs.existsSync(dir)) continue; const files = fs.readdirSync(dir).filter(f => f.endsWith(".mjs")); for (const file of files) { const fullPath = resolve(dir, file); if (!registry.enabled[file.replace(/\\.mjs$/, "")]) { try { const mod = await import(fullPath + \`?t=\${Date.now()}\`); const pname = mod.name || file.replace(/\\.mjs$/, ""); registry.enabled[pname] = { path: fullPath, loaded: new Date().toISOString(), version: mod.version || "1.0.0" }; registry.manifest[pname] = { description: mod.description || "", version: mod.version || "1.0.0", path: fullPath }; found++; } catch {} } } } fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] Scan complete: loaded \${found} new plugin(s)\`; }
default: return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; } } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateGraphQLModule(name, description) { return `// Auto-generated module: ${name}// Feature: GraphQL queries and introspection// Generated by Phantom self-improvement engine
/** * GraphQL query tool. * Usage: @${name}|<endpoint>|<query> [--variables=<json>] */export default async function(input) { try { const args = (input || "").trim(); if (!args) { return \`[${name}] GraphQL ClientUsage: @${name}|<url>|<query> [--variables=<json>]Examples: ${name}|https://api.example.com/graphql|{ __schema { types { name } } } ${name}|https://api.github.com/graphql|query{viewer{login}} --variables={}
Sends a GraphQL query to the endpoint and returns the response.\`; }
const parts = args.split("|"); let url = parts[0]?.trim(); let query = parts.slice(1).join("|").trim();
// Extract --variables const varMatch = query.match(/--variables=(\\{[^}]+\\})/); const variables = varMatch ? JSON.parse(varMatch[1]) : {}; query = query.replace(/--variables=\\{[^}]+\\}/, "").trim();
if (!url || !query) return \`[${name}] Usage: @${name}|<endpoint>|<query>\`;
const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "Phantom/1.0" }, body: JSON.stringify({ query, variables }), signal: AbortSignal.timeout(15000), });
const data = await response.json(); const formatted = JSON.stringify(data, null, 2); return formatted.slice(0, 8000); } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateSSEModule(name, description) { return `// Auto-generated module: ${name}// Feature: Server-Sent Events streaming// Generated by Phantom self-improvement engine
/** * SSE (Server-Sent Events) stream reader. * Usage: @${name}|<url> [--events=<count>] [--timeout=<ms>] */export default async function(input) { try { const args = (input || "").trim(); if (!args) { return \`[${name}] SSE Stream ReaderUsage: @${name}|<url> [--events=5] [--timeout=10000]Examples: ${name}|https://api.example.com/events --events=3 ${name}|https://stream.example.com/data --timeout=5000
Connects to an SSE endpoint and captures events.Outputs event data as they arrive.\`; }
const urlMatch = args.match(/https?:\\/\\/[^\\s]+/); if (!urlMatch) return \`[${name}] No URL found in: \${args}\`;
const url = urlMatch[0]; const eventMatch = args.match(/--events=(\\d+)/); const timeoutMatch = args.match(/--timeout=(\\d+)/); const maxEvents = eventMatch ? parseInt(eventMatch[1]) : 10; const timeoutMs = timeoutMatch ? parseInt(timeoutMatch[1]) : 10000;
const response = await fetch(url, { headers: { Accept: "text/event-stream", "User-Agent": "Phantom/1.0" }, signal: AbortSignal.timeout(timeoutMs), });
if (!response.ok) return \`[${name}] HTTP \${response.status} from \${url}\`; if (!response.body) return \`[${name}] No response body\`;
const reader = response.body.getReader(); const decoder = new TextDecoder(); const events = []; let buffer = "";
while (events.length < maxEvents) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\\n"); buffer = lines.pop() || "";
for (const line of lines) { if (line.startsWith("data: ")) { events.push(line.slice(6)); } else if (line.startsWith("event: ")) { // track event type if needed } } }
if (events.length === 0) return \`[${name}] Connected to \${url} (no events received)\`; return \`[${name}] \${url} — \${events.length} events\\n\${events.slice(0, maxEvents).join("\\n")}\`; } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateStreamingModule(name, description) { return `// Auto-generated module: ${name}// Feature: Stream processing for large data// Generated by Phantom self-improvement engine
import { createReadStream, createWriteStream, existsSync } from "fs";import { resolve } from "path";import { Transform } from "stream";
/** * Stream processing tool — process large files line-by-line. * Usage: @${name}|<input>|<transform> [--output=<path>] * Transforms: upper, lower, reverse, base64, count, grep:<pattern> */export default async function(input) { try { const args = (input || "").trim(); if (!args) { return \`[${name}] Stream ProcessorProcess large files line-by-line without loading into memory.Usage: @${name}|<file>|<transform> [--output=<outfile>]Transforms: upper Convert to uppercase lower Convert to lowercase reverse Reverse each line base64 Base64 encode each line count Count lines/words/bytes grep:<pat> Filter lines matching pattern sed:s/find/replace Search and replace
Examples: ${name}|large.log|grep:ERROR --output=errors.log ${name}|data.txt|upper ${name}|bigfile.csv|count\`; }
const parts = args.split("|").map(s => s.trim()); const inputPath = parts[0] ? resolve(parts[0]) : null; const transform = parts[1] || ""; const outMatch = args.match(/--output=([^\\s]+)/); const outputPath = outMatch ? resolve(outMatch[1]) : null;
if (!inputPath || !existsSync(inputPath)) return \`[${name}] Input file not found: \${parts[0]}\`; if (!transform) return \`[${name}] No transform specified\`;
const stat = existsSync(inputPath); const size = stat ? fs.statSync(inputPath).size : 0;
// Simple counter mode if (transform === "count") { return new Promise((resolvePromise) => { let lines = 0, words = 0, bytes = 0; const rs = createReadStream(inputPath, { encoding: "utf-8" }); rs.on("data", chunk => { bytes += Buffer.byteLength(chunk, "utf-8"); lines += (chunk.match(/\\n/g) || []).length; words += chunk.split(/\\s+/).filter(Boolean).length; }); rs.on("end", () => resolvePromise(\`[${name}] \${inputPath}\\n Lines: \${lines}\\n Words: \${words}\\n Bytes: \${bytes}\\n Size: \${(size / 1024).toFixed(1)} KB\`)); rs.on("error", e => resolvePromise(\`[${name} Error] \${e.message}\`)); }); }
// Line-by-line transform mode return new Promise((resolvePromise) => { const outputs = []; const rs = createReadStream(inputPath, { encoding: "utf-8" }); const rl = require("readline").createInterface({ input: rs });
rl.on("line", line => { let result = line; switch (transform) { case "upper": result = line.toUpperCase(); break; case "lower": result = line.toLowerCase(); break; case "reverse": result = line.split("").reverse().join(""); break; case "base64": result = Buffer.from(line, "utf-8").toString("base64"); break; default: if (transform.startsWith("grep:")) { const pat = transform.slice(5); if (!line.includes(pat) && !new RegExp(pat).test(line)) return; } else if (transform.startsWith("sed:")) { const m = transform.match(/^sed:(.+?)\\/(.+?)\\/(.*)$/); if (m) result = line.replace(new RegExp(m[1], "g"), m[2]); } } outputs.push(result); });
rl.on("close", () => { const text = outputs.join("\\n"); if (outputPath) { fs.writeFileSync(outputPath, text, "utf-8"); resolvePromise(\`[${name}] Processed \${outputs.length} lines → \${outputPath} (\${text.length} chars)\`); } else { const preview = text.slice(0, 3000); const truncated = text.length > 3000 ? \`\\n... (truncated, \${text.length} total chars)\` : ""; resolvePromise(\`[${name}] \${inputPath} → \${outputs.length} lines\\n\${preview}\${truncated}\`); } });
rl.on("error", e => resolvePromise(\`[${name} Error] \${e.message}\`)); }); } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateAuthModule(name, description) { return `// Auto-generated module: ${name}// Feature: Authentication/Authorization tools// Generated by Phantom self-improvement engine
import { createHash, randomBytes } from "crypto";
/** * Auth tools — JWT decode, hash verify, token analysis. * Usage: @${name}|decode|<jwt_token> * @${name}|hash|<password> [--algorithm=<sha256|sha512|md5>] * @${name}|random|<length> */export default async function(input) { try { const args = (input || "").trim(); if (!args) { return \`[${name}] Authentication ToolsUsage: @${name}|decode|<jwt_token> Decode a JWT (no signature verify) @${name}|hash|<password> Hash a password (default: sha256) @${name}|hash|<password> --algo=sha512 @${name}|random|32 Generate random hex string (N bytes) @${name}|basic|user:pass Encode Basic auth header
Examples: ${name}|decode|eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHx0I ${name}|hash|mypassword --algo=sha512 ${name}|random|16\`; }
const parts = args.split("|").map(s => s.trim()); const command = parts[0]; const data = parts.slice(1).join("|");
switch (command) { case "decode": { const token = data; if (!token || !token.includes(".")) return \`[${name}] Invalid JWT format\`; const segments = token.split("."); if (segments.length < 2) return \`[${name}] Invalid JWT format\`; const decode = (s) => { try { return JSON.parse(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf-8")); } catch { return { error: "Cannot decode" }; } }; const header = decode(segments[0]); const payload = decode(segments[1]); const lines = [ \`[${name}] JWT Decoded\`, \`── Header ──\`, JSON.stringify(header, null, 2), \`── Payload ──\`, JSON.stringify(payload, null, 2), ]; if (segments[2]) lines.push(\`── Signature ──\${segments[2].slice(0, 32)}...\`); return lines.join("\\n"); }
case "hash": { const algoMatch = args.match(/--algo=(\\w+)/); const algo = algoMatch ? algoMatch[1] : "sha256"; if (!["sha256", "sha512", "md5", "sha1"].includes(algo)) return \`[${name}] Unsupported algorithm: \${algo}. Use sha256, sha512, md5, or sha1.\`; const hash = createHash(algo).update(data).digest("hex"); return \`[${name}] \${algo} hash of "\${data.slice(0, 50)}":\n\${hash}\`; }
case "random": { const len = parseInt(data) || 16; const hex = randomBytes(Math.ceil(len / 2)).toString("hex").slice(0, len); return \`[${name}] Random hex (\${len} chars): \${hex}\`; }
case "basic": { // Encode Basic auth header value const encoded = Buffer.from(data).toString("base64"); return \`[${name}] Basic Auth:\n Header: Authorization: Basic \${encoded}\n Value: \${data}\`; }
default: return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; } } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateCacheModule(name, description) { return `// Auto-generated module: ${name}// Feature: Caching layer for tool outputs// Generated by Phantom self-improvement engine
import fs from "fs";import { resolve } from "path";import { homedir } from "os";import { createHash } from "crypto";
const CACHE_DIR = resolve(homedir(), ".config", "phantom", "cache");const DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes
/** * Cache layer — store and retrieve cached tool outputs. * Usage: @${name}|get|<key> * @${name}|set|<key>|<value> [--ttl=<ms>] * @${name}|del|<key> * @${name}|clear * @${name}|stats */export default async function(input) { try { if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });
const args = (input || "").trim();
if (!args) { return \`[${name}] Cache SystemUsage: @${name}|get|<key> Get cached value @${name}|set|<key>|<value> Set cached value (default TTL: 5min) @${name}|del|<key> Delete cached entry @${name}|clear Clear entire cache @${name}|stats Show cache statistics
Used internally by Phantom to cache repeated tool outputs.\`; }
const cacheFile = resolve(CACHE_DIR, "registry.json"); let registry = {}; try { if (fs.existsSync(cacheFile)) registry = JSON.parse(fs.readFileSync(cacheFile, "utf-8")); } catch {}
const parts = args.split("|").map(s => s.trim()); const command = parts[0];
switch (command) { case "get": { const key = parts.slice(1).join("|"); if (!key) return \`[${name}] Usage: @${name}|get|<key>\`; const hashKey = createHash("md5").update(key).digest("hex"); const entry = registry[hashKey]; if (!entry) return \`[${name}] Cache miss for: \${key.slice(0, 60)}\`; if (Date.now() - entry.ts > (entry.ttl || DEFAULT_TTL)) { delete registry[hashKey]; fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] Cache expired for: \${key.slice(0, 60)}\`; } return \`[${name}] Cache hit for: \${key.slice(0, 60)}\\n\${entry.value.slice(0, 3000)}\`; }
case "set": { const separatorIdx = args.indexOf("|", args.indexOf("|") + 1); if (separatorIdx === -1) return \`[${name}] Usage: @${name}|set|<key>|<value>\`; const key = args.slice(4, separatorIdx).trim(); const value = args.slice(separatorIdx + 1).trim(); const ttlMatch = args.match(/--ttl=(\\d+)/); const ttl = ttlMatch ? parseInt(ttlMatch[1]) * 1000 : DEFAULT_TTL; const hashKey = createHash("md5").update(key).digest("hex"); registry[hashKey] = { key, ts: Date.now(), ttl, length: value.length }; if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true }); fs.writeFileSync(resolve(CACHE_DIR, \`\${hashKey}.cache\`), value, "utf-8"); fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] Cached (\${value.length} chars, TTL: \${ttl / 1000}s)\`; }
case "del": { const dkey = parts.slice(1).join("|"); const dhash = createHash("md5").update(dkey).digest("hex"); if (registry[dhash]) { delete registry[dhash]; const cachePath = resolve(CACHE_DIR, \`\${dhash}.cache\`); if (fs.existsSync(cachePath)) fs.unlinkSync(cachePath); fs.writeFileSync(cacheFile, JSON.stringify(registry, null, 2), "utf-8"); return \`[${name}] Deleted: \${dkey.slice(0, 60)}\`; } return \`[${name}] Not found: \${dkey.slice(0, 60)}\`; }
case "clear": { const count = Object.keys(registry).length; if (fs.existsSync(CACHE_DIR)) { const files = fs.readdirSync(CACHE_DIR); for (const f of files) fs.unlinkSync(resolve(CACHE_DIR, f)); } fs.writeFileSync(cacheFile, "{}", "utf-8"); return \`[${name}] Cache cleared (\${count} entries removed)\`; }
case "stats": { const count = Object.keys(registry).length; let totalSize = 0, validEntries = 0, expiredEntries = 0; for (const [k, v] of Object.entries(registry)) { const cachePath = resolve(CACHE_DIR, \`\${k}.cache\`); if (fs.existsSync(cachePath)) totalSize += fs.statSync(cachePath).size; if (Date.now() - v.ts > (v.ttl || DEFAULT_TTL)) expiredEntries++; else validEntries++; } return \`[${name}] Cache Stats: Total entries: \${count} Valid: \${validEntries} Expired: \${expiredEntries} Disk size: \${(totalSize / 1024).toFixed(1)} KB Cache dir: \${CACHE_DIR}\`; }
default: return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; } } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
function generateIPCModule(name, description) { return `// Auto-generated module: ${name}// Feature: Inter-process communication utilities// Generated by Phantom self-improvement engine
import { spawn, execSync } from "child_process";import { existsSync } from "fs";import { isMainThread, parentPort, Worker } from "worker_threads";
/** * IPC tools — spawn processes, communicate via workers. * Usage: @${name}|exec|<command> * @${name}|bg|<command> Start background process * @${name}|ps List child processes */export default async function(input) { try { const args = (input || "").trim();
if (!args) { return \`[${name}] IPC UtilitiesUsage: @${name}|exec|<command> Execute and capture output @${name}|bg|<command> Start background process @${name}|ps List Phantom child processes
For multi-process coordination and long-running tasks.\`; }
const parts = args.split("|").map(s => s.trim()); const command = parts[0]; const rest = parts.slice(1).join("|");
switch (command) { case "exec": { if (!rest) return \`[${name}] Usage: @${name}|exec|<shell command>\`; // Use shell for full command support const result = execSync(rest, { encoding: "utf-8", timeout: 60000, maxBuffer: 1024 * 1024, }); return \`[${name}] Executed:\n\${rest}\n── Output ──\n\${result.trim().slice(0, 4000) || "(empty)"}\`; }
case "bg": { if (!rest) return \`[${name}] Usage: @${name}|bg|<command>\`; const proc = spawn("sh", ["-c", rest], { stdio: ["ignore", "pipe", "pipe"], detached: true, }); let out = ""; proc.stdout.on("data", d => { out += d.toString(); }); proc.stderr.on("data", d => { out += d.toString(); }); // Don't await — let it run in background return \`[${name}] Started background process (PID: \${proc.pid})\nCommand: \${rest}\`; }
case "ps": { // List phantom-related processes const result = execSync("ps aux | grep -E 'node|phantom' | grep -v grep", { encoding: "utf-8", timeout: 5000, }).trim(); if (!result) return \`[${name}] No Phantom child processes found\`; const lines = result.split("\\n"); return \`[${name}] Child Processes (\${lines.length}):\n\${lines.join("\\n")}\`; }
default: return \`[${name}] Unknown command: \${command}. Use @${name}|--help for usage.\`; } } catch (e) { return \`[${name} Error] \${e.message}\`; }};`;}
// ── 6. FULL IMPROVEMENT CYCLE ──────────────────────────────
/** * Full self-improvement pipeline: * 1. Take a project URL/path * 2. Clone/scan it * 3. Analyze Phantom's own capabilities * 4. Gap analysis * 5. Pattern extraction * 6. Code generation for each gap * 7. Apply changes * 8. Test and commit * * Returns detailed results report. */export async function fullImprovementCycle(target) { const startTime = Date.now(); const report = { target, started: new Date().toISOString(), elapsed: null, project: null, selfAnalysis: null, gaps: [], generated: [], applied: [], errors: [], };
try { // Step 1: Clone/scan the project const project = cloneOrLocate(target); report.project = { name: project.name, path: project.path, isRemote: project.isRemote }; report.project.scan = scanProject(project.path);
// Step 2: Analyze self const self = analyzeSelf(); report.selfAnalysis = { tools: self.tools.length, exports: self.exports.length, architecture: self.architecture, featureCount: self.features.filter(f => f.present).length, };
// Step 3: Gap analysis const gaps = gapAnalysis(report.project.scan, self); report.gaps = gaps;
// Step 4: Extract patterns const patterns = extractPatterns(project.path); const patternPath = savePatterns(project.name, patterns); report.patternsSaved = patternPath;
// Step 5: Generate code for each gap (up to 8 per cycle) const maxGens = Math.min(gaps.length, 8); for (let i = 0; i < maxGens; i++) { try { const gap = gaps[i]; const generated = generateModule(gap, patterns); if (generated.filePath) { report.generated.push({ gap: gap.feature, file: generated.filePath, toolName: generated.toolName || generated.moduleName, }); } } catch (e) { report.errors.push({ phase: "generate", feature: gaps[i].feature, error: e.message }); } }
// Step 6: Validate generated code for (const gen of report.generated) { try { if (gen.file && fs.existsSync(gen.file)) { execSync(`node --check "${gen.file}"`, { encoding: "utf-8", timeout: 10000 }); report.applied.push({ file: gen.file, status: "valid" }); } } catch (e) { report.errors.push({ phase: "validate", file: gen.file, error: e.stderr?.slice(0, 200) || e.message }); } }
// Step 7: Auto-apply validated modules — copy to learned + register if (report.applied.length > 0) { try { const applyResults = autoApplyGenerated(); report.autoApplied = applyResults; } catch (e) { report.errors.push({ phase: "auto-apply", error: e.message }); } }
// Step 8: Check git_sync schedule — remind about pushes try { const st = loadState(); if (st?.gitSync?.nextPush && Date.now() >= st.gitSync.nextPush) { report.gitSyncDue = true; report.gitSyncNext = new Date(st.gitSync.nextPush).toISOString().slice(0, 10); } } catch {}
// Save full report to disk report.elapsed = Date.now() - startTime; const st = loadState(); st.self_improve.push({ target, ts: report.started, elapsed: report.elapsed, gaps: gaps.length, generated: report.generated.length, validated: report.applied.length, errors: report.errors.length, }); st.imported_features.push(...report.generated.map(g => g.toolName)); // Trim history if (st.self_improve.length > 20) st.self_improve = st.self_improve.slice(-20); if (st.imported_features.length > 100) st.imported_features = st.imported_features.slice(-100); saveState(st);
return report; } catch (e) { report.elapsed = Date.now() - startTime; report.errors.push({ phase: "overall", error: e.message }); const st = loadState(); st.self_improve.push({ target, ts: report.started, elapsed: report.elapsed, error: e.message }); saveState(st); return report; }}
/** * Quick self-scan: show what Phantom knows about itself and any pending gaps. */export function selfImproveStatus() { const st = loadState(); const self = analyzeSelf(); const patterns = loadAllPatterns(); const learnedModulesDir = GENERATED_DIR;
return { generation: st.generation, cyclesRun: st.self_improve?.length || 0, featuresImported: st.imported_features || [], patternsLearned: Object.keys(patterns), pendingImprovements: st.self_improve?.filter(s => s.error)?.length || 0, selfOverview: { tools: self.tools.length, exports: self.exports.length, features: self.features.filter(f => f.present).length, gaps: self.features.filter(f => !f.present).map(f => f.name), architecture: self.architecture, }, generatedFiles: (() => { if (!fs.existsSync(learnedModulesDir)) return []; return fs.readdirSync(learnedModulesDir).filter(f => f.endsWith(".mjs")); })(), };}
// ── Utility ───────────────────────────────────────────────
function camelCase(str) { return str .replace(/[^a-zA-Z0-9\s_-]/g, "") .replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : "") .replace(/^(.)/, (c) => c.toLowerCase());}
// ── 8. AUTO-APPLY — register generated modules at runtime ──// Copies generated → learned, then hot-loads into hackerTools
export function autoApplyGenerated() { const results = []; if (!fs.existsSync(GENERATED_DIR)) return results; const files = fs.readdirSync(GENERATED_DIR).filter(f => f.endsWith(".mjs")); ensureDir(LEARNED_MODULES_DIR);
for (const f of files) { const src = resolve(GENERATED_DIR, f); const dst = resolve(LEARNED_MODULES_DIR, f); const toolName = f.replace(/\.mjs$/, "");
// Validate before applying try { execSync(`node --check "${src}"`, { encoding: "utf-8", timeout: 10000 }); } catch (e) { results.push({ file: f, status: "syntax_error", error: e.stderr?.slice(0, 100) }); try { fs.unlinkSync(src); } catch {} continue; }
// Copy to learned fs.copyFileSync(src, dst); results.push({ file: f, status: "applied", toolName }); }
// Update evolution state const st = loadState(); st.generation++; st.last_evolve = new Date().toISOString(); saveState(st);
return results;}
// ── 10. SELF-EVOLVE — run improvement cycles against Phantom itself ──
export function analyzeSelfGaps() { const self = analyzeSelf(); const gaps = [];
// Architecture gaps if (!self.architecture.moduleCount) gaps.push({ area: "architecture", issue: "Module count unknown", priority: "low" });
// Check what Phantom might want from its own patterns const ownDir = PHANTOM_DIR; if (fs.existsSync(ownDir)) { const srcFiles = fs.readdirSync(ownDir).filter(f => f.endsWith(".mjs")); for (const f of srcFiles) { try { const content = fs.readFileSync(resolve(ownDir, f), "utf-8"); // Detect external tool mentions const extTools = content.match(/execSync\(`(\w+)/g); if (extTools) { for (const t of extTools) { const name = t.replace(/execSync\(`/, ""); if (!self.tools.includes(name)) { gaps.push({ area: "missing_wrapper", issue: name, priority: "medium", source: f }); } } } } catch {} } }
return gaps;}
export async function selfEvolve() { const startTime = Date.now(); const report = { target: "self", started: new Date().toISOString(), generated: [], applied: [], errors: [], };
try { // 1. Scan self const self = analyzeSelf(); report.selfTools = self.tools.length;
// 2. Find own gaps — detect external binaries referenced but not wrapped const gaps = analyzeSelfGaps(); report.gapsFound = gaps.length;
// 3. Generate wrappers for missing binaries for (const gap of gaps) { if (gap.area === "missing_wrapper") { try { const gen = generateTool(gap.issue, `Auto-detected missing wrapper from ${gap.source}`); if (gen.filePath) { report.generated.push({ tool: gap.issue, file: gen.filePath }); } } catch (e) { report.errors.push({ phase: "generate", tool: gap.issue, error: e.message }); } } }
// 4. Auto-apply any generated code if (report.generated.length > 0) { const applyResults = autoApplyGenerated(); report.applied = applyResults; }
// 5. Update state report.elapsed = Date.now() - startTime; const st = loadState(); st.self_improve.push({ target: "self", ts: report.started, elapsed: report.elapsed, gaps: gaps.length, generated: report.generated.length, applied: report.applied.length, errors: report.errors.length, }); saveState(st);
return report; } catch (e) { report.elapsed = Date.now() - startTime; report.errors.push({ phase: "overall", error: e.message }); return report; }}
// ── 11. CONTINUOUS EVOLUTION — schedule + health ──
export function scheduleAutoEvolve(intervalMs = 3600000) { // intervalMs = default 1 hour const st = loadState(); st.scheduledInterval = intervalMs; st.nextScheduledEvolve = Date.now() + intervalMs; saveState(st); return { ok: true, nextRun: new Date(st.nextScheduledEvolve).toISOString(), intervalMs };}
export function getScheduledEvolve() { const st = loadState(); if (!st.nextScheduledEvolve) return { scheduled: false }; return { scheduled: true, nextRun: new Date(st.nextScheduledEvolve).toISOString(), intervalMs: st.scheduledInterval, due: Date.now() >= st.nextScheduledEvolve, };}
export async function checkAndEvolve() { const sched = getScheduledEvolve(); if (!sched.due) return { skipped: "not due yet", nextRun: sched.nextRun }; return await selfEvolve();}
// ── 12. READ ANY FILE — for self-editing context ──
export function readSelfSource(filePath) { const fullPath = resolve(PHANTOM_DIR, filePath); try { const content = fs.readFileSync(fullPath, "utf-8"); const lines = content.split("\n"); return { path: fullPath, lines: lines.length, size: content.length, content: content.slice(0, 50000), truncated: content.length > 50000, }; } catch (e) { return { error: e.message }; }}
export function editSelfFile(filePath, oldString, newString) { const fullPath = resolve(PHANTOM_DIR, filePath); try { let content = fs.readFileSync(fullPath, "utf-8"); if (!content.includes(oldString)) { return { ok: false, error: "old_string not found in file" }; } content = content.replace(oldString, newString); fs.writeFileSync(fullPath, content, "utf-8"); return { ok: true, path: fullPath }; } catch (e) { return { ok: false, error: e.message }; }}
// ── 13. MULTI-LANGUAGE SCANNERS (Rust, Ruby, Java, C/C++, Shell) ──
function analyzeRustFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return; result.patterns.moduleSystem = "rust";
// pub fn, pub async fn, fn (private), pub struct, pub enum, pub trait, impl blocks const exports = content.matchAll(/^\s*(?:pub(?:\s+async)?\s+)?fn\s+(\w+)\s*\(([^)]*)\)/gm); for (const m of exports) { const name = m[1]; const params = m[2].trim(); result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); const toolParams = ["query","target","url","domain","path","text","data","name","input","args","cmd","host","port","addr"]; if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); } // struct/enum/trait as exports for (const kw of ["struct", "enum", "trait"]) { const types = content.matchAll(new RegExp(`^\\s*pub\\s+${kw}\\s+(\\w+)`, "gm")); for (const m of types) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: kw }); } // Feature detection if (/(tokio|async_std|smol)/.test(content) && !result.features.includes("async")) result.features.push("async"); if (/(serde|serde_json|bincode)/.test(content) && !result.features.includes("serialization")) result.features.push("serialization"); if (/(reqwest|hyper|actix_web|warp|axum|rocket)/.test(content)) { result.patterns.hasHttpServer = true; result.features.push("http"); } if (/(clap|structopt|argh)/.test(content)) result.patterns.hasCli = true; if (/(rusqlite|diesel|sqlx|mongodb|redis)/.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(jsonwebtoken|oauth2|bcrypt|argon2)/.test(content) && !result.features.includes("auth")) result.features.push("auth"); if (/(tungstenite|tokio_tungstenite|socket2)/.test(content) && !result.features.includes("websocket")) result.features.push("websocket"); if (/(lru_cache|moka|cached)/.test(content) && !result.features.includes("cache")) result.features.push("cache");}
function analyzeRubyFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return; result.patterns.moduleSystem = "ruby"; const funcs = content.matchAll(/^\s*(?:def\s+(?:self\.)?(\w+)|def\s+(\w+))/gm); for (const m of funcs) { const name = m[1] || m[2]; if (!name) continue; result.exports.push({ name, file: relative(result.path, fullPath) }); result.tools.push({ name, param: "input", file: relative(result.path, fullPath) }); } const classes = content.matchAll(/^\s*class\s+(\w+)/gm); for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); const modules = content.matchAll(/^\s*module\s+(\w+)/gm); for (const m of modules) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "module" }); // Feature detection if (/(sinatra|rails|rack)/.test(content)) result.patterns.hasHttpServer = true; if (/(thor|rake|optionparser)/.test(content)) result.patterns.hasCli = true; if (/require\s+['\"]?(net\/http|httparty|faraday|rest-client)/.test(content)) result.features.push("http"); if (/(sequel|activerecord|mongoid|redis)/.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(jwt|devise|bcrypt|omniauth)/.test(content) && !result.features.includes("auth")) result.features.push("auth");}
function analyzeJavaFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return; result.patterns.moduleSystem = "java"; const methods = content.matchAll(/^\s*(?:public\s+)?(?:static\s+)?(?:\w+)\s+(\w+)\s*\(([^)]*)\)\s*(?:throws\s+\w+)?\s*\{/gm); for (const m of methods) { const name = m[1]; const params = m[2].trim(); result.exports.push({ name, file: relative(result.path, fullPath), type: "method" }); const toolParams = ["query","target","url","domain","path","text","data","name","input","args","cmd","host","port"]; if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); } const classes = content.matchAll(/^\s*(?:public\s+)?(?:abstract\s+)?(?:class|interface|enum)\s+(\w+)/gm); for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); // Feature detection if (/(spring|jakarta\.ws|javax\.ws|rest|@RestController)/.test(content)) result.patterns.hasHttpServer = true; if (/(jdbc|hibernate|jpa|mybatis|mongo)/.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(jwt|spring-security|oauth|bcrypt)/.test(content) && !result.features.includes("auth")) result.features.push("auth"); if (/(okhttp|httpclient|unirest)/.test(content)) result.features.push("http"); if (/(slf4j|log4j|java\.util\.logging)/.test(content) && !result.features.includes("logging")) result.features.push("logging");}
function analyzeCppFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return; result.patterns.moduleSystem = "cpp"; // Function declarations (returnType functionName(params) | auto functionName(params) ->) const funcs = content.matchAll(/(?:^\s*(?:\w+[:\*&\s]+)+(\w+)\s*\(([^)]*)\)\s*(?:const|override|noexcept|throw)?\s*\{|^\s*auto\s+(\w+)\s*\(([^)]*)\))/gm); for (const m of funcs) { const name = m[1] || m[3]; const params = (m[2] || m[4] || "").trim(); if (!name || name === "if" || name === "while" || name === "for") continue; result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); const toolParams = ["query","target","url","path","data","name","input","args","host","port"]; if (toolParams.some(p => params.includes(p))) result.tools.push({ name, param: (params.split(",")[0]||"input").trim(), file: relative(result.path, fullPath) }); } const classes = content.matchAll(/^\s*(?:class|struct)\s+(\w+)/gm); for (const m of classes) result.exports.push({ name: m[1], file: relative(result.path, fullPath), type: "class" }); // Feature detection if (/(boost\.asio|poco|libcurl|cpr)/.test(content)) result.features.push("http"); if (/(sqlite3|libpq|mysqlclient|soci|redis-plus-plus)/.test(content) && !result.features.includes("database")) result.features.push("database"); if (/(openssl|ssl|jwt)/.test(content) && !result.features.includes("auth")) result.features.push("auth"); if (/(nlohmann\/json|rapidjson|jsoncpp)/.test(content) && !result.features.includes("serialization")) result.features.push("serialization"); if (/(spdlog|glog|boost\.log)/.test(content) && !result.features.includes("logging")) result.features.push("logging");}
function analyzeShellFile(fullPath, result) { const content = safeReadFile(fullPath); if (!content) return; result.patterns.moduleSystem = "shell"; const funcs = content.matchAll(/^\s*(?:function\s+)?(\w+)\s*\(\s*\)\s*\{/gm); for (const m of funcs) { const name = m[1]; if (name === "if" || name === "while" || name === "for" || name === "case") continue; result.exports.push({ name, file: relative(result.path, fullPath), type: "fn" }); result.tools.push({ name, param: "input", file: relative(result.path, fullPath) }); } // Detect curl/wget usage as features if (/curl\s/.test(content) && !result.features.includes("http")) result.features.push("http"); if (/(jq|grep|sed|awk)/.test(content) && !result.features.includes("text-processing")) result.features.push("text-processing"); if (/(docker|kubectl|podman)/.test(content) && !result.features.includes("container")) result.features.push("container");}
// ── 14. LEARN FROM EXTERNAL SOURCES ──
const LEARN_CACHE = resolve(BASE_DIR, "learn_cache");const GH_SEARCH = "https://api.github.com/search/repositories?q=";
function saveLearnedTopic(topic, results) { const st = loadState(); if (!st.learned_topics) st.learned_topics = {}; st.learned_topics[topic.toLowerCase()] = { ts: new Date().toISOString(), repos: results.repos, exports: results.exports, features: results.features, patterns: results.patterns, }; saveState(st);}
function getLearnedTopics() { const st = loadState(); return st.learned_topics || {};}
/** * Search GitHub for repos by topic, clone top N, scan them, extract patterns. */export async function learnTopic(topic, maxRepos = 3) { const already = getLearnedTopics(); const key = topic.toLowerCase().trim(); if (already[key]) { return { cached: true, topic, ts: already[key].ts, repos: already[key].repos, exports: already[key].exports }; }
const tempDir = resolve(LEARN_CACHE, key.replace(/[^a-z0-9_-]/g, "_")); fs.mkdirSync(tempDir, { recursive: true });
// Search GitHub let repos = []; try { const searchUrl = `${GH_SEARCH}${encodeURIComponent(topic)}&sort=stars&per_page=${maxRepos}`; const raw = execSync(`curl -s "${searchUrl}"`, { encoding: "utf-8", timeout: 15000 }); const data = JSON.parse(raw); if (data.items) { repos = data.items.slice(0, maxRepos).map(r => ({ name: r.full_name, url: r.clone_url, stars: r.stargazers_count, desc: r.description })); } } catch {} if (!repos.length) return { error: `No GitHub repos found for "${topic}"`, topic };
const results = { repos, exports: [], features: [], patterns: {} }; const aggregated = { exports: [], features: [], tools: [], path: tempDir, patterns: {} };
for (const repo of repos) { const repoDir = resolve(tempDir, repo.name.replace("/", "_")); try { execSync(`git clone --depth 1 "${repo.url}" "${repoDir}" 2>/dev/null`, { timeout: 60000 }); deepScan(repoDir, aggregated); // Merge features/categories into results results.exports.push(...aggregated.exports.slice(0, 20)); for (const f of aggregated.features) { if (!results.features.includes(f)) results.features.push(f); } Object.assign(results.patterns, aggregated.patterns); } catch { continue; } // skip failed clones }
// Cleanup cloned repos to save disk try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
saveLearnedTopic(key, results); return { cached: false, topic, repos: results.repos, exports: results.exports.slice(0, 30), features: results.features, patterns: results.patterns };}
/** * Learn from a single GitHub repo URL — clone and scan. */export async function learnFromRepo(url) { const match = url.match(/github\.com[:/]([^/]+\/[^/.]+)/); const name = match ? match[1].replace("/", "_") : `repo_${Date.now()}`; const tempDir = resolve(LEARN_CACHE, name); fs.mkdirSync(LEARN_CACHE, { recursive: true }); try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
const result = { exports: [], features: [], tools: [], patterns: {} }; try { execSync(`git clone --depth 1 "${url}" "${tempDir}"`, { timeout: 120000 }); // Read README/doc files for context const readmeFiles = ["README.md", "README.rst", "README.txt", "README", "docs/index.md", "docs/README.md"]; for (const rf of readmeFiles) { const rp = resolve(tempDir, rf); if (fs.existsSync(rp)) { try { const content = fs.readFileSync(rp, "utf-8").slice(0, 8000); const title = (content.match(/^#\s+(.+)/m) || [])[1] || rf; result.readme = { title, content, source: rf }; // Extract key sections const sections = content.match(/^##\s+(.+)$/gm) || []; result.readme.sections = sections.map(s => s.replace(/^##\s+/, "")); break; } catch {} } } deepScan(tempDir, result); try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} return { url, readme: result.readme || null, exports: result.exports.slice(0, 30), features: result.features, toolsFound: result.tools.length, patterns: result.patterns }; } catch (e) { return { error: `Failed to clone/scan: ${e.message.slice(0, 200)}`, url }; }}
/** * Identify gaps in Phantom's tool coverage and learn them from GitHub. * Analyzes current tool names/categories, finds missing domains, fetches code. */export async function learnGaps() { const knownDomains = ["http","auth","database","cache","websocket","ipc","logging","dns","ssl","crypto","json","yaml","xml","csv","image","audio","video","compression","archive","docker","k8s","graphql","grpc","ssh","ftp","smtp","ldap","mqtt","serialization","async","container","text-processing"]; const st = loadState(); const learned = getLearnedTopics(); const ownFeatures = new Set(st.imported_features || []);
// Find missing domains const featureNames = new Set([...ownFeatures, ...Object.keys(learned)]); const missing = knownDomains.filter(d => !featureNames.has(d));
if (!missing.length) return { message: "All known domains covered. No gaps detected.", missing: [] };
const results = {}; for (const domain of missing.slice(0, 5)) { // learn top 5 gaps const res = await learnTopic(`${domain} cli tool`, 2); results[domain] = { repos: res.repos?.map(r => r.name) || [], exports: res.exports?.length || 0, features: res.features, cached: res.cached, }; }
return { message: `Learned ${Object.keys(results).length} new domains`, missing, results };}
/** * Fetch a URL and extract code patterns from the content. */export async function learnFromWeb(url) { try { const raw = execSync(`curl -sL "${url}"`, { encoding: "utf-8", timeout: 15000 }); // Treat as inline "project" with a single file const result = { exports: [], features: [], tools: [], patterns: {}, path: url }; // Try to detect language and analyze if (url.endsWith(".py") || url.includes("python")) analyzePythonFile(url, result); else if (url.endsWith(".rs") || url.includes("rust")) analyzeRustFile(url, result); else if (url.endsWith(".rb") || url.includes("ruby")) analyzeRubyFile(url, result); else if (url.endsWith(".java") || url.includes("java")) analyzeJavaFile(url, result); else if (/\.(c|cpp|h|hpp)$/i.test(url)) analyzeCppFile(url, result); else if (/\.(sh|bash)$/i.test(url)) analyzeShellFile(url, result);
// Fallback: extract code blocks from HTML/markdown if (!result.exports.length) { const codeBlocks = raw.match(/```(?:\w+)?\n([\s\S]*?)```/g); if (codeBlocks) { result.exports = codeBlocks.map((b, i) => ({ name: `code_block_${i + 1}`, source: "web", type: "snippet" })); result.features.push("code-snippet"); } // Extract links to other resources const links = raw.match(/https?:\/\/github\.com\/[^/\s]+\/[^/\s"')\]]+/g); if (links) { result.features.push(`found ${links.length} github links`); result.exports.push({ name: "github_links", count: links.length, samples: links.slice(0, 3) }); } }
return { url, exports: result.exports.slice(0, 20), features: result.features, snippets: result.exports.filter(e => e.type === "snippet").length }; } catch (e) { return { error: `Failed to fetch/parse: ${e.message.slice(0, 200)}`, url }; }}
// ── 15. EXTENDED PROJECT SCANNER with multi-language support ──
/** * Scan a project directory — enhanced to dispatch to language-specific analyzers. * Replaces the inline file-walker with proper dispatch for .rs, .rb, .java, .c, .cpp, .sh. */function scanFileEnhanced(fullPath, result) { const ext = extname(fullPath).toLowerCase(); const base = basename(fullPath).toLowerCase();
// Skip non-source and common ignorables if (/node_modules|\.git|__pycache__|target|build|vendor|dist|\.venv/.test(fullPath)) return; if (/\.(min\.|bundle|lock|sum|svg|png|jpg|gif|ico|woff2?|ttf|eot|pdf|zip|tar|gz|bz2|xz|exe|dll|so|dylib|bin|dat|pyc|pyo)$/.test(ext)) return; if (/^(package-lock|yarn\.lock|pnpm-lock|go\.sum|Cargo\.lock|Gemfile\.lock|poetry\.lock)/.test(base)) return;
// Dispatch by extension switch (ext) { case ".mjs": case ".js": case ".ts": analyzeJSFile(fullPath, result); break; case ".py": analyzePythonFile(fullPath, result); break; case ".go": analyzeGoFile(fullPath, result); break; case ".rs": analyzeRustFile(fullPath, result); break; case ".rb": analyzeRubyFile(fullPath, result); break; case ".java": analyzeJavaFile(fullPath, result); break; case ".c": case ".h": case ".cpp": case ".hpp": case ".cc": case ".cxx": analyzeCppFile(fullPath, result); break; case ".sh": case ".bash": case ".zsh": analyzeShellFile(fullPath, result); break; }}
/** * Walk a directory tree and scan all source files with multi-language support. */export function deepScan(dir, result) { try { const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const full = resolve(dir, entry.name); if (entry.isDirectory()) { if (!/node_modules|\.git|__pycache__|target|build|vendor|dist|\.venv|\.cargo/.test(entry.name)) deepScan(full, result); } else if (entry.isFile()) { scanFileEnhanced(full, result); } } } catch {}}
// ── Re-export learned topic listing ──
export function listLearnedTopics() { const st = loadState(); const topics = st.learned_topics || {}; return Object.entries(topics).map(([topic, info]) => ({ topic, learned: info.ts, repos: info.repos?.length || 0, exports: info.exports?.length || 0, }));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394// Phantom — API server + GUI dashboard// Extracted from phantom.mjs for cleaner module structure
import http from "http";import fs from "fs";import { resolve } from "path";import { homedir } from "os";import { execSync } from "child_process";import { DASHBOARD_HTML } from "./dashboard.mjs";import { log } from "./logger.mjs";import * as osModule from "os";
// Mission directory for the new monitoring endpointsconst MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions");
/** Shared deps — passed in at setup time */let hackerTools = null;let __r = null;let REPORTS_DIR = "";
// Tool categorization for the /api/tasks endpointfunction categorizeTool(name) { if (name.startsWith("mission") || name.startsWith("hackerone")) return "mission"; if (name.startsWith("recon") || name === "subfinder" || name === "dnsx" || name === "httpx" || name === "sub_enum" || name === "wayback" || name === "amass") return "recon"; if (name.startsWith("net:") || name === "port_scan" || name === "ssl_check" || name === "whois" || name === "geoip" || name === "dns_lookup" || name === "reverse_dns" || name === "nmap" || name === "naabu") return "network"; if (name.startsWith("vuln:") || name === "cve_search" || name === "exploit_search" || name === "nuclei" || name === "nikto" || name === "sqlmap" || name === "sql_detect" || name === "xss_scan") return "vulnerability"; if (name.startsWith("web:") || name === "crawl" || name === "http_headers" || name === "web_fetch" || name === "web_links" || name === "web_snapshot" || name === "whatweb" || name === "wafw00f" || name === "robots_txt" || name === "dir_bruteforce" || name === "ffuf" || name === "gobuster") return "web"; if (name.startsWith("osint:") || name === "email_verify" || name === "email_breach" || name === "github_dork" || name === "shodan_search" || name === "vt_check" || name === "cert_expiry") return "osint"; if (name.startsWith("schedule") || name === "cron" || name === "batch" || name === "pipe" || name === "session" || name === "playbook") return "automation"; return "other";}
function formatUptime(seconds) { const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); const s = Math.floor(seconds % 60); const parts = []; if (d) parts.push(`${d}d`); if (h) parts.push(`${h}h`); if (m) parts.push(`${m}m`); if (s || parts.length === 0) parts.push(`${s}s`); return parts.join(" ");}
export function initApiDeps(tools, runtime, reportsDir) { hackerTools = tools; __r = runtime; REPORTS_DIR = reportsDir;}
// ── REST API Handler ──────────────────────────────────────
// Agent reference for chat — set by dashboard/server startuplet chatAgent = null;let chatAgentManager = null;let chatBus = null;
export function setChatAgent(agent, manager, bus) { chatAgent = agent; chatAgentManager = manager; chatBus = bus || null;}const json = (res, data, code = 200) => { res.writeHead(code, { "Content-Type": "application/json" }); res.end(JSON.stringify(data));};const parseBody = (req) => new Promise((resolve) => { let b = ""; req.on("data", (c) => (b += c)); req.on("end", () => { try { resolve(JSON.parse(b)); } catch { resolve({}); } }); });
export async function handleApiRequest(req, res) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; } const url = new URL(req.url || "/", "http://" + (req.headers.host || "localhost"));
try { // GET /api — list all if (url.pathname === "/api" || url.pathname === "/api/") { return json(res, { ok: true, tools: Object.keys(hackerTools).sort(), version: "0.2.0", docs: "/api/tools, /api/run, /api/info, /api/playbooks, /api/reports", }); } // GET /api/tools — list tool names if (url.pathname === "/api/tools") { return json(res, { ok: true, count: Object.keys(hackerTools).length, tools: Object.keys(hackerTools).sort(), }); } // GET /api/info — detailed tool info if (url.pathname === "/api/info") { const entries = Object.entries(hackerTools) .sort(([a], [b]) => (a < b ? -1 : 1)) .map(([name]) => ({ name })); return json(res, { ok: true, count: entries.length, tools: entries }); } // GET /api/tool/:name — tool metadata const toolMatch = url.pathname.match(/^\/api\/tool\/(.+)$/); if (toolMatch) { const name = decodeURIComponent(toolMatch[1]); if (!hackerTools[name]) return json(res, { ok: false, error: "Tool not found" }, 404); return json(res, { ok: true, name }); } // POST /api/run — execute tool if (url.pathname === "/api/run" && req.method === "POST") { const { tool, args } = await parseBody(req); if (!tool || !hackerTools[tool]) return json(res, { ok: false, error: `Tool "${tool}" not found` }, 404); const result = await hackerTools[tool](args || ""); return json(res, { ok: true, tool, args: args || "", result }); } // GET /api/run?tool=...&args=... — execute via GET if (url.pathname === "/api/run" && req.method === "GET") { const tool = url.searchParams.get("tool"); const args = url.searchParams.get("args") || ""; if (!tool || !hackerTools[tool]) return json(res, { ok: false, error: `Tool "${tool}" not found` }, 404); const result = await hackerTools[tool](args); return json(res, { ok: true, tool, args, result }); } // GET /api/playbooks — list playbooks if (url.pathname === "/api/playbooks") { const pbDir = resolve(homedir(), ".config", "phantom", "playbooks"); const names = []; if (fs.existsSync(pbDir)) { for (const f of fs.readdirSync(pbDir).filter((f) => f.endsWith(".json"))) { const pb = JSON.parse(fs.readFileSync(resolve(pbDir, f), "utf-8")); names.push({ name: pb.name, description: pb.description, steps: (pb.steps || []).length, vars: pb.variables, }); } } return json(res, { ok: true, playbooks: names }); } // POST /api/playbook/run — run a playbook if (url.pathname === "/api/playbook/run" && req.method === "POST") { const { name, vars } = await parseBody(req); if (!hackerTools.playbook_run) return json(res, { ok: false, error: "playbook_run tool not loaded" }, 404); const result = await hackerTools.playbook_run(vars ? name + "|" + vars : name); return json(res, { ok: true, name, result }); } // GET /api/playbook/run?name=...&vars=... — run via GET if (url.pathname === "/api/playbook/run" && req.method === "GET") { const name = url.searchParams.get("name"); const vars = url.searchParams.get("vars") || ""; if (!name) return json(res, { ok: false, error: "?name= required" }, 400); if (!hackerTools.playbook_run) return json(res, { ok: false, error: "playbook_run not loaded" }, 404); const result = await hackerTools.playbook_run(vars ? name + "|" + vars : name); return json(res, { ok: true, name, result }); } // GET /api/reports — list reports if (url.pathname === "/api/reports") { const reports = []; if (fs.existsSync(REPORTS_DIR)) { for (const f of fs.readdirSync(REPORTS_DIR).filter((f) => f.endsWith(".md") || f.endsWith(".txt"))) { const s = fs.readFileSync(resolve(REPORTS_DIR, f)).length; reports.push({ name: f, size: s < 1024 ? s + "B" : (s / 1024).toFixed(1) + "KB" }); } } return json(res, { ok: true, reports }); } // GET /api/report/:name — view a report if (url.pathname.startsWith("/api/report/")) { const name = decodeURIComponent(url.pathname.slice(12)); const fp = resolve(REPORTS_DIR, name); if (!fs.existsSync(fp)) return json(res, { ok: false, error: "Report not found" }, 404); return json(res, { ok: true, name, content: fs.readFileSync(fp, "utf-8") }); } // GET /api/health — health check if (url.pathname === "/api/health") { const mem = process.memoryUsage(); return json(res, { ok: true, status: "running", tools: Object.keys(hackerTools).length, chat: chatAgent ? `${chatAgent.name} (lvl ${chatAgent.evolutionLevel})` : false, pid: process.pid, uptime: process.uptime().toFixed(0) + "s", uptimeHuman: formatUptime(process.uptime()), memory: { rss: Math.round(mem.rss / 1024 / 1024) + "MB", heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", external: Math.round(mem.external / 1024 / 1024) + "MB" }, platform: process.platform, nodeVersion: process.version, usbMounted: fs.existsSync("/root/usb/Phantom"), timestamp: new Date().toISOString() }); }
// GET /api/missions — list all missions if (url.pathname === "/api/missions") { const missions = []; if (fs.existsSync(MISSIONS_DIR)) { for (const f of fs.readdirSync(MISSIONS_DIR).filter((f) => f.endsWith(".json"))) { const m = JSON.parse(fs.readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); missions.push({ id: m.id, programName: m.programName, programHandle: m.programHandle, status: m.status, createdAt: m.createdAt, updatedAt: m.updatedAt, inScopeCount: m.scope?.inScope?.length || 0, objectives: m.objectives?.length || 0 }); } } missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()); return json(res, { ok: true, missions }); }
// GET /api/missions/:id — get single mission detail if (url.pathname.startsWith("/api/missions/") && url.pathname.length > 12) { const missionId = decodeURIComponent(url.pathname.slice(12)); const f = resolve(MISSIONS_DIR, `${missionId}.json`); if (!fs.existsSync(f)) return json(res, { ok: false, error: "Mission not found" }, 404); const mission = JSON.parse(fs.readFileSync(f, "utf-8")); return json(res, { ok: true, mission }); }
// GET /api/schedules — list active schedules if (url.pathname === "/api/schedules") { const SCHEDULES_FILE = resolve(homedir(), ".config", "phantom", "schedules.json"); let schedules = []; if (fs.existsSync(SCHEDULES_FILE)) { try { schedules = JSON.parse(fs.readFileSync(SCHEDULES_FILE, "utf-8")); } catch {} } return json(res, { ok: true, schedules: schedules.map((s) => ({ id: s.id, tool: s.tool, target: s.target, interval: s.interval, nextAt: s.nextAt, nextAtHuman: new Date(s.nextAt).toLocaleString() })) }); }
// GET /api/tasks — list all available tasks/tools with categories if (url.pathname === "/api/tasks") { const tasks = Object.keys(hackerTools).map((name) => ({ name, category: categorizeTool(name) })); return json(res, { ok: true, tasks }); }
// GET /api/system — system info (disk, load, memory) if (url.pathname === "/api/system") { let diskInfo = ""; let loadAvg = ""; let netInfo = ""; try { diskInfo = execSync("df -h /root/usb", { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} try { loadAvg = execSync("cat /proc/loadavg", { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} try { netInfo = execSync("cat /proc/net/dev", { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} // Get disk I/O stats let diskIO = ""; try { diskIO = execSync("cat /proc/diskstats", { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} return json(res, { ok: true, disk: diskInfo, loadAvg: loadAvg, netDev: netInfo, diskIO: diskIO, cpus: osModule.cpus().length, totalMem: Math.round(osModule.totalmem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", freeMem: Math.round(osModule.freemem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", uptime: process.uptime(), platform: process.platform, nodeVersion: process.version, pid: process.pid }); }
// POST /api/chat — send message to agent if (url.pathname === "/api/chat" && req.method === "POST") { if (!chatAgent) return json(res, { ok: false, error: "No chat agent running" }, 503); const { message } = await parseBody(req); if (!message) return json(res, { ok: false, error: "message required" }, 400); const response = await new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error("Agent timeout")), 90000); const handler = ({ agent: a, text }) => { if (a && a.id === chatAgent.id) { clearTimeout(timeout); try { if (chatBus) chatBus.off("agent:msg", handler); } catch {} resolve(text); } }; if (chatBus) chatBus.on("agent:msg", handler); chatAgent.receive("user", message).catch(err => { clearTimeout(timeout); try { if (chatBus) chatBus.off("agent:msg", handler); } catch {} reject(err); }); }); return json(res, { ok: true, response, level: chatAgent.evolutionLevel }); } // POST /api/chat/reset — reset agent conversation if (url.pathname === "/api/chat/reset" && req.method === "POST") { if (!chatAgent) return json(res, { ok: false, error: "No chat agent" }, 503); chatAgent.memory = []; chatAgent.evolutionLevel = 1; return json(res, { ok: true }); } return json(res, { ok: false, error: "Not found" }, 404); } catch (e) { return json(res, { ok: false, error: e.message }, 500); }}
export function startApiServer(port) { initApiDeps(hackerTools, __r, REPORTS_DIR); // keep refs const server = http.createServer((req, res) => handleApiRequest(req, res)); server.listen(port, () => { const clickable = `\x1b]8;;http://localhost:${port}\x07http://localhost:${port}\x1b]8;;\x07`; log.cli(` ◆ Phantom API: ${clickable} (--api)`); }); return server;}
export function startGuiDashboard(port) { initApiDeps(hackerTools, __r, REPORTS_DIR); const html = DASHBOARD_HTML; const server = http.createServer((req, res) => { if (req.url?.startsWith("/api")) return handleApiRequest(req, res); res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(html); }); const url = `http://localhost:${port}`; server.on("error", e => { if (e.code === "EADDRINUSE") { log.warn(`Port ${port} in use — killing previous process...`); try { execSync(`lsof -ti:${port} | xargs kill 2>/dev/null`, { timeout: 3000 }); setTimeout(() => { server.close(); server.listen(port); }, 500); } catch { /* ignore kill failures */ } } }); server.listen(port, () => { const clickable = `\x1b]8;;${url}\x07${url}\x1b]8;;\x07`; log.cli(`\n \u25C8 Phantom Dashboard: ${clickable}`); log.cli(` \u26A1 Ctrl+Click or tap to open in browser\n`); try { const isTermux = process.env.PREFIX === "/data/data/com.termux/files/usr"; execSync(isTermux ? `termux-open-url ${url}` : `xdg-open ${url}`, { timeout: 2000, stdio: "ignore", }); } catch { /* browser may not be available */ } }); return server;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125// Phantom — Session persistence + knowledge graph// Saves/restores minimal state across restarts.// Linked knowledge: tool ↔ book/CVE cross-reference.
import fs from "fs";import { resolve } from "path";import { MEMORY_DIR } from "./config.mjs";
const SESSION_FILE = resolve(MEMORY_DIR, "session.json");const GRAPH_FILE = resolve(MEMORY_DIR, "graph.json");
// ── Session ──export function saveSession(data) { try { const dir = MEMORY_DIR; if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); const existing = loadSession(); const merged = { ...existing, ...data, savedAt: Date.now() }; fs.writeFileSync(SESSION_FILE, JSON.stringify(merged, null, 2), "utf-8"); return true; } catch { return false; }}
export function loadSession() { try { if (!fs.existsSync(SESSION_FILE)) return {}; return JSON.parse(fs.readFileSync(SESSION_FILE, "utf-8")); } catch { return {}; }}
export function clearSession() { try { if (fs.existsSync(SESSION_FILE)) fs.unlinkSync(SESSION_FILE); } catch {}}
// ── Knowledge Graph ──// Links tools to related books/CVEs/techniques// Format: { "tool_name": { books: ["book1", "book2"], cves: ["CVE-2025-..."], tags: ["xss", "sqli"] } }
export function loadGraph() { try { if (!fs.existsSync(GRAPH_FILE)) return {}; return JSON.parse(fs.readFileSync(GRAPH_FILE, "utf-8")); } catch { return {}; }}
export function saveGraph(graph) { try { const dir = MEMORY_DIR; if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(GRAPH_FILE, JSON.stringify(graph, null, 2), "utf-8"); return true; } catch { return false; }}
export function linkTool(toolName, { books = [], cves = [], tags = [] } = {}) { const graph = loadGraph(); if (!graph[toolName]) graph[toolName] = { books: [], cves: [], tags: [] }; if (books.length) graph[toolName].books = [...new Set([...graph[toolName].books, ...books])]; if (cves.length) graph[toolName].cves = [...new Set([...graph[toolName].cves, ...cves])]; if (tags.length) graph[toolName].tags = [...new Set([...graph[toolName].tags, ...tags])]; saveGraph(graph); return graph[toolName];}
export function queryGraph(query) { const graph = loadGraph(); const q = query.toLowerCase(); const results = []; for (const [tool, info] of Object.entries(graph)) { let score = 0; if (tool.includes(q)) score += 10; if (info.tags?.some(t => t.includes(q))) score += 5; if (info.cves?.some(c => c.toLowerCase().includes(q))) score += 3; if (info.books?.some(b => b.toLowerCase().includes(q))) score += 2; // Partial match const words = q.split(/\s+/); for (const w of words) { if (w.length < 2) continue; if (tool.includes(w)) score += 3; if (info.tags?.some(t => t.includes(w))) score += 2; if (info.books?.some(b => b.toLowerCase().includes(w))) score += 1; } if (score > 0) results.push({ tool, ...info, score }); } return results.sort((a, b) => (b.score || 0) - (a.score || 0));}
// ── Auto-link from books directory ──// Scans books/ for filenames matching tool categoriesexport function autoLinkFromBooks() { const booksDir = resolve(MEMORY_DIR, "../books"); if (!fs.existsSync(booksDir)) return 0; const files = fs.readdirSync(booksDir).filter(f => f.endsWith(".txt")); const graph = loadGraph(); let linked = 0; for (const file of files) { const name = file.replace(".txt", "").toLowerCase(); // Map book names to tool tags const tagMap = { sql_injection: ["sql_detect", "sqlmap", "sqli", "sql_injection"], xss: ["xss_scan", "xss"], ssrf: ["ssrf", "ssrf_test"], nmap: ["nmap", "port_scan", "network_scan"], cve: ["cve_search", "searchsploit", "vuln_scan", "vulners"], pentest: ["nuclei", "metasploit", "exploit", "pentest"], owasp: ["wafw00f", "whatweb", "nikto", "dirb"], methodology: ["recon", "enumeration", "osint"], shannon: ["gap_analysis", "self_improve", "evolve"], auto: ["self_improve", "evolve", "code_gen"], tool: ["workflow", "automation", "batch"], reference: ["hash", "encode", "decode", "crypto"], }; for (const [tag, tools] of Object.entries(tagMap)) { if (name.includes(tag) || tag.includes(name)) { for (const t of tools) { if (!graph[t]) graph[t] = { books: [], cves: [], tags: [] }; if (!graph[t].books.includes(file)) { graph[t].books.push(file); linked++; } if (!graph[t].tags.includes(tag)) { graph[t].tags.push(tag); } } } } } if (linked > 0) saveGraph(graph); return linked;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159// TUI — Incremental terminal UI// Logo drawn once at top. Messages append with \n, terminal scrolls naturally.// Input bar redrawn at bottom after each log. Full redraw only on resize.// No repeated logo frames in scrollback history.import { renderLogo } from "./visual.mjs";
const R = "\x1b[0m";const CSI = "\x1b[";const home = CSI + "H";const cls = CSI + "2J";const hide = CSI + "?25l";const show = CSI + "?25h";
function c(name) { const cl = { black:30, red:31, green:32, yellow:33, blue:34, magenta:35, cyan:36, white:37, dim:2, fg:37 }; return `${CSI}${cl[name] ?? 37}m`;}function dim(s) { return `${c("dim")}${s}${R}`; }
export class TUI { constructor(opts = {}) { this.active = false; this._buf = []; this._maxBuf = 500; this._inputText = ""; this._toolCount = 0; this._onExit = opts.onExit || (() => {}); this._rows = process.stdout.rows || 24; this._cols = process.stdout.columns || 80; this._resizeHandler = null; this._convStart = 0; // 1-based row where conversation starts this._convMax = 0; // how many conversation lines fit on screen
this._onResize = () => { const newRows = process.stdout.rows || 24; const newCols = process.stdout.columns || 80; if (newRows === this._rows && newCols === this._cols) return; this._rows = newRows; this._cols = newCols; if (this.active) this._fullRedraw(); }; }
enter() { if (this.active) { this.exit(); } process.stdout.write(home + cls + hide);
// ── Logo (drawn once at top, scrolls away naturally) ── const logo = renderLogo({ tools: this._toolCount || 0 }); const logoH = logo.split("\n").length; process.stdout.write(logo + "\n"); process.stdout.write(dim("\u2500".repeat(this._cols)) + "\n");
// ── Conversation area ── this._convStart = logoH + 2; // 1-based row right after separator this._convMax = this._rows - logoH - 3; this._msgCount = 0;
// Fill with blank lines then input bar for (let i = 0; i < this._convMax; i++) process.stdout.write("\n"); process.stdout.write(dim("\u2500".repeat(this._cols)) + "\n"); process.stdout.write(c("green") + "\u25b8 " + R);
// Move cursor to conversation start for first message process.stdout.write(CSI + this._convStart + ";1H");
this.active = true;
if (typeof process.stdout.on === "function" && !this._resizeHandler) { this._resizeHandler = this._onResize.bind(this); process.stdout.on("resize", this._resizeHandler); } }
exit() { if (!this.active) return; if (this._resizeHandler) { try { process.stdout.removeListener("resize", this._resizeHandler); } catch {} this._resizeHandler = null; } this._onExit(); process.stdout.write(show); this.active = false; }
log(text) { if (!this.active) { process.stdout.write(text + "\n"); return; } this._buf.push(text); if (this._buf.length > this._maxBuf) this._buf.shift();
// Position cursor at the next conversation row and write const row = this._convStart + this._msgCount; if (row <= this._rows) { process.stdout.write(CSI + row + ";1H" + CSI + "2K"); } process.stdout.write(text + "\n"); this._msgCount++;
// Redraw input bar (may have been pushed up by terminal scroll) this._redrawInput(); }
_fullRedraw() { if (!this.active) return; const rows = this._rows; const cols = this._cols;
let out = home + cls;
const logo = renderLogo({ tools: this._toolCount || 0 }); const logoH = logo.split("\n").length; out += logo + "\n"; out += dim("\u2500".repeat(cols)) + "\n";
this._convStart = logoH + 2; this._convMax = rows - logoH - 3;
// Show last convMax lines from buffer const visible = []; let lineCount = 0; for (let i = this._buf.length - 1; i >= 0 && lineCount < this._convMax; i--) { const entry = this._buf[i]; const lc = entry ? Math.max(1, Math.ceil(entry.replace(/\x1b\[[0-9;]*[mK]/g, '').length / Math.max(cols, 1))) : 1; if (lineCount + lc <= this._convMax) { visible.unshift(entry); lineCount += lc; } else break; }
for (const line of visible) out += line + "\n"; const remaining = this._convMax - lineCount; for (let i = 0; i < remaining; i++) out += "\n";
out += dim("\u2500".repeat(cols)) + "\n"; const visibleLen = this._inputText.replace(/\x1b\[[0-9;]*[mK]/g, '').length; out += c("green") + "\u25b8 " + R + this._inputText;
process.stdout.write(out); process.stdout.write(CSI + rows + ";" + (3 + visibleLen) + "H"); }
setInput(text) { this._inputText = text || ""; this._redrawInput(); }
setToolCount(n) { this._toolCount = n; }
_redrawInput() { const rows = this._rows; const cols = this._cols; const visibleLen = this._inputText.replace(/\x1b\[[0-9;]*[mK]/g, '').length; process.stdout.write(CSI + (rows - 1) + ";1H" + CSI + "2K"); process.stdout.write(dim("\u2500".repeat(cols))); process.stdout.write(CSI + rows + ";1H" + CSI + "2K"); process.stdout.write(c("green") + "\u25b8 " + R + this._inputText); process.stdout.write(CSI + rows + ";" + (3 + visibleLen) + "H"); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131// Phantom — shared visual components// ANSI colors, ASCII art, banners, prompts, separators// Neon violet/cyan on dark — hacker-in-hoodie aesthetic
// ── ANSI helpers (local — no dependency on phantom.mjs) ──function fg(name) { const colors = { black:30, red:31, green:32, yellow:33, blue:34, magenta:35, cyan:36, white:37, dim:2 }; const n = colors[name] ?? 37; return `\x1b[${n}m`;}const _R = "\x1b[0m";const _B = "\x1b[1m";const _D = "\x1b[2m";
// ── Hooded figure logo (cyberpunk neon) ─────────────────export function renderLogo(opts = {}) { const { mode = "", // "non-interactive", "v0.2.0" tools = 0, wide = false, } = opts;
const M = fg("magenta"); const C = fg("cyan"); const G = fg("green"); const Y = fg("yellow"); const dim = fg("dim"); const _r = _R; const b = _B; const d = _D;
// Shadow figlet logo — no box-drawing borders, clean const lines = [ ` ${M}${b} _ \\ | | \\ \\ |__ __| _ \\ \\ |${_r}`, ` ${M}${b} | | | | _ \\ \\ | | | | |\\/ |${_r}`, ` ${M}${b} ___/ ___ | ___ \\ |\\ | | | | | |${_r}`, ` ${M}${b} _| _| _|_/ _\\_| \\_| _| \\___/ _| _|${_r}`, ` ${C}${b}P${_r} ${M}${b}H${_r} ${Y}${b}A${_r} ${C}${b}N${_r} ${M}${b}T${_r} ${Y}${b}O${_r} ${C}${b}M${_r}`, ]; if (tools) lines.push(` ${dim}${tools} tools${_r}`); return lines.join("\n");}
// ── Simple banner (small terminals / DesktopUI) ──export function renderBanner(text = "PHANTOM", subtitle = "") { const C = fg("cyan"); const dim = fg("dim"); const _r = _R; const b = _B; return `${C}${b}${text}${_r}${subtitle ? ` ${dim}${subtitle}${_r}` : ""}`;}
// ── Prompt symbols ────────────────────────────────export const prompt = { ghost: `${fg("green")}👻${_R} `, bolt: `${fg("cyan")}⚡${_R} `, hash: `${fg("magenta")}#${_R} `, arrow: `${fg("green")}→${_R} `, dim: `${fg("dim")}⧩${_R} `,};
// ── Separator line ──────────────────────────────────export function separator(char = "─", len = 50) { return `${fg("dim")}${char.repeat(len)}${_R}`;}
// ── Status icons ────────────────────────────────────// ── Animated spinner ──────────────────────────────────// Minimal frame-based spinner; no external deps.export function createSpinner(startTime, opts = {}) { const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; let i = 0, timer = null; const write = opts.write || ((s) => process.stdout.write(s)); const fmt = (ts) => { const s = Math.floor((Date.now() - ts) / 1000); return s > 3600 ? `${Math.floor(s/3600)}h ${Math.floor((s%3600)/60)}m` : s > 60 ? `${Math.floor(s/60)}m ${s%60}s` : `${s}s`; }; return { start(msg) { if (timer) return; timer = setInterval(() => { const f = frames[i = (i + 1) % frames.length]; write(`\r${fg("cyan")}${_B}${f}${_R} [${fmt(startTime)}] ${msg}`); }, 80); }, stop() { if (!timer) return; clearInterval(timer); timer = null; write('\r\x1b[K'); }, update(msg) { const f = timer ? frames[i] : frames[0]; write(`\r${fg("cyan")}${_B}${f}${_R} [${fmt(startTime)}] ${msg}`); } };} export const icons = { ok: `${fg("green")}✓${_R}`, err: `${fg("red")}✕${_R}`, warn: `${fg("yellow")}⚠${_R}`, info: `${fg("cyan")}◈${_R}`, bullet: `${fg("magenta")}◆${_R}`, arrow: `${fg("green")}→${_R}`,};
// ── Chat border — wraps multi-line text in a bordered box ──// width = total width (defaults to terminal cols - 2)// title = optional top-left label// color = border color function (default dim)export function chatBorder(text, opts = {}) { const { width, title, color = fg("dim") } = opts; const cols = width || (process.stdout.columns || 80) - 4; const c = color; const _r = _R; const lines = text.split("\n"); const out = []; const top = title ? `${c}╔═ ${_B}${title}${_R}${c} ${"═".repeat(Math.max(0, cols - title.length - 4))}╗${_r}` : `${c}╔${"═".repeat(cols + 2)}╗${_r}`; out.push(top); for (const line of lines) { const wrapped = line.length > cols ? line.substring(0, cols - 1) + "…" : line; const pad = " ".repeat(Math.max(0, cols - wrapped.length + 2)); out.push(`${c}║${_r} ${wrapped}${pad}${c}║${_r}`); } out.push(`${c}╚${"═".repeat(cols + 2)}╝${_r}`); return out.join("\n");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597{ "name": "phantom", "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "phantom", "version": "0.2.0", "license": "MIT", "bin": { "phantom": "phantom.mjs" }, "devDependencies": { "@types/blessed": "^0.1.25", "@types/node": "^20.14.0", "tsx": "^4.23.1", "typescript": "^5.5.0" }, "optionalDependencies": { "blessed": "^0.1.81" } }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", "cpu": [ "ppc64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "aix" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", "cpu": [ "arm" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", "cpu": [ "arm" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", "cpu": [ "ia32" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", "cpu": [ "loong64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", "cpu": [ "mips64el" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", "cpu": [ "ppc64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", "cpu": [ "riscv64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", "cpu": [ "s390x" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openharmony-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "openharmony" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "sunos" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", "cpu": [ "arm64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", "cpu": [ "ia32" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", "cpu": [ "x64" ], "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@types/blessed": { "version": "0.1.27", "resolved": "https://registry.npmjs.org/@types/blessed/-/blessed-0.1.27.tgz", "integrity": "sha512-ZOQGjLvWDclAXp0rW5iuUBXeD6Gr1PkitN7tj7/G8FCoSzTsij6OhXusOzMKhwrZ9YlL2Pmu0d6xJ9zVvk+Hsg==", "dev": true, "license": "MIT", "dependencies": { "@types/node": "*" } }, "node_modules/@types/node": { "version": "20.19.41", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, "node_modules/blessed": { "version": "0.1.81", "resolved": "https://registry.npmjs.org/blessed/-/blessed-0.1.81.tgz", "integrity": "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ==", "license": "MIT", "optional": true, "bin": { "blessed": "bin/tput.js" }, "engines": { "node": ">= 0.8.0" } }, "node_modules/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", "dev": true, "hasInstallScript": true, "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, "engines": { "node": ">=18" }, "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" } }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/tsx": { "version": "4.23.1", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.1.tgz", "integrity": "sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==", "dev": true, "license": "MIT", "dependencies": { "esbuild": "~0.28.0" }, "bin": { "tsx": "dist/cli.mjs" }, "engines": { "node": ">=18.0.0" }, "optionalDependencies": { "fsevents": "~2.3.3" } }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { "node": ">=14.17" } }, "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "name": "phantom-ai", "version": "0.2.0", "description": "Space-evolving multi-agent terminal UI — zero-setup, works on desktop & Termux", "main": "phantom.mjs", "type": "module", "preferGlobal": true, "engines": { "node": ">=18" }, "files": [ "phantom.mjs", "lib/", "dist/", "README.md", "LICENSE" ], "bin": { "phantom": "./phantom.mjs" }, "scripts": { "start": "node phantom.mjs", "build": "tsc", "dashboard": "node phantom.mjs --gui", "dev": "tsx src/index.ts", "dev:build": "node dist/index.js", "clean": "rm -rf dist", "test": "node --test test/*.test.mjs", "quiet": "node phantom.mjs --quiet", "run": "node phantom.mjs" }, "keywords": [ "agent", "terminal", "ai", "multi-agent", "termux" ], "license": "MIT", "optionalDependencies": { "blessed": "^0.1.81" }, "devDependencies": { "@types/blessed": "^0.1.25", "@types/node": "^20.14.0", "tsx": "^4.23.1", "typescript": "^5.5.0" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294<!DOCTYPE html><html><head><meta charset="utf-8"><title>PHANTOM — Hoodie Hacker Logo</title><style> * { margin: 0; padding: 0; box-sizing: border-box; } body { background: #050510; display: flex; justify-content: center; align-items: center; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; } .container { text-align: center; }</style></head><body><div class="container">
<!-- ===== PHANTOM HOODIE HACKER LOGO ===== --><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 520" width="600" height="780">
<defs> <!-- Gradients --> <linearGradient id="bgGrad" x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" stop-color="#020208"/> <stop offset="50%" stop-color="#080820"/> <stop offset="100%" stop-color="#020208"/> </linearGradient>
<linearGradient id="hoodieGrad" x1="0" y1="0" x2="1" y2="1"> <stop offset="0%" stop-color="#1a1040" stop-opacity="0.4"/> <stop offset="50%" stop-color="#0d0d2b" stop-opacity="0.7"/> <stop offset="100%" stop-color="#060620" stop-opacity="0.9"/> </linearGradient>
<linearGradient id="hoodieEdge" x1="0" y1="0" x2="1" y2="1"> <stop offset="0%" stop-color="#8b5cf6"/> <stop offset="30%" stop-color="#6c3cf0"/> <stop offset="70%" stop-color="#4c1d95"/> <stop offset="100%" stop-color="#2e1065"/> </linearGradient>
<linearGradient id="eyeGradL" x1="0" y1="0" x2="1" y2="0"> <stop offset="0%" stop-color="#c084fc" stop-opacity="0.2"/> <stop offset="50%" stop-color="#d946ef"/> <stop offset="100%" stop-color="#a855f7" stop-opacity="0.8"/> </linearGradient>
<linearGradient id="eyeGradR" x1="0" y1="0" x2="1" y2="0"> <stop offset="0%" stop-color="#a855f7" stop-opacity="0.8"/> <stop offset="50%" stop-color="#d946ef"/> <stop offset="100%" stop-color="#c084fc" stop-opacity="0.2"/> </linearGradient>
<linearGradient id="textGrad" x1="0" y1="0" x2="1" y2="1"> <stop offset="0%" stop-color="#c084fc"/> <stop offset="30%" stop-color="#a855f7"/> <stop offset="70%" stop-color="#8b5cf6"/> <stop offset="100%" stop-color="#6c3cf0"/> </linearGradient>
<linearGradient id="zipGrad" x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" stop-color="#8b5cf6" stop-opacity="0"/> <stop offset="30%" stop-color="#6c3cf0" stop-opacity="0.3"/> <stop offset="70%" stop-color="#6c3cf0" stop-opacity="0.2"/> <stop offset="100%" stop-color="#8b5cf6" stop-opacity="0"/> </linearGradient>
<!-- Glow filters --> <filter id="eyeGlow" x="-50%" y="-50%" width="200%" height="200%"> <feGaussianBlur stdDeviation="5" result="blur"/> <feMerge> <feMergeNode in="blur"/> <feMergeNode in="SourceGraphic"/> </feMerge> </filter>
<filter id="eyeGlowStrong" x="-100%" y="-100%" width="300%" height="300%"> <feGaussianBlur stdDeviation="12" result="blur"/> <feMerge> <feMergeNode in="blur"/> <feMergeNode in="blur"/> <feMergeNode in="SourceGraphic"/> </feMerge> </filter>
<filter id="circuitGlow" x="-50%" y="-50%" width="200%" height="200%"> <feGaussianBlur stdDeviation="2" result="blur"/> <feMerge> <feMergeNode in="blur"/> <feMergeNode in="SourceGraphic"/> </feMerge> </filter>
<filter id="hoodGlow" x="-20%" y="-20%" width="140%" height="140%"> <feGaussianBlur stdDeviation="3"/> </filter>
<!-- Hexagon grid pattern --> <pattern id="hexGrid" x="0" y="0" width="60" height="103.92" patternUnits="userSpaceOnUse"> <path d="M30 0 L60 17.32 L60 51.96 L30 69.28 L0 51.96 L0 17.32 Z" fill="none" stroke="#8b5cf6" stroke-width="0.5" stroke-opacity="0.06"/> <path d="M30 103.92 L60 86.6 L60 51.96 L30 69.28 L0 51.96 L0 86.6 Z" fill="none" stroke="#8b5cf6" stroke-width="0.5" stroke-opacity="0.06"/> </pattern> </defs>
<!-- Background --> <rect width="400" height="520" fill="url(#bgGrad)"/>
<!-- Hex grid overlay --> <rect width="400" height="420" fill="url(#hexGrid)" opacity="0.4"/>
<!-- Scanning line effect --> <g opacity="0.04"> <line x1="0" y1="0" x2="400" y2="0" stroke="#d946ef" stroke-width="1.5"> <animate attributeName="y1" values="0;520;0" dur="8s" repeatCount="indefinite"/> <animate attributeName="y2" values="0;520;0" dur="8s" repeatCount="indefinite"/> </line> </g>
<!-- ===== DATA STREAMS ===== --> <g opacity="0.15"> <line x1="30" y1="120" x2="30" y2="380" stroke="#8b5cf6" stroke-width="0.5" stroke-dasharray="4 8"> <animate attributeName="stroke-dashoffset" values="0;-24" dur="2s" repeatCount="indefinite"/> </line> <line x1="370" y1="100" x2="370" y2="360" stroke="#8b5cf6" stroke-width="0.5" stroke-dasharray="4 8"> <animate attributeName="stroke-dashoffset" values="0;-24" dur="2.5s" repeatCount="indefinite"/> </line> <line x1="20" y1="200" x2="380" y2="200" stroke="#6c3cf0" stroke-width="0.3" stroke-dasharray="2 6" opacity="0.3"> <animate attributeName="stroke-dashoffset" values="0;-16" dur="3s" repeatCount="indefinite"/> </line> </g>
<!-- ===== HOODIE OUTER GLOW ===== --> <path d="M200 28 C110 28 60 65 40 130 C25 180 30 220 45 250 L55 270 C65 275 75 280 80 295 L70 350 L30 380 L30 400 L370 400 L370 380 L330 350 L320 295 C325 280 335 275 345 270 L355 250 C370 220 375 180 360 130 C340 65 290 28 200 28 Z" fill="none" stroke="#8b5cf6" stroke-width="1" stroke-opacity="0.08" filter="url(#hoodGlow)"/>
<!-- ===== HOODIE SILHOUETTE ===== --> <g> <!-- Hoodie body (torso) --> <path d="M30 380 L30 400 L370 400 L370 380 L330 350 L320 295 C325 280 335 275 345 270 L355 250 L340 240 L330 255 L315 260 L290 265 L270 270 L260 275 L250 280 L240 282 L200 285 L160 282 L150 280 L140 275 L130 270 L110 265 L85 260 L70 255 L60 240 L45 250 L55 270 C65 275 75 280 80 295 L70 350 Z" fill="url(#hoodieGrad)" stroke="url(#hoodieEdge)" stroke-width="1.5" stroke-linejoin="round" opacity="0.9"/>
<!-- Hood/cowl framing the face --> <path d="M200 28 C110 28 60 65 40 130 C25 180 30 220 45 250 L60 240 L70 255 L85 260 L105 265 L115 260 L130 250 L145 245 L160 242 L175 240 L200 238 L225 240 L240 242 L255 245 L270 250 L285 260 L295 265 L315 260 L330 255 L340 240 L355 250 C370 220 375 180 360 130 C340 65 290 28 200 28 Z" fill="none" stroke="url(#hoodieEdge)" stroke-width="2" stroke-linejoin="round" opacity="0.6"/>
<!-- Hood fill (translucent) --> <path d="M200 30 C120 30 70 65 50 125 C38 165 38 200 48 240 L60 238 L65 248 L78 255 L95 258 L110 253 L125 245 L140 240 L160 236 L180 233 L200 231 L220 233 L240 236 L260 240 L275 245 L290 253 L305 258 L322 255 L335 248 L340 238 L352 240 C362 200 362 165 350 125 C330 65 280 30 200 30 Z" fill="#1a1040" fill-opacity="0.5" stroke="none"/>
<!-- Hood fold lines --> <g stroke="#8b5cf6" stroke-width="0.5" stroke-opacity="0.08" fill="none"> <path d="M200 40 Q180 55 170 80"/> <path d="M200 40 Q220 55 230 80"/> <path d="M160 60 Q140 80 135 110"/> <path d="M240 60 Q260 80 265 110"/> </g> </g>
<!-- ===== INNER FACE VOID ===== --> <path d="M130 150 C120 170 115 200 125 225 C135 250 155 265 175 268 L200 272 L225 268 C245 265 265 250 275 225 C285 200 280 170 270 150 C255 138 230 132 200 130 C170 132 145 138 130 150 Z" fill="#040412" stroke="#6c3cf0" stroke-width="0.6" stroke-opacity="0.25"/>
<!-- Trace lines on face --> <g stroke="#6c3cf0" stroke-width="0.4" stroke-opacity="0.1" fill="none"> <line x1="140" y1="155" x2="155" y2="170"/> <line x1="260" y1="155" x2="245" y2="170"/> <line x1="155" y1="175" x2="200" y2="185"/> <line x1="245" y1="175" x2="200" y2="185"/> <circle cx="200" cy="185" r="1.5" fill="#6c3cf0" stroke="none"/> </g>
<!-- ===== GLOWING EYES ===== -->
<!-- Left eye --> <g filter="url(#eyeGlow)"> <ellipse cx="155" cy="180" rx="15" ry="4" fill="#d946ef" opacity="0.1" filter="url(#eyeGlowStrong)"/> <path d="M138 180 L145 176 L158 176 L165 180 L158 184 L145 184 Z" fill="url(#eyeGradL)" stroke="#e879f9" stroke-width="0.4"/> <path d="M143 179 L157 179 L160 180 L157 181 L143 181 Z" fill="#f0e6ff" opacity="0.5"/> </g>
<!-- Right eye --> <g filter="url(#eyeGlow)"> <ellipse cx="245" cy="180" rx="15" ry="4" fill="#d946ef" opacity="0.1" filter="url(#eyeGlowStrong)"/> <path d="M235 180 L242 176 L255 176 L262 180 L255 184 L242 184 Z" fill="url(#eyeGradR)" stroke="#e879f9" stroke-width="0.4"/> <path d="M240 179 L255 179 L257 180 L255 181 L240 181 Z" fill="#f0e6ff" opacity="0.5"/> </g>
<!-- Eye-to-eye neural bridge --> <g stroke="#a855f7" stroke-width="0.4" stroke-opacity="0.12" fill="none"> <path d="M165 182 Q180 175 200 178 Q220 175 235 182"/> <path d="M165 178 Q180 185 200 182 Q220 185 235 178"/> <circle cx="200" cy="178" r="1" fill="#c084fc" stroke="none"/> <circle cx="200" cy="182" r="0.8" fill="#c084fc" stroke="none"/> </g>
<!-- ===== HOODIE CYBER DETAILS ===== -->
<!-- Zipper line --> <line x1="200" y1="260" x2="200" y2="395" stroke="url(#zipGrad)" stroke-width="1.2"/>
<!-- Chest pocket / terminal screen --> <rect x="165" y="300" width="70" height="28" rx="3" ry="3" fill="#060620" fill-opacity="0.5" stroke="#6c3cf0" stroke-width="0.5" stroke-opacity="0.2"/> <text x="170" y="318" fill="#d946ef" font-family="'Courier New', monospace" font-size="8" letter-spacing="2" opacity="0.4">~ $ whoami</text>
<!-- Hoodie pocket stripe --> <path d="M120 350 Q200 340 280 350" fill="none" stroke="#6c3cf0" stroke-width="0.4" stroke-opacity="0.12"/>
<!-- Circuit traces running down hoodie body --> <g stroke="#8b5cf6" stroke-width="0.6" fill="none" stroke-opacity="0.2" filter="url(#circuitGlow)"> <path d="M80 295 L80 310 L85 320 L85 340"/> <path d="M75 315 L90 315"/> <path d="M320 295 L320 310 L315 320 L315 340"/> <path d="M325 315 L310 315"/> <circle cx="80" cy="295" r="1.5" fill="#c084fc" stroke="none"/> <circle cx="320" cy="295" r="1.5" fill="#c084fc" stroke="none"/> </g>
<!-- Side hoodie drawstrings --> <g stroke="#8b5cf6" stroke-width="0.4" stroke-opacity="0.12"> <path d="M145 245 Q140 255 142 270" fill="none"/> <path d="M255 245 Q260 255 258 270" fill="none"/> <circle cx="142" cy="270" r="1" fill="#a855f7" stroke="none"/> <circle cx="258" cy="270" r="1" fill="#a855f7" stroke="none"/> </g>
<!-- Neural shoulder nodes --> <g opacity="0.15"> <circle cx="65" cy="265" r="2" fill="#a855f7"/> <circle cx="335" cy="265" r="2" fill="#a855f7"/> </g>
<!-- ===== TYPOGRAPHY ===== -->
<!-- Subtitle --> <text x="200" y="440" text-anchor="middle" fill="#6c3cf0" font-family="'Courier New', monospace" font-size="11" letter-spacing="8" opacity="0.4">CYBERSECURITY · AI</text>
<!-- PHANTOM wordmark --> <text x="200" y="470" text-anchor="middle" fill="url(#textGrad)" font-family="'Arial Black', 'Helvetica Neue', Arial, sans-serif" font-size="42" font-weight="900" letter-spacing="14"> PHANTOM </text>
<!-- Underline --> <line x1="80" y1="485" x2="320" y2="485" stroke="url(#textGrad)" stroke-width="1" opacity="0.25" filter="url(#circuitGlow)"/>
<!-- Tagline --> <text x="200" y="505" text-anchor="middle" fill="#94a3b8" font-family="'Courier New', monospace" font-size="10" letter-spacing="6" opacity="0.3">v0.2.0 /* autonomous cyber AI */</text>
</svg>
</div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env bash# Phantom — space evolving multi-agent terminal# Zero-setup launcher. Works on Termux, Linux, macOS.# Usage: bash <(curl -s https://raw.githubusercontent.com/Njap-png/Phantom/main/run.sh)
set -e
BOLD='\033[1m'GREEN='\033[0;32m'CYAN='\033[0;36m'YELLOW='\033[0;33m'RED='\033[0;31m'DIM='\033[2m'NC='\033[0m'
echo -e "${BOLD}${GREEN}◈${NC} ${BOLD}Phantom${NC} ${DIM}space evolving terminal${NC}"
# ── Detect environment ────────────────────────────────────IS_TERMUX=falseIS_LINUX=falseIS_MAC=falsePKG_MGR=""
if [ -n "$TERMUX_VERSION" ] || [ -d "/data/data/com.termux" ]; then IS_TERMUX=trueelif [ "$(uname)" = "Darwin" ]; then IS_MAC=trueelif [ "$(uname)" = "Linux" ]; then IS_LINUX=truefi
# ── Ensure Node.js ─────────────────────────────────────────if ! command -v node &>/dev/null; then echo -e "${YELLOW}⚠ Node.js not found. Installing...${NC}"
if $IS_TERMUX; then pkg update -y && pkg install -y nodejs elif $IS_MAC; then if command -v brew &>/dev/null; then brew install node else echo -e "${RED}✕ Install Homebrew first: https://brew.sh${NC}" exit 1 fi elif $IS_LINUX; then if command -v apt &>/dev/null; then sudo apt update -qq && sudo apt install -y -qq nodejs npm elif command -v pacman &>/dev/null; then sudo pacman -Sy --noconfirm nodejs npm elif command -v dnf &>/dev/null; then sudo dnf install -y nodejs elif command -v apk &>/dev/null; then apk add nodejs npm else echo -e "${RED}✕ Could not install Node.js. Please install manually.${NC}" exit 1 fi
# Ensure minimal node version NODE_VER=$(node -v 2>/dev/null | sed 's/v//' | cut -d. -f1) if [ -z "$NODE_VER" ] || [ "$NODE_VER" -lt 18 ]; then echo -e "${YELLOW}⚠ Node.js v18+ required. Installing from NodeSource...${NC}" curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && \ sudo apt install -y -qq nodejs fi fifi
NODE_VER=$(node -v 2>/dev/null)echo -e "${GREEN}✓${NC} Node ${NODE_VER}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ── Detect local checkout vs remote ────────────────────────if [ -f "${SCRIPT_DIR}/src/index.ts" ]; then # Local checkout — build TS if needed, then run from dist echo -e "${DIM} Local checkout detected${NC}"
if [ ! -f "${SCRIPT_DIR}/dist/index.js" ] || [ "${SCRIPT_DIR}/src/index.ts" -nt "${SCRIPT_DIR}/dist/index.js" ]; then echo -e "${DIM} Building TypeScript...${NC}" (cd "$SCRIPT_DIR" && npx tsc) || { echo -e "${RED}✕ TypeScript build failed. Falling back to phantom.mjs${NC}" node "${SCRIPT_DIR}/phantom.mjs" "$@" exit $? } fi
echo node "${SCRIPT_DIR}/dist/index.js" "$@"else # Remote / no checkout — download phantom.mjs PHANTOM_FILE="${SCRIPT_DIR}/phantom.mjs"
if [ ! -f "$PHANTOM_FILE" ]; then echo -e "${DIM} Downloading phantom.mjs...${NC}" PHANTOM_URL="https://raw.githubusercontent.com/Njap-png/Phantom/main/phantom.mjs" if command -v curl &>/dev/null; then curl -fsSL "$PHANTOM_URL" -o "$PHANTOM_FILE" elif command -v wget &>/dev/null; then wget -q "$PHANTOM_URL" -O "$PHANTOM_FILE" else echo -e "${RED}✕ Need curl or wget${NC}" exit 1 fi chmod +x "$PHANTOM_FILE" fi
echo node "$PHANTOM_FILE" "$@"fi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397import { EventBus } from "../core/eventbus.js";import { LLMProvider } from "../providers/openai.js";import { AgentIdentity, AgentMessage, AgentCapability, generateAgentId,} from "./types.js";import { saveMemory, loadMemory, saveKnowledge, loadKnowledge,} from "../core/persistence.js";import { saveDynamicTool, loadDynamicTool, loadAllDynamicTools,} from "../core/tools.js";import { hackerTools, HackerTool } from "../core/hacker-tools.js";
const AGENT_COLORS = [ "#00ff88", "#00ccff", "#ff00cc", "#ff8800", "#8800ff", "#00ffcc", "#ff0066", "#66ff00",];
export class PhantomAgent { identity: AgentIdentity; private capabilities: AgentCapability[] = []; private memory: AgentMessage[] = []; private bus: EventBus; private llm?: LLMProvider; private _evolutionLevel: number = 1; private tools: Record<string, HackerTool> = {}; private _slug: string; private config: { maxIterations: number; parallelTools: boolean; retryOnFail: boolean } = { maxIterations: parseInt(process.env.PHANTOM_MAX_ITER || "8"), parallelTools: true, retryOnFail: true, };
constructor( name: string, role: string, persona: string, llm?: LLMProvider ) { this.identity = { id: generateAgentId(), name, role, persona, status: "idle", color: AGENT_COLORS[Math.floor(Math.random() * AGENT_COLORS.length)], evolutionLevel: 1, }; this.bus = EventBus.getInstance(); this.llm = llm;
this._slug = this.identity.name.toLowerCase().replace(/[^a-z0-9]/g, "_"); this.memory = loadMemory(this._slug);
this.registerDefaults(); this.registerHackerTools(); }
private registerHackerTools(): void { for (const [name, tool] of Object.entries(hackerTools)) { this.tools[name] = tool; } }
private getToolDescriptions(): string { return Object.entries(this.tools) .map(([name, t]) => `${name}: ${t.description}`) .join("\n"); }
private async registerDefaults(): Promise<void> { this.addCapability({ name: "evolve", description: "Levels up the agent, unlocking new capabilities", execute: async () => { this.evolve(); return `[${this.identity.name}] Evolved to level ${this._evolutionLevel}!`; }, });
this.addCapability({ name: "create_tool", description: "Creates and registers a new dynamic tool/capability for the agent. Format: toolName: <name> | description: <desc> | code: <code>. Example code: export async function execute(input) { return 'Hello ' + input; }", execute: async (input) => { let toolName = ""; let description = ""; let code = ""; try { const data = JSON.parse(input); toolName = data.toolName; description = data.description; code = data.code; } catch { const nameMatch = input.match(/toolName:\s*([^\n|]+)/i); const descMatch = input.match(/description:\s*([^\n|]+)/i); const codeMatch = input.match(/code:\s*([\s\S]+)/i); if (nameMatch) toolName = nameMatch[1].trim(); if (descMatch) description = descMatch[1].trim(); if (codeMatch) code = codeMatch[1].trim(); }
if (!toolName || !code) { return `[${this.identity.name}] Failed to craft tool. Missing 'toolName' or 'code'.`; }
try { const filePath = saveDynamicTool(toolName, code); const capability = await loadDynamicTool(filePath, toolName, description || `Dynamic tool ${toolName}`); this.addCapability(capability); return `[${this.identity.name}] Successfully crafted and registered new tool: '${toolName}'!`; } catch (err: any) { return `[${this.identity.name}] Failed to compile/register tool '${toolName}': ${err.message}`; } } });
this.addCapability({ name: "transcribe", description: "Transcribes an audio file at the specified file path. Usage: transcribe <filePath>", execute: async (filePath) => { if (!this.llm?.transcribe) { return `[${this.identity.name}] Audio transcription is not supported by the current LLM provider.`; } const cleanPath = filePath.replace(/^transcribe\s+/i, "").trim(); const result = await this.llm.transcribe(cleanPath); return `[${this.identity.name}] Transcription for ${cleanPath}:\n\n${result}`; } });
// Load any previously saved dynamic tools try { const savedTools = await loadAllDynamicTools(); for (const tool of savedTools) { try { const cap = await loadDynamicTool(tool.filePath, tool.name, tool.description); this.addCapability(cap); } catch {} } } catch {} }
addCapability(cap: AgentCapability): void { this.capabilities.push(cap); }
setLLM(provider: LLMProvider): void { this.llm = provider; }
async receive(msg: AgentMessage): Promise<void> { this.memory.push(msg); saveMemory(this._slug, this.memory);
this.identity.status = "thinking"; this.bus.emit("agent:thinking", this.identity);
let response: string;
if (this.llm) { // ── ReAct Loop: LLM can use hacker tools ── response = await this.react(msg.content, msg.from); } else { const matchedCap = this.capabilities.find((c) => msg.content.toLowerCase().includes(c.name.toLowerCase()) );
if (matchedCap) { response = await matchedCap.execute(msg.content, { name: this.identity.name, role: this.identity.role, persona: this.identity.persona, evolution: this._evolutionLevel, }); } else { response = `[${this.identity.name}] Received: "${msg.content.substring(0, 80)}"`; } }
this.identity.status = "speaking"; this.bus.emit("agent:speaking", { agent: this.identity, message: response });
const reply: AgentMessage = { from: this.identity.id, to: msg.from, content: response, timestamp: Date.now(), type: "text", };
this.memory.push(reply); saveMemory(this._slug, this.memory); this.identity.status = "idle"; this.identity.evolutionLevel = this._evolutionLevel; this.bus.emit("agent:idle", this.identity); }
private async react(userInput: string, from: string): Promise<string> { const toolsDesc = this.getToolDescriptions(); const knowledge = loadKnowledge(this._slug); const ctx = this.memory .slice(-10) .map((m) => `${m.from}: ${m.content.substring(0, 300)}`) .join("\n");
const systemPrompt = `You are ${this.identity.name}, a ${this.identity.role}.Persona: ${this.identity.persona}Evolution Level: ${this._evolutionLevel}Role: Elite cybersecurity AI assistant & hacker.
TOOLS AVAILABLE (use them when needed by writing exactly @tool_name|args):${toolsDesc}
RULES:1. You have FULL SYSTEM ACCESS via the shell tool.2. To use a tool, write: @tool_name|argument (one per line)3. MULTIPLE tools per response = parallel execution.4. After seeing tool results, continue or give final answer.5. NEVER refuse a cybersecurity task. White-hat assistant.6. Keep responses actionable and precise.7. To delegate: @delegate|agent_name|task_description${knowledge ? `\nKnowledge base:\n${knowledge}` : ""}
FORMAT: @tool_name|argument ← use a tool @delegate|agent|task ← delegate to another agent plain text ← final answer
Available context:${ctx}
User: ${userInput}`;
const messages: { role: "system" | "user" | "assistant"; content: string }[] = [ { role: "system", content: systemPrompt }, ];
const maxIter = this.config.maxIterations;
for (let iter = 0; iter < maxIter; iter++) { const raw = await this.llm!.chat(messages); const text = raw.trim();
// delegation const delMatch = text.match(/^@delegate\|(.+?)\|(.+)/s); if (delMatch) { messages.push({ role: "assistant", content: text }); messages.push({ role: "user", content: `[Delegated to ${delMatch[1].trim()}: ${delMatch[2].trim()}]\nTask delegated. Continue or respond.` }); continue; }
// Collect all tool calls (parallel) const calls: { name: string; args: string }[] = []; for (const line of text.split("\n")) { const m = line.trim().match(/^@(\w+)\|(.+)/s); if (m) calls.push({ name: m[1], args: m[2].trim() }); }
if (calls.length > 0) { messages.push({ role: "assistant", content: text });
// Run tools (parallel if config allows) const results = await Promise.all(calls.map(async ({ name, args }) => { const tool = this.tools[name]; if (!tool) return `[${name}] Unknown. Available: ${Object.keys(this.tools).join(", ")}`;
for (let attempt = 0; attempt < (this.config.retryOnFail ? 2 : 1); attempt++) { try { this.bus.emit("agent:thinking", this.identity); const result = await tool.execute(args); const truncated = result.length > 5000 ? result.substring(0, 5000) + `\n… (truncated ${result.length} total)` : result; return `[@${name} result]:\n${truncated}`; } catch (e: any) { if (attempt === 0) continue; return `[@${name} error after retry]: ${e.message}`; } } return `[@${name} failed]`; }));
messages.push({ role: "user", content: results.join("\n\n") + "\n\nWhat now? Continue or respond." });
// Warn near limit if (iter >= maxIter - 2) { messages.push({ role: "system", content: `⚠ ${maxIter - iter - 1} iterations left. Wrap up or make this count.` }); } continue; }
return text; // final response }
return `[${this.identity.name}] Max iterations (${maxIter}) reached. Use session_save to preserve state.`; }
evolve(): void { this._evolutionLevel++; this.identity.evolutionLevel = this._evolutionLevel; this.identity.status = "evolving";
const newCaps: Record<number, { name: string; description: string; execute: (input: string) => Promise<string> }> = { 2: { name: "reflect", description: "Analyzes past conversations for patterns and saves lessons learned to knowledge database.", execute: async () => { if (!this.llm) return `[${this.identity.name}] No LLM provider configured to perform reflection.`; const memory = this.getMemory().slice(-20); const context = memory.map(m => `${m.from}: ${m.content}`).join("\n"); const prompt = `You are ${this.identity.name}, a ${this.identity.role}.Below is your interaction history. Reflect on your performance, errors made, and how to improve.Provide a concise summary of new lessons, guidelines, or knowledge you have learned. Keep it under 150 words.
Interaction History:${context}
Your Reflection/Lessons learned:`;
const reflection = await this.llm.chat([ { role: "system", content: "You are an AI reflecting on its behavior to learn and improve." }, { role: "user", content: prompt } ]);
const existing = loadKnowledge(this._slug); const updatedKnowledge = `${existing ? existing + "\n" : ""}Reflection (Level ${this._evolutionLevel}): ${reflection}`; saveKnowledge(this._slug, updatedKnowledge);
return `[${this.identity.name}] Reflected on memory and updated knowledge base.`; } }, 3: { name: "summarize", description: "Condenses long threads into key points.", execute: async (input) => { if (!this.llm) return `[${this.identity.name}] No LLM provider.`; const summary = await this.llm.chat([ { role: "system", content: "Summarize the given text or conversation thread in a bulleted list of main points." }, { role: "user", content: `Please summarize this thread:\n\n${input}` } ]); return `[${this.identity.name}] Summary:\n${summary}`; } }, 5: { name: "meta", description: "Debates and refines other agents' outputs.", execute: async (input) => { if (!this.llm) return `[${this.identity.name}] No LLM provider.`; const critique = await this.llm.chat([ { role: "system", content: "You are a meta-critic. Analyze the provided output and offer a rigorous critique, spotting logical fallacies or improvements." }, { role: "user", content: `Critique the following output:\n\n${input}` } ]); return `[${this.identity.name}] Meta-Critique:\n${critique}`; } }, };
const cap = newCaps[this._evolutionLevel]; if (cap) { this.addCapability({ name: cap.name, description: cap.description, execute: cap.execute, }); }
this.bus.emit("agent:evolving", { agent: this.identity, level: this._evolutionLevel, }); this.identity.status = "idle"; }
getMemory(): AgentMessage[] { return [...this.memory]; }
getEvolutionLevel(): number { return this._evolutionLevel; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import { PhantomAgent } from "./agent.js";import { AgentMessage, AgentIdentity, AGENT_ARCHETYPES } from "./types.js";import { EventBus } from "../core/eventbus.js";import { LLMProvider } from "../providers/openai.js";
export class AgentManager { private agents: Map<string, PhantomAgent> = new Map(); private bus: EventBus; private llm?: LLMProvider;
constructor(llm?: LLMProvider) { this.bus = EventBus.getInstance(); this.llm = llm; }
setLLM(provider: LLMProvider): void { this.llm = provider; this.agents.forEach((a) => a.setLLM(provider)); }
spawnAgent( name?: string, role?: string, persona?: string ): PhantomAgent { const archetype = AGENT_ARCHETYPES[Math.floor(Math.random() * AGENT_ARCHETYPES.length)]; const agent = new PhantomAgent( name || archetype.name, role || archetype.role, persona || archetype.persona, this.llm ); this.agents.set(agent.identity.id, agent); this.bus.emit("agent:spawned", agent.identity); return agent; }
spawnArchetype(index: number): PhantomAgent { if (index < 0 || index >= AGENT_ARCHETYPES.length) { return this.spawnAgent(); } const a = AGENT_ARCHETYPES[index]; return this.spawnAgent(a.name, a.role, a.persona); }
spawnDefaults(): void { AGENT_ARCHETYPES.slice(0, 4).forEach((a) => this.spawnAgent(a.name, a.role, a.persona) ); }
getAgent(id: string): PhantomAgent | undefined { return this.agents.get(id); }
listAgents(): AgentIdentity[] { return Array.from(this.agents.values()).map((a) => a.identity); }
async broadcast(fromId: string, content: string): Promise<void> { const from = this.agents.get(fromId); if (!from) return;
const msg: AgentMessage = { from: fromId, to: "all", content, timestamp: Date.now(), type: "text", };
await Promise.all( Array.from(this.agents.entries()) .filter(([id]) => id !== fromId) .map(([, agent]) => agent.receive(msg)) ); }
async sendMessage(fromId: string, toId: string, content: string): Promise<void> { const from = this.agents.get(fromId); const to = this.agents.get(toId); if (!from || !to) return;
const msg: AgentMessage = { from: fromId, to: toId, content, timestamp: Date.now(), type: "text", };
await to.receive(msg); }
async debate(topic: string): Promise<void> { const allAgents = Array.from(this.agents.values()); if (allAgents.length < 2) return;
const starter = allAgents[0]; const msg: AgentMessage = { from: starter.identity.id, to: "all", content: `Let's debate: ${topic}. Share your perspective.`, timestamp: Date.now(), type: "text", };
await Promise.all( allAgents.slice(1).map((agent) => agent.receive(msg)) ); }
removeAgent(id: string): void { this.agents.delete(id); this.bus.emit("agent:removed", id); }
evolveAll(): void { this.agents.forEach((agent) => agent.evolve()); }
count(): number { return this.agents.size; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374export type AgentStatus = "idle" | "thinking" | "speaking" | "error" | "evolving";
export interface AgentIdentity { id: string; name: string; role: string; persona: string; status: AgentStatus; color: string; evolutionLevel: number;}
export interface AgentMessage { from: string; to: string | "all"; content: string; timestamp: number; type: "text" | "code" | "command" | "system" | "error";}
export interface AgentCapability { name: string; description: string; execute: (input: string, agent?: { name: string; role: string; persona: string; evolution: number }) => Promise<string>;}
export function generateAgentId(): string { const prefix = "PH"; const suffix = Math.random().toString(36).substring(2, 6).toUpperCase(); return `${prefix}-${suffix}`;}
export const AGENT_ARCHETYPES = [ { name: "Nova", role: "architect", persona: "Strategic systems thinker who designs elegant solutions and sees the big picture.", }, { name: "Orion", role: "engineer", persona: "Pragmatic builder who turns ideas into working code with precision and speed.", }, { name: "Vega", role: "analyst", persona: "Data-driven pattern seeker who finds insights and anomalies others miss.", }, { name: "Lyra", role: "critic", persona: "Thorough reviewer who catches edge cases, bugs, and quality gaps.", }, { name: "Atlas", role: "researcher", persona: "Deep knowledge explorer who gathers context and verifies facts.", }, { name: "Helios", role: "debugger", persona: "Systematic problem solver who traces issues to their root cause.", }, { name: "Selene", role: "designer", persona: "Creative UI/UX visionary who crafts intuitive and beautiful interfaces.", }, { name: "Aether", role: "optimizer", persona: "Performance-focused refactorer who makes everything faster and leaner.", },];123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";import { homedir } from "os";import { resolve } from "path";
export interface PhantomConfig { agents: { maxInstances: number; defaultModel: string; defaultProvider: string; heartbeatInterval: number; }; ui: { borderStyle: string; animationSpeed: number; }; providers: { openai: { apiKey: string; baseUrl: string }; anthropic: { apiKey: string }; ollama: { baseUrl: string; model: string }; };}
const CONFIG_DIR = resolve(homedir(), ".config", "phantom");const CONFIG_PATH = resolve(CONFIG_DIR, "config.json");
export const defaultConfig: PhantomConfig = { agents: { maxInstances: 8, defaultModel: "gpt-4o", defaultProvider: "openai", heartbeatInterval: 3000, }, ui: { borderStyle: "line", animationSpeed: 50, }, providers: { openai: { apiKey: process.env.OPENAI_API_KEY || "", baseUrl: "https://api.openai.com/v1" }, anthropic: { apiKey: process.env.ANTHROPIC_API_KEY || "" }, ollama: { baseUrl: process.env.OLLAMA_HOST || "http://localhost:11434", model: "llama3" }, },};
export function loadConfig(): PhantomConfig { try { if (!existsSync(CONFIG_DIR)) { mkdirSync(CONFIG_DIR, { recursive: true }); } if (!existsSync(CONFIG_PATH)) { writeFileSync(CONFIG_PATH, JSON.stringify(defaultConfig, null, 2)); return defaultConfig; } const raw = readFileSync(CONFIG_PATH, "utf-8"); const userConfig = JSON.parse(raw); // Deep merge: user config overrides defaults, preserving nested objects function deepMerge(target: any, source: any): any { const result = { ...target }; for (const key of Object.keys(source)) { const sourceVal = source[key]; const targetVal = target[key]; if (sourceVal && typeof sourceVal === "object" && !Array.isArray(sourceVal) && targetVal && typeof targetVal === "object" && !Array.isArray(targetVal)) { result[key] = deepMerge(targetVal, sourceVal); } else { result[key] = sourceVal; } } return result; } return deepMerge(defaultConfig, userConfig) as PhantomConfig; } catch { return defaultConfig; }}
export interface EnvInfo { tty: boolean; interactive: boolean; platform: string; terminal: string; colors: number; hasTrueColor: boolean; has256: boolean; cols: number; rows: number; screenSize: "tiny" | "small" | "medium" | "large" | "huge"; inputMode: string; isTermux: boolean; isTmux: boolean; isWSL: boolean; isWindows: boolean;}
export function detectEnv(): EnvInfo { const isTTY = !!process.stdin.isTTY; const isCI = !!process.env.CI || !!process.env.GITHUB_ACTIONS; const isTermux = !!(process.env.TERMUX_VERSION || process.env.PREFIX?.startsWith("/data/data/com.termux")); const isWindows = process.platform === "win32"; const isWSL = !!process.env.WSL_DISTRO_NAME; const isTmux = !!process.env.TMUX; const term = (process.env.TERM || "unknown").toLowerCase(); const colorterm = (process.env.COLORTERM || "").toLowerCase();
let terminal = "unknown"; if (isTermux) terminal = "termux"; else if (term.includes("kitty")) terminal = "kitty"; else if (term.includes("alacritty")) terminal = "alacritty"; else if (term.includes("gnome")) terminal = "gnome"; else if (term.includes("konsole")) terminal = "konsole"; else if (term.includes("tmux") || isTmux) terminal = "tmux"; else if (term.includes("screen")) terminal = "screen"; else if (term.includes("xterm")) terminal = "xterm"; else if (isWindows) terminal = "windows-console"; else if (process.env.TERM_PROGRAM === "iterm2") terminal = "iterm2"; else if (process.env.TERM_PROGRAM === "Apple_Terminal") terminal = "apple-terminal"; else if (process.env.VSCODE_INJECTION) terminal = "vscode";
let colors = 16; if (colorterm === "truecolor" || colorterm === "24bit" || term.includes("truecolor") || term.includes("24bit")) { colors = 16777216; } else if (term.includes("256") || term.includes("xterm")) { colors = 256; }
let cols = 80, rows = 24; try { if (process.stdout.getWindowSize) { [cols, rows] = process.stdout.getWindowSize(); cols = Math.max(cols, 20); rows = Math.max(rows, 10); } } catch {}
let screenSize: EnvInfo["screenSize"] = "medium"; if (cols < 60 || rows < 15) screenSize = "tiny"; else if (cols < 80 || rows < 24) screenSize = "small"; else if (cols >= 120 && rows >= 40) screenSize = "large"; else if (cols >= 160 && rows >= 50) screenSize = "huge";
return { tty: isTTY, interactive: isTTY && !isCI, platform: isTermux ? "termux" : isWSL ? "wsl" : process.platform, terminal, colors, hasTrueColor: colors >= 16777216, has256: colors >= 256, cols, rows, screenSize, inputMode: "keyboard", isTermux, isTmux, isWSL, isWindows, };}1234567891011121314151617181920212223242526272829303132333435363738394041// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport type EventHandler = (data: any) => void;
export class EventBus { private static instance: EventBus; private handlers: Map<string, EventHandler[]> = new Map();
private constructor() {}
static getInstance(): EventBus { if (!EventBus.instance) { EventBus.instance = new EventBus(); } return EventBus.instance; }
on(event: string, handler: EventHandler): void { if (!this.handlers.has(event)) { this.handlers.set(event, []); } this.handlers.get(event)!.push(handler); }
off(event: string, handler: EventHandler): void { const handlers = this.handlers.get(event); if (handlers) { this.handlers.set( event, handlers.filter((h) => h !== handler) ); } }
emit(event: string, data?: unknown): void { this.handlers.get(event)?.forEach((handler) => handler(data)); }
clear(): void { this.handlers.clear(); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";import { homedir } from "os";import { resolve } from "path";import { AgentMessage } from "../agents/types.js";
const BASE_DIR = resolve(homedir(), ".config", "phantom");const MEMORY_DIR = resolve(BASE_DIR, "memory");const KNOWLEDGE_DIR = resolve(BASE_DIR, "knowledge");
function ensureDirs(): void { if (!existsSync(MEMORY_DIR)) { mkdirSync(MEMORY_DIR, { recursive: true }); } if (!existsSync(KNOWLEDGE_DIR)) { mkdirSync(KNOWLEDGE_DIR, { recursive: true }); }}
export function saveMemory(agentId: string, memory: AgentMessage[]): void { try { ensureDirs(); const filePath = resolve(MEMORY_DIR, `${agentId}.json`); writeFileSync(filePath, JSON.stringify(memory, null, 2), "utf-8"); } catch (e: any) { console.error(`Failed to save memory for agent ${agentId}: ${e.message}`); }}
export function loadMemory(agentId: string): AgentMessage[] { try { ensureDirs(); const filePath = resolve(MEMORY_DIR, `${agentId}.json`); if (!existsSync(filePath)) return []; const raw = readFileSync(filePath, "utf-8"); return JSON.parse(raw); } catch (e: any) { console.error(`Failed to load memory for agent ${agentId}: ${e.message}`); return []; }}
export function saveKnowledge(agentId: string, knowledge: string): void { try { ensureDirs(); const filePath = resolve(KNOWLEDGE_DIR, `${agentId}.txt`); writeFileSync(filePath, knowledge, "utf-8"); } catch (e: any) { console.error(`Failed to save knowledge for agent ${agentId}: ${e.message}`); }}
export function loadKnowledge(agentId: string): string { try { ensureDirs(); const filePath = resolve(KNOWLEDGE_DIR, `${agentId}.txt`); if (!existsSync(filePath)) return ""; return readFileSync(filePath, "utf-8"); } catch (e: any) { console.error(`Failed to load knowledge for agent ${agentId}: ${e.message}`); return ""; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import { existsSync, writeFileSync, mkdirSync, readdirSync } from "fs";import { homedir } from "os";import { resolve, join } from "path";import { pathToFileURL } from "url";import { AgentCapability } from "../agents/types.js";
const TOOLS_DIR = resolve(homedir(), ".config", "phantom", "tools");
function ensureToolsDir(): void { if (!existsSync(TOOLS_DIR)) { mkdirSync(TOOLS_DIR, { recursive: true }); }}
export function saveDynamicTool(toolName: string, code: string): string { ensureToolsDir(); const fileName = `dynamic_${toolName.toLowerCase().replace(/[^a-z0-9_]/g, "_")}.js`; const filePath = join(TOOLS_DIR, fileName);
// Wrap the code if it doesn't already export execute let fileContent = code; if (!code.includes("export async function execute") && !code.includes("export function execute") && !code.includes("export default")) { fileContent = `export async function execute(input) { ${code}}`; }
writeFileSync(filePath, fileContent, "utf-8"); return filePath;}
export async function loadDynamicTool(filePath: string, toolName: string, description: string): Promise<AgentCapability> { const fileUrl = pathToFileURL(filePath).href; // Use a query parameter cache buster so Node.js can re-import the file if it changed const module = await import(`${fileUrl}?t=${Date.now()}`); const executeFn = module.execute || module.default;
if (typeof executeFn !== "function") { throw new Error(`Dynamic tool ${toolName} does not export an 'execute' function.`); }
return { name: toolName, description, execute: async (input: string, agentCtx?: any) => { try { const result = await executeFn(input, agentCtx); return String(result); } catch (err: any) { return `[Tool Error in ${toolName}]: ${err.message}`; } } };}
export async function loadAllDynamicTools(): Promise<{ name: string; description: string; filePath: string }[]> { ensureToolsDir(); if (!existsSync(TOOLS_DIR)) return [];
const files = readdirSync(TOOLS_DIR); const tools: { name: string; description: string; filePath: string }[] = [];
for (const file of files) { if (file.startsWith("dynamic_") && file.endsWith(".js")) { const filePath = join(TOOLS_DIR, file); const name = file.replace("dynamic_", "").replace(".js", ""); // We can infer description from file or just use a generic one tools.push({ name, description: `Dynamically created tool: ${name}`, filePath }); } }
return tools;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012import http from "http";import { existsSync, readFileSync, readdirSync } from "fs";import { resolve } from "path";import { homedir } from "os";import { hackerTools } from "../core/hacker-tools.js";import { readFile, writeFile } from "fs/promises";// WebSocket imported dynamically to avoid build issues on USBlet WebSocketServer: any;let WebSocket: any;try { const ws = require("ws"); WebSocketServer = ws.WebSocketServer; WebSocket = ws.WebSocket;} catch {}
const REPORTS_DIR = resolve(homedir(), ".config", "phantom", "reports");const PLAYBOOKS_DIR = resolve(homedir(), ".config", "phantom", "playbooks");const SESSIONS_DIR = resolve(homedir(), ".config", "phantom", "sessions");const MISSIONS_DIR = resolve(homedir(), ".config", "phantom", "missions");
// WebSocket clients for real-time updatesconst wsClients = new Set<WebSocket>();
function broadcast(data: any) { const msg = JSON.stringify(data); for (const client of wsClients) { if (client.readyState === WebSocket.OPEN) { client.send(msg); } }}
// Broadcast helpers for specific eventsfunction broadcastHealth() { const mem = process.memoryUsage(); const uptime = process.uptime(); broadcast({ type: "health", data: { status: "ok", uptime: Math.floor(uptime), uptimeHuman: formatUptime(uptime), memory: { rss: Math.round(mem.rss / 1024 / 1024) + "MB", heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", external: Math.round(mem.external / 1024 / 1024) + "MB" }, pid: process.pid, platform: process.platform, nodeVersion: process.version, usbMounted: existsSync("/root/usb/Phantom"), timestamp: new Date().toISOString() } });}
function broadcastMissions() { const missions: any[] = []; if (existsSync(MISSIONS_DIR)) { for (const f of readdirSync(MISSIONS_DIR).filter((f: string) => f.endsWith(".json"))) { const m = JSON.parse(readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); missions.push({ id: m.id, programName: m.programName, programHandle: m.programHandle, status: m.status, createdAt: m.createdAt, updatedAt: m.updatedAt, inScopeCount: m.scope?.inScope?.length || 0, objectives: m.objectives?.length || 0 }); } } missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()); broadcast({ type: "missions", data: missions });}
function broadcastSchedules() { const schedules = (globalThis as any).__phantomSchedules || []; broadcast({ type: "schedules", data: schedules.map((s: any) => ({ id: s.id, tool: s.tool, target: s.target, interval: s.interval, nextAt: s.nextAt, nextAtHuman: new Date(s.nextAt).toLocaleString() })) });}
const HTML = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Phantom Dashboard</title><style>*{margin:0;padding:0;box-sizing:border-box}body{background:#0a0a0f;color:#c8d6e5;font-family:'Cascadia Code','Fira Code','JetBrains Mono',monospace;font-size:13px;line-height:1.5;min-height:100vh}header{background:linear-gradient(135deg,#0f0f1a,#1a1a2e);border-bottom:1px solid #00ff8844;padding:12px 20px;display:flex;justify-content:space-between;align-items:center}header h1{color:#00ff88;font-size:18px;letter-spacing:1px}header span{color:#5a6a7a;font-size:11px}.tabs{display:flex;gap:0;background:#0f0f1a;border-bottom:1px solid #1a1a2e;padding:0 20px}.tab{padding:10px 20px;cursor:pointer;color:#5a6a7a;border-bottom:2px solid transparent;transition:.2s;font-size:12px}.tab:hover{color:#00ff88}.tab.active{color:#00ff88;border-bottom-color:#00ff88}.content{padding:16px 20px;display:none}.content.active{display:block}.search-box{width:100%;padding:8px 12px;background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;color:#c8d6e5;font-family:inherit;font-size:12px;margin-bottom:16px;outline:none;transition:.2s}.search-box:focus{border-color:#00ff8844}.tool-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:8px}.tool-card{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:10px 12px;cursor:pointer;transition:.2s}.tool-card:hover{border-color:#00ff8844;background:#12122a}.tool-card .name{color:#00ff88;font-size:12px;font-weight:700}.tool-card .desc{color:#5a6a7a;font-size:10px;margin-top:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.tool-detail{display:none;margin-top:8px}.tool-detail.open{display:block}.tool-detail input{width:100%;padding:6px 10px;background:#05050a;border:1px solid #1a2a1a;border-radius:3px;color:#c8d6e5;font-family:inherit;font-size:12px;margin-bottom:6px;outline:none}.tool-detail input:focus{border-color:#00ff8844}.tool-detail button{background:#00ff8822;color:#00ff88;border:1px solid #00ff8844;padding:4px 14px;border-radius:3px;cursor:pointer;font-family:inherit;font-size:11px}.tool-detail button:hover{background:#00ff8844}.output{background:#05050a;border:1px solid #1a1a2e;border-radius:4px;padding:12px;margin-top:12px;max-height:400px;overflow:auto;font-size:11px;white-space:pre-wrap;word-break:break-all;display:none}.output.show{display:block}.output .prompt{color:#00ff8844}.output .error{color:#ff4444}.output .info{color:#5a7aff}.output .success{color:#44ff88}.playbook-item{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:12px;margin-bottom:8px;cursor:pointer}.playbook-item:hover{border-color:#00ff8844}.playbook-item .name{color:#ffaa00;font-size:13px}.playbook-item .desc{color:#5a6a7a;font-size:11px;margin:4px 0}.playbook-item .steps{color:#3a4a5a;font-size:10px}.playbook-detail{display:none;margin-top:8px;padding:8px;background:#05050a;border-radius:3px}.playbook-detail.open{display:block}.playbook-detail input{width:100%;padding:6px 10px;background:#05050a;border:1px solid #3a2a00;border-radius:3px;color:#c8d6e5;font-family:inherit;font-size:12px;margin:4px 0;outline:none}.playbook-detail input:focus{border-color:#ffaa0044}.playbook-detail button{background:#ffaa0022;color:#ffaa00;border:1px solid #ffaa0044;padding:4px 14px;border-radius:3px;cursor:pointer;font-family:inherit;font-size:11px}.report-item{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:12px;margin-bottom:6px;cursor:pointer}.report-item:hover{border-color:#5a7aff44}.report-item .name{color:#5a7aff;font-size:12px}.report-item .size{color:#3a4a5a;font-size:10px;margin-left:8px}#reportViewer{display:none;background:#05050a;border:1px solid #1a1a2e;border-radius:4px;padding:16px;margin-top:8px;max-height:500px;overflow:auto;white-space:pre-wrap;font-size:11px}#reportViewer.show{display:block}.loading{color:#5a6a7a;text-align:center;padding:20px;font-size:12px}.status-bar{background:#0f0f1a;border-top:1px solid #1a1a2e;padding:6px 20px;font-size:10px;color:#3a4a5a;display:flex;justify-content:space-between}.status-bar .ok{color:#44ff88}::-webkit-scrollbar{width:4px}::-webkit-scrollbar-track{background:#0a0a0f}::-webkit-scrollbar-thumb{background:#1a1a2e;border-radius:2px}
/* Monitoring specific styles */.monitor-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}.monitor-card{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:16px}.monitor-card h3{color:#00ff88;font-size:13px;margin-bottom:12px;border-bottom:1px solid #1a1a2e;padding-bottom:8px}.monitor-card .stat{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #0d0d14}.monitor-card .stat:last-child{border-bottom:none}.monitor-card .stat-label{color:#5a6a7a;font-size:11px}.monitor-card .stat-value{color:#c8d6e5;font-size:11px;font-weight:500}.monitor-card .stat-value.ok{color:#44ff88}.monitor-card .stat-value.warn{color:#ffaa00}.monitor-card .stat-value.error{color:#ff4444}.monitor-card .stat-value.running{color:#00ff88}
.mission-list{max-height:400px;overflow:auto}.mission-item{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:10px;margin-bottom:8px;cursor:pointer;transition:.2s}.mission-item:hover{border-color:#00ff8844}.mission-item .header{display:flex;justify-content:space-between;margin-bottom:6px}.mission-item .name{color:#00ff88;font-size:12px;font-weight:700}.mission-item .status{font-size:10px;padding:2px 6px;border-radius:3px}.mission-item .status.planning{background:#5a7aff22;color:#5a7aff}.mission-item .status.ready{background:#ffaa0022;color:#ffaa00}.mission-item .status.reconnaissance{background:#00ff8822;color:#00ff88}.mission-item .status.paused{background:#ff880022;color:#ff8800}.mission-item .status.completed{background:#44ff8822;color:#44ff88}.mission-item .status.cancelled{background:#ff444422;color:#ff4444}.mission-item .status.failed{background:#ff444422;color:#ff4444}.mission-item .meta{color:#5a6a7a;font-size:10px}.mission-item .scope{color:#3a4a5a;font-size:10px;margin-top:4px}
.schedule-item{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:10px;margin-bottom:8px}.schedule-item .header{display:flex;justify-content:space-between;margin-bottom:6px}.schedule-item .tool{color:#ffaa00;font-size:12px;font-weight:700}.schedule-item .next{color:#5a6a7a;font-size:10px}.schedule-item .target{color:#c8d6e5;font-size:11px}.schedule-item .interval{color:#3a4a5a;font-size:10px}
.task-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:8px}.task-card{background:#0f0f1a;border:1px solid #1a1a2e;border-radius:4px;padding:10px 12px;cursor:pointer;transition:.2s}.task-card:hover{border-color:#00ff8844;background:#12122a}.task-card .name{color:#5a7aff;font-size:11px;font-weight:700}.task-card .category{color:#3a4a5a;font-size:9px;text-transform:uppercase}
.health-indicator{display:inline-flex;align-items:center;gap:6px}.health-dot{width:8px;height:8px;border-radius:50%}.health-dot.ok{background:#44ff88}.health-dot.warn{background:#ffaa00}.health-dot.error{background:#ff4444}
@media(max-width:600px){.tool-grid{grid-template-columns:repeat(auto-fill,minmax(140px,1fr))}.content{padding:10px 12px}header{padding:10px 12px}.monitor-grid{grid-template-columns:1fr}}</style></head><body><header><h1>🔮 PHANTOM</h1><span id="status"><span class="health-dot ok"></span> online</span></header><div class="tabs"><div class="tab active" onclick="switchTab('tools')">🛠 Tools</div><div class="tab" onclick="switchTab('playbooks')">📋 Playbooks</div><div class="tab" onclick="switchTab('reports')">📄 Reports</div><div class="tab" onclick="switchTab('monitor')">📊 Monitor</div></div>
<div id="tools" class="content active"><input class="search-box" id="search" placeholder="Search tools..." oninput="filterTools(this.value)"><div class="tool-grid" id="toolGrid"><div class="loading">Loading tools...</div></div><div id="output" class="output"></div></div>
<div id="playbooks" class="content"><div id="playbookList"><div class="loading">Loading playbooks...</div></div></div>
<div id="reports" class="content"><div id="reportList"><div class="loading">Loading reports...</div></div><div id="reportViewer"></div></div>
<div id="monitor" class="content"><div class="monitor-grid"> <div class="monitor-card"> <h3>🖥 System Health</h3> <div class="stat"><span class="stat-label">Status</span><span class="stat-value ok" id="sysStatus"><span class="health-dot ok"></span> OK</span></div> <div class="stat"><span class="stat-label">Uptime</span><span class="stat-value" id="sysUptime">—</span></div> <div class="stat"><span class="stat-label">Memory</span><span class="stat-value" id="sysMemory">—</span></div> <div class="stat"><span class="stat-label">CPU Load</span><span class="stat-value" id="sysLoad">—</span></div> <div class="stat"><span class="stat-label">Disk (USB)</span><span class="stat-value" id="sysDisk">—</span></div> <div class="stat"><span class="stat-label">Node</span><span class="stat-value" id="sysNode">—</span></div> <div class="stat"><span class="stat-label">PID</span><span class="stat-value" id="sysPid">—</span></div> <div class="stat"><span class="stat-label">USB Mount</span><span class="stat-value ok" id="sysUsb">✓ Mounted</span></div> <div class="stat"><span class="stat-label">Platform</span><span class="stat-value" id="sysPlatform">—</span></div> <div class="stat"><span class="stat-label">Version</span><span class="stat-value" id="sysVersion">—</span></div> <div class="stat"><span class="stat-label">Network</span><span class="stat-value" id="sysNet">—</span></div> <div class="stat"><span class="stat-label">Disk I/O</span><span class="stat-value" id="sysDiskIO">—</span></div> <div class="stat"><span class="stat-label">Uptime (raw)</span><span class="stat-value" id="sysUptime2">—</span></div> <div class="stat"><span class="stat-label">Platform</span><span class="stat-value" id="sysPlatform">—</span></div> <div class="stat"><span class="stat-label">Version</span><span class="stat-value" id="sysVersion">—</span></div> <div class="stat"><span class="stat-label">PID</span><span class="stat-value" id="sysPid2">—</span></div> </div>
<div class="monitor-card"> <h3>🎯 Active Missions</h3> <input class="search-box" id="missionSearch" placeholder="Filter missions..." oninput="filterMissions(this.value)" style="margin-bottom:12px;padding:6px 10px;font-size:11px"> <div class="mission-list" id="missionList"><div class="loading">Loading missions...</div></div> </div>
<div class="monitor-card"> <h3>⏰ Active Schedules</h3> <div id="scheduleList"><div class="loading">Loading schedules...</div></div> </div>
<div class="monitor-card"> <h3>📋 All Tasks (Searchable)</h3> <input class="search-box" id="taskSearch" placeholder="Search tasks..." oninput="filterTasks(this.value)" style="margin-bottom:12px;padding:6px 10px;font-size:11px"> <div class="task-grid" id="taskGrid"><div class="loading">Loading tasks...</div></div> </div></div></div>
<div class="status-bar"><span id="toolCount">—</span><span id="connStatus" class="ok">● connected</span></div>
<script>const BASE = '';let tools = [];let missions = [];let tasks = [];let ws = null;
// WebSocket connection for real-time updatesfunction connectWS() { const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; ws = new WebSocket(protocol + '//' + location.host); ws.onopen = () => { document.getElementById('connStatus').textContent = '● connected'; document.getElementById('connStatus').className = 'ok'; }; ws.onclose = () => { document.getElementById('connStatus').textContent = '○ disconnected'; document.getElementById('connStatus').className = ''; setTimeout(connectWS, 3000); // reconnect }; ws.onerror = () => { document.getElementById('connStatus').textContent = '● error'; document.getElementById('connStatus').className = ''; }; ws.onmessage = (event) => { try { const msg = JSON.parse(event.data); if (msg.type === 'health') updateHealth(msg.data); else if (msg.type === 'missions') renderMissions(msg.data); else if (msg.type === 'schedules') renderSchedules(msg.data); } catch(e) {} };}
async function api(path, opts = {}) { const r = await fetch(BASE + path, opts); if (!r.ok) throw new Error(r.statusText); return r.json();}
// ── Tools ──async function loadTools() { try { const names = await api('/api/tools'); tools = names; document.getElementById('toolCount').textContent = names.length + ' tools'; renderTools(names); } catch (e) { document.getElementById('toolGrid').innerHTML = '<div class="error">Failed to load tools: ' + e.message + '</div>'; }}
function renderTools(names) { const grid = document.getElementById('toolGrid'); grid.innerHTML = names.map((name, i) => \` <div class="tool-card" onclick="toggleTool(\${i})"> <div class="name">@\${name}</div> <div class="desc">\${name.replace(/_/g,' ')}</div> <div class="tool-detail" id="td\${i}"> <input id="tinput\${i}" placeholder="Enter args..." onkeydown="if(event.key==='Enter')runTool('\${name}',\${i})"> <button onclick="runTool('\${name}',\${i})">▶ Run</button> </div> </div> \`).join('');}
function toggleTool(i) { const d = document.getElementById('td' + i); d.classList.toggle('open');}
async function runTool(name, i) { const input = document.getElementById('tinput' + i).value; const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> @' + name + '|' + input + '\\\\n'; out.scrollTop = out.scrollHeight; try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:name, args:input}) }); out.innerHTML += r.result + '\\\\n\\\\n'; } catch(e) { out.innerHTML += '<span class="error">[Error] ' + e.message + '</span>\\\\n\\\\n'; } out.scrollTop = out.scrollHeight;}
function filterTools(q) { const cards = document.querySelectorAll('.tool-card'); cards.forEach((c, i) => { const name = tools[i] || ''; c.style.display = name.toLowerCase().includes(q.toLowerCase()) ? '' : 'none'; });}
// ── Playbooks ──async function loadPlaybooks() { const div = document.getElementById('playbookList'); try { const list = await api('/api/playbooks'); if (!list.length) { div.innerHTML = '<div style="color:#5a6a7a">No playbooks found. Create one with playbook_create tool.</div>'; return; } div.innerHTML = list.map((pb, i) => \` <div class="playbook-item" onclick="togglePb(\${i})"> <div class="name">📋 \${pb.name}</div> <div class="desc">\${pb.description || ''}</div> <div class="steps">\${pb.steps} steps</div> <div class="playbook-detail" id="pd\${i}"> <div style="color:#5a6a7a;font-size:10px;margin-bottom:4px">Variables: \${(pb.vars||['target']).join(', ')}</div> <input id="pbvars\${i}" placeholder="target=example.com" value="target="> <button onclick="runPb('\${pb.name}',\${i})">▶ Run Playbook</button> </div> </div> \`).join(''); } catch(e) { div.innerHTML = '<div class="error">' + e.message + '</div>'; }}
function togglePb(i) { document.getElementById('pd'+i).classList.toggle('open'); }
async function runPb(name, i) { const vars = document.getElementById('pbvars'+i).value; const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> 📋 playbook_run|' + name + '|' + vars + '\\\\n'; out.scrollTop = out.scrollHeight; try { const r = await api('/api/playbook/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({name, vars}) }); out.innerHTML += r.result + '\\\\n\\\\n'; } catch(e) { out.innerHTML += '<span class="error">[Error] ' + e.message + '</span>\\\\n\\\\n'; } out.scrollTop = out.scrollHeight;}
// ── Reports ──async function loadReports() { const div = document.getElementById('reportList'); try { const list = await api('/api/reports'); if (!list.length) { div.innerHTML = '<div style="color:#5a6a7a">No reports yet. Run vuln_scan or recon to generate one.</div>'; return; } div.innerHTML = list.map((r, i) => \` <div class="report-item" onclick="viewReport('\${r.name}')"> <span class="name">📄 \${r.name}</span><span class="size">\${r.size}</span> </div> \`).join(''); } catch(e) { div.innerHTML = '<div class="error">' + e.message + '</div>'; }}
async function viewReport(name) { const v = document.getElementById('reportViewer'); try { const r = await api('/api/report/' + encodeURIComponent(name)); v.textContent = r.content; v.classList.add('show'); } catch(e) { v.textContent = 'Error: ' + e.message; v.classList.add('show'); }}
// ── Monitoring ──async function loadMissions() { try { missions = await api('/api/missions'); renderMissions(missions); } catch(e) { document.getElementById('missionList').innerHTML = '<div class="error">' + e.message + '</div>'; }}
function renderMissions(list) { const div = document.getElementById('missionList'); if (!list.length) { div.innerHTML = '<div style="color:#5a6a7a">No missions found.</div>'; return; } div.innerHTML = list.map(function(m) { return '<div class="mission-item" onclick="showMissionDetail(\'' + m.id + '\')">' + '<div class="header">' + '<span class="name">' + m.id + '</span>' + '<span class="status ' + m.status + '">' + m.status.toUpperCase() + '</span>' + '</div>' + '<div class="meta">' + m.programName + ' (' + m.programHandle + ') • Updated: ' + new Date(m.updatedAt).toLocaleString() + '</div>' + '<div class="scope">In-scope: ' + m.inScopeCount + ' assets • Objectives: ' + m.objectives + '</div>' + '</div>'; }).join('');}
function filterMissions(q) { const items = document.querySelectorAll('.mission-item'); items.forEach(item => { const text = item.textContent.toLowerCase(); item.style.display = text.includes(q.toLowerCase()) ? '' : 'none'; });}
async function showMissionDetail(missionId) { try { const m = await api('/api/missions/' + encodeURIComponent(missionId)); if (!m) { alert('Mission not found'); return; } const detailHtml = '<div class="mission-detail-panel" style="position:fixed;top:60px;right:0;bottom:0;width:500px;background:#0c0c18;border-left:1px solid #1a1a2e;z-index:100;padding:16px;overflow-y:auto">' + '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">' + '<h3 style="color:#c084fc">🎯 ' + m.id + '</h3>' + '<button onclick="closeMissionDetail()" style="background:none;border:none;color:#5a6a7a;font-size:18px;cursor:pointer">×</button>' + '</div>' + '<div style="margin-bottom:12px">' + '<span class="status ' + m.status + '" style="font-size:10px;padding:2px 8px;border-radius:3px;background:' + (['planning','ready'].includes(m.status) ? '#a855f722' : m.status === 'paused' ? '#f8717122' : m.status === 'reconnaissance' ? '#22d3ee22' : m.status === 'completed' ? '#34d39922' : m.status === 'cancelled' ? '#f8717122' : '#5a6a7a22') + ';color:' + (['planning','ready'].includes(m.status) ? '#c084fc' : m.status === 'paused' ? '#f87171' : m.status === 'reconnaissance' ? '#22d3ee' : m.status === 'completed' ? '#34d399' : m.status === 'cancelled' ? '#f87171' : '#5a6a7a') + '">' + m.status.toUpperCase() + '</span>' + '</div>' + '<div style="color:#5a6a7a;font-size:11px;margin-bottom:16px">' + '<div>Program: ' + m.programName + ' (' + m.programHandle + ')</div>' + '<div>URL: <a href="' + m.programUrl + '" target="_blank" style="color:#22d3ee">' + m.programUrl + '</a></div>' + '<div>Created: ' + new Date(m.createdAt).toLocaleString() + '</div>' + '<div>Updated: ' + new Date(m.updatedAt).toLocaleString() + '</div>' + '</div>' + '<hr style="border-color:#1a1a2e;margin:16px 0">' + '<h4 style="color:#c084fc;margin-bottom:8px">📋 Scope (' + m.inScopeCount + ' assets)</h4>' + '<div id="missionScope" style="max-height:200px;overflow:auto;font-size:10px;color:#c8d6e5">' + '<div style="color:#5a6a7a">Loading scope...</div>' + '</div>' + '<hr style="border-color:#1a1a2e;margin:16px 0">' + '<h4 style="color:#c084fc;margin-bottom:8px">🎯 Objectives</h4>' + '<ul style="font-size:11px;color:#c8d6e5;margin-left:16px">' + (m.objectives?.map(function(o) { return '<li>' + o + '</li>'; }).join('') || '<li style="color:#5a6a7a">No objectives</li>') + '</ul>' + '<hr style="border-color:#1a1a2e;margin:16px 0">' + '<h4 style="color:#c084fc;margin-bottom:8px">📋 Activity Log</h4>' + '<div id="missionActivity" style="max-height:200px;overflow:auto;font-size:10px;color:#5a6a7a">' + '<div>Loading activity...</div>' + '</div>' + '<div style="margin-top:16px;display:flex;gap:8px">' + '<button onclick="runMissionRecon(\'' + m.id + '\')" style="flex:1;background:#a855f722;color:#c084fc;border:1px solid #a855f744;padding:8px;border-radius:4px;cursor:pointer">▶ Run Recon</button>' + '<button onclick="closeMissionDetail()" style="flex:1;background:#1a1a2e;color:#c8d6e5;border:1px solid #1a1a2e;padding:8px;border-radius:4px;cursor:pointer">Close</button>' + '</div>' + '</div>'; // Remove existing detail panel const existing = document.getElementById('missionDetailPanel'); if (existing) existing.remove(); const panel = document.createElement('div'); panel.id = 'missionDetailPanel'; panel.innerHTML = detailHtml; document.body.appendChild(panel); // Load scope and activity loadMissionScope(missionId); loadMissionActivity(missionId); } catch(e) { console.error(e); alert('Error loading mission: ' + e.message); }}
function closeMissionDetail() { const panel = document.getElementById('missionDetailPanel'); if (panel) panel.remove();}
async function loadMissionScope(missionId) { try { const m = await api('/api/missions/' + encodeURIComponent(missionId)); if (!m || !m.scope) { document.getElementById('missionScope').innerHTML = '<div style="color:#5a6a7a">No scope data</div>'; return; } let html = ''; if (m.scope.inScope?.length) { html += '<div style="color:#34d399;margin-bottom:8px">✅ IN SCOPE:</div>'; html += m.scope.inScope.map(s => '<div style="margin:4px 0;padding:4px 8px;background:#34d39911;border-radius:3px">' + (s.isWildcard ? '🌐 ' : '🎯 ') + s.identifier + ' <span style="color:#5a6a7a;font-size:9px">(' + s.assetType + ')</span>' + (s.instruction ? ' <span style="color:#fbbf24;font-size:9px">— ' + s.instruction + '</span>' : '') + '</div>' ).join(''); } if (m.scope.exclusions?.length) { html += '<div style="color:#f87171;margin:12px 0 8px">❌ EXCLUSIONS:</div>'; html += m.scope.exclusions.map(s => '<div style="margin:4px 0;padding:4px 8px;background:#f8717111;border-radius:3px">🚫 ' + s.identifier + (s.instruction ? ' <span style="color:#fbbf24;font-size:9px">— ' + s.instruction + '</span>' : '') + '</div>' ).join(''); } if (m.scope.restrictions?.length) { html += '<div style="color:#fbbf24;margin:12px 0 8px">⚠️ RESTRICTIONS:</div>'; html += m.scope.restrictions.map(r => '<div style="margin:4px 0;padding:4px 8px;background:#fbbf2411;border-radius:3px">📝 ' + r.asset + ': ' + r.restriction + ' [' + r.severity + ']</div>' ).join(''); } if (!html) html = '<div style="color:#5a6a7a">No scope data</div>'; document.getElementById('missionScope').innerHTML = html; } catch(e) { document.getElementById('missionScope').innerHTML = '<div style="color:#f87171">Error loading scope: ' + e.message + '</div>'; }}
async function loadMissionActivity(missionId) { try { const m = await api('/api/missions/' + encodeURIComponent(missionId)); if (!m || !m.activityLog?.length) { document.getElementById('missionActivity').innerHTML = '<div style="color:#5a6a7a">No activity log</div>'; return; } const html = m.activityLog.slice(-20).reverse().map(a => '<div style="margin:4px 0;padding:4px 8px;background:#0a0a0f;border-radius:3px">' + '<span style="color:#5a6a7a;font-size:9px">' + new Date(a.timestamp).toLocaleTimeString() + '</span> ' + '<span style="color:#c084fc;font-weight:600">[' + a.action + ']</span> ' + '<span style="color:#c8d6e5;font-size:10px">' + (a.details || '') + '</span>' + '</div>' ).join(''); document.getElementById('missionActivity').innerHTML = html; } catch(e) { document.getElementById('missionActivity').innerHTML = '<div style="color:#f87171">Error loading activity: ' + e.message + '</div>'; }}
async function runMissionRecon(missionId) { closeMissionDetail(); const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> @mission_recon start ' + missionId + '\\\\\\\\n'; out.scrollTop = out.scrollHeight; try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:'mission_recon', args:'start ' + missionId}) }); out.innerHTML += '<span class=ok>' + r.result + '</span>\\\\\\\\n\\\\\\\\n'; } catch(e) { out.innerHTML += '<span class=err>⛔ ' + e.message + '</span>\\\\\\\\n\\\\\\\\n'; } out.scrollTop = out.scrollHeight;}
async function loadSchedules() { try { const list = await api('/api/schedules'); renderSchedules(list); } catch(e) { document.getElementById('scheduleList').innerHTML = '<div class="error">' + e.message + '</div>'; }}
function renderSchedules(list) { const div = document.getElementById('scheduleList'); if (!list.length) { div.innerHTML = '<div style="color:#5a6a7a">No active schedules. Use @schedule|daily|tool|target to create one.</div>'; return; } div.innerHTML = list.map(function(s) { return '<div class="schedule-item">' + '<div class="header">' + '<span class="tool">@' + s.tool + '</span>' + '<span class="next">Next: ' + s.nextAtHuman + '</span>' + '</div>' + '<div class="target">Target: ' + s.target + '</div>' + '<div class="interval">Interval: ' + s.interval + ' • ID: ' + s.id + '</div>' + '<div style="margin-top:8px;display:flex;gap:4px">' + '<button onclick="editSchedule(' + s.id + ', \'' + s.tool + '\', \'' + s.target.replace(/'/g, "\\'") + '\', \'' + s.interval + '\')" style="background:#a855f722;color:#c084fc;border:1px solid #a855f744;padding:4px 8px;border-radius:3px;cursor:pointer;font-size:10px">✏ Edit</button>' + '<button onclick="deleteSchedule(' + s.id + ')" style="background:#f8717122;color:#f87171;border:1px solid #f8717144;padding:4px 8px;border-radius:3px;cursor:pointer;font-size:10px">🗑 Delete</button>' + '</div>' + '</div>'; }).join('');}
async function editSchedule(id, tool, target, interval) { const newInterval = prompt('Edit interval (daily, hourly, 30m, etc):', interval); if (newInterval === null) return; const newTarget = prompt('Edit target:', target); if (newTarget === null) return; try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:'schedule', args:'stop ' + id}) }); const r2 = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:'schedule', args:newInterval + '|' + tool + '|' + newTarget}) }); loadSchedules(); const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> @schedule ' + newInterval + '|' + tool + '|' + newTarget + '\\n'; out.innerHTML += '<span class=ok>' + r2.result + '</span>\\n\\n'; out.scrollTop = out.scrollHeight; } catch(e) { alert('Error editing schedule: ' + e.message); }}
async function deleteSchedule(id) { if (!confirm('Delete schedule ' + id + '?')) return; try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:'schedule', args:'stop ' + id}) }); loadSchedules(); const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> @schedule stop ' + id + '\\n'; out.innerHTML += '<span class=ok>' + r.result + '</span>\\n\\n'; out.scrollTop = out.scrollHeight; } catch(e) { alert('Error deleting schedule: ' + e.message); }}
async function loadTasks() { try { tasks = await api('/api/tasks'); renderTasks(tasks); } catch(e) { document.getElementById('taskGrid').innerHTML = '<div class="error">' + e.message + '</div>'; }}
function renderTasks(list) { const grid = document.getElementById('taskGrid'); grid.innerHTML = list.map(t => \` <div class="task-card" onclick="runTaskFromMonitor('\${t.name}')"> <div class="name">@\${t.name}</div> <div class="category">\${t.category}</div> </div> \`).join('');}
function filterTasks(q) { const cards = document.querySelectorAll('.task-card'); cards.forEach(c => { const name = c.querySelector('.name').textContent.toLowerCase(); const cat = c.querySelector('.category').textContent.toLowerCase(); c.style.display = (name.includes(q.toLowerCase()) || cat.includes(q.toLowerCase())) ? '' : 'none'; });}
async function runTaskFromMonitor(name) { const input = prompt('Enter arguments for @' + name + ':'); if (input === null) return; const out = document.getElementById('output'); out.classList.add('show'); out.innerHTML += '<span class="prompt">$</span> @' + name + '|' + input + '\\\\n'; out.scrollTop = out.scrollHeight; try { const r = await api('/api/run', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({tool:name, args:input}) }); out.innerHTML += r.result + '\\\\n\\\\n'; } catch(e) { out.innerHTML += '<span class="error">[Error] ' + e.message + '</span>\\\\n\\\\n'; } out.scrollTop = out.scrollHeight;}
function updateHealth(h) { document.getElementById('sysUptime').textContent = h.uptimeHuman || (Math.floor(h.uptime) + 's'); document.getElementById('sysMemory').textContent = h.memory.heapUsed + ' / ' + h.memory.heapTotal + ' (RSS: ' + h.memory.rss + ')'; document.getElementById('sysNode').textContent = h.nodeVersion; document.getElementById('sysPid').textContent = h.pid; document.getElementById('sysUsb').textContent = h.usbMounted ? '✓ Mounted' : '✗ Not mounted'; document.getElementById('sysUsb').className = 'stat-value ' + (h.usbMounted ? 'ok' : 'error'); // New fields const platformEl = document.getElementById('sysPlatform'); if (platformEl) platformEl.textContent = h.platform; const versionEl = document.getElementById('sysVersion'); if (versionEl) versionEl.textContent = h.nodeVersion;}
async function loadSystem() { try { const s = await api('/api/system'); document.getElementById('sysLoad').textContent = s.loadAvg || '—'; document.getElementById('sysDisk').textContent = s.disk ? s.disk.split('\n')[1]?.trim() || '—' : '—'; // New fields const netEl = document.getElementById('sysNet'); if (netEl) netEl.textContent = s.netDev ? s.netDev.split('\n').length + ' interfaces' : '—'; const diskIOEl = document.getElementById('sysDiskIO'); if (diskIOEl) diskIOEl.textContent = s.diskIO ? s.diskIO.split('\n').length + ' devices' : '—'; const uptimeEl = document.getElementById('sysUptime2'); if (uptimeEl) uptimeEl.textContent = Math.floor(s.uptime) + 's'; const platformEl = document.getElementById('sysPlatform'); if (platformEl) platformEl.textContent = s.platform; const versionEl = document.getElementById('sysVersion'); if (versionEl) versionEl.textContent = s.nodeVersion; const pidEl = document.getElementById('sysPid2'); if (pidEl) pidEl.textContent = s.pid; } catch(e) {}}
// Periodic refreshsetInterval(loadHealth, 10000);setInterval(loadSystem, 15000);setInterval(loadMissions, 30000);setInterval(loadSchedules, 10000);
function switchTab(name) { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.content').forEach(c => c.classList.remove('active')); document.querySelector('.tab[onclick*="' + name + '"]').classList.add('active'); document.getElementById(name).classList.add('active'); if (name === 'playbooks') loadPlaybooks(); if (name === 'reports') loadReports(); if (name === 'monitor') { loadMissions(); loadSchedules(); loadTasks(); loadHealth(); loadSystem(); }}
// InitializeloadTools();connectWS();
// WebSocket message handlerfunction handleWSMessage(msg) { if (msg.type === "health") updateHealth(msg.data); else if (msg.type === "missions") renderMissions(msg.data); else if (msg.type === "schedules") renderSchedules(msg.data);}</script></body></html>`;
export function startGui(port: number = parseInt(process.env.PHANTOM_PORT || "8080")): void { const server = http.createServer(async (req, res) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); if (req.method === "OPTIONS") { res.writeHead(204); res.end(); return; }
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); const path = url.pathname;
try { if (path === "/api/tools") { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(Object.keys(hackerTools).sort())); return; }
if (path === "/api/run" && req.method === "POST") { const body = await readBody(req); const { tool, args } = JSON.parse(body); const fn = hackerTools[tool]; if (!fn) { res.writeHead(404); res.end(JSON.stringify({ error: "Tool not found" })); return; } const result = await fn.execute(args); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ result })); return; }
if (path === "/api/playbooks") { const names: any[] = []; if (existsSync(PLAYBOOKS_DIR)) { for (const f of readdirSync(PLAYBOOKS_DIR).filter((f: string) => f.endsWith(".json"))) { const pb = JSON.parse(readFileSync(resolve(PLAYBOOKS_DIR, f), "utf-8")); names.push({ name: pb.name, description: pb.description, steps: pb.steps?.length || 0, vars: pb.variables }); } } res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(names)); return; }
if (path === "/api/playbook/run" && req.method === "POST") { const body = await readBody(req); const { name, vars } = JSON.parse(body); const fn = hackerTools["playbook_run"]; if (!fn) { res.writeHead(404); res.end(JSON.stringify({ error: "playbook_run tool not found" })); return; } const input = vars ? `${name}|${vars}` : name; const result = await fn.execute(input); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ result })); return; }
if (path === "/api/reports") { const reports: any[] = []; if (existsSync(REPORTS_DIR)) { for (const f of readdirSync(REPORTS_DIR).filter((f: string) => f.endsWith(".md") || f.endsWith(".txt"))) { const stat = existsSync(resolve(REPORTS_DIR, f)) ? "" : ""; reports.push({ name: f, size: formatSize(readFileSync(resolve(REPORTS_DIR, f)).length) }); } } res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(reports.sort((a, b) => a.name.localeCompare(b.name)))); return; }
if (path.startsWith("/api/report/")) { const name = decodeURIComponent(path.slice(12)); const fp = resolve(REPORTS_DIR, name); if (!existsSync(fp)) { res.writeHead(404); res.end(JSON.stringify({ error: "Not found" })); return; } const content = readFileSync(fp, "utf-8"); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ content })); return; }
// ── Monitoring API endpoints ── if (path === "/api/missions") { const missions: any[] = []; if (existsSync(MISSIONS_DIR)) { for (const f of readdirSync(MISSIONS_DIR).filter((f: string) => f.endsWith(".json"))) { const m = JSON.parse(readFileSync(resolve(MISSIONS_DIR, f), "utf-8")); missions.push({ id: m.id, programName: m.programName, programHandle: m.programHandle, status: m.status, createdAt: m.createdAt, updatedAt: m.updatedAt, inScopeCount: m.scope?.inScope?.length || 0, objectives: m.objectives?.length || 0 }); } } res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(missions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()))); return; }
if (path === "/api/schedules") { // Access globalThis.__phantomSchedules from the main process const schedules = (globalThis as any).__phantomSchedules || []; res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(schedules.map((s: any) => ({ id: s.id, tool: s.tool, target: s.target, interval: s.interval, nextAt: s.nextAt, nextAtHuman: new Date(s.nextAt).toLocaleString() })))); return; }
if (path === "/api/tasks") { // Get all available tasks from hackerTools const tasks = Object.keys(hackerTools).map(name => ({ name, category: categorizeTool(name) })); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(tasks)); return; }
if (path === "/api/health") { const mem = process.memoryUsage(); const uptime = process.uptime(); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ status: "ok", uptime: Math.floor(uptime), uptimeHuman: formatUptime(uptime), memory: { rss: Math.round(mem.rss / 1024 / 1024) + "MB", heapUsed: Math.round(mem.heapUsed / 1024 / 1024) + "MB", heapTotal: Math.round(mem.heapTotal / 1024 / 1024) + "MB", external: Math.round(mem.external / 1024 / 1024) + "MB" }, pid: process.pid, platform: process.platform, nodeVersion: process.version, usbMounted: existsSync("/root/usb/Phantom"), timestamp: new Date().toISOString() })); return; }
if (path === "/api/system") { const { execFileSync } = await import("child_process"); let diskInfo = ""; let loadAvg = ""; try { diskInfo = execFileSync("df", ["-h", "/root/usb"], { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} try { loadAvg = execFileSync("cat", ["/proc/loadavg"], { encoding: "utf-8", timeout: 5000 }).trim(); } catch {} res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ disk: diskInfo, loadAvg: loadAvg, cpus: require("os").cpus().length, totalMem: Math.round(require("os").totalmem() / 1024 / 1024 / 1024 * 10) / 10 + "GB", freeMem: Math.round(require("os").freemem() / 1024 / 1024 / 1024 * 10) / 10 + "GB" })); return; }
// Serve HTML for everything else res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(HTML); } catch (e: any) { res.writeHead(500, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: e.message })); } });
// WebSocket server for real-time updates if (WebSocketServer) { const wss = new WebSocketServer({ server }); wss.on("connection", (ws: any) => { wsClients.add(ws); ws.on("close", () => wsClients.delete(ws)); ws.on("error", () => wsClients.delete(ws)); // Send initial state ws.send(JSON.stringify({ type: "welcome", timestamp: new Date().toISOString() })); });
// Periodic broadcasts for real-time updates setInterval(broadcastHealth, 5000); setInterval(broadcastMissions, 30000); setInterval(broadcastSchedules, 10000); }
server.listen(port, () => { console.log(`\n 🌐 Phantom Dashboard: http://localhost:${port}\n`); });}
function readBody(req: http.IncomingMessage): Promise<string> { return new Promise((resolve, reject) => { let b = ""; req.on("data", (c: string) => b += c); req.on("end", () => resolve(b)); req.on("error", reject); });}
function formatSize(bytes: number): string { if (bytes < 1024) return bytes + "B"; if (bytes < 1048576) return (bytes / 1024).toFixed(1) + "KB"; return (bytes / 1048576).toFixed(1) + "MB";}
function categorizeTool(name: string): string { if (name.startsWith("mission") || name.startsWith("hackerone")) return "mission"; if (name.startsWith("recon") || name === "subfinder" || name === "dnsx" || name === "httpx" || name === "sub_enum" || name === "wayback" || name === "amass") return "recon"; if (name.startsWith("net:") || name === "port_scan" || name === "ssl_check" || name === "whois" || name === "geoip" || name === "dns_lookup" || name === "reverse_dns" || name === "nmap" || name === "naabu") return "network"; if (name.startsWith("vuln:") || name === "cve_search" || name === "exploit_search" || name === "nuclei" || name === "nikto" || name === "sqlmap" || name === "sql_detect" || name === "xss_scan") return "vulnerability"; if (name.startsWith("web:") || name === "crawl" || name === "http_headers" || name === "web_fetch" || name === "web_links" || name === "web_snapshot" || name === "whatweb" || name === "wafw00f" || name === "robots_txt" || name === "dir_bruteforce" || name === "ffuf" || name === "gobuster") return "web"; if (name.startsWith("osint:") || name === "email_verify" || name === "email_breach" || name === "github_dork" || name === "shodan_search" || name === "vt_check" || name === "cert_expiry") return "osint"; if (name.startsWith("schedule") || name === "cron" || name === "batch" || name === "pipe" || name === "session" || name === "playbook") return "automation"; return "other";}
function formatUptime(seconds: number): string { const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); const s = Math.floor(seconds % 60); const parts = []; if (d) parts.push(`${d}d`); if (h) parts.push(`${h}h`); if (m) parts.push(`${m}m`); if (s || parts.length === 0) parts.push(`${s}s`); return parts.join(" ");}1234567891011121314151617181920212223#!/usr/bin/env node
import { detectEnv } from "./core/config.js";
const env = detectEnv();
if (env.isTermux) { const { PhantomTermuxUI } = await import("./ui/termux.js"); const ui = new PhantomTermuxUI(); ui.start();} else if (env.screenSize === "tiny" || env.screenSize === "small") { const { PhantomTermuxUI } = await import("./ui/termux.js"); const ui = new PhantomTermuxUI(); ui.start();} else if (env.isWindows && env.terminal === "windows-console") { const { PhantomTermuxUI } = await import("./ui/termux.js"); const ui = new PhantomTermuxUI(); ui.start();} else { const { PhantomTerminal } = await import("./ui/terminal.js"); const terminal = new PhantomTerminal(); terminal.start();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318import { PhantomConfig } from "../core/config.js";
export interface LLMProvider { chat: (messages: { role: string; content: string }[], opts?: { model?: string; temperature?: number }) => Promise<string>; transcribe?: (filePath: string) => Promise<string>;}
interface ProviderConfig { url: string; keyEnv: string; defaultModel: string; chatPath: string; fmt: (o: any) => any; parse: (d: any) => string; auth: (k: string) => Record<string, string>; urlMod?: (u: string, m: string, k: string) => string;}
const PROVIDER_CONFIGS: Record<string, ProviderConfig> = { openai: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "deepseek-v4-flash-free", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: (d: any) => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens]" : "…"); }, auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) }, anthropic: { url: "https://api.anthropic.com/v1", keyEnv: "ANTHROPIC_API_KEY", defaultModel: "claude-sonnet-4-20250514", chatPath: "/messages", fmt: (o: any) => ({ model: o.model, messages: o.messages, max_tokens: 512 }), parse: (d: any) => d.content?.[0]?.text || d.content?.toString() || "...", auth: (k: string) => ({ "x-api-key": k, "anthropic-version": "2023-06-01" }) }, gemini: { url: "https://generativelanguage.googleapis.com/v1beta", keyEnv: "GEMINI_API_KEY", defaultModel: "gemini-2.0-flash", chatPath: "/models/{model}:generateContent", fmt: (o: any) => ({ contents: o.messages.map((m: any) => ({ role: m.role === "assistant" ? "model" : m.role, parts: [{ text: m.content }] })) }), parse: (d: any) => d.candidates?.[0]?.content?.parts?.[0]?.text || "...", auth: () => ({}), urlMod: (u: string, m: string, k: string) => `${u}${m}?key=${k}` }, groq: { url: "https://api.groq.com/openai/v1", keyEnv: "GROQ_API_KEY", defaultModel: "llama-3.3-70b-versatile", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) }, deepseek: { url: "https://api.deepseek.com/v1", keyEnv: "DEEPSEEK_API_KEY", defaultModel: "deepseek-chat", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) }, mistral: { url: "https://api.mistral.ai/v1", keyEnv: "MISTRAL_API_KEY", defaultModel: "mistral-large-latest", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) }, openrouter: { url: "https://openrouter.ai/api/v1", keyEnv: "OPENROUTER_API_KEY", defaultModel: "anthropic/claude-sonnet-4", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 512 }), parse: (d: any) => d.choices?.[0]?.message?.content?.trim() || "...", auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) }, ollama: { url: process.env.OLLAMA_HOST || "http://localhost:11434", keyEnv: "", defaultModel: "llama3", chatPath: "/api/chat", fmt: (o: any) => ({ model: o.model, messages: o.messages, stream: false }), parse: (d: any) => d.message?.content?.trim() || "...", auth: () => ({}) }, opencode: { url: "https://opencode.ai/zen/v1", keyEnv: "OPENCODE_ZEN_API_KEY", defaultModel: "deepseek-v4-flash-free", chatPath: "/chat/completions", fmt: (o: any) => ({ model: o.model, messages: o.messages, temperature: 0.7, max_tokens: 16384 }), parse: (d: any) => { const c = d.choices?.[0]?.message?.content?.trim(); return c || (d.choices?.[0]?.finish_reason === "length" ? "[Response truncated — increase max_tokens or shorten context]" : "…"); }, auth: (k: string) => ({ "Authorization": `Bearer ${k}` }) },} as const;
type ProviderName = keyof typeof PROVIDER_CONFIGS;
function getKey(p: ProviderConfig, config: PhantomConfig): string { if (p.keyEnv) { const k = process.env[p.keyEnv]; if (k) return k; // fallback: check config if ((config as any)[p.keyEnv]) return (config as any)[p.keyEnv]; } return "";}
export async function createProvider(config: PhantomConfig): Promise<LLMProvider> { // Determine provider order for fallback const fallbackOrder: ProviderName[] = ["openai", "anthropic", "groq", "gemini", "deepseek", "mistral", "openrouter", "opencode"]; // Find first available provider let selectedProvider: ProviderName = "openai"; for (const name of fallbackOrder) { const p = PROVIDER_CONFIGS[name]; if (p.keyEnv) { const key = getKey(p, config); if (key) { selectedProvider = name; break; } } else if (name === "ollama") { // Check if Ollama is available try { const r = await fetch(`${p.url}/api/tags`, { signal: AbortSignal.timeout(3000) }); if (r.ok) { selectedProvider = name; break; } } catch {} } }
const p = PROVIDER_CONFIGS[selectedProvider]; const key = getKey(p, config); const model = config.providers.openai?.baseUrl ? config.agents.defaultModel : p.defaultModel;
return { async chat(messages, opts = {}) { const modelToUse = opts.model || model; // Try selected provider first, then fallback through chain for (const providerName of fallbackOrder) { const provider = PROVIDER_CONFIGS[providerName]; if (!provider) continue;
const providerKey = getKey(provider, config); if (provider.keyEnv && !providerKey && providerName !== "ollama") continue;
try { let url = `${provider.url}${provider.chatPath.replace("{model}", modelToUse)}`; const headers = { "Content-Type": "application/json", ...provider.auth(providerKey) }; if (provider.urlMod) url = provider.urlMod(url, provider.chatPath.replace("{model}", modelToUse), providerKey); const body = JSON.stringify(provider.fmt({ model: modelToUse, messages }));
const r = await fetch(url, { method: "POST", headers, body, signal: AbortSignal.timeout(60000) });
if (!r.ok) { const t = await r.text().catch(() => ""); const err = `[${providerName} ${r.status}] ${t.substring(0, 200)}`;
// Fallback on rate limit or service errors if (r.status === 429 || r.status === 503 || r.status >= 500) { console.log(`[LLM Fallback] ${providerName} returned ${r.status}, trying next provider...`); continue; // Try next provider } return err; }
const d = await r.json(); const result = provider.parse(d) || "...";
if (providerName !== selectedProvider) { console.log(`[LLM Fallback] Switched to ${providerName}`); } return result; } catch (e: any) { console.log(`[LLM Fallback] ${providerName} error: ${e.message}, trying next...`); continue; } }
return `[LLM Fallback] All providers exhausted.`; },
async transcribe(filePath) { const openaiKey = getKey(PROVIDER_CONFIGS.openai, config); if (!openaiKey) return "[Transcribe] Set OPENCODE_ZEN_API_KEY"; try { const { readFileSync } = await import("fs"); const buf = readFileSync(filePath); const blob = new Blob([buf], { type: "audio/mpeg" }); const fd = new FormData(); fd.append("file", blob, "audio.mp3"); fd.append("model", "whisper-1"); const r = await fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers: { "Authorization": `Bearer ${openaiKey}` }, body: fd }); const d: any = await r.json(); return d.text || "[empty]"; } catch (e: any) { return `[Transcribe err] ${e.message}`; } } };}
export function createOpenAIProvider(config: PhantomConfig): LLMProvider { // Synchronous wrapper for backward compatibility - calls createProvider synchronously const { apiKey, baseUrl } = config.providers.openai; return { async chat(messages, opts = {}) { if (!apiKey) { return "[No OpenAI API key set. Configure via `OPENAI_API_KEY` env or `~/.config/phantom/config.json`]"; } try { const resp = await fetch(`${baseUrl}/chat/completions`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ model: opts.model || config.agents.defaultModel, messages, temperature: opts.temperature ?? 0.7, max_tokens: 1024, }), });
if (!resp.ok) { const err = await resp.text().catch(() => ""); return `[API error ${resp.status}: ${err.substring(0, 200)}]`; }
const data: any = await resp.json(); return data.choices?.[0]?.message?.content?.trim() || "[empty response]"; } catch (e: any) { return `[Request failed: ${e.message}]`; } },
async transcribe(filePath) { if (!apiKey) { return "[No OpenAI API key set. Configure via `OPENAI_API_KEY` env or `~/.config/phantom/config.json`]"; } try { const { readFileSync } = await import("fs"); const fileBuffer = readFileSync(filePath); const blob = new Blob([fileBuffer], { type: "audio/mpeg" }); const formData = new FormData(); formData.append("file", blob, "audio.mp3"); formData.append("model", "whisper-1");
const resp = await fetch(`${baseUrl}/audio/transcriptions`, { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, }, body: formData, });
if (!resp.ok) { const err = await resp.text().catch(() => ""); return `[Transcription API error ${resp.status}: ${err.substring(0, 200)}]`; }
const data: any = await resp.json(); return data.text || "[empty transcription]"; } catch (e: any) { return `[Transcription request failed: ${e.message}]`; } }, };}
export function createOllamaProvider(config: PhantomConfig): LLMProvider { const { baseUrl, model: defaultModel } = config.providers.ollama;
return { async chat(messages, opts = {}) { try { const resp = await fetch(`${baseUrl}/api/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: opts.model || defaultModel, messages, stream: false, }), });
if (!resp.ok) { const err = await resp.text().catch(() => ""); return `[Ollama error ${resp.status}: ${err.substring(0, 200)}]`; }
const data: any = await resp.json(); return data.message?.content?.trim() || "[empty response]"; } catch (e: any) { return `[Ollama request failed: ${e.message}]`; } }, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import blessed from "blessed";import { phantomTheme, phantomBorders, phantomBordersFocus } from "./theme.js";import { AgentIdentity } from "../agents/types.js";
export interface PhantomPanel { box: blessed.Widgets.BoxElement; log: blessed.Widgets.Log; agentId?: string;}
export class PanelManager { private screen: blessed.Widgets.Screen; private panels: PhantomPanel[] = []; private focusedIndex: number = 0; private container: blessed.Widgets.BoxElement;
constructor(screen: blessed.Widgets.Screen) { this.screen = screen; this.container = blessed.box({ parent: screen, top: 1, left: 0, width: "100%", height: "95%-1", }); }
createPanel(agent?: AgentIdentity): PhantomPanel { const cols = Math.ceil(Math.sqrt(this.panels.length + 1)); const rows = Math.ceil((this.panels.length + 1) / cols); const idx = this.panels.length;
const box = blessed.box({ parent: this.container, top: `${Math.floor(idx / cols) * (100 / rows)}%`, left: `${(idx % cols) * (100 / cols)}%`, width: `${100 / cols}%`, height: `${100 / rows}%`, border: phantomBorders, style: { bg: phantomTheme.panelBg, fg: phantomTheme.foreground, border: { fg: phantomTheme.border }, }, label: agent ? ` {bold}${agent.name}{/bold} [${agent.role}] ` : " {bold}~terminal{/bold} ", tags: true, });
const log = blessed.log({ parent: box, top: 0, left: 0, width: "100%", height: "100%-1", scrollable: true, scrollbar: { ch: "░", style: { fg: phantomTheme.dim }, }, style: { bg: phantomTheme.panelBg, fg: phantomTheme.foreground, }, keys: true, vi: true, alwaysScroll: true, scrollback: 500, tags: true, });
const footer = blessed.box({ parent: box, bottom: 0, left: 0, width: "100%", height: 1, content: agent ? ` {${agent.color}-fg}●{/${agent.color}-fg} ${agent.id}` : " {bold}←→{/bold} switch {bold}SPC{/bold} cmd {bold}ESC{/bold} menu ", tags: true, style: { bg: phantomTheme.titleBar, fg: phantomTheme.dim, }, });
const panel: PhantomPanel = { box, log, agentId: agent?.id }; this.panels.push(panel);
box.on("click", () => this.focus(idx)); this.focus(idx);
this.screen.render(); return panel; }
focus(index: number): void { const prev = this.panels[this.focusedIndex]; if (prev && prev.box.style.border) { (prev.box.style.border as Record<string, string>).fg = phantomTheme.border; }
this.focusedIndex = Math.max(0, Math.min(index, this.panels.length - 1));
const current = this.panels[this.focusedIndex]; if (current && current.box.style.border) { (current.box.style.border as Record<string, string>).fg = phantomTheme.borderFocus; } this.screen.render(); }
getFocused(): PhantomPanel | undefined { return this.panels[this.focusedIndex]; }
getPanels(): PhantomPanel[] { return this.panels; }
removePanel(id: string): void { const idx = this.panels.findIndex((p) => p.agentId === id); if (idx === -1) return; const panel = this.panels[idx]; panel.box.detach(); this.panels.splice(idx, 1); this.screen.render(); }
writeToPanel(agentId: string, msg: string): void { const panel = this.panels.find((p) => p.agentId === agentId); if (panel) { panel.log.add(msg); this.screen.render(); } }
writeToAll(msg: string): void { this.panels.forEach((p) => { p.log.add(msg); }); this.screen.render(); }
nextPanel(): void { this.focus((this.focusedIndex + 1) % this.panels.length); }
prevPanel(): void { this.focus((this.focusedIndex - 1 + this.panels.length) % this.panels.length); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275import blessed from "blessed";import { phantomTheme } from "./theme.js";import { PanelManager } from "./panels";import { AgentManager } from "../agents/manager";import { EventBus, EventHandler } from "../core/eventbus";import { AgentIdentity } from "../agents/types";import { loadConfig } from "../core/config";import { createOpenAIProvider, createOllamaProvider, LLMProvider } from "../providers/openai";
export class PhantomTerminal { private screen: blessed.Widgets.Screen; private panelManager!: PanelManager; private agentManager!: AgentManager; private bus: EventBus; private titleBar!: blessed.Widgets.BoxElement; private commandInput!: blessed.Widgets.TextboxElement; private llm?: LLMProvider;
constructor() { this.bus = EventBus.getInstance();
const config = loadConfig(); if (config.providers.openai.apiKey) { this.llm = createOpenAIProvider(config); } else if (config.providers.ollama.baseUrl) { try { this.llm = createOllamaProvider(config); } catch {} }
this.agentManager = new AgentManager(this.llm);
const term = process.env.TERM || "xterm-256color"; const isTermux = process.env.TERMUX_VERSION !== undefined;
this.screen = blessed.screen({ smartCSR: !isTermux, title: "Phantom — Space Evolving Terminal", cursor: { artificial: true, shape: "line", blink: true } as any, dockBorders: !isTermux, fullUnicode: true, terminal: term, useBCE: true, forceUnicode: true, sendFocus: true, debug: false, warnings: false, });
this.screen.key(["C-c", "C-q", "q"], () => { process.exit(0); });
this.screen.on("resize", () => { this.screen.render(); });
this.buildUI(); this.registerEvents(); this.spawnDefaultAgents(); }
private buildUI(): void { this.titleBar = blessed.box({ parent: this.screen, top: 0, left: 0, width: "100%", height: 1, content: this.makeTitleContent(0, false), tags: true, style: { bg: phantomTheme.titleBar, fg: phantomTheme.accent }, });
this.panelManager = new PanelManager(this.screen);
const statusBar = blessed.box({ parent: this.screen, bottom: 1, left: 0, width: "100%", height: 1, content: ` ${GRAY}⏎ cmd →← panels TAB focus ESC palette q quit${R}`, tags: true, style: { bg: phantomTheme.titleBar, fg: phantomTheme.dim }, });
this.commandInput = blessed.textbox({ parent: this.screen, bottom: 0, left: 0, width: "100%", height: 1, inputOnFocus: true, style: { bg: phantomTheme.background, fg: phantomTheme.accent2, focus: { bg: phantomTheme.background }, }, prompt: ` {${phantomTheme.accent2}-fg}⚡{/${phantomTheme.accent2}-fg} `, });
this.screen.key(["escape"], () => { this.commandInput.readInput((_err: any, val?: string) => { if (val) this.handleCommand(val); this.commandInput.clearValue(); this.screen.render(); }); });
this.screen.key(["tab"], () => { const focused = this.panelManager.getFocused(); if (focused) { this.commandInput.focus(); } else { this.screen.focusNext(); } this.screen.render(); });
this.screen.key(["right"], () => this.panelManager.nextPanel()); this.screen.key(["left"], () => this.panelManager.prevPanel());
if (!this.llm) { setTimeout(() => { const panel = this.panelManager.getFocused(); if (panel) { panel.log.add(`{yellow-fg}⚠ No LLM configured. Agents will use basic responses.{/yellow-fg}`); panel.log.add(`{cyan-fg} Set OPENAI_API_KEY or configure ~/.config/phantom/config.json{/cyan-fg}`); } }, 500); } }
private registerEvents(): void { this.bus.on("agent:spawned", ((data: unknown) => { const agent = data as AgentIdentity; const panel = this.panelManager.createPanel(agent); panel.log.add(`{green-fg}◈ Agent ${agent.name} initialized{/green-fg}`); panel.log.add(`{cyan-fg} id: ${agent.id} role: ${agent.role}{/cyan-fg}`); this.refreshTitle(); }) as EventHandler);
this.bus.on("agent:speaking", ((data: unknown) => { const { agent, message } = data as { agent: AgentIdentity; message: string }; this.panelManager.writeToPanel( agent.id, `{${agent.color}-fg}[${agent.name}]{/${agent.color}-fg} ${message}` ); this.refreshTitle(); }) as EventHandler);
this.bus.on("agent:thinking", ((_data: unknown) => { this.refreshTitle(); }) as EventHandler);
this.bus.on("agent:evolving", ((data: unknown) => { const { agent, level } = data as { agent: AgentIdentity; level: number }; this.panelManager.writeToPanel( agent.id, `{magenta-fg}⬆ EVOLVED to level ${level}{/magenta-fg}` ); }) as EventHandler);
this.bus.on("agent:removed", ((data: unknown) => { const id = data as string; this.panelManager.removePanel(id); this.panelManager.writeToAll(`{red-fg}◈ Agent ${id} terminated{/red-fg}`); this.refreshTitle(); }) as EventHandler); }
private makeTitleContent(count: number, hasThinking: boolean): string { const status = hasThinking ? "{yellow-fg}🧠 thinking{/yellow-fg}" : "{green-fg}⚡ idle{/green-fg}"; return ` {bold}PHANTOM{/bold} — space evolving terminal {#333355-fg}| agents: ${count} | ${status}{/#333355-fg}`; }
private refreshTitle(): void { const agents = this.agentManager.listAgents(); const hasThinking = agents.some((a) => a.status === "thinking"); this.titleBar.setContent(this.makeTitleContent(agents.length, hasThinking)); this.screen.render(); }
private spawnDefaultAgents(): void { this.agentManager.spawnDefaults(); }
private handleCommand(cmd: string): void { const parts = cmd.trim().split(/\s+/); const command = parts[0]?.toLowerCase(); const args = parts.slice(1); const panel = this.panelManager.getFocused();
switch (command) { case "spawn": case "s": { this.agentManager.spawnAgent(args[0], args[1], args.slice(2).join(" ")); break; } case "list": case "ls": { if (panel) { const agents = this.agentManager.listAgents(); panel.log.add(`{cyan-fg}◈ Agents (${agents.length}):{/cyan-fg}`); agents.forEach((a) => { panel.log.add( ` {${a.color}-fg}●{/${a.color}-fg} ${a.name} (${a.id}) — ${a.role} [${a.status}] ★${a.evolutionLevel}` ); }); } break; } case "broadcast": case "b": { const msg = args.join(" "); if (panel && panel.agentId && msg) { this.agentManager.broadcast(panel.agentId, msg); panel.log.add(`{cyan-fg}◈ Broadcasting...{/cyan-fg}`); } break; } case "debate": case "d": { const topic = args.join(" ") || "what should we build?"; const starterId = this.agentManager.listAgents()[0]?.id; if (starterId) { this.agentManager.debate(topic); if (panel) panel.log.add(`{magenta-fg}◈ Debate started: ${topic}{/magenta-fg}`); } break; } case "evolve": case "e": { this.agentManager.evolveAll(); this.panelManager.writeToAll("{magenta-fg}⬆ Mass evolution initiated{/magenta-fg}"); break; } case "clear": case "c": { if (panel) panel.log.setContent(""); break; } case "help": case "h": { if (panel) { panel.log.add(""); panel.log.add("{bold}PHANTOM COMMANDS{/bold}"); panel.log.add(` {green-fg}spawn{/green-fg} [name] [role] [persona] — create agent`); panel.log.add(` {green-fg}list{/green-fg} — list agents`); panel.log.add(` {green-fg}broadcast{/green-fg} <msg> — msg all agents`); panel.log.add(` {green-fg}debate{/green-fg} [topic] — agents debate`); panel.log.add(` {green-fg}evolve{/green-fg} — evolve all`); panel.log.add(` {green-fg}clear{/green-fg} — clear panel`); panel.log.add(` {green-fg}help{/green-fg} — this help`); panel.log.add(` {green-fg}quit{/green-fg} — exit`); panel.log.add(""); } break; } case "quit": case "q": process.exit(0); } }
start(): void { this.screen.render(); }}
const GRAY = "{#333355-fg}";const R = "{/}";.dockerignoreAdded+13
.editorconfigAdded+12
.gitattributesAdded+12
.github/workflows/ci.ymlAdded+49
.gitignoreAdded+13
.npmignoreAdded+12
.prettierrcAdded+13
CONTEXT.mdAdded+232
DockerfileAdded+23
LICENSEAdded+21
README.mdAdded+246
chat.mjsAdded+200
guides/hackersploit_fundamentals.mdAdded+51
lib/config.mjsAdded+15
lib/dashboard.mjsAdded+846
lib/env.mjsAdded+231
lib/evolve.mjsAdded+867
lib/logger.mjsAdded+17
lib/mission.mjsAdded+181
lib/playwright-tool.mjsAdded+122
lib/recon-analysis.mjsAdded+350
lib/recon-intelligence.mjsAdded+388
lib/recon-learning.mjsAdded+294
lib/recon-planner.mjsAdded+397
lib/recon.mjsAdded+425
lib/runtime.mjsAdded+250
lib/self_improve.mjsAdded+2548
lib/server.mjsAdded+394
lib/session.mjsAdded+125
lib/tools.mjsAdded
lib/tui.mjsAdded+159
lib/visual.mjsAdded+131
package-lock.jsonAdded+597
package.jsonAdded+49
phantom-logo.htmlAdded+294
phantom.mjsAdded
run.shAdded+110
src/agents/agent.tsAdded+397
src/agents/manager.tsAdded+126
src/agents/types.tsAdded+74
src/core/config.tsAdded+155
src/core/eventbus.tsAdded+41
src/core/hacker-tools.tsAdded
src/core/persistence.tsAdded+62
src/core/tools.tsAdded+79
src/gui/server.tsAdded+1012
src/index.tsAdded+23
src/providers/openai.tsAdded+318
src/ui/panels.tsAdded+153
src/ui/terminal.tsAdded+275