mirror of
https://github.com/myronblair/jarvis
synced 2026-07-29 17:22:35 -05:00
Compare commits
24 Commits
24b96e809c
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| ee0e116963 | |||
| adbd1a7a24 | |||
| 73aac8ab01 | |||
| 646da21b86 | |||
| d97a345672 | |||
| 141191bcdd | |||
| 8399048252 | |||
| 652e44f7b3 | |||
| 43be3e1105 | |||
| 3d16061709 | |||
| 80588efa7a | |||
| f7309a15fc | |||
| 18783dc137 | |||
| 8f6be645ed | |||
| 185d2c889f | |||
| b5c47d898b | |||
| ffc01c3d4a | |||
| 156b210184 | |||
| 09f73edb0b | |||
| a4336ebdd6 | |||
| e7f555fff1 | |||
| 8034fc67e9 | |||
| 48b2a8523a | |||
| 5ff4f3e311 |
@@ -1,4 +1,5 @@
|
|||||||
# Credentials - never commit
|
# Credentials - never commit
|
||||||
|
public_html/admin/downloads/INFRASTRUCTURE-REFERENCE.md
|
||||||
api/config.php
|
api/config.php
|
||||||
backup/
|
backup/
|
||||||
|
|
||||||
|
|||||||
+17
-38
@@ -6,20 +6,26 @@
|
|||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Installs JARVIS Agent as a Windows Service that auto-starts at boot.
|
Installs JARVIS Agent as a Windows Service that auto-starts at boot.
|
||||||
Requires: PowerShell 5.1+, internet access, and Administrator rights.
|
Requires: PowerShell 5.1+, internet access, and Administrator rights.
|
||||||
|
No Python installation needed — this installs the standalone .exe build.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
# Interactive install (prompts for registration key):
|
# Interactive install (prompts for registration key):
|
||||||
irm https://jarvis.orbishosting.com/agent/install-windows.ps1 | iex
|
irm https://jarvis.orbishosting.com:1972/agent/install-windows.ps1 | iex
|
||||||
|
|
||||||
# Silent install with key:
|
# Silent install with key:
|
||||||
$env:JARVIS_REG_KEY='your_key_here'; irm https://jarvis.orbishosting.com/agent/install-windows.ps1 | iex
|
$env:JARVIS_REG_KEY='your_key_here'; irm https://jarvis.orbishosting.com:1972/agent/install-windows.ps1 | iex
|
||||||
#>
|
#>
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$JARVIS_URL = 'https://jarvis.orbishosting.com'
|
# Fixed 2026-07-07: jarvis.orbishosting.com on the default port (80/443) is not
|
||||||
|
# reachable from outside the LAN at all (no FortiGate VIP forwards it) — every
|
||||||
|
# external install using the old default URL would have failed outright. Port
|
||||||
|
# 1972 is the confirmed-working external path (same fix applied to the GitHub
|
||||||
|
# webhook the same day).
|
||||||
|
$JARVIS_URL = 'http://jarvis.orbishosting.com:1972'
|
||||||
$INSTALL_DIR = 'C:\ProgramData\jarvis-agent'
|
$INSTALL_DIR = 'C:\ProgramData\jarvis-agent'
|
||||||
$SERVICE_NAME = 'JARVISAgent'
|
$SERVICE_NAME = 'JARVISAgent'
|
||||||
$AGENT_SCRIPT = "$INSTALL_DIR\jarvis-agent-windows.py"
|
$AGENT_EXE = "$INSTALL_DIR\jarvis-agent-windows.exe"
|
||||||
$CONFIG_FILE = "$INSTALL_DIR\config.json"
|
$CONFIG_FILE = "$INSTALL_DIR\config.json"
|
||||||
|
|
||||||
function Write-Step { param($msg) Write-Host "`n[JARVIS] $msg" -ForegroundColor Cyan }
|
function Write-Step { param($msg) Write-Host "`n[JARVIS] $msg" -ForegroundColor Cyan }
|
||||||
@@ -39,49 +45,23 @@ if ($existing) {
|
|||||||
Start-Sleep 2
|
Start-Sleep 2
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
& python "$INSTALL_DIR\jarvis-agent-windows.py" remove 2>$null
|
if (Test-Path $AGENT_EXE) { & $AGENT_EXE remove 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
Write-OK "Existing service removed."
|
Write-OK "Existing service removed."
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Check / install Python ────────────────────────────────────────────────────
|
|
||||||
Write-Step "Checking Python..."
|
|
||||||
$py = Get-Command python -ErrorAction SilentlyContinue
|
|
||||||
if (-not $py) {
|
|
||||||
Write-Host " Python not found. Installing via winget..." -ForegroundColor Yellow
|
|
||||||
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
|
|
||||||
Write-Fail "winget not available. Please install Python 3.11+ from https://python.org and re-run."
|
|
||||||
}
|
|
||||||
winget install -e --id Python.Python.3.11 --silent --accept-package-agreements --accept-source-agreements
|
|
||||||
$env:PATH = [System.Environment]::GetEnvironmentVariable("PATH","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH","User")
|
|
||||||
$py = Get-Command python -ErrorAction SilentlyContinue
|
|
||||||
if (-not $py) { Write-Fail "Python install failed. Please install manually from https://python.org" }
|
|
||||||
}
|
|
||||||
$pyVersion = & python --version 2>&1
|
|
||||||
Write-OK $pyVersion
|
|
||||||
|
|
||||||
# ── Install pywin32 ───────────────────────────────────────────────────────────
|
|
||||||
Write-Step "Checking pywin32..."
|
|
||||||
$checkWin32 = & python -c "import win32service; print('ok')" 2>&1
|
|
||||||
if ($checkWin32 -ne 'ok') {
|
|
||||||
Write-Host " Installing pywin32..." -ForegroundColor Yellow
|
|
||||||
& python -m pip install --quiet pywin32
|
|
||||||
& python -m pywin32_postinstall -install 2>$null
|
|
||||||
Write-OK "pywin32 installed."
|
|
||||||
} else {
|
|
||||||
Write-OK "pywin32 already installed."
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Create install dir ────────────────────────────────────────────────────────
|
# ── Create install dir ────────────────────────────────────────────────────────
|
||||||
Write-Step "Creating install directory..."
|
Write-Step "Creating install directory..."
|
||||||
New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
|
New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
|
||||||
Write-OK $INSTALL_DIR
|
Write-OK $INSTALL_DIR
|
||||||
|
|
||||||
# ── Download agent script ─────────────────────────────────────────────────────
|
# ── Download agent exe ─────────────────────────────────────────────────────────
|
||||||
|
# No Python/pywin32 dependency anymore — this is a self-contained PyInstaller
|
||||||
|
# build with everything it needs bundled in.
|
||||||
Write-Step "Downloading JARVIS agent..."
|
Write-Step "Downloading JARVIS agent..."
|
||||||
try {
|
try {
|
||||||
Invoke-WebRequest -Uri "$JARVIS_URL/agent/jarvis-agent-windows.py" -OutFile $AGENT_SCRIPT -UseBasicParsing
|
Invoke-WebRequest -Uri "$JARVIS_URL/agent/jarvis-agent-windows.exe" -OutFile $AGENT_EXE -UseBasicParsing
|
||||||
Write-OK "Agent downloaded to $AGENT_SCRIPT"
|
Write-OK "Agent downloaded to $AGENT_EXE"
|
||||||
} catch {
|
} catch {
|
||||||
Write-Fail "Failed to download agent: $_"
|
Write-Fail "Failed to download agent: $_"
|
||||||
}
|
}
|
||||||
@@ -121,8 +101,7 @@ Write-OK "Config written to $CONFIG_FILE"
|
|||||||
|
|
||||||
# ── Install Windows Service ───────────────────────────────────────────────────
|
# ── Install Windows Service ───────────────────────────────────────────────────
|
||||||
Write-Step "Installing Windows service..."
|
Write-Step "Installing Windows service..."
|
||||||
$pyPath = (Get-Command python).Source
|
& $AGENT_EXE --startup auto install
|
||||||
& $pyPath "$AGENT_SCRIPT" --startup auto install
|
|
||||||
if ($LASTEXITCODE -ne 0) { Write-Fail "Service install failed." }
|
if ($LASTEXITCODE -ne 0) { Write-Fail "Service install failed." }
|
||||||
Write-OK "Service '$SERVICE_NAME' installed."
|
Write-OK "Service '$SERVICE_NAME' installed."
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -35,7 +35,7 @@ INSTALL_DIR = Path(r"C:\ProgramData\jarvis-agent")
|
|||||||
CONFIG_PATH = INSTALL_DIR / "config.json"
|
CONFIG_PATH = INSTALL_DIR / "config.json"
|
||||||
STATE_PATH = INSTALL_DIR / "state.json"
|
STATE_PATH = INSTALL_DIR / "state.json"
|
||||||
LOG_PATH = INSTALL_DIR / "jarvis-agent.log"
|
LOG_PATH = INSTALL_DIR / "jarvis-agent.log"
|
||||||
AGENT_VERSION = "3.1"
|
AGENT_VERSION = "3.2"
|
||||||
|
|
||||||
# Set by the service wrapper so self_update knows to stop instead of exec
|
# Set by the service wrapper so self_update knows to stop instead of exec
|
||||||
_is_service = False
|
_is_service = False
|
||||||
@@ -92,7 +92,7 @@ def api_post(url: str, payload: dict, headers: dict = {}, timeout: int = 15,
|
|||||||
body = json.dumps(payload).encode()
|
body = json.dumps(payload).encode()
|
||||||
req = urllib.request.Request(url, data=body, method="POST")
|
req = urllib.request.Request(url, data=body, method="POST")
|
||||||
req.add_header("Content-Type", "application/json")
|
req.add_header("Content-Type", "application/json")
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
for k, v in headers.items():
|
for k, v in headers.items():
|
||||||
@@ -109,7 +109,7 @@ def api_post(url: str, payload: dict, headers: dict = {}, timeout: int = 15,
|
|||||||
def api_get(url: str, headers: dict = {}, timeout: int = 10,
|
def api_get(url: str, headers: dict = {}, timeout: int = 10,
|
||||||
ssl_verify: bool = True) -> dict:
|
ssl_verify: bool = True) -> dict:
|
||||||
req = urllib.request.Request(url)
|
req = urllib.request.Request(url)
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
for k, v in headers.items():
|
for k, v in headers.items():
|
||||||
@@ -375,18 +375,28 @@ def _sysinfo_snapshot() -> dict:
|
|||||||
# ── Self-update ────────────────────────────────────────────────────────────────
|
# ── Self-update ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def self_update(cfg: dict) -> bool:
|
def self_update(cfg: dict) -> bool:
|
||||||
|
# Added: supports both script-mode (plain .py, run via a system Python) and
|
||||||
|
# frozen-mode (standalone PyInstaller .exe — sys.frozen is set, __file__ isn't
|
||||||
|
# meaningful/writable the way it is for a real .py file on disk). A running
|
||||||
|
# .exe can't be overwritten in place on Windows, but CAN be renamed while
|
||||||
|
# running, so frozen mode uses a download-new/rename-old/rename-new swap
|
||||||
|
# instead of the direct overwrite the script-mode path uses.
|
||||||
jarvis_url = cfg.get("jarvis_url", "").rstrip("/")
|
jarvis_url = cfg.get("jarvis_url", "").rstrip("/")
|
||||||
|
is_frozen = bool(getattr(sys, "frozen", False))
|
||||||
|
if is_frozen:
|
||||||
|
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.exe" if jarvis_url else ""
|
||||||
|
else:
|
||||||
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.py" if jarvis_url else ""
|
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.py" if jarvis_url else ""
|
||||||
update_url = cfg.get("update_url", default_update_url)
|
update_url = cfg.get("update_url", default_update_url)
|
||||||
if not update_url:
|
if not update_url:
|
||||||
return False
|
return False
|
||||||
script_path = os.path.abspath(__file__)
|
target_path = os.path.abspath(sys.executable) if is_frozen else os.path.abspath(__file__)
|
||||||
ssl_verify = bool(cfg.get("ssl_verify", True))
|
ssl_verify = bool(cfg.get("ssl_verify", True))
|
||||||
try:
|
try:
|
||||||
# Download expected hash
|
# Download expected hash
|
||||||
hash_url = update_url + ".sha256"
|
hash_url = update_url + ".sha256"
|
||||||
req_hash = urllib.request.Request(hash_url)
|
req_hash = urllib.request.Request(hash_url)
|
||||||
req_hash.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req_hash.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req_hash.add_header("Host", _host_header)
|
req_hash.add_header("Host", _host_header)
|
||||||
expected_hash = None
|
expected_hash = None
|
||||||
@@ -397,13 +407,13 @@ def self_update(cfg: dict) -> bool:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Download new script
|
# Download new script/exe
|
||||||
req = urllib.request.Request(update_url)
|
req = urllib.request.Request(update_url)
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
ctx = _make_ssl_ctx(ssl_verify)
|
ctx = _make_ssl_ctx(ssl_verify)
|
||||||
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
|
with urllib.request.urlopen(req, timeout=60, context=ctx) as resp:
|
||||||
new_content = resp.read()
|
new_content = resp.read()
|
||||||
|
|
||||||
# Verify hash
|
# Verify hash
|
||||||
@@ -413,20 +423,42 @@ def self_update(cfg: dict) -> bool:
|
|||||||
log(f"Update hash mismatch (expected {expected_hash[:16]}… got {actual_hash[:16]}…) — aborting")
|
log(f"Update hash mismatch (expected {expected_hash[:16]}… got {actual_hash[:16]}…) — aborting")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
with open(script_path, "rb") as f:
|
with open(target_path, "rb") as f:
|
||||||
current = f.read()
|
current = f.read()
|
||||||
if new_content != current:
|
if new_content == current:
|
||||||
log(f"Update verified — replacing {script_path} and restarting...")
|
return False
|
||||||
with open(script_path, "wb") as f:
|
|
||||||
|
log(f"Update verified — replacing {target_path} and restarting...")
|
||||||
|
if is_frozen:
|
||||||
|
# Can't overwrite a running exe, but can rename it and drop the new
|
||||||
|
# one in its place; the old copy is cleaned up on the next update.
|
||||||
|
old_path = target_path + ".old"
|
||||||
|
new_path = target_path + ".new"
|
||||||
|
with open(new_path, "wb") as f:
|
||||||
f.write(new_content)
|
f.write(new_content)
|
||||||
|
try:
|
||||||
|
if os.path.exists(old_path):
|
||||||
|
os.remove(old_path)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
os.rename(target_path, old_path)
|
||||||
|
os.rename(new_path, target_path)
|
||||||
|
else:
|
||||||
|
with open(target_path, "wb") as f:
|
||||||
|
f.write(new_content)
|
||||||
|
|
||||||
if _is_service:
|
if _is_service:
|
||||||
# Signal the main loop to exit; SCM failure-recovery will restart us
|
# Signal the main loop to exit; SCM failure-recovery will restart us
|
||||||
log("Running as service — stopping for SCM-managed restart after update.")
|
log("Running as service — stopping for SCM-managed restart after update.")
|
||||||
_stop_event.set()
|
_stop_event.set()
|
||||||
|
elif is_frozen:
|
||||||
|
# sys.argv[0] is already the exe's own path for a frozen app — don't
|
||||||
|
# prepend sys.executable again or the new process misreads its own
|
||||||
|
# path as a command-line argument.
|
||||||
|
os.execv(sys.executable, sys.argv)
|
||||||
else:
|
else:
|
||||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||||
return True
|
return True
|
||||||
return False
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(f"Self-update check failed: {e}")
|
log(f"Self-update check failed: {e}")
|
||||||
return False
|
return False
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@ fi
|
|||||||
SUBNET="10.48.200.0/24"
|
SUBNET="10.48.200.0/24"
|
||||||
|
|
||||||
TMPFILE=$(mktemp)
|
TMPFILE=$(mktemp)
|
||||||
nmap -sn --send-ip "$SUBNET" 2>/dev/null > "$TMPFILE"
|
nmap -sn "$SUBNET" 2>/dev/null > "$TMPFILE"
|
||||||
|
|
||||||
if [ ! -s "$TMPFILE" ]; then
|
if [ ! -s "$TMPFILE" ]; then
|
||||||
echo "$(date): nmap produced no output" >&2
|
echo "$(date): nmap produced no output" >&2
|
||||||
|
|||||||
@@ -47,8 +47,11 @@ define(chr(39)+'HA_TOKEN'.chr(39), chr(39)+'YOUR_HA_LONG_LIVED_TOKEN'.chr(39));
|
|||||||
define(chr(39)+'SESSION_LIFETIME'.chr(39), 86400 * 7);
|
define(chr(39)+'SESSION_LIFETIME'.chr(39), 86400 * 7);
|
||||||
define(chr(39)+'SITE_URL'.chr(39), chr(39)+'https://jarvis.orbishosting.com'.chr(39));
|
define(chr(39)+'SITE_URL'.chr(39), chr(39)+'https://jarvis.orbishosting.com'.chr(39));
|
||||||
|
|
||||||
error_reporting(0);
|
error_reporting(E_ALL);
|
||||||
ini_set(chr(39)+'display_errors'.chr(39), 0);
|
ini_set(chr(39)+'display_errors'.chr(39), 0);
|
||||||
ini_set(chr(39)+'log_errors'.chr(39), 1);
|
ini_set(chr(39)+'log_errors'.chr(39), 1);
|
||||||
ini_set(chr(39)+'error_log'.chr(39), chr(39)+'/var/log/apache2/jarvis_errors.log'.chr(39));
|
ini_set(chr(39)+'error_log'.chr(39), chr(39)+'/var/log/apache2/jarvis_errors.log'.chr(39));
|
||||||
date_default_timezone_set(chr(39)+'America/Chicago'.chr(39));
|
date_default_timezone_set(chr(39)+'America/Chicago'.chr(39));
|
||||||
|
|
||||||
|
define('JELLYFIN_URL', 'http://10.48.200.33:8096');
|
||||||
|
define('JELLYFIN_API_KEY', 'your-jellyfin-api-key');
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ function update_agent_seen(string $agentId, string $status = 'online', ?string $
|
|||||||
// ── Auth (all actions except register) ───────────────────────────────────────
|
// ── Auth (all actions except register) ───────────────────────────────────────
|
||||||
|
|
||||||
$agentKey = $_SERVER['HTTP_X_AGENT_KEY'] ?? '';
|
$agentKey = $_SERVER['HTTP_X_AGENT_KEY'] ?? '';
|
||||||
$browserActions = ['list', 'status', 'myip'];
|
$browserActions = ['list', 'status', 'myip', 'regkey'];
|
||||||
|
|
||||||
if ($agentAction !== 'register') {
|
if ($agentAction !== 'register') {
|
||||||
if (in_array($agentAction, $browserActions)) {
|
if (in_array($agentAction, $browserActions)) {
|
||||||
@@ -212,6 +212,10 @@ switch ($agentAction) {
|
|||||||
);
|
);
|
||||||
agent_ok();
|
agent_ok();
|
||||||
|
|
||||||
|
// ── REGKEY (browser: session-authed fetch of registration key) ───────────
|
||||||
|
case 'regkey':
|
||||||
|
agent_ok(['registration_key' => AGENT_REGISTRATION_KEY]);
|
||||||
|
|
||||||
// ── LIST (admin: get all agents status) ──────────────────────────────────
|
// ── LIST (admin: get all agents status) ──────────────────────────────────
|
||||||
case 'list':
|
case 'list':
|
||||||
// Mark agents offline if last_seen > 2 minutes ago
|
// Mark agents offline if last_seen > 2 minutes ago
|
||||||
|
|||||||
@@ -197,6 +197,11 @@ function collect_all(): array {
|
|||||||
'orbisportal' => 'https://orbis.orbishosting.com',
|
'orbisportal' => 'https://orbis.orbishosting.com',
|
||||||
'tomtomgames' => 'https://tomtomgames.com',
|
'tomtomgames' => 'https://tomtomgames.com',
|
||||||
];
|
];
|
||||||
|
// Sites intentionally gated behind HTTP Basic Auth (e.g. a password-protected
|
||||||
|
// "Coming Soon" page during a rebuild) — treat these status codes as up, not down.
|
||||||
|
$expectedCodes = [
|
||||||
|
'parkerslingshotrentals' => [401],
|
||||||
|
];
|
||||||
$down = [];
|
$down = [];
|
||||||
foreach ($sites as $key => $url) {
|
foreach ($sites as $key => $url) {
|
||||||
$parsed = parse_url($url);
|
$parsed = parse_url($url);
|
||||||
@@ -216,7 +221,8 @@ function collect_all(): array {
|
|||||||
curl_exec($ch);
|
curl_exec($ch);
|
||||||
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
$status = ($code >= 200 && $code < 400) ? 'up' : "down-$code";
|
$ok = ($code >= 200 && $code < 400) || in_array($code, $expectedCodes[$key] ?? [], true);
|
||||||
|
$status = $ok ? 'up' : "down-$code";
|
||||||
KBEngine::storeFact('sites', $key, $status, $url, 180);
|
KBEngine::storeFact('sites', $key, $status, $url, 180);
|
||||||
if ($status !== 'up') $down[] = "$key($code)";
|
if ($status !== 'up') $down[] = "$key($code)";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
// Chat history search endpoint
|
// Chat history search endpoint
|
||||||
require_once __DIR__ . '/../config.php';
|
require_once __DIR__ . '/../config.php';
|
||||||
require_once __DIR__ . '/../../includes/auth.php';
|
|
||||||
|
|
||||||
header('Content-Type: application/json');
|
header('Content-Type: application/json');
|
||||||
AuthMiddleware::requireAuth();
|
|
||||||
|
|
||||||
$q = trim($_GET['q'] ?? '');
|
$q = trim($_GET['q'] ?? '');
|
||||||
if (strlen($q) < 2) {
|
if (strlen($q) < 2) {
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
require_once __DIR__ . '/../config.php';
|
require_once __DIR__ . '/../config.php';
|
||||||
require_once __DIR__ . '/../../includes/auth.php';
|
|
||||||
|
|
||||||
header('Content-Type: application/json');
|
header('Content-Type: application/json');
|
||||||
AuthMiddleware::requireAuth();
|
|
||||||
|
|
||||||
$action = $_GET['action'] ?? 'sessions';
|
$action = $_GET['action'] ?? 'sessions';
|
||||||
|
|
||||||
|
|||||||
@@ -1,284 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
* JARVIS KB Intent Generator
|
|
||||||
* Generates 1,000+ educational KB intents via Groq LLM and imports to kb_intents table.
|
|
||||||
* Also runs a cleanup pass: deduplication, short-response pruning, pattern normalisation.
|
|
||||||
*
|
|
||||||
* CLI / cron: /usr/bin/php8.3 /var/www/jarvis/api/endpoints/kb_intent_generator.php
|
|
||||||
* Schedule: Weekly – Sunday 3 am
|
|
||||||
*/
|
|
||||||
|
|
||||||
require_once __DIR__ . '/../config.php';
|
|
||||||
require_once __DIR__ . '/../lib/db.php';
|
|
||||||
|
|
||||||
/* ── helpers ── */
|
|
||||||
function ts(): string { return '[' . date('Y-m-d H:i:s') . ']'; }
|
|
||||||
function log_line(string $msg): void { echo ts() . ' KB Intent Generator: ' . $msg . "\n"; flush(); }
|
|
||||||
function groq(string $system, string $user, int $max = 3000): ?string {
|
|
||||||
$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
|
|
||||||
curl_setopt_array($ch, [
|
|
||||||
CURLOPT_RETURNTRANSFER => true,
|
|
||||||
CURLOPT_POST => true,
|
|
||||||
CURLOPT_TIMEOUT => 60,
|
|
||||||
CURLOPT_HTTPHEADER => [
|
|
||||||
'Authorization: Bearer ' . GROQ_API_KEY,
|
|
||||||
'Content-Type: application/json',
|
|
||||||
],
|
|
||||||
CURLOPT_POSTFIELDS => json_encode([
|
|
||||||
'model' => 'llama-3.3-70b-versatile',
|
|
||||||
'max_tokens' => $max,
|
|
||||||
'temperature' => 0.7,
|
|
||||||
'messages' => [
|
|
||||||
['role' => 'system', 'content' => $system],
|
|
||||||
['role' => 'user', 'content' => $user],
|
|
||||||
],
|
|
||||||
]),
|
|
||||||
]);
|
|
||||||
$raw = curl_exec($ch);
|
|
||||||
$err = curl_error($ch);
|
|
||||||
curl_close($ch);
|
|
||||||
if ($err || !$raw) return null;
|
|
||||||
$d = json_decode($raw, true);
|
|
||||||
return $d['choices'][0]['message']['content'] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── daily guard: skip if already ran within last 20 hours ── */
|
|
||||||
$lastRun = JarvisDB::single(
|
|
||||||
"SELECT updated_at FROM kb_facts WHERE category='kb_generator' AND fact_key='last_run'"
|
|
||||||
);
|
|
||||||
if ($lastRun && (time() - strtotime($lastRun['updated_at'])) < 72000) {
|
|
||||||
log_line('Skipping – ran within last 6 days (next run Sunday 3am).');
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_line('Starting weekly KB intent generation run.');
|
|
||||||
|
|
||||||
/* ── topic batches (25 topics × ~40 intents = 1,000+) ── */
|
|
||||||
$BATCHES = [
|
|
||||||
['id' => 'math_elem', 'category' => 'math_elementary', 'topic' => 'Elementary school mathematics',
|
|
||||||
'desc' => 'counting, basic arithmetic, place value, simple fractions, 2D/3D shapes, measurement, telling time, money, patterns'],
|
|
||||||
['id' => 'math_mid', 'category' => 'math_middle', 'topic' => 'Middle school mathematics',
|
|
||||||
'desc' => 'ratios, percentages, integers, exponents, pre-algebra equations, coordinate planes, probability, statistics (mean/median/mode), geometry area/volume'],
|
|
||||||
['id' => 'math_high', 'category' => 'math_high', 'topic' => 'High school mathematics',
|
|
||||||
'desc' => 'quadratic equations, polynomials, functions, logarithms, trigonometry (SOH-CAH-TOA, unit circle), sequences, permutations and combinations, matrices'],
|
|
||||||
['id' => 'math_college', 'category' => 'math_college', 'topic' => 'College-level mathematics',
|
|
||||||
'desc' => 'limits and continuity, derivatives, integrals, chain rule, L\'Hopital, differential equations, vectors, eigenvalues, hypothesis testing, normal distribution'],
|
|
||||||
['id' => 'bio_cell', 'category' => 'biology', 'topic' => 'Cell biology and genetics',
|
|
||||||
'desc' => 'organelles, mitosis vs meiosis, DNA structure, protein synthesis (transcription/translation), Mendelian genetics, dominant/recessive, mutations, genetic disorders'],
|
|
||||||
['id' => 'bio_body', 'category' => 'biology', 'topic' => 'Human body systems',
|
|
||||||
'desc' => 'skeletal, muscular, cardiovascular, respiratory, digestive, nervous, endocrine, immune, reproductive, and excretory systems'],
|
|
||||||
['id' => 'bio_ecology', 'category' => 'biology', 'topic' => 'Ecology and evolution',
|
|
||||||
'desc' => 'ecosystems, biomes, food webs, trophic levels, symbiosis (mutualism/commensalism/parasitism), natural selection, adaptation, speciation, biodiversity'],
|
|
||||||
['id' => 'chem_basics', 'category' => 'chemistry', 'topic' => 'Chemistry fundamentals',
|
|
||||||
'desc' => 'atomic structure, periodic table trends, ionic vs covalent bonds, Lewis structures, polarity, molecular geometry (VSEPR), intermolecular forces'],
|
|
||||||
['id' => 'chem_rxns', 'category' => 'chemistry', 'topic' => 'Chemical reactions and thermochemistry',
|
|
||||||
'desc' => 'balancing equations, stoichiometry, limiting reagents, reaction types, enthalpy, entropy, Gibbs free energy, Le Chatelier\'s principle, equilibrium constants'],
|
|
||||||
['id' => 'phys_mech', 'category' => 'physics', 'topic' => 'Physics – mechanics and energy',
|
|
||||||
'desc' => 'kinematics, Newton\'s three laws, friction, momentum, conservation of energy, work and power, circular motion, gravitation, projectile motion'],
|
|
||||||
['id' => 'phys_em', 'category' => 'physics', 'topic' => 'Physics – waves, electricity and magnetism',
|
|
||||||
'desc' => 'wave properties (amplitude, frequency, wavelength), sound, light spectrum, reflection/refraction, Ohm\'s law, series vs parallel circuits, magnetic fields, electromagnetic induction'],
|
|
||||||
['id' => 'earth_sci', 'category' => 'earth_science', 'topic' => 'Earth and environmental science',
|
|
||||||
'desc' => 'rock cycle, plate tectonics, earthquakes, volcanoes, atmosphere layers, weather vs climate, greenhouse effect, water cycle, ocean currents, soil formation'],
|
|
||||||
['id' => 'astronomy', 'category' => 'astronomy', 'topic' => 'Astronomy and space science',
|
|
||||||
'desc' => 'solar system planets, star life cycles, galaxies, Big Bang theory, light-years, telescopes, space exploration milestones, dark matter/energy, black holes'],
|
|
||||||
['id' => 'hist_us', 'category' => 'history_us', 'topic' => 'United States history',
|
|
||||||
'desc' => 'colonial era, American Revolution, Constitution, westward expansion, Civil War, Reconstruction, Gilded Age, WWI, Great Depression, WWII, Civil Rights, Cold War, modern era'],
|
|
||||||
['id' => 'hist_world', 'category' => 'history_world', 'topic' => 'World history',
|
|
||||||
'desc' => 'ancient civilisations (Egypt, Greece, Rome, Mesopotamia, China, India), Medieval period, Renaissance, Reformation, age of exploration, colonialism, Industrial Revolution, WWI, WWII, decolonisation, Cold War'],
|
|
||||||
['id' => 'geo_world', 'category' => 'geography', 'topic' => 'World geography',
|
|
||||||
'desc' => 'continents and oceans, countries and capitals, physical features (mountains, rivers, deserts), climate zones, latitude/longitude, map projections, time zones, population distribution'],
|
|
||||||
['id' => 'civics', 'category' => 'civics', 'topic' => 'Civics and US government',
|
|
||||||
'desc' => 'three branches of government, checks and balances, Bill of Rights, Constitutional amendments, federalism, Electoral College, legislative process, Supreme Court landmark cases, political parties'],
|
|
||||||
['id' => 'econ', 'category' => 'economics', 'topic' => 'Economics',
|
|
||||||
'desc' => 'supply and demand, market equilibrium, elasticity, GDP, inflation, unemployment, fiscal vs monetary policy, comparative advantage, market structures (monopoly, oligopoly, perfect competition), opportunity cost'],
|
|
||||||
['id' => 'lit_writing', 'category' => 'literature', 'topic' => 'Literature and writing',
|
|
||||||
'desc' => 'figurative language (simile, metaphor, personification, irony), plot structure, literary themes, point of view, genre types, essay structure, thesis statements, grammar rules, poetry forms, citing sources'],
|
|
||||||
['id' => 'cs_prog', 'category' => 'computer_science', 'topic' => 'Computer science and programming',
|
|
||||||
'desc' => 'variables, data types, loops, conditionals, functions, OOP concepts, arrays/lists, sorting and searching algorithms, time/space complexity, binary, hexadecimal, recursion, debugging'],
|
|
||||||
['id' => 'cs_systems', 'category' => 'computer_science', 'topic' => 'Computer systems and networking',
|
|
||||||
'desc' => 'CPU/RAM/storage, operating systems, file systems, TCP/IP, DNS, HTTP/HTTPS, databases (SQL vs NoSQL), cybersecurity threats (phishing, SQL injection, XSS, malware), encryption basics, cloud computing'],
|
|
||||||
['id' => 'psych', 'category' => 'psychology', 'topic' => 'Psychology',
|
|
||||||
'desc' => 'classical and operant conditioning, Maslow\'s hierarchy, Piaget\'s stages, Erikson\'s stages, memory types, sleep stages, cognitive biases, Freud\'s theory, social influence, abnormal psychology basics'],
|
|
||||||
['id' => 'phil', 'category' => 'philosophy', 'topic' => 'Philosophy and logic',
|
|
||||||
'desc' => 'Socrates/Plato/Aristotle, ethical theories (utilitarianism, deontology, virtue ethics), epistemology, deductive vs inductive reasoning, logical fallacies, existentialism, free will vs determinism, political philosophy'],
|
|
||||||
['id' => 'health_sci', 'category' => 'health', 'topic' => 'Health and life skills',
|
|
||||||
'desc' => 'nutrition (macronutrients, vitamins, minerals), exercise physiology, mental health (anxiety, depression, stress response), reproductive health, substance abuse, first aid, disease prevention, sleep hygiene'],
|
|
||||||
['id' => 'arts_music', 'category' => 'arts', 'topic' => 'Arts and music',
|
|
||||||
'desc' => 'elements of art (line, shape, color, texture), colour theory, major art movements, famous artists and their works, music notes and scales, rhythm and meter, instrument families, major composers and genres'],
|
|
||||||
];
|
|
||||||
|
|
||||||
/* ── system prompt ── */
|
|
||||||
$SYSTEM = <<<'SYS'
|
|
||||||
You are an expert educator generating KB (knowledge-base) intents for an AI assistant called JARVIS.
|
|
||||||
Each intent is a question/phrase a student might ask, paired with a clear educational answer.
|
|
||||||
|
|
||||||
Respond ONLY with a valid JSON array (no markdown, no backticks, no commentary).
|
|
||||||
Each element must have exactly these keys:
|
|
||||||
"n" – intent_name: unique snake_case identifier ≤ 60 chars, prefixed with the batch id given
|
|
||||||
"p" – pattern: a PHP PCRE regex (use (?i) for case-insensitive) that matches the question
|
|
||||||
"r" – response: a thorough but concise educational answer (2–5 sentences or a short structured list)
|
|
||||||
"c" – category: the category string provided
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- Patterns must use \\b word boundaries; escape backslashes for JSON (\\b not \b)
|
|
||||||
- Patterns should NOT start with ^ or end with $ (they are substring matches)
|
|
||||||
- Responses must be factually accurate
|
|
||||||
- Do not duplicate intent names; every "n" must be unique within this batch
|
|
||||||
- Return exactly 40 intents
|
|
||||||
SYS;
|
|
||||||
|
|
||||||
/* ── insert helper ── */
|
|
||||||
$inserted = 0;
|
|
||||||
$skipped = 0;
|
|
||||||
$errors = 0;
|
|
||||||
|
|
||||||
function safe_insert(array $intent, string $batchCategory): void {
|
|
||||||
global $inserted, $skipped, $errors;
|
|
||||||
$name = trim($intent['n'] ?? '');
|
|
||||||
$pattern = trim($intent['p'] ?? '');
|
|
||||||
$response = trim($intent['r'] ?? '');
|
|
||||||
$category = trim($intent['c'] ?? $batchCategory);
|
|
||||||
|
|
||||||
if (!$name || !$pattern || !$response) { $errors++; return; }
|
|
||||||
if (strlen($name) > 64) $name = substr($name, 0, 64);
|
|
||||||
if (strlen($pattern) > 512) $pattern = substr($pattern, 0, 512);
|
|
||||||
if (strlen($response) < 30) { $skipped++; return; } // too short
|
|
||||||
|
|
||||||
try {
|
|
||||||
JarvisDB::execute(
|
|
||||||
'INSERT INTO kb_intents (intent_name, pattern, response_template, fact_category, action_type, priority, active)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
||||||
ON DUPLICATE KEY UPDATE
|
|
||||||
pattern=VALUES(pattern),
|
|
||||||
response_template=VALUES(response_template),
|
|
||||||
fact_category=VALUES(fact_category)',
|
|
||||||
[$name, $pattern, $response, $category, 'response', 5, 1]
|
|
||||||
);
|
|
||||||
$inserted++;
|
|
||||||
} catch (Exception $e) {
|
|
||||||
$errors++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── main generation loop ── */
|
|
||||||
$totalBatches = count($BATCHES);
|
|
||||||
foreach ($BATCHES as $idx => $batch) {
|
|
||||||
$num = $idx + 1;
|
|
||||||
log_line("Batch {$num}/{$totalBatches}: {$batch['topic']}");
|
|
||||||
|
|
||||||
$user = "Generate 40 KB intents for the topic: {$batch['topic']}.\n"
|
|
||||||
. "Subtopics to cover: {$batch['desc']}.\n"
|
|
||||||
. "Prefix every intent_name with \"{$batch['id']}_\".\n"
|
|
||||||
. "Category string to use: \"{$batch['category']}\".";
|
|
||||||
|
|
||||||
$raw = groq($SYSTEM, $user, 3500);
|
|
||||||
if ($raw === null) {
|
|
||||||
log_line(" ✗ API call failed – skipping batch.");
|
|
||||||
$errors += 40;
|
|
||||||
sleep(3);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strip markdown code fences if model added them
|
|
||||||
$raw = preg_replace('/^```(?:json)?\s*/m', '', $raw);
|
|
||||||
$raw = preg_replace('/^```\s*/m', '', $raw);
|
|
||||||
$raw = trim($raw);
|
|
||||||
|
|
||||||
// Extract JSON array (even if the model added preamble text)
|
|
||||||
if (!preg_match('/\[\s*\{.*\}\s*\]/s', $raw, $m)) {
|
|
||||||
log_line(" ✗ No JSON array found in response – skipping batch.");
|
|
||||||
$errors += 40;
|
|
||||||
sleep(2);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$items = json_decode($m[0], true);
|
|
||||||
if (!is_array($items)) {
|
|
||||||
log_line(" ✗ JSON parse failed – skipping batch.");
|
|
||||||
$errors += 40;
|
|
||||||
sleep(2);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$batchInserted = 0;
|
|
||||||
foreach ($items as $item) {
|
|
||||||
if (!is_array($item)) continue;
|
|
||||||
safe_insert($item, $batch['category']);
|
|
||||||
$batchInserted++;
|
|
||||||
}
|
|
||||||
log_line(" ✓ Parsed {$batchInserted} intents (running total inserted: {$inserted}).");
|
|
||||||
|
|
||||||
// Polite delay between API calls to avoid rate limiting
|
|
||||||
if ($num < $totalBatches) sleep(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_line("Generation complete. Inserted/updated: {$inserted} | Short/invalid skipped: {$skipped} | Errors: {$errors}");
|
|
||||||
|
|
||||||
/* ── cleanup phase ── */
|
|
||||||
log_line('Starting cleanup phase...');
|
|
||||||
|
|
||||||
// 1. Remove exact duplicate intent_names (keep the one with the longer response)
|
|
||||||
$dups = JarvisDB::query(
|
|
||||||
'SELECT intent_name, COUNT(*) AS cnt FROM kb_intents GROUP BY intent_name HAVING cnt > 1'
|
|
||||||
);
|
|
||||||
$dupsPruned = 0;
|
|
||||||
foreach ($dups as $dup) {
|
|
||||||
$rows = JarvisDB::query(
|
|
||||||
'SELECT id, LENGTH(response_template) AS rlen FROM kb_intents WHERE intent_name=? ORDER BY rlen DESC',
|
|
||||||
[$dup['intent_name']]
|
|
||||||
);
|
|
||||||
// Delete all but the first (longest response)
|
|
||||||
array_shift($rows);
|
|
||||||
foreach ($rows as $row) {
|
|
||||||
JarvisDB::execute('DELETE FROM kb_intents WHERE id=?', [$row['id']]);
|
|
||||||
$dupsPruned++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log_line(" Duplicate intent_names pruned: {$dupsPruned}");
|
|
||||||
|
|
||||||
// 2. Remove intents with very short responses (< 40 chars) — likely garbage
|
|
||||||
$shortPruned = JarvisDB::execute(
|
|
||||||
"DELETE FROM kb_intents WHERE LENGTH(response_template) < 40 AND priority <= 5"
|
|
||||||
);
|
|
||||||
log_line(" Short-response rows pruned: {$shortPruned}");
|
|
||||||
|
|
||||||
// 3. Trim whitespace on all text columns for the auto-generated ones
|
|
||||||
JarvisDB::execute(
|
|
||||||
"UPDATE kb_intents SET
|
|
||||||
intent_name = TRIM(intent_name),
|
|
||||||
pattern = TRIM(pattern),
|
|
||||||
response_template = TRIM(response_template),
|
|
||||||
fact_category = TRIM(fact_category)
|
|
||||||
WHERE priority = 5"
|
|
||||||
);
|
|
||||||
log_line(' Whitespace trimmed on all generated intents.');
|
|
||||||
|
|
||||||
// 4. Deactivate intents whose pattern is invalid PCRE
|
|
||||||
$all = JarvisDB::query('SELECT id, pattern FROM kb_intents WHERE active=1 AND priority=5');
|
|
||||||
$badPattern = 0;
|
|
||||||
foreach ($all as $row) {
|
|
||||||
if (@preg_match($row['pattern'], '') === false) {
|
|
||||||
JarvisDB::execute('UPDATE kb_intents SET active=0 WHERE id=?', [$row['id']]);
|
|
||||||
$badPattern++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log_line(" Bad PCRE patterns deactivated: {$badPattern}");
|
|
||||||
|
|
||||||
// 5. Stats
|
|
||||||
$stats = JarvisDB::single('SELECT COUNT(*) AS total, SUM(active) AS active FROM kb_intents');
|
|
||||||
log_line("Final KB Intents table: {$stats['total']} total, {$stats['active']} active.");
|
|
||||||
|
|
||||||
/* ── record last-run timestamp in kb_facts ── */
|
|
||||||
JarvisDB::execute(
|
|
||||||
"INSERT INTO kb_facts (category, fact_key, fact_value, host)
|
|
||||||
VALUES ('kb_generator', 'last_run', NOW(), 'local')
|
|
||||||
ON DUPLICATE KEY UPDATE fact_value=NOW(), updated_at=NOW()",
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
JarvisDB::execute(
|
|
||||||
"INSERT INTO kb_facts (category, fact_key, fact_value, host)
|
|
||||||
VALUES ('kb_generator', 'last_inserted', ?, 'local')
|
|
||||||
ON DUPLICATE KEY UPDATE fact_value=VALUES(fact_value), updated_at=NOW()",
|
|
||||||
[$inserted]
|
|
||||||
);
|
|
||||||
|
|
||||||
log_line('Done.');
|
|
||||||
@@ -1,270 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
* JARVIS KB Intent Generator
|
|
||||||
* Generates 1,000+ educational KB intents via Groq LLM and imports to kb_intents table.
|
|
||||||
* Also runs a cleanup pass: deduplication, short-response pruning, pattern normalisation.
|
|
||||||
*
|
|
||||||
* CLI / cron: /usr/bin/php8.3 /var/www/jarvis/api/endpoints/kb_intent_generator.php
|
|
||||||
* Schedule: Daily – 3 am
|
|
||||||
*/
|
|
||||||
|
|
||||||
require_once __DIR__ . '/../config.php';
|
|
||||||
require_once __DIR__ . '/../lib/db.php';
|
|
||||||
|
|
||||||
/* ── helpers ── */
|
|
||||||
function ts(): string { return '[' . date('Y-m-d H:i:s') . ']'; }
|
|
||||||
function log_line(string $msg): void { echo ts() . ' KB Intent Generator: ' . $msg . "\n"; flush(); }
|
|
||||||
|
|
||||||
function groq(string $system, string $user, int $max = 3000, int $retries = 2): ?string {
|
|
||||||
for ($attempt = 0; $attempt <= $retries; $attempt++) {
|
|
||||||
if ($attempt > 0) {
|
|
||||||
log_line(" Retry {$attempt}/{$retries} after rate-limit pause...");
|
|
||||||
sleep(25);
|
|
||||||
}
|
|
||||||
$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
|
|
||||||
curl_setopt_array($ch, [
|
|
||||||
CURLOPT_RETURNTRANSFER => true,
|
|
||||||
CURLOPT_POST => true,
|
|
||||||
CURLOPT_TIMEOUT => 60,
|
|
||||||
CURLOPT_HTTPHEADER => [
|
|
||||||
'Authorization: Bearer ' . GROQ_API_KEY,
|
|
||||||
'Content-Type: application/json',
|
|
||||||
],
|
|
||||||
CURLOPT_POSTFIELDS => json_encode([
|
|
||||||
'model' => 'llama-3.3-70b-versatile',
|
|
||||||
'max_tokens' => $max,
|
|
||||||
'temperature' => 0.7,
|
|
||||||
'messages' => [
|
|
||||||
['role' => 'system', 'content' => $system],
|
|
||||||
['role' => 'user', 'content' => $user],
|
|
||||||
],
|
|
||||||
]),
|
|
||||||
]);
|
|
||||||
$raw = curl_exec($ch);
|
|
||||||
$err = curl_error($ch);
|
|
||||||
$info = curl_getinfo($ch);
|
|
||||||
curl_close($ch);
|
|
||||||
|
|
||||||
if ($err || !$raw) continue;
|
|
||||||
|
|
||||||
// Check for rate limit response (429)
|
|
||||||
if (($info['http_code'] ?? 0) === 429) continue;
|
|
||||||
|
|
||||||
$d = json_decode($raw, true);
|
|
||||||
$content = $d['choices'][0]['message']['content'] ?? null;
|
|
||||||
if ($content !== null) return $content;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── normalize a pattern to valid PHP PCRE ── */
|
|
||||||
function normalize_pattern(string $pat): string {
|
|
||||||
$pat = trim($pat);
|
|
||||||
// If pattern already has PCRE delimiters, leave it alone
|
|
||||||
if (preg_match('/^[\/|~#!@%]/', $pat)) return $pat;
|
|
||||||
// Strip any (?i) inline flag — we'll add /i at the delimiter level
|
|
||||||
$pat = preg_replace('/^\(\?i\)/', '', $pat);
|
|
||||||
// Escape forward slashes inside the pattern
|
|
||||||
$pat = str_replace('/', '\\/', $pat);
|
|
||||||
return '/' . $pat . '/i';
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── run guard: skip if ran within last 4 hours ── */
|
|
||||||
/* Set JARVIS_FORCE_RUN=1 (env) or pass --force (argv) to bypass */
|
|
||||||
/* Comparison done in SQL (NOW()) rather than PHP time()/strtotime() — this process's
|
|
||||||
date_default_timezone_set('America/Chicago') makes strtotime() misread MySQL's naive
|
|
||||||
(UTC) timestamps as Chicago time, throwing elapsed-time checks off by the UTC offset. */
|
|
||||||
$recentRun = JarvisDB::single(
|
|
||||||
"SELECT (updated_at > DATE_SUB(NOW(), INTERVAL 14400 SECOND)) AS is_recent FROM kb_facts WHERE category='kb_generator' AND fact_key='last_run'"
|
|
||||||
);
|
|
||||||
$forceRun = !empty(getenv('JARVIS_FORCE_RUN')) || (isset($argv[1]) && $argv[1] === '--force');
|
|
||||||
if (!$forceRun && $recentRun && $recentRun['is_recent']) {
|
|
||||||
log_line('Skipping – ran within last 4 hours. Use --force to override.');
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
if ($forceRun) log_line('Force-run flag set — bypassing 4-hour guard.');
|
|
||||||
|
|
||||||
log_line('Starting daily KB intent generation run.');
|
|
||||||
|
|
||||||
/* ── load active topics from database ── */
|
|
||||||
$BATCHES = JarvisDB::query(
|
|
||||||
"SELECT t.topic_id AS id, t.category, t.topic_name AS topic, t.description AS `desc`
|
|
||||||
FROM kb_generator_topics t WHERE t.active=1 ORDER BY t.id ASC"
|
|
||||||
);
|
|
||||||
if (empty($BATCHES)) {
|
|
||||||
log_line('ERROR: No active topics in kb_generator_topics table. Add topics via the JARVIS admin panel.');
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
log_line('Loaded ' . count($BATCHES) . ' active topics from database.');
|
|
||||||
|
|
||||||
/* ── ROTATION ENGINE: process BATCH_SIZE topics per run, cycling through all ── */
|
|
||||||
define('BATCH_SIZE', 25);
|
|
||||||
$totalTopics = count($BATCHES);
|
|
||||||
$offsetRow = JarvisDB::single(
|
|
||||||
"SELECT CAST(fact_value AS SIGNED) AS v FROM kb_facts WHERE category='kb_generator' AND fact_key='batch_offset'"
|
|
||||||
);
|
|
||||||
$batchOffset = max(0, (int)($offsetRow['v'] ?? 0));
|
|
||||||
if ($batchOffset >= $totalTopics) $batchOffset = 0;
|
|
||||||
$nextOffset = ($batchOffset + BATCH_SIZE) % $totalTopics;
|
|
||||||
$cycleComplete = ($batchOffset + BATCH_SIZE) >= $totalTopics;
|
|
||||||
$cycleLen = (int)ceil($totalTopics / BATCH_SIZE);
|
|
||||||
|
|
||||||
$runBatches = [];
|
|
||||||
for ($i = 0; $i < BATCH_SIZE; $i++) {
|
|
||||||
$runBatches[] = $BATCHES[($batchOffset + $i) % $totalTopics];
|
|
||||||
}
|
|
||||||
$endIdx = ($batchOffset + BATCH_SIZE - 1) % $totalTopics;
|
|
||||||
log_line("Rotation: topics " . ($batchOffset + 1) . "–" . ($endIdx + 1) . " of {$totalTopics} | cycle = {$cycleLen} runs × 6h = " . ($cycleLen * 6) . "h full cycle.");
|
|
||||||
if ($cycleComplete) log_line(" ↻ Full cycle complete — restarting from topic 1 next run.");
|
|
||||||
|
|
||||||
/* ── main generation loop ── */
|
|
||||||
$totalBatches = count($runBatches);
|
|
||||||
foreach ($runBatches as $idx => $batch) {
|
|
||||||
$num = $idx + 1;
|
|
||||||
log_line("Batch {$num}/{$totalBatches}: {$batch['topic']}");
|
|
||||||
|
|
||||||
$user = "Generate 20 KB intents for the topic: {$batch['topic']}.\n"
|
|
||||||
. "Subtopics to cover: {$batch['desc']}.\n"
|
|
||||||
. "Prefix every intent_name with \"{$batch['id']}_\".\n"
|
|
||||||
. "Category string to use: \"{$batch['category']}\".";
|
|
||||||
|
|
||||||
$raw = groq($SYSTEM, $user, 5000);
|
|
||||||
if ($raw === null) {
|
|
||||||
log_line(" ✗ API call failed after retries – skipping batch.");
|
|
||||||
$errors += 20;
|
|
||||||
sleep(8);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strip markdown code fences if model added them
|
|
||||||
$raw = preg_replace('/^```(?:json)?\s*/m', '', $raw);
|
|
||||||
$raw = preg_replace('/^```\s*/m', '', $raw);
|
|
||||||
$raw = trim($raw);
|
|
||||||
|
|
||||||
// Extract JSON array; fall back to partial recovery for truncated responses
|
|
||||||
$items = null;
|
|
||||||
if (preg_match('/\[\s*\{.*\}\s*\]/s', $raw, $m)) {
|
|
||||||
$items = json_decode($m[0], true);
|
|
||||||
if (!is_array($items)) {
|
|
||||||
log_line(" ✗ JSON parse failed – skipping batch.");
|
|
||||||
$errors += 20; sleep(8); continue;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$start = strpos($raw, '[');
|
|
||||||
if ($start !== false) {
|
|
||||||
$partial = substr($raw, $start);
|
|
||||||
if (preg_match_all('/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/s', $partial, $objs) && !empty($objs[0])) {
|
|
||||||
$recovered = '[' . implode(',', $objs[0]) . ']';
|
|
||||||
$items = json_decode($recovered, true);
|
|
||||||
if (is_array($items) && count($items) > 0)
|
|
||||||
log_line(" ⚠ Truncated — recovered " . count($items) . " items.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!is_array($items) || count($items) === 0) {
|
|
||||||
log_line(" ✗ No JSON array found — raw[0:120]: " . substr(str_replace("\n", ' ', $raw), 0, 120));
|
|
||||||
$errors += 20; sleep(8); continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$batchInserted = 0;
|
|
||||||
foreach ($items as $item) {
|
|
||||||
if (!is_array($item)) continue;
|
|
||||||
safe_insert($item, $batch['category']);
|
|
||||||
$batchInserted++;
|
|
||||||
}
|
|
||||||
log_line(" ✓ Parsed {$batchInserted} intents (running total inserted: {$inserted}).");
|
|
||||||
|
|
||||||
// Polite delay between API calls — Groq TPM limit needs ~8s between batches
|
|
||||||
if ($num < $totalBatches) sleep(8);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_line("Generation complete. Inserted/updated: {$inserted} | Short/invalid skipped: {$skipped} | Errors: {$errors}");
|
|
||||||
|
|
||||||
/* ── cleanup phase ── */
|
|
||||||
log_line('Starting cleanup phase...');
|
|
||||||
|
|
||||||
// 1. Remove exact duplicate intent_names (keep the one with the longer response)
|
|
||||||
$dups = JarvisDB::query(
|
|
||||||
'SELECT intent_name, COUNT(*) AS cnt FROM kb_intents GROUP BY intent_name HAVING cnt > 1'
|
|
||||||
);
|
|
||||||
$dupsPruned = 0;
|
|
||||||
foreach ($dups as $dup) {
|
|
||||||
$rows = JarvisDB::query(
|
|
||||||
'SELECT id, LENGTH(response_template) AS rlen FROM kb_intents WHERE intent_name=? ORDER BY rlen DESC',
|
|
||||||
[$dup['intent_name']]
|
|
||||||
);
|
|
||||||
array_shift($rows);
|
|
||||||
foreach ($rows as $row) {
|
|
||||||
JarvisDB::execute('DELETE FROM kb_intents WHERE id=?', [$row['id']]);
|
|
||||||
$dupsPruned++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log_line(" Duplicate intent_names pruned: {$dupsPruned}");
|
|
||||||
|
|
||||||
// 2. Remove intents with very short responses (< 40 chars)
|
|
||||||
$shortPruned = JarvisDB::execute(
|
|
||||||
"DELETE FROM kb_intents WHERE LENGTH(response_template) < 40 AND priority <= 5"
|
|
||||||
);
|
|
||||||
log_line(" Short-response rows pruned: {$shortPruned}");
|
|
||||||
|
|
||||||
// 3. Trim whitespace on all generated intents
|
|
||||||
JarvisDB::execute(
|
|
||||||
"UPDATE kb_intents SET
|
|
||||||
intent_name = TRIM(intent_name),
|
|
||||||
pattern = TRIM(pattern),
|
|
||||||
response_template = TRIM(response_template),
|
|
||||||
fact_category = TRIM(fact_category)
|
|
||||||
WHERE priority = 5"
|
|
||||||
);
|
|
||||||
log_line(' Whitespace trimmed on all generated intents.');
|
|
||||||
|
|
||||||
// 4. Fix and validate PCRE patterns — normalize then deactivate only truly broken ones
|
|
||||||
$all = JarvisDB::query('SELECT id, pattern FROM kb_intents WHERE priority=5');
|
|
||||||
$badPattern = 0;
|
|
||||||
$fixedPattern = 0;
|
|
||||||
foreach ($all as $row) {
|
|
||||||
$pat = normalize_pattern($row['pattern']);
|
|
||||||
if ($pat !== $row['pattern']) {
|
|
||||||
// Update to normalized form
|
|
||||||
JarvisDB::execute('UPDATE kb_intents SET pattern=?, active=1 WHERE id=?', [$pat, $row['id']]);
|
|
||||||
$fixedPattern++;
|
|
||||||
} elseif (@preg_match($pat, '') === false) {
|
|
||||||
JarvisDB::execute('UPDATE kb_intents SET active=0 WHERE id=?', [$row['id']]);
|
|
||||||
$badPattern++;
|
|
||||||
} else {
|
|
||||||
// Valid pattern — make sure it's active
|
|
||||||
JarvisDB::execute('UPDATE kb_intents SET active=1 WHERE id=?', [$row['id']]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log_line(" Patterns normalized: {$fixedPattern} | Bad PCRE deactivated: {$badPattern}");
|
|
||||||
|
|
||||||
// 5. Enable ALL remaining inactive intents (including pre-existing ones)
|
|
||||||
$reactivated = JarvisDB::execute('UPDATE kb_intents SET active=1 WHERE active=0 AND priority <= 5');
|
|
||||||
log_line(" Re-activated previously inactive intents: {$reactivated}");
|
|
||||||
|
|
||||||
// 6. Final stats
|
|
||||||
$stats = JarvisDB::single('SELECT COUNT(*) AS total, SUM(active) AS active FROM kb_intents');
|
|
||||||
log_line("Final KB Intents table: {$stats['total']} total, {$stats['active']} active.");
|
|
||||||
|
|
||||||
/* ── record last-run timestamp ── */
|
|
||||||
JarvisDB::execute(
|
|
||||||
"INSERT INTO kb_facts (category, fact_key, fact_value, host)
|
|
||||||
VALUES ('kb_generator', 'last_run', NOW(), 'local')
|
|
||||||
ON DUPLICATE KEY UPDATE fact_value=NOW(), updated_at=NOW()",
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
JarvisDB::execute(
|
|
||||||
"INSERT INTO kb_facts (category, fact_key, fact_value, host)
|
|
||||||
VALUES ('kb_generator', 'batch_offset', ?, 'local')
|
|
||||||
ON DUPLICATE KEY UPDATE fact_value=VALUES(fact_value), updated_at=NOW()",
|
|
||||||
[$nextOffset]
|
|
||||||
);
|
|
||||||
log_line("Next run will start at topic offset {$nextOffset}/{$totalTopics}.");
|
|
||||||
JarvisDB::execute(
|
|
||||||
"INSERT INTO kb_facts (category, fact_key, fact_value, host)
|
|
||||||
VALUES ('kb_generator', 'last_inserted', ?, 'local')
|
|
||||||
ON DUPLICATE KEY UPDATE fact_value=VALUES(fact_value), updated_at=NOW()",
|
|
||||||
[$inserted]
|
|
||||||
);
|
|
||||||
|
|
||||||
log_line('Done.');
|
|
||||||
@@ -2,14 +2,14 @@
|
|||||||
// Network scan push endpoint — called by PVE1 cron with nmap results
|
// Network scan push endpoint — called by PVE1 cron with nmap results
|
||||||
// Authenticates via X-Registration-Key header (same key as agent installer)
|
// Authenticates via X-Registration-Key header (same key as agent installer)
|
||||||
|
|
||||||
define('NETSCAN_KEY', 'f846a9aaf7ce9a61742c63c87c4186052a71d2a580c65518');
|
define('NETSCAN_KEY', AGENT_REGISTRATION_KEY);
|
||||||
|
|
||||||
if ($method !== 'POST') {
|
if ($method !== 'POST') {
|
||||||
echo json_encode(['error' => 'POST only']); exit;
|
echo json_encode(['error' => 'POST only']); exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
$reqKey = $_SERVER['HTTP_X_REGISTRATION_KEY'] ?? '';
|
$reqKey = $_SERVER['HTTP_X_REGISTRATION_KEY'] ?? '';
|
||||||
if ($reqKey !== NETSCAN_KEY) {
|
if (!hash_equals(NETSCAN_KEY, $reqKey)) {
|
||||||
http_response_code(401);
|
http_response_code(401);
|
||||||
echo json_encode(['error' => 'Unauthorized']); exit;
|
echo json_encode(['error' => 'Unauthorized']); exit;
|
||||||
}
|
}
|
||||||
@@ -35,6 +35,11 @@ foreach ($devices as $d) {
|
|||||||
if (!$ip) continue;
|
if (!$ip) continue;
|
||||||
|
|
||||||
$discoveredIPs[] = $ip;
|
$discoveredIPs[] = $ip;
|
||||||
|
if ($mac) {
|
||||||
|
// Device likely moved to a new IP (DHCP) — drop the stale row so it
|
||||||
|
// doesn't linger as an orphaned duplicate under the old address.
|
||||||
|
JarvisDB::execute('DELETE FROM network_devices WHERE mac=? AND ip<>?', [$mac, $ip]);
|
||||||
|
}
|
||||||
JarvisDB::execute(
|
JarvisDB::execute(
|
||||||
'INSERT INTO network_devices (ip, mac, hostname, status, last_seen)
|
'INSERT INTO network_devices (ip, mac, hostname, status, last_seen)
|
||||||
VALUES (?,?,?,?,NOW())
|
VALUES (?,?,?,?,NOW())
|
||||||
|
|||||||
@@ -213,7 +213,7 @@ if ($weatherAge > 1800) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
$weatherRaw = curlGet(
|
$weatherRaw = curlGet(
|
||||||
'https://wttr.in/FortWorth,TX?format=j1',
|
'https://wttr.in/76088?format=j1',
|
||||||
['User-Agent: curl/7.88 Jarvis/1.0'],
|
['User-Agent: curl/7.88 Jarvis/1.0'],
|
||||||
15
|
15
|
||||||
);
|
);
|
||||||
@@ -245,7 +245,7 @@ if ($weatherAge > 1800) {
|
|||||||
|
|
||||||
cacheStore('weather', [
|
cacheStore('weather', [
|
||||||
'source' => 'wttr.in',
|
'source' => 'wttr.in',
|
||||||
'location' => 'Fort Worth, TX',
|
'location' => 'Weatherford, TX',
|
||||||
'current' => [
|
'current' => [
|
||||||
'temp' => (int)($cu['temp_F'] ?? 0),
|
'temp' => (int)($cu['temp_F'] ?? 0),
|
||||||
'feels' => (int)($cu['FeelsLikeF'] ?? 0),
|
'feels' => (int)($cu['FeelsLikeF'] ?? 0),
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Copy to /etc/jarvis/db.env (root:root 0600). Sourced by the root cron scripts
|
||||||
|
# (jarvis-backup.sh, jarvis-deploy.sh, jarvis-watchdog.sh).
|
||||||
|
JARVIS_DB_PASS=your-db-password
|
||||||
+24
-4
@@ -1,11 +1,16 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# JARVIS backup — DB dump as tar.gz, admin-panel compatible
|
[ -r /etc/jarvis/db.env ] && . /etc/jarvis/db.env
|
||||||
|
# JARVIS backup — DB dump + all files needed to actually restore JARVIS, as tar.gz
|
||||||
|
# Fixed 2026-07-07: this only ever backed up the MySQL database. If this VM were
|
||||||
|
# lost, the DB alone is useless without the application code, the reactor daemon,
|
||||||
|
# its systemd unit, and the nginx site config — none of which were captured. Also
|
||||||
|
# fixed a typo ($SIYE -> $SIZE) that silently broke the size line in the log.
|
||||||
BACKUP_DIR="/var/backups/jarvis"
|
BACKUP_DIR="/var/backups/jarvis"
|
||||||
LOG="$BACKUP_DIR/backup.log"
|
LOG="$BACKUP_DIR/backup.log"
|
||||||
LOCK="$BACKUP_DIR/backup.lock"
|
LOCK="$BACKUP_DIR/backup.lock"
|
||||||
DB_NAME="jarvis_db"
|
DB_NAME="jarvis_db"
|
||||||
DB_USER="jarvis_user"
|
DB_USER="jarvis_user"
|
||||||
DB_PASS="J4rv1s_Pr0t0c0l_2026!"
|
DB_PASS="${JARVIS_DB_PASS:?DB pass unset - see /etc/jarvis/db.env}"
|
||||||
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
|
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
|
||||||
OUTFILE="$BACKUP_DIR/jarvis_backup_${TIMESTAMP}.tar.gz"
|
OUTFILE="$BACKUP_DIR/jarvis_backup_${TIMESTAMP}.tar.gz"
|
||||||
TMPDIR=$(mktemp -d)
|
TMPDIR=$(mktemp -d)
|
||||||
@@ -18,9 +23,24 @@ cleanup() { rm -rf "$TMPDIR"; rm -f "$LOCK"; }
|
|||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
|
|
||||||
if mysqldump -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$TMPDIR/jarvis_db.sql" 2>>"$LOG"; then
|
if mysqldump -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$TMPDIR/jarvis_db.sql" 2>>"$LOG"; then
|
||||||
tar -czf "$OUTFILE" -C "$TMPDIR" jarvis_db.sql
|
mkdir -p "$TMPDIR/files/etc"
|
||||||
|
cp -a /var/www/jarvis "$TMPDIR/files/var-www-jarvis"
|
||||||
|
cp -a /opt/jarvis-arc "$TMPDIR/files/opt-jarvis-arc"
|
||||||
|
cp -a /etc/nginx/sites-enabled/jarvis "$TMPDIR/files/etc/nginx-site-jarvis" 2>>"$LOG"
|
||||||
|
cp -a /etc/systemd/system/jarvis-arc.service "$TMPDIR/files/etc/jarvis-arc.service" 2>>"$LOG"
|
||||||
|
crontab -l > "$TMPDIR/files/etc/root-crontab.txt" 2>>"$LOG"
|
||||||
|
# Phase 1/2 additions: secrets + systemd drop-ins + operational scripts
|
||||||
|
# (these live outside /var/www/jarvis and /opt/jarvis-arc, so must be
|
||||||
|
# captured explicitly or a restore comes back with no keys/DB pass).
|
||||||
|
cp -a /etc/jarvis-arc "$TMPDIR/files/etc/jarvis-arc-etc" 2>>"$LOG" # reactor.env
|
||||||
|
cp -a /etc/jarvis "$TMPDIR/files/etc/jarvis-etc" 2>>"$LOG" # db.env
|
||||||
|
cp -a /etc/systemd/system/jarvis-arc.service.d "$TMPDIR/files/etc/jarvis-arc.service.d" 2>>"$LOG"
|
||||||
|
mkdir -p "$TMPDIR/files/usr-local-bin"
|
||||||
|
cp -a /usr/local/bin/jarvis-*.sh "$TMPDIR/files/usr-local-bin/" 2>>"$LOG" # health/deploy/watchdog/netscan
|
||||||
|
|
||||||
|
tar -czf "$OUTFILE" -C "$TMPDIR" jarvis_db.sql files
|
||||||
SIZE=$(du -sh "$OUTFILE" | cut -f1)
|
SIZE=$(du -sh "$OUTFILE" | cut -f1)
|
||||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup OK: $(basename "$OUTFILE") ($SIYE)" >> "$LOG"
|
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup OK: $(basename "$OUTFILE") ($SIZE)" >> "$LOG"
|
||||||
else
|
else
|
||||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: mysqldump failed" >> "$LOG"
|
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: mysqldump failed" >> "$LOG"
|
||||||
exit 1
|
exit 1
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
[ -r /etc/jarvis/db.env ] && . /etc/jarvis/db.env
|
||||||
# JARVIS Auto-Deploy Runner — processes GitHub webhook queue every minute.
|
# JARVIS Auto-Deploy Runner — processes GitHub webhook queue every minute.
|
||||||
# Validates PHP syntax before deploying; auto-reverts on bad code.
|
# Validates PHP syntax before deploying; auto-reverts on bad code.
|
||||||
# Restarts OLS after JARVIS deploys to pick up PHP changes.
|
# Restarts OLS after JARVIS deploys to pick up PHP changes.
|
||||||
@@ -64,7 +65,7 @@ while IFS= read -r path; do
|
|||||||
fi
|
fi
|
||||||
# Insert alert into JARVIS DB
|
# Insert alert into JARVIS DB
|
||||||
BAD_ESCAPED=$(printf '%s' "$BAD_FILE" | sed "s/'/\\\\\\'/g")
|
BAD_ESCAPED=$(printf '%s' "$BAD_FILE" | sed "s/'/\\\\\\'/g")
|
||||||
mysql -u jarvis_user -pJ4rv1s_Pr0t0c0l_2026! jarvis_db -se \
|
mysql -u jarvis_user -p"$JARVIS_DB_PASS" jarvis_db -se \
|
||||||
"INSERT INTO alerts (alert_type,title,message,severity)
|
"INSERT INTO alerts (alert_type,title,message,severity)
|
||||||
VALUES ('deploy_fail','Deploy reverted: syntax error',
|
VALUES ('deploy_fail','Deploy reverted: syntax error',
|
||||||
'PHP syntax error in $BAD_ESCAPED. Commit $AFTER was reverted and force-pushed to GitHub.','critical');" 2>/dev/null
|
'PHP syntax error in $BAD_ESCAPED. Commit $AFTER was reverted and force-pushed to GitHub.','critical');" 2>/dev/null
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# JARVIS Health Self-Check — runs every 5 min via root cron (separate from the
|
||||||
|
# service watchdog). Detects silent failures the watchdog can't: stalled crons,
|
||||||
|
# stuck Arc jobs, low disk, and services the watchdog had to restart. Writes
|
||||||
|
# findings to the `alerts` table (auto-resolving when clear) and emails on any
|
||||||
|
# NEW finding. Added 2026-07-07 (Phase 2 reliability).
|
||||||
|
set -u
|
||||||
|
[ -r /etc/jarvis/db.env ] && . /etc/jarvis/db.env
|
||||||
|
DB_USER="jarvis_user"; DB_NAME="jarvis_db"
|
||||||
|
MYSQL=(mysql -u "$DB_USER" -p"${JARVIS_DB_PASS:-}" "$DB_NAME" -N -B -e)
|
||||||
|
CRONLOG=/var/log/jarvis/cron.log
|
||||||
|
WDLOG=/var/log/jarvis/watchdog.log
|
||||||
|
ALERT_TO="myronblair@gmail.com"
|
||||||
|
REACTOR_ENV=/etc/jarvis-arc/reactor.env
|
||||||
|
NEW_FINDINGS=""
|
||||||
|
|
||||||
|
sql() { "${MYSQL[@]}" "$1" 2>/dev/null; }
|
||||||
|
esc() { printf '%s' "$1" | sed "s/'/''/g"; }
|
||||||
|
|
||||||
|
# Raise (or keep) an alert for a condition. Emails only when it is newly raised.
|
||||||
|
# $1=source_key $2=severity $3=title $4=message
|
||||||
|
raise() {
|
||||||
|
local key sev title msg exists
|
||||||
|
key=$(esc "$1"); sev=$(esc "$2"); title=$(esc "$3"); msg=$(esc "$4")
|
||||||
|
exists=$(sql "SELECT COUNT(*) FROM alerts WHERE source_key='$key' AND resolved=0")
|
||||||
|
if [ "${exists:-0}" = "0" ]; then
|
||||||
|
sql "INSERT INTO alerts (alert_type,title,message,severity,source_key,auto_resolve,created_at)
|
||||||
|
VALUES ('health','$title','$msg','$sev','$key',1,NOW())"
|
||||||
|
NEW_FINDINGS="${NEW_FINDINGS}- [$2] $3: $4"$'\n'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
# Clear a condition's alert when it's no longer true.
|
||||||
|
clear_cond() {
|
||||||
|
local key; key=$(esc "$1")
|
||||||
|
sql "UPDATE alerts SET resolved=1, resolved_at=NOW()
|
||||||
|
WHERE source_key='$key' AND resolved=0 AND auto_resolve=1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 1) Disk usage on / > 85%
|
||||||
|
DISK=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
|
||||||
|
if [ "${DISK:-0}" -gt 85 ]; then
|
||||||
|
raise "health:disk" "critical" "Disk usage high" "Root filesystem at ${DISK}% (threshold 85%)."
|
||||||
|
else clear_cond "health:disk"; fi
|
||||||
|
|
||||||
|
# 2) Arc jobs stuck in 'running' > 30 min
|
||||||
|
STUCK=$(sql "SELECT COUNT(*) FROM arc_jobs WHERE status='running'
|
||||||
|
AND COALESCE(started_at, created_at) < NOW() - INTERVAL 30 MINUTE")
|
||||||
|
if [ "${STUCK:-0}" -gt 0 ]; then
|
||||||
|
raise "health:arc_stuck" "critical" "Arc jobs stuck" "$STUCK Arc job(s) have been 'running' for over 30 minutes."
|
||||||
|
else clear_cond "health:arc_stuck"; fi
|
||||||
|
|
||||||
|
# 3) Cron stalled — cron.log is written by facts_collector every 3 min. If it
|
||||||
|
# hasn't changed in 10 min (>2 consecutive missed runs), cron work has stopped.
|
||||||
|
if [ -f "$CRONLOG" ]; then
|
||||||
|
AGE=$(( $(date +%s) - $(stat -c %Y "$CRONLOG") ))
|
||||||
|
if [ "$AGE" -gt 600 ]; then
|
||||||
|
raise "health:cron" "critical" "Cron jobs stalled" "No cron activity in $((AGE/60)) min (facts_collector runs every 3 min) — crons appear stopped."
|
||||||
|
else clear_cond "health:cron"; fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4) Watched service restarted by the watchdog in the last 6 min
|
||||||
|
if [ -f "$WDLOG" ]; then
|
||||||
|
RECENT=$(awk -v cutoff="$(date -d '6 minutes ago' '+%Y-%m-%d %H:%M:%S')" \
|
||||||
|
'match($0,/^\[([0-9-]+ [0-9:]+)\]/,m){ if(m[1]>=cutoff && /restarted successfully/) print }' "$WDLOG")
|
||||||
|
if [ -n "$RECENT" ]; then
|
||||||
|
SVC=$(printf '%s' "$RECENT" | grep -oE '(nginx|php8.3-fpm|mariadb|redis-server)' | sort -u | tr '\n' ' ')
|
||||||
|
raise "health:wd_restart" "warning" "Service auto-restarted" "Watchdog restarted: ${SVC:-a service}. Investigate why it died."
|
||||||
|
else
|
||||||
|
clear_cond "health:wd_restart"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Email any NEW findings via the reactor's Gmail SMTP creds.
|
||||||
|
if [ -n "$NEW_FINDINGS" ]; then
|
||||||
|
GPASS=""
|
||||||
|
[ -r "$REACTOR_ENV" ] && GPASS=$(grep -E '^GMAIL_PASS=' "$REACTOR_ENV" | cut -d= -f2-)
|
||||||
|
if [ -n "$GPASS" ]; then
|
||||||
|
GMAIL_PASS="$GPASS" ALERT_TO="$ALERT_TO" FINDINGS="$NEW_FINDINGS" python3 - <<'PY'
|
||||||
|
import os, smtplib, ssl, socket
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
user = "myronblair@gmail.com"
|
||||||
|
msg = MIMEText("JARVIS health self-check raised new alerts on %s:\n\n%s" % (socket.gethostname(), os.environ["FINDINGS"]))
|
||||||
|
msg["Subject"] = "JARVIS health alert"
|
||||||
|
msg["From"] = user; msg["To"] = os.environ["ALERT_TO"]
|
||||||
|
try:
|
||||||
|
with smtplib.SMTP("smtp.gmail.com", 587, timeout=20) as s:
|
||||||
|
s.starttls(context=ssl.create_default_context())
|
||||||
|
s.login(user, os.environ["GMAIL_PASS"])
|
||||||
|
s.send_message(msg)
|
||||||
|
print("health-email: sent")
|
||||||
|
except Exception as e:
|
||||||
|
print("health-email: FAILED", e)
|
||||||
|
PY
|
||||||
|
else
|
||||||
|
echo "health-email: no GMAIL_PASS available, skipped"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
[ -r /etc/jarvis/db.env ] && . /etc/jarvis/db.env
|
||||||
# JARVIS Self-Healing Watchdog — runs every 5 min via root cron
|
# JARVIS Self-Healing Watchdog — runs every 5 min via root cron
|
||||||
# Checks: lsws, mysql, redis, JARVIS HTTP, disk, memory
|
# Checks: lsws, mysql, redis, JARVIS HTTP, disk, memory
|
||||||
# Auto-heals: restarts failed services, restarts offline Proxmox VM agents
|
# Auto-heals: restarts failed services, restarts offline Proxmox VM agents
|
||||||
# Logs to: /home/jarvis.orbishosting.com/logs/watchdog.log
|
# Logs to: /home/jarvis.orbishosting.com/logs/watchdog.log
|
||||||
|
|
||||||
LOG=/home/jarvis.orbishosting.com/logs/watchdog.log
|
LOG=/home/jarvis.orbishosting.com/logs/watchdog.log
|
||||||
MYSQL="mysql -u jarvis_user -pJ4rv1s_Pr0t0c0l_2026! jarvis_db -se"
|
MYSQL="mysql -u jarvis_user -p$JARVIS_DB_PASS jarvis_db -se"
|
||||||
TS() { date '+%Y-%m-%d %H:%M:%S'; }
|
TS() { date '+%Y-%m-%d %H:%M:%S'; }
|
||||||
|
|
||||||
log() { echo "[$(TS)] $1" >> "$LOG"; }
|
log() { echo "[$(TS)] $1" >> "$LOG"; }
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# JARVIS Arc Reactor — required secrets. Copy to /etc/jarvis-arc/reactor.env
|
||||||
|
# (root:www-data 0640), loaded by systemd EnvironmentFile. Not committed.
|
||||||
|
JARVIS_DB_PASS=your-db-password
|
||||||
|
CLAUDE_API_KEY=sk-ant-...
|
||||||
|
GROQ_API_KEY=gsk_...
|
||||||
|
GMAIL_PASS=your-gmail-app-password
|
||||||
|
ICLOUD_PASS=your-icloud-app-password
|
||||||
+90
-16
@@ -39,24 +39,24 @@ VERSION = "9.0.0"
|
|||||||
DB_HOST = "localhost"
|
DB_HOST = "localhost"
|
||||||
DB_PORT = 3306
|
DB_PORT = 3306
|
||||||
DB_USER = "jarvis_user"
|
DB_USER = "jarvis_user"
|
||||||
DB_PASS = "J4rv1s_Pr0t0c0l_2026!"
|
DB_PASS = os.environ.get("JARVIS_DB_PASS", "")
|
||||||
DB_NAME = "jarvis_db"
|
DB_NAME = "jarvis_db"
|
||||||
LOG_FILE = "/var/log/jarvis/arc_reactor.log"
|
LOG_FILE = "/var/log/jarvis/arc_reactor.log"
|
||||||
POLL_INTERVAL = 3
|
POLL_INTERVAL = 3
|
||||||
HEARTBEAT_INTERVAL = 30
|
HEARTBEAT_INTERVAL = 30
|
||||||
|
|
||||||
CLAUDE_API_KEY = "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"
|
CLAUDE_API_KEY = os.environ.get("CLAUDE_API_KEY", "")
|
||||||
CLAUDE_MODEL = "claude-sonnet-4-6"
|
CLAUDE_MODEL = "claude-sonnet-4-6"
|
||||||
GROQ_API_KEY = "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"
|
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
|
||||||
GROQ_MODEL = "llama-3.3-70b-versatile"
|
GROQ_MODEL = "llama-3.3-70b-versatile"
|
||||||
OLLAMA_HOST = "http://10.48.200.210:11434"
|
OLLAMA_HOST = "http://10.48.200.210:11434"
|
||||||
OLLAMA_MODEL = "llama3.1:8b"
|
OLLAMA_MODEL = "llama3.1:8b"
|
||||||
OLLAMA_VISION_MODEL = os.environ.get("OLLAMA_VISION_MODEL", "") # e.g. "llava" or "moondream" -- empty = disabled
|
OLLAMA_VISION_MODEL = os.environ.get("OLLAMA_VISION_MODEL", "") # e.g. "llava" or "moondream" -- empty = disabled
|
||||||
|
|
||||||
GMAIL_USER = "myronblair@gmail.com"
|
GMAIL_USER = "myronblair@gmail.com"
|
||||||
GMAIL_PASS = "demsvdylwweacbcx"
|
GMAIL_PASS = os.environ.get("GMAIL_PASS", "")
|
||||||
ICLOUD_USER = "myronblair@icloud.com"
|
ICLOUD_USER = "myronblair@icloud.com"
|
||||||
ICLOUD_PASS = "yxfi-yvzu-geqk-japr"
|
ICLOUD_PASS = os.environ.get("ICLOUD_PASS", "")
|
||||||
|
|
||||||
# ── LOGGING ───────────────────────────────────────────────────────────────────
|
# ── LOGGING ───────────────────────────────────────────────────────────────────
|
||||||
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
||||||
@@ -130,18 +130,35 @@ async def handle_shell(payload: dict) -> dict:
|
|||||||
# ═══════════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
async def llm_call(messages: list, provider: str = "claude", system: str = "") -> str:
|
async def llm_call(messages: list, provider: str = "claude", system: str = "") -> str:
|
||||||
if provider == "claude" and CLAUDE_API_KEY:
|
# Fixed 2026-07-07: previously, an explicitly-requested provider (e.g. "claude")
|
||||||
return await _claude_call(messages, system)
|
# called its API directly with no exception handling, so any failure (rate limit,
|
||||||
elif provider == "groq" and GROQ_API_KEY:
|
# depleted credits, outage) raised straight up instead of falling back to the other
|
||||||
return await _groq_call(messages, system)
|
# providers below. The fallback loop only ever ran for an unrecognized provider
|
||||||
elif provider == "ollama":
|
# string, which never happens in practice — so callers requesting "claude" got zero
|
||||||
return await _ollama_call(messages, system)
|
# real resilience. Now every explicit request tries its provider first, then falls
|
||||||
for p in ["groq", "ollama"]:
|
# through the remaining ones in order before giving up.
|
||||||
|
order = {"claude": ["claude", "groq", "ollama"],
|
||||||
|
"groq": ["groq", "ollama"],
|
||||||
|
"ollama": ["ollama"]}.get(provider, ["claude", "groq", "ollama"])
|
||||||
|
last_err = None
|
||||||
|
for p in order:
|
||||||
try:
|
try:
|
||||||
return await llm_call(messages, p, system)
|
if p == "claude" and CLAUDE_API_KEY:
|
||||||
except Exception:
|
result = await _claude_call(messages, system)
|
||||||
|
elif p == "groq" and GROQ_API_KEY:
|
||||||
|
result = await _groq_call(messages, system)
|
||||||
|
elif p == "ollama":
|
||||||
|
result = await _ollama_call(messages, system)
|
||||||
|
else:
|
||||||
continue
|
continue
|
||||||
raise RuntimeError("All LLM providers failed")
|
if not result or not result.strip():
|
||||||
|
raise RuntimeError(f"{p} returned empty content")
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
log.warning(f"[LLM] Provider {p} failed: {type(e).__name__}: {e}")
|
||||||
|
last_err = e
|
||||||
|
continue
|
||||||
|
raise RuntimeError(f"All LLM providers failed (last error: {last_err})")
|
||||||
|
|
||||||
async def _claude_call(messages: list, system: str = "") -> str:
|
async def _claude_call(messages: list, system: str = "") -> str:
|
||||||
payload = {"model": CLAUDE_MODEL, "max_tokens": 4096, "messages": messages}
|
payload = {"model": CLAUDE_MODEL, "max_tokens": 4096, "messages": messages}
|
||||||
@@ -156,13 +173,36 @@ async def _claude_call(messages: list, system: str = "") -> str:
|
|||||||
raise RuntimeError(f"Claude API error {resp.status}: {data.get('error',{}).get('message','')}")
|
raise RuntimeError(f"Claude API error {resp.status}: {data.get('error',{}).get('message','')}")
|
||||||
return data["content"][0]["text"]
|
return data["content"][0]["text"]
|
||||||
|
|
||||||
|
def _parse_groq_reset(val: str) -> float:
|
||||||
|
"""Parse Groq's Go-style duration strings ('229ms', '2.5s', '2m52.8s') into seconds."""
|
||||||
|
import re as _re
|
||||||
|
if not val:
|
||||||
|
return 0.0
|
||||||
|
total = 0.0
|
||||||
|
for num, unit in _re.findall(r'([\d.]+)(ms|s|m|h)', val):
|
||||||
|
n = float(num)
|
||||||
|
total += n/1000 if unit == 'ms' else n*60 if unit == 'm' else n*3600 if unit == 'h' else n
|
||||||
|
return total
|
||||||
|
|
||||||
async def _groq_call(messages: list, system: str = "") -> str:
|
async def _groq_call(messages: list, system: str = "") -> str:
|
||||||
|
# Added 2026-07-07: retry once on 429 (rate limit) using Groq's own reset-time
|
||||||
|
# header, capped short — this account's tier has a low 12k-tokens/min ceiling that
|
||||||
|
# gmail_triage alone can exhaust, so transient contention here is common and often
|
||||||
|
# clears in well under a second. Capped so a genuinely long reset just falls
|
||||||
|
# through to Ollama instead of blocking the whole compose flow.
|
||||||
all_msgs = ([{"role": "system", "content": system}] if system else []) + messages
|
all_msgs = ([{"role": "system", "content": system}] if system else []) + messages
|
||||||
payload = {"model": GROQ_MODEL, "messages": all_msgs, "max_tokens": 4096}
|
payload = {"model": GROQ_MODEL, "messages": all_msgs, "max_tokens": 4096}
|
||||||
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
||||||
|
for attempt in range(2):
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.post("https://api.groq.com/openai/v1/chat/completions", json=payload,
|
async with session.post("https://api.groq.com/openai/v1/chat/completions", json=payload,
|
||||||
headers=headers, timeout=aiohttp.ClientTimeout(total=45)) as resp:
|
headers=headers, timeout=aiohttp.ClientTimeout(total=45)) as resp:
|
||||||
|
if resp.status == 429 and attempt == 0:
|
||||||
|
wait = min(_parse_groq_reset(resp.headers.get("x-ratelimit-reset-tokens", "")) or
|
||||||
|
_parse_groq_reset(resp.headers.get("x-ratelimit-reset-requests", "")) or 2.0, 8.0)
|
||||||
|
log.info(f"[LLM] Groq 429 — retrying in {wait:.1f}s")
|
||||||
|
await asyncio.sleep(wait)
|
||||||
|
continue
|
||||||
data = await resp.json()
|
data = await resp.json()
|
||||||
if resp.status != 200:
|
if resp.status != 200:
|
||||||
raise RuntimeError(f"Groq error {resp.status}")
|
raise RuntimeError(f"Groq error {resp.status}")
|
||||||
@@ -172,8 +212,14 @@ async def _ollama_call(messages: list, system: str = "") -> str:
|
|||||||
prompt = (system + "\n\n" if system else "") + "\n".join(f"{m['role'].upper()}: {m['content']}" for m in messages)
|
prompt = (system + "\n\n" if system else "") + "\n".join(f"{m['role'].upper()}: {m['content']}" for m in messages)
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.post(f"{OLLAMA_HOST}/api/generate", json={"model": OLLAMA_MODEL, "prompt": prompt, "stream": False},
|
async with session.post(f"{OLLAMA_HOST}/api/generate", json={"model": OLLAMA_MODEL, "prompt": prompt, "stream": False},
|
||||||
timeout=aiohttp.ClientTimeout(total=30)) as resp:
|
timeout=aiohttp.ClientTimeout(total=90)) as resp: # bumped from 30s 2026-07-07: cold model loads on this CPU-only host alone took 15s+ in testing, leaving no room for actual generation
|
||||||
data = await resp.json()
|
data = await resp.json()
|
||||||
|
# Fixed 2026-07-07: this had no error checking at all — if the model wasn't
|
||||||
|
# pulled (or any other Ollama-side error), the API returns {"error": "..."}
|
||||||
|
# with no "response" key, and this silently returned "" instead of raising,
|
||||||
|
# which fooled llm_call()'s fallback into treating it as a real success.
|
||||||
|
if "error" in data:
|
||||||
|
raise RuntimeError(f"Ollama error: {data['error']}")
|
||||||
return data.get("response", "")
|
return data.get("response", "")
|
||||||
|
|
||||||
|
|
||||||
@@ -2785,5 +2831,33 @@ async def comms_sent_delete(sent_id: int):
|
|||||||
await db_execute("DELETE FROM email_sent WHERE id=%s", (sent_id,))
|
await db_execute("DELETE FROM email_sent WHERE id=%s", (sent_id,))
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
@app.post("/comms/sent/{sent_id}/send")
|
||||||
|
async def comms_sent_send(sent_id: int):
|
||||||
|
"""
|
||||||
|
Added 2026-07-07: sends a previously-composed queued draft. Compose always
|
||||||
|
created a draft (status='queued') for review, but there was no action anywhere
|
||||||
|
to actually send one — this closes that gap. handle_send_email() records its own
|
||||||
|
fresh row in email_sent (sent/failed), so the original queued draft row is removed
|
||||||
|
here once we've handed its content off, rather than leaving a stale duplicate.
|
||||||
|
"""
|
||||||
|
row = await db_fetchone(
|
||||||
|
"SELECT account, to_email, to_name, subject, body, triage_id FROM email_sent WHERE id=%s AND status='queued'",
|
||||||
|
(sent_id,)
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Queued draft not found")
|
||||||
|
|
||||||
|
result = await handle_send_email({
|
||||||
|
"account": row["account"],
|
||||||
|
"to_email": row["to_email"],
|
||||||
|
"to_name": row["to_name"],
|
||||||
|
"subject": row["subject"],
|
||||||
|
"body": row["body"],
|
||||||
|
"triage_id": row["triage_id"],
|
||||||
|
})
|
||||||
|
|
||||||
|
await db_execute("DELETE FROM email_sent WHERE id=%s", (sent_id,))
|
||||||
|
return result
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
uvicorn.run("reactor:app", host=HOST, port=PORT, log_level="info", access_log=False)
|
uvicorn.run("reactor:app", host=HOST, port=PORT, log_level="info", access_log=False)
|
||||||
|
|||||||
+100
-22
@@ -324,16 +324,35 @@ if ($action) {
|
|||||||
|
|
||||||
// ── USERS ────────────────────────────────────────────────────────────
|
// ── USERS ────────────────────────────────────────────────────────────
|
||||||
case 'email_inbox':
|
case 'email_inbox':
|
||||||
// Call via server's own IP — REMOTE_ADDR matches JARVIS_IP so auth bypass applies
|
// Fixed 2026-07-07: this used to proxy to the OLD DO-hosted JARVIS
|
||||||
|
// (165.22.1.228/api/email with a spoofed Host header) — a leftover from
|
||||||
|
// before JARVIS moved to this VM (211). That endpoint no longer exists
|
||||||
|
// (404), so the inbox always failed. Reads the local email_triage table
|
||||||
|
// directly now, same source gmail_triage jobs already write to, matching
|
||||||
|
// the pattern email_action_items already used.
|
||||||
$acct = $_GET['account'] ?? 'all';
|
$acct = $_GET['account'] ?? 'all';
|
||||||
$force = !empty($_GET['force']) ? '&force=1' : '';
|
$where = '1=1'; $params = [];
|
||||||
$ch = curl_init('https://165.22.1.228/api/email?account=' . $acct . $force);
|
if ($acct && $acct !== 'all') { $where .= ' AND account=?'; $params[] = $acct; }
|
||||||
curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>25,
|
$rows = JarvisDB::query(
|
||||||
CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_SSL_VERIFYHOST=>false,
|
"SELECT account, from_name, from_email, subject, date_received, summary, category
|
||||||
CURLOPT_HTTPHEADER=>['Host: jarvis.orbishosting.com']]);
|
FROM email_triage WHERE {$where} ORDER BY date_received DESC LIMIT 100",
|
||||||
$r = curl_exec($ch); $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
|
$params
|
||||||
if($code===200 && $r) j(json_decode($r,true));
|
) ?? [];
|
||||||
else j(['error'=>'Email fetch failed (HTTP '.$code.')']);
|
$recent = array_map(function($r) {
|
||||||
|
return [
|
||||||
|
'account' => $r['account'],
|
||||||
|
'from_name' => $r['from_name'],
|
||||||
|
'from_email'=> $r['from_email'],
|
||||||
|
'subject' => $r['subject'],
|
||||||
|
'date' => $r['date_received'],
|
||||||
|
'preview' => $r['summary'],
|
||||||
|
'unread' => false,
|
||||||
|
];
|
||||||
|
}, $rows);
|
||||||
|
$actionCount = JarvisDB::single(
|
||||||
|
"SELECT COUNT(*) AS c FROM email_actions WHERE dismissed=0 AND task_id IS NULL AND appointment_id IS NULL"
|
||||||
|
);
|
||||||
|
j(['summary' => ['recent' => $recent], 'action_items_count' => (int)($actionCount['c'] ?? 0)]);
|
||||||
|
|
||||||
case 'email_action_items':
|
case 'email_action_items':
|
||||||
$rows = JarvisDB::query("SELECT * FROM email_actions WHERE dismissed=0 AND task_id IS NULL AND appointment_id IS NULL ORDER BY received_at DESC LIMIT 100") ?? [];
|
$rows = JarvisDB::query("SELECT * FROM email_actions WHERE dismissed=0 AND task_id IS NULL AND appointment_id IS NULL ORDER BY received_at DESC LIMIT 100") ?? [];
|
||||||
@@ -474,7 +493,7 @@ if ($action) {
|
|||||||
$latestVersions = [
|
$latestVersions = [
|
||||||
'linux' => '3.1',
|
'linux' => '3.1',
|
||||||
'proxmox' => '3.1',
|
'proxmox' => '3.1',
|
||||||
'windows' => '3.0',
|
'windows' => '3.2',
|
||||||
'macos' => '3.0',
|
'macos' => '3.0',
|
||||||
'homeassistant' => null,
|
'homeassistant' => null,
|
||||||
];
|
];
|
||||||
@@ -837,19 +856,44 @@ if ($action) {
|
|||||||
$raw = curl_exec($ch); curl_close($ch);
|
$raw = curl_exec($ch); curl_close($ch);
|
||||||
j(json_decode($raw, true) ?: ['error'=>'failed']);
|
j(json_decode($raw, true) ?: ['error'=>'failed']);
|
||||||
|
|
||||||
|
// Added 2026-07-07: fetch a single outbox item WITH its body — outbox_list
|
||||||
|
// deliberately omits body for list-view performance, but VIEW needs the full text.
|
||||||
|
case 'outbox_get':
|
||||||
|
$id = (int)($_GET['id'] ?? 0); if (!$id) bad('Missing id');
|
||||||
|
$ch = curl_init('http://127.0.0.1:7474/comms/sent/' . $id);
|
||||||
|
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5]);
|
||||||
|
$raw = curl_exec($ch); curl_close($ch);
|
||||||
|
j(json_decode($raw, true) ?: ['error'=>'failed']);
|
||||||
|
|
||||||
|
// Added 2026-07-07: closes the "compose creates a draft but nothing can ever
|
||||||
|
// send it" gap — dispatches a queued draft through the real send path.
|
||||||
|
case 'outbox_send':
|
||||||
|
$id = (int)($_GET['id'] ?? 0); if (!$id) bad('Missing id');
|
||||||
|
$ch = curl_init('http://127.0.0.1:7474/comms/sent/' . $id . '/send');
|
||||||
|
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>30, CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>'']);
|
||||||
|
$raw = curl_exec($ch); curl_close($ch);
|
||||||
|
j(json_decode($raw, true) ?: ['error'=>'failed']);
|
||||||
|
|
||||||
case 'send_reply':
|
case 'send_reply':
|
||||||
|
// Fixed 2026-07-07: sent 'content', but handle_send_email() reads 'body' —
|
||||||
|
// any edits made to the reply text in the UI were silently discarded and it
|
||||||
|
// always sent the original AI-drafted reply from email_triage instead.
|
||||||
$id = (int)($_GET['id'] ?? 0); if (!$id) bad('Missing triage id');
|
$id = (int)($_GET['id'] ?? 0); if (!$id) bad('Missing triage id');
|
||||||
$content = $_GET['content'] ?? '';
|
$content = $_GET['content'] ?? '';
|
||||||
$ch = curl_init('http://127.0.0.1:7474/job');
|
$ch = curl_init('http://127.0.0.1:7474/job');
|
||||||
curl_setopt_array($ch, [
|
curl_setopt_array($ch, [
|
||||||
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_POST => true,
|
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_POST => true,
|
||||||
CURLOPT_POSTFIELDS => json_encode(['type'=>'send_email','payload'=>['triage_id'=>$id,'content'=>$content],'priority'=>8,'created_by'=>'admin']),
|
CURLOPT_POSTFIELDS => json_encode(['type'=>'send_email','payload'=>['triage_id'=>$id,'body'=>$content],'priority'=>8,'created_by'=>'admin']),
|
||||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||||
]);
|
]);
|
||||||
$raw = curl_exec($ch); curl_close($ch);
|
$raw = curl_exec($ch); curl_close($ch);
|
||||||
j(json_decode($raw, true) ?: ['error' => 'Arc Reactor unreachable']);
|
j(json_decode($raw, true) ?: ['error' => 'Arc Reactor unreachable']);
|
||||||
|
|
||||||
case 'compose_email':
|
case 'compose_email':
|
||||||
|
// Fixed 2026-07-07: this was sending 'recipient'/'subject'/'auto_send', but
|
||||||
|
// reactor.py's handle_compose_email() reads 'to_email'/'subject_hint'/'send' —
|
||||||
|
// every compose dispatch silently produced a draft with blank recipient and
|
||||||
|
// subject, regardless of whether the LLM drafting step itself succeeded.
|
||||||
$to = $_GET['to'] ?? ''; if (!$to) bad('Missing recipient');
|
$to = $_GET['to'] ?? ''; if (!$to) bad('Missing recipient');
|
||||||
$subject = $_GET['subject'] ?? '';
|
$subject = $_GET['subject'] ?? '';
|
||||||
$body = $_GET['body'] ?? '';
|
$body = $_GET['body'] ?? '';
|
||||||
@@ -857,7 +901,7 @@ if ($action) {
|
|||||||
$ch = curl_init('http://127.0.0.1:7474/job');
|
$ch = curl_init('http://127.0.0.1:7474/job');
|
||||||
curl_setopt_array($ch, [
|
curl_setopt_array($ch, [
|
||||||
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_POST => true,
|
CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_POST => true,
|
||||||
CURLOPT_POSTFIELDS => json_encode(['type'=>'compose_email','payload'=>['recipient'=>$to,'subject'=>$subject,'instructions'=>$body,'account'=>$account,'auto_send'=>false],'priority'=>7,'created_by'=>'admin']),
|
CURLOPT_POSTFIELDS => json_encode(['type'=>'compose_email','payload'=>['to_email'=>$to,'subject_hint'=>$subject,'instructions'=>$body,'account'=>$account,'send'=>false],'priority'=>7,'created_by'=>'admin']),
|
||||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||||
]);
|
]);
|
||||||
$raw = curl_exec($ch); curl_close($ch);
|
$raw = curl_exec($ch); curl_close($ch);
|
||||||
@@ -4370,6 +4414,7 @@ async function loadOutbox() {
|
|||||||
<td style="font-size:0.6rem;color:var(--dim)">${m.account||'gmail'}</td>
|
<td style="font-size:0.6rem;color:var(--dim)">${m.account||'gmail'}</td>
|
||||||
<td style="font-size:0.6rem;color:var(--dim)">${ts}</td>
|
<td style="font-size:0.6rem;color:var(--dim)">${ts}</td>
|
||||||
<td style="white-space:nowrap">
|
<td style="white-space:nowrap">
|
||||||
|
${sc==='queued' ? `<button class="btn btn-xs btn-green" onclick="outboxSend(${m.id})">SEND</button>` : ''}
|
||||||
<button class="btn btn-xs" onclick="outboxViewBody(${m.id})">VIEW</button>
|
<button class="btn btn-xs" onclick="outboxViewBody(${m.id})">VIEW</button>
|
||||||
<button class="btn btn-xs btn-red" onclick="outboxDelete(${m.id})">DEL</button>
|
<button class="btn btn-xs btn-red" onclick="outboxDelete(${m.id})">DEL</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -4385,12 +4430,19 @@ async function outboxDelete(id) {
|
|||||||
else toast('Delete failed: ' + (d.error||''), 'err');
|
else toast('Delete failed: ' + (d.error||''), 'err');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Added 2026-07-07: composing only ever created a queued draft — there was no
|
||||||
|
// button anywhere to actually send one. This closes that gap.
|
||||||
|
async function outboxSend(id) {
|
||||||
|
if (!confirm('Send this draft now?')) return;
|
||||||
|
const d = await api('outbox_send', {id});
|
||||||
|
if (d.success) { toast('Sent', 'ok'); loadOutbox(); }
|
||||||
|
else toast('Send failed: ' + (d.error||'unknown error'), 'err');
|
||||||
|
}
|
||||||
|
|
||||||
async function outboxViewBody(id) {
|
async function outboxViewBody(id) {
|
||||||
const d = await api('outbox_list', {limit: 200});
|
const m = await api('outbox_get', {id});
|
||||||
const sent = Array.isArray(d) ? d : (d.sent || []);
|
if (!m || m.error) { toast('Failed to load message', 'err'); return; }
|
||||||
const m = sent.find(x => x.id == id);
|
openModal((m.status==='queued'?'DRAFT — ':'SENT MESSAGE — ') + esc(m.subject||''), `
|
||||||
if (!m) return;
|
|
||||||
openModal('SENT MESSAGE — ' + esc(m.subject||''), `
|
|
||||||
<div style="font-family:var(--mono);font-size:0.65rem;color:var(--text-dim);margin-bottom:8px">TO: ${esc(m.to_email||'')} · ACCOUNT: ${m.account||'gmail'}</div>
|
<div style="font-family:var(--mono);font-size:0.65rem;color:var(--text-dim);margin-bottom:8px">TO: ${esc(m.to_email||'')} · ACCOUNT: ${m.account||'gmail'}</div>
|
||||||
<pre style="font-size:0.65rem;white-space:pre-wrap;max-height:300px;overflow-y:auto;background:rgba(0,212,255,0.03);border:1px solid var(--border);border-radius:3px;padding:8px">${esc(m.body||'(no body)')}</pre>
|
<pre style="font-size:0.65rem;white-space:pre-wrap;max-height:300px;overflow-y:auto;background:rgba(0,212,255,0.03);border:1px solid var(--border);border-radius:3px;padding:8px">${esc(m.body||'(no body)')}</pre>
|
||||||
`, null, null);
|
`, null, null);
|
||||||
@@ -4406,6 +4458,7 @@ function outboxCompose() {
|
|||||||
<input id="oc-to" class="inp" placeholder="To: email address" type="email">
|
<input id="oc-to" class="inp" placeholder="To: email address" type="email">
|
||||||
<input id="oc-subject" class="inp" placeholder="Subject">
|
<input id="oc-subject" class="inp" placeholder="Subject">
|
||||||
<textarea id="oc-body" class="inp" rows="5" style="resize:vertical" placeholder="Describe what to say — AI will draft the full message"></textarea>
|
<textarea id="oc-body" class="inp" rows="5" style="resize:vertical" placeholder="Describe what to say — AI will draft the full message"></textarea>
|
||||||
|
<div id="oc-status" style="display:none;font-size:0.65rem;color:var(--text-dim);padding:8px;background:#060a0e;border:1px solid var(--border);border-radius:3px"></div>
|
||||||
</div>
|
</div>
|
||||||
`, async () => {
|
`, async () => {
|
||||||
const to = document.getElementById('oc-to')?.value.trim();
|
const to = document.getElementById('oc-to')?.value.trim();
|
||||||
@@ -4413,14 +4466,39 @@ function outboxCompose() {
|
|||||||
const body = document.getElementById('oc-body')?.value.trim();
|
const body = document.getElementById('oc-body')?.value.trim();
|
||||||
const account = document.getElementById('oc-account')?.value;
|
const account = document.getElementById('oc-account')?.value;
|
||||||
if (!to || !body) { toast('Please fill To and message description', 'err'); return; }
|
if (!to || !body) { toast('Please fill To and message description', 'err'); return; }
|
||||||
|
const statusEl = document.getElementById('oc-status');
|
||||||
const d = await api('compose_email', {to, subject, body, account});
|
const d = await api('compose_email', {to, subject, body, account});
|
||||||
if (d.job_id) {
|
if (!d.job_id) { toast('Failed: ' + (d.error||'Arc Reactor offline'), 'err'); return; }
|
||||||
toast('Compose job dispatched — Job #' + d.job_id, 'ok');
|
// Fixed 2026-07-07: this used to toast "dispatched" and close immediately, with
|
||||||
|
// no way to ever find out if the job later failed — it just silently vanished.
|
||||||
|
// Now polls the actual job status until it finishes, so failures are visible.
|
||||||
|
if (statusEl) { statusEl.style.display = 'block'; statusEl.textContent = 'Drafting — Job #' + d.job_id + '...'; }
|
||||||
|
document.getElementById('modalSave').disabled = true;
|
||||||
|
const jobId = d.job_id;
|
||||||
|
const deadline = Date.now() + 120000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
await new Promise(r => setTimeout(r, 3000));
|
||||||
|
const j = await api('arc_job_get', {id: jobId}).catch(() => null);
|
||||||
|
if (!j || j.error) continue;
|
||||||
|
if (j.status === 'done') {
|
||||||
|
toast('Draft ready: ' + (j.result?.subject || '(no subject)'), 'ok');
|
||||||
closeModal();
|
closeModal();
|
||||||
setTimeout(loadOutbox, 5000);
|
loadOutbox();
|
||||||
} else {
|
return;
|
||||||
toast('Failed: ' + (d.error||'Arc Reactor offline'), 'err');
|
} else if (j.status === 'failed') {
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.style.color = 'var(--red)';
|
||||||
|
statusEl.textContent = '✗ Failed: ' + (j.error || 'unknown error');
|
||||||
}
|
}
|
||||||
|
document.getElementById('modalSave').disabled = false;
|
||||||
|
document.getElementById('modalSave').textContent = 'CLOSE';
|
||||||
|
document.getElementById('modalSave').onclick = closeModal;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (statusEl) statusEl.textContent = 'Drafting — Job #' + jobId + ' (' + j.status + ')...';
|
||||||
|
}
|
||||||
|
if (statusEl) { statusEl.style.color = 'var(--yellow)'; statusEl.textContent = '⚠ Still running in background — check outbox shortly.'; }
|
||||||
|
document.getElementById('modalSave').disabled = false;
|
||||||
}, 'DISPATCH');
|
}, 'DISPATCH');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,20 +6,26 @@
|
|||||||
.DESCRIPTION
|
.DESCRIPTION
|
||||||
Installs JARVIS Agent as a Windows Service that auto-starts at boot.
|
Installs JARVIS Agent as a Windows Service that auto-starts at boot.
|
||||||
Requires: PowerShell 5.1+, internet access, and Administrator rights.
|
Requires: PowerShell 5.1+, internet access, and Administrator rights.
|
||||||
|
No Python installation needed — this installs the standalone .exe build.
|
||||||
|
|
||||||
.EXAMPLE
|
.EXAMPLE
|
||||||
# Interactive install (prompts for registration key):
|
# Interactive install (prompts for registration key):
|
||||||
irm https://jarvis.orbishosting.com/agent/install-windows.ps1 | iex
|
irm https://jarvis.orbishosting.com:1972/agent/install-windows.ps1 | iex
|
||||||
|
|
||||||
# Silent install with key:
|
# Silent install with key:
|
||||||
$env:JARVIS_REG_KEY='your_key_here'; irm https://jarvis.orbishosting.com/agent/install-windows.ps1 | iex
|
$env:JARVIS_REG_KEY='your_key_here'; irm https://jarvis.orbishosting.com:1972/agent/install-windows.ps1 | iex
|
||||||
#>
|
#>
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
$JARVIS_URL = 'https://jarvis.orbishosting.com'
|
# Fixed 2026-07-07: jarvis.orbishosting.com on the default port (80/443) is not
|
||||||
|
# reachable from outside the LAN at all (no FortiGate VIP forwards it) — every
|
||||||
|
# external install using the old default URL would have failed outright. Port
|
||||||
|
# 1972 is the confirmed-working external path (same fix applied to the GitHub
|
||||||
|
# webhook the same day).
|
||||||
|
$JARVIS_URL = 'http://jarvis.orbishosting.com:1972'
|
||||||
$INSTALL_DIR = 'C:\ProgramData\jarvis-agent'
|
$INSTALL_DIR = 'C:\ProgramData\jarvis-agent'
|
||||||
$SERVICE_NAME = 'JARVISAgent'
|
$SERVICE_NAME = 'JARVISAgent'
|
||||||
$AGENT_SCRIPT = "$INSTALL_DIR\jarvis-agent-windows.py"
|
$AGENT_EXE = "$INSTALL_DIR\jarvis-agent-windows.exe"
|
||||||
$CONFIG_FILE = "$INSTALL_DIR\config.json"
|
$CONFIG_FILE = "$INSTALL_DIR\config.json"
|
||||||
|
|
||||||
function Write-Step { param($msg) Write-Host "`n[JARVIS] $msg" -ForegroundColor Cyan }
|
function Write-Step { param($msg) Write-Host "`n[JARVIS] $msg" -ForegroundColor Cyan }
|
||||||
@@ -39,49 +45,23 @@ if ($existing) {
|
|||||||
Start-Sleep 2
|
Start-Sleep 2
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
& python "$INSTALL_DIR\jarvis-agent-windows.py" remove 2>$null
|
if (Test-Path $AGENT_EXE) { & $AGENT_EXE remove 2>$null }
|
||||||
} catch {}
|
} catch {}
|
||||||
Write-OK "Existing service removed."
|
Write-OK "Existing service removed."
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Check / install Python ────────────────────────────────────────────────────
|
|
||||||
Write-Step "Checking Python..."
|
|
||||||
$py = Get-Command python -ErrorAction SilentlyContinue
|
|
||||||
if (-not $py) {
|
|
||||||
Write-Host " Python not found. Installing via winget..." -ForegroundColor Yellow
|
|
||||||
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
|
|
||||||
Write-Fail "winget not available. Please install Python 3.11+ from https://python.org and re-run."
|
|
||||||
}
|
|
||||||
winget install -e --id Python.Python.3.11 --silent --accept-package-agreements --accept-source-agreements
|
|
||||||
$env:PATH = [System.Environment]::GetEnvironmentVariable("PATH","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH","User")
|
|
||||||
$py = Get-Command python -ErrorAction SilentlyContinue
|
|
||||||
if (-not $py) { Write-Fail "Python install failed. Please install manually from https://python.org" }
|
|
||||||
}
|
|
||||||
$pyVersion = & python --version 2>&1
|
|
||||||
Write-OK $pyVersion
|
|
||||||
|
|
||||||
# ── Install pywin32 ───────────────────────────────────────────────────────────
|
|
||||||
Write-Step "Checking pywin32..."
|
|
||||||
$checkWin32 = & python -c "import win32service; print('ok')" 2>&1
|
|
||||||
if ($checkWin32 -ne 'ok') {
|
|
||||||
Write-Host " Installing pywin32..." -ForegroundColor Yellow
|
|
||||||
& python -m pip install --quiet pywin32
|
|
||||||
& python -m pywin32_postinstall -install 2>$null
|
|
||||||
Write-OK "pywin32 installed."
|
|
||||||
} else {
|
|
||||||
Write-OK "pywin32 already installed."
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Create install dir ────────────────────────────────────────────────────────
|
# ── Create install dir ────────────────────────────────────────────────────────
|
||||||
Write-Step "Creating install directory..."
|
Write-Step "Creating install directory..."
|
||||||
New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
|
New-Item -ItemType Directory -Path $INSTALL_DIR -Force | Out-Null
|
||||||
Write-OK $INSTALL_DIR
|
Write-OK $INSTALL_DIR
|
||||||
|
|
||||||
# ── Download agent script ─────────────────────────────────────────────────────
|
# ── Download agent exe ─────────────────────────────────────────────────────────
|
||||||
|
# No Python/pywin32 dependency anymore — this is a self-contained PyInstaller
|
||||||
|
# build with everything it needs bundled in.
|
||||||
Write-Step "Downloading JARVIS agent..."
|
Write-Step "Downloading JARVIS agent..."
|
||||||
try {
|
try {
|
||||||
Invoke-WebRequest -Uri "$JARVIS_URL/agent/jarvis-agent-windows.py" -OutFile $AGENT_SCRIPT -UseBasicParsing
|
Invoke-WebRequest -Uri "$JARVIS_URL/agent/jarvis-agent-windows.exe" -OutFile $AGENT_EXE -UseBasicParsing
|
||||||
Write-OK "Agent downloaded to $AGENT_SCRIPT"
|
Write-OK "Agent downloaded to $AGENT_EXE"
|
||||||
} catch {
|
} catch {
|
||||||
Write-Fail "Failed to download agent: $_"
|
Write-Fail "Failed to download agent: $_"
|
||||||
}
|
}
|
||||||
@@ -121,8 +101,7 @@ Write-OK "Config written to $CONFIG_FILE"
|
|||||||
|
|
||||||
# ── Install Windows Service ───────────────────────────────────────────────────
|
# ── Install Windows Service ───────────────────────────────────────────────────
|
||||||
Write-Step "Installing Windows service..."
|
Write-Step "Installing Windows service..."
|
||||||
$pyPath = (Get-Command python).Source
|
& $AGENT_EXE --startup auto install
|
||||||
& $pyPath "$AGENT_SCRIPT" --startup auto install
|
|
||||||
if ($LASTEXITCODE -ne 0) { Write-Fail "Service install failed." }
|
if ($LASTEXITCODE -ne 0) { Write-Fail "Service install failed." }
|
||||||
Write-OK "Service '$SERVICE_NAME' installed."
|
Write-OK "Service '$SERVICE_NAME' installed."
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,34 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# JARVIS Agent Installer — one-liner for any Linux host:
|
# JARVIS Agent Installer — one-liner for any Linux host:
|
||||||
# curl -sk https://jarvis.orbishosting.com/install-agent.sh | bash -s <hostname> <agent_type>
|
# curl -sk http://jarvis.orbishosting.com:1972/agent/install.sh | bash -s <hostname> <agent_type>
|
||||||
#
|
#
|
||||||
# agent_type: linux | proxmox | homeassistant
|
# agent_type: linux | proxmox | homeassistant
|
||||||
# Example: curl -sk https://jarvis.orbishosting.com/install-agent.sh | bash -s myserver linux
|
# Example: curl -sk http://jarvis.orbishosting.com:1972/agent/install.sh | bash -s myserver linux
|
||||||
|
#
|
||||||
|
# On the LAN, set JARVIS_URL to the direct internal address instead (faster,
|
||||||
|
# doesn't hairpin through Cloudflare): JARVIS_URL=http://10.48.200.211 curl ... | bash -s ...
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
HOSTNAME_ARG="${1:-$(hostname -s)}"
|
HOSTNAME_ARG="${1:-$(hostname -s)}"
|
||||||
AGENT_TYPE="${2:-linux}"
|
AGENT_TYPE="${2:-linux}"
|
||||||
JARVIS_URL="${JARVIS_URL:-https://jarvis.orbishosting.com}"
|
# Fixed 2026-07-07: jarvis.orbishosting.com on the default port isn't reachable
|
||||||
|
# from outside the LAN at all (no FortiGate VIP forwards it) — :1972 is the
|
||||||
|
# confirmed-working external path (same fix as the GitHub webhook and the
|
||||||
|
# Windows agent installer).
|
||||||
|
JARVIS_URL="${JARVIS_URL:-http://jarvis.orbishosting.com:1972}"
|
||||||
JARVIS_HOST=""
|
JARVIS_HOST=""
|
||||||
INSTALL_DIR="/opt/jarvis-agent"
|
INSTALL_DIR="/opt/jarvis-agent"
|
||||||
CONFIG_DIR="/etc/jarvis-agent"
|
CONFIG_DIR="/etc/jarvis-agent"
|
||||||
STATE_DIR="/var/lib/jarvis-agent"
|
STATE_DIR="/var/lib/jarvis-agent"
|
||||||
REG_KEY="f846a9aaf7ce9a61742c63c87c4186052a71d2a580c65518"
|
REG_KEY="${JARVIS_REG_KEY:-}"
|
||||||
|
if [ -z "$REG_KEY" ] && [ -r /dev/tty ]; then
|
||||||
|
read -rp "Enter JARVIS registration key: " REG_KEY </dev/tty
|
||||||
|
fi
|
||||||
|
if [ -z "$REG_KEY" ]; then
|
||||||
|
echo "ERROR: registration key required (set JARVIS_REG_KEY env var or enter at prompt)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
SERVICE_FILE="/etc/systemd/system/jarvis-agent.service"
|
SERVICE_FILE="/etc/systemd/system/jarvis-agent.service"
|
||||||
|
|
||||||
echo "=== JARVIS Agent Installer v3.0 ==="
|
echo "=== JARVIS Agent Installer v3.0 ==="
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1 @@
|
|||||||
|
ad9b59c09e5862c5abc35f73999aa2666f8401817b053c385505fa420ca473e7
|
||||||
@@ -35,12 +35,11 @@ INSTALL_DIR = Path(r"C:\ProgramData\jarvis-agent")
|
|||||||
CONFIG_PATH = INSTALL_DIR / "config.json"
|
CONFIG_PATH = INSTALL_DIR / "config.json"
|
||||||
STATE_PATH = INSTALL_DIR / "state.json"
|
STATE_PATH = INSTALL_DIR / "state.json"
|
||||||
LOG_PATH = INSTALL_DIR / "jarvis-agent.log"
|
LOG_PATH = INSTALL_DIR / "jarvis-agent.log"
|
||||||
AGENT_VERSION = "3.1"
|
AGENT_VERSION = "3.2"
|
||||||
|
|
||||||
# Set by the service wrapper so self_update knows to stop instead of exec
|
# Set by the service wrapper so self_update knows to stop instead of exec
|
||||||
_is_service = False
|
_is_service = False
|
||||||
_stop_event = threading.Event()
|
_stop_event = threading.Event()
|
||||||
_update_restart = False # True when stopping for self-update; triggers SCM restart
|
|
||||||
|
|
||||||
# ── Logging ────────────────────────────────────────────────────────────────────
|
# ── Logging ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -93,7 +92,7 @@ def api_post(url: str, payload: dict, headers: dict = {}, timeout: int = 15,
|
|||||||
body = json.dumps(payload).encode()
|
body = json.dumps(payload).encode()
|
||||||
req = urllib.request.Request(url, data=body, method="POST")
|
req = urllib.request.Request(url, data=body, method="POST")
|
||||||
req.add_header("Content-Type", "application/json")
|
req.add_header("Content-Type", "application/json")
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
for k, v in headers.items():
|
for k, v in headers.items():
|
||||||
@@ -110,7 +109,7 @@ def api_post(url: str, payload: dict, headers: dict = {}, timeout: int = 15,
|
|||||||
def api_get(url: str, headers: dict = {}, timeout: int = 10,
|
def api_get(url: str, headers: dict = {}, timeout: int = 10,
|
||||||
ssl_verify: bool = True) -> dict:
|
ssl_verify: bool = True) -> dict:
|
||||||
req = urllib.request.Request(url)
|
req = urllib.request.Request(url)
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
for k, v in headers.items():
|
for k, v in headers.items():
|
||||||
@@ -376,18 +375,28 @@ def _sysinfo_snapshot() -> dict:
|
|||||||
# ── Self-update ────────────────────────────────────────────────────────────────
|
# ── Self-update ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def self_update(cfg: dict) -> bool:
|
def self_update(cfg: dict) -> bool:
|
||||||
|
# Added: supports both script-mode (plain .py, run via a system Python) and
|
||||||
|
# frozen-mode (standalone PyInstaller .exe — sys.frozen is set, __file__ isn't
|
||||||
|
# meaningful/writable the way it is for a real .py file on disk). A running
|
||||||
|
# .exe can't be overwritten in place on Windows, but CAN be renamed while
|
||||||
|
# running, so frozen mode uses a download-new/rename-old/rename-new swap
|
||||||
|
# instead of the direct overwrite the script-mode path uses.
|
||||||
jarvis_url = cfg.get("jarvis_url", "").rstrip("/")
|
jarvis_url = cfg.get("jarvis_url", "").rstrip("/")
|
||||||
|
is_frozen = bool(getattr(sys, "frozen", False))
|
||||||
|
if is_frozen:
|
||||||
|
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.exe" if jarvis_url else ""
|
||||||
|
else:
|
||||||
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.py" if jarvis_url else ""
|
default_update_url = f"{jarvis_url}/agent/jarvis-agent-windows.py" if jarvis_url else ""
|
||||||
update_url = cfg.get("update_url", default_update_url)
|
update_url = cfg.get("update_url", default_update_url)
|
||||||
if not update_url:
|
if not update_url:
|
||||||
return False
|
return False
|
||||||
script_path = os.path.abspath(__file__)
|
target_path = os.path.abspath(sys.executable) if is_frozen else os.path.abspath(__file__)
|
||||||
ssl_verify = bool(cfg.get("ssl_verify", True))
|
ssl_verify = bool(cfg.get("ssl_verify", True))
|
||||||
try:
|
try:
|
||||||
# Download expected hash
|
# Download expected hash
|
||||||
hash_url = update_url + ".sha256"
|
hash_url = update_url + ".sha256"
|
||||||
req_hash = urllib.request.Request(hash_url)
|
req_hash = urllib.request.Request(hash_url)
|
||||||
req_hash.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req_hash.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req_hash.add_header("Host", _host_header)
|
req_hash.add_header("Host", _host_header)
|
||||||
expected_hash = None
|
expected_hash = None
|
||||||
@@ -398,13 +407,13 @@ def self_update(cfg: dict) -> bool:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Download new script
|
# Download new script/exe
|
||||||
req = urllib.request.Request(update_url)
|
req = urllib.request.Request(update_url)
|
||||||
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.0")
|
req.add_header("User-Agent", "JARVIS-Agent-Windows/3.2")
|
||||||
if _host_header:
|
if _host_header:
|
||||||
req.add_header("Host", _host_header)
|
req.add_header("Host", _host_header)
|
||||||
ctx = _make_ssl_ctx(ssl_verify)
|
ctx = _make_ssl_ctx(ssl_verify)
|
||||||
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
|
with urllib.request.urlopen(req, timeout=60, context=ctx) as resp:
|
||||||
new_content = resp.read()
|
new_content = resp.read()
|
||||||
|
|
||||||
# Verify hash
|
# Verify hash
|
||||||
@@ -414,21 +423,42 @@ def self_update(cfg: dict) -> bool:
|
|||||||
log(f"Update hash mismatch (expected {expected_hash[:16]}… got {actual_hash[:16]}…) — aborting")
|
log(f"Update hash mismatch (expected {expected_hash[:16]}… got {actual_hash[:16]}…) — aborting")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
with open(script_path, "rb") as f:
|
with open(target_path, "rb") as f:
|
||||||
current = f.read()
|
current = f.read()
|
||||||
if new_content != current:
|
if new_content == current:
|
||||||
log(f"Update verified — replacing {script_path} and restarting...")
|
return False
|
||||||
with open(script_path, "wb") as f:
|
|
||||||
|
log(f"Update verified — replacing {target_path} and restarting...")
|
||||||
|
if is_frozen:
|
||||||
|
# Can't overwrite a running exe, but can rename it and drop the new
|
||||||
|
# one in its place; the old copy is cleaned up on the next update.
|
||||||
|
old_path = target_path + ".old"
|
||||||
|
new_path = target_path + ".new"
|
||||||
|
with open(new_path, "wb") as f:
|
||||||
f.write(new_content)
|
f.write(new_content)
|
||||||
|
try:
|
||||||
|
if os.path.exists(old_path):
|
||||||
|
os.remove(old_path)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
os.rename(target_path, old_path)
|
||||||
|
os.rename(new_path, target_path)
|
||||||
|
else:
|
||||||
|
with open(target_path, "wb") as f:
|
||||||
|
f.write(new_content)
|
||||||
|
|
||||||
if _is_service:
|
if _is_service:
|
||||||
global _update_restart
|
# Signal the main loop to exit; SCM failure-recovery will restart us
|
||||||
_update_restart = True
|
|
||||||
log("Running as service — stopping for SCM-managed restart after update.")
|
log("Running as service — stopping for SCM-managed restart after update.")
|
||||||
_stop_event.set()
|
_stop_event.set()
|
||||||
|
elif is_frozen:
|
||||||
|
# sys.argv[0] is already the exe's own path for a frozen app — don't
|
||||||
|
# prepend sys.executable again or the new process misreads its own
|
||||||
|
# path as a command-line argument.
|
||||||
|
os.execv(sys.executable, sys.argv)
|
||||||
else:
|
else:
|
||||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||||
return True
|
return True
|
||||||
return False
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(f"Self-update check failed: {e}")
|
log(f"Self-update check failed: {e}")
|
||||||
return False
|
return False
|
||||||
@@ -592,9 +622,6 @@ if _HAS_WIN32:
|
|||||||
(self._svc_name_, ""),
|
(self._svc_name_, ""),
|
||||||
)
|
)
|
||||||
main()
|
main()
|
||||||
if _update_restart:
|
|
||||||
# Non-zero exit triggers SCM failure recovery → automatic restart
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
224a634375b5d49ccc0a012e0e122ade5f8a1302615450dffbf9a03eac6b7a19
|
fff217657488830084780115665d0c772af1f7fe31f2084d61a7560424a5a91a
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ $_e1 = $_earlyParts[1] ?? '';
|
|||||||
$_skipSession = match(true) {
|
$_skipSession = match(true) {
|
||||||
$_e0 === 'ping' => true,
|
$_e0 === 'ping' => true,
|
||||||
$_e0 === 'netscan' => true,
|
$_e0 === 'netscan' => true,
|
||||||
$_e0 === 'agent' && !in_array($_e1, ['list','status','myip'], true) => true,
|
$_e0 === 'agent' && !in_array($_e1, ['list','status','myip','regkey'], true) => true,
|
||||||
default => false,
|
default => false,
|
||||||
};
|
};
|
||||||
if (!$_skipSession) {
|
if (!$_skipSession) {
|
||||||
|
|||||||
@@ -982,6 +982,7 @@ async function loadWeather() {
|
|||||||
const d = await api('weather');
|
const d = await api('weather');
|
||||||
if (!d || !d.current) return;
|
if (!d || !d.current) return;
|
||||||
const c = d.current;
|
const c = d.current;
|
||||||
|
if (d.location) document.getElementById('weather-loc').textContent = d.location.toUpperCase();
|
||||||
document.getElementById('weather-temp').textContent = c.temp;
|
document.getElementById('weather-temp').textContent = c.temp;
|
||||||
document.getElementById('weather-desc').textContent = (c.desc || '').toUpperCase();
|
document.getElementById('weather-desc').textContent = (c.desc || '').toUpperCase();
|
||||||
document.getElementById('weather-feels').textContent = c.feels + '°F';
|
document.getElementById('weather-feels').textContent = c.feels + '°F';
|
||||||
@@ -1631,11 +1632,18 @@ async function checkAgentStatus() {
|
|||||||
sta.textContent = online.length > 0 ? online.length + ' ONLINE' : 'NONE';
|
sta.textContent = online.length > 0 ? online.length + ' ONLINE' : 'NONE';
|
||||||
const cnt = document.getElementById('net-agent-count');
|
const cnt = document.getElementById('net-agent-count');
|
||||||
if (cnt) cnt.textContent = online.length + ' AGENT' + (online.length !== 1 ? 'S' : '') + ' ONLINE';
|
if (cnt) cnt.textContent = online.length + ' AGENT' + (online.length !== 1 ? 'S' : '') + ' ONLINE';
|
||||||
|
// Fixed 2026-07-07: this used to fall back to "any agent on the same /24
|
||||||
|
// subnet" when the exact IP didn't match, meant to handle NAT — but when
|
||||||
|
// a LAN client hits the dashboard via its external hostname (hairpin NAT,
|
||||||
|
// or through Cloudflare), the server sees the SAME single reflected/proxy
|
||||||
|
// IP for every visitor on the LAN, not each machine's real one. The exact
|
||||||
|
// match then always fails, and the subnet fallback just grabbed whichever
|
||||||
|
// agent happened to be first in the list — showing a *different real
|
||||||
|
// machine* as "yours", not a harmless guess. Exact match only now; if it
|
||||||
|
// fails, the button correctly falls through to "not detected" instead of
|
||||||
|
// reporting someone else's agent as this one.
|
||||||
const myIp = data.my_ip || '';
|
const myIp = data.my_ip || '';
|
||||||
// Match by exact IP first, then by same /24 subnet (handles NAT behind same router)
|
_myAgent = online.find(a => a.ip_address === myIp) || null;
|
||||||
const mySubnet = myIp.split('.').slice(0,3).join('.');
|
|
||||||
_myAgent = online.find(a => a.ip_address === myIp)
|
|
||||||
|| online.find(a => a.ip_address && a.ip_address.startsWith(mySubnet + '.'));
|
|
||||||
_agentOnline = !!_myAgent;
|
_agentOnline = !!_myAgent;
|
||||||
if (btn) {
|
if (btn) {
|
||||||
const isTablet = detectOS() === 'tablet';
|
const isTablet = detectOS() === 'tablet';
|
||||||
|
|||||||
@@ -432,14 +432,23 @@ function renderAgentsTab(agents, metrics) {
|
|||||||
}).join('');
|
}).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
function openAgentModal() {
|
async function openAgentModal() {
|
||||||
const os = detectOS();
|
const os = detectOS();
|
||||||
const title = document.getElementById('agentModalTitle');
|
const title = document.getElementById('agentModalTitle');
|
||||||
const content = document.getElementById('agentModalContent');
|
const content = document.getElementById('agentModalContent');
|
||||||
const modal = document.getElementById('agentModal');
|
const modal = document.getElementById('agentModal');
|
||||||
const regKey = 'f846a9aaf7ce9a61742c63c87c4186052a71d2a580c65518';
|
let regKey = '<YOUR-REGISTRATION-KEY>';
|
||||||
const baseUrl = 'https://jarvis.orbishosting.com/agent';
|
try {
|
||||||
|
const rkResp = await fetch('/api/agent/regkey');
|
||||||
|
if (rkResp.ok) { const rk = await rkResp.json(); if (rk.registration_key) regKey = rk.registration_key; }
|
||||||
|
} catch (e) { /* not logged in — placeholder stays */ }
|
||||||
const jUrl = window.location.origin;
|
const jUrl = window.location.origin;
|
||||||
|
// Fixed 2026-07-07: this used to be hardcoded to https://jarvis.orbishosting.com/agent,
|
||||||
|
// which isn't reachable from outside the LAN at all (no FortiGate VIP forwards the
|
||||||
|
// default port there — confirmed HTTP:000). Using the current page's own origin
|
||||||
|
// instead means the download link always matches wherever the visitor actually
|
||||||
|
// reached this dashboard from, LAN or external.
|
||||||
|
const baseUrl = jUrl + '/agent';
|
||||||
|
|
||||||
if (os === 'tablet') {
|
if (os === 'tablet') {
|
||||||
title.textContent = '● JARVIS — TABLET / MOBILE';
|
title.textContent = '● JARVIS — TABLET / MOBILE';
|
||||||
@@ -460,9 +469,12 @@ function openAgentModal() {
|
|||||||
const inst = {
|
const inst = {
|
||||||
windows: {
|
windows: {
|
||||||
label:'Windows',
|
label:'Windows',
|
||||||
cmd:'# Run PowerShell as Administrator:\nSet-ExecutionPolicy Bypass -Scope Process -Force\nInvoke-WebRequest -Uri "'+baseUrl+'/install-windows.ps1" -OutFile "$env:TEMP\\install.ps1"\n& "$env:TEMP\\install.ps1" -JarvisUrl '+jUrl+' -Key '+regKey,
|
// install-windows.ps1 takes no parameters — it reads the reg key from
|
||||||
dl: baseUrl+'/install-windows.ps1',
|
// $env:JARVIS_REG_KEY and downloads the standalone exe itself (no
|
||||||
note:'Run PowerShell as Administrator. Installs as a Windows Task Scheduler service.'
|
// Python/pywin32 needed on the target machine as of the 2026-07-07 rebuild).
|
||||||
|
cmd:'# Run PowerShell as Administrator:\n$env:JARVIS_REG_KEY=\''+regKey+'\'\nirm '+baseUrl+'/install-windows.ps1 | iex',
|
||||||
|
dl: baseUrl+'/install-windows.exe',
|
||||||
|
note:'Run PowerShell as Administrator. Installs as a real Windows Service (auto-starts at boot, no window to keep open).'
|
||||||
},
|
},
|
||||||
mac: {
|
mac: {
|
||||||
label:'macOS',
|
label:'macOS',
|
||||||
@@ -472,15 +484,17 @@ function openAgentModal() {
|
|||||||
},
|
},
|
||||||
linux: {
|
linux: {
|
||||||
label:'Linux',
|
label:'Linux',
|
||||||
cmd:'curl -sSL '+baseUrl+'/install.sh | sudo bash -s -- \\\n --jarvis-url '+jUrl+' \\\n --key '+regKey,
|
// install.sh takes positional args (hostname, agent_type); JARVIS URL and
|
||||||
|
// registration key come from env vars (key is no longer baked into the script).
|
||||||
|
cmd:'curl -sSL '+baseUrl+'/install.sh | JARVIS_URL='+jUrl+' JARVIS_REG_KEY=\''+regKey+'\' bash -s -- $(hostname) linux',
|
||||||
dl: baseUrl+'/install.sh',
|
dl: baseUrl+'/install.sh',
|
||||||
note:'Run in terminal. Installs as a systemd service.'
|
note:'Run in terminal (sudo). Installs as a systemd service.'
|
||||||
},
|
},
|
||||||
unknown: {
|
unknown: {
|
||||||
label:'Your System',
|
label:'Your System',
|
||||||
cmd:'# Browse installers:\nhttps://jarvis.orbishosting.com/agent/',
|
cmd:'# Couldn\'t detect your OS automatically. Installers are at:\n'+baseUrl+'/install.sh (Linux)\n'+baseUrl+'/install-mac.sh (macOS)\n'+baseUrl+'/install-windows.ps1 (Windows)',
|
||||||
dl: 'https://jarvis.orbishosting.com/agent/',
|
dl: baseUrl+'/install.sh',
|
||||||
note:'Choose your platform installer from the JARVIS agent directory.'
|
note:'Auto-detection didn\'t recognize this browser/OS — pick the matching installer above.'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const i = inst[os] || inst.unknown;
|
const i = inst[os] || inst.unknown;
|
||||||
|
|||||||
@@ -84,7 +84,7 @@
|
|||||||
<div id="leftPanel">
|
<div id="leftPanel">
|
||||||
<!-- Weather Widget -->
|
<!-- Weather Widget -->
|
||||||
<div class="panel" style="flex:0 0 auto">
|
<div class="panel" style="flex:0 0 auto">
|
||||||
<div class="panel-title">WEATHER <span id="weather-loc" style="font-size:0.55rem;color:var(--text-dim)">FORT WORTH, TX</span></div>
|
<div class="panel-title">WEATHER <span id="weather-loc" style="font-size:0.55rem;color:var(--text-dim)">WEATHERFORD, TX</span></div>
|
||||||
<div style="display:flex;align-items:flex-start;gap:12px;margin-bottom:8px">
|
<div style="display:flex;align-items:flex-start;gap:12px;margin-bottom:8px">
|
||||||
<div style="flex:1">
|
<div style="flex:1">
|
||||||
<div style="display:flex;align-items:baseline;gap:8px">
|
<div style="display:flex;align-items:baseline;gap:8px">
|
||||||
|
|||||||
@@ -1,20 +1,34 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# JARVIS Agent Installer — one-liner for any Linux host:
|
# JARVIS Agent Installer — one-liner for any Linux host:
|
||||||
# curl -sk https://jarvis.orbishosting.com/install-agent.sh | bash -s <hostname> <agent_type>
|
# curl -sk http://jarvis.orbishosting.com:1972/agent/install.sh | bash -s <hostname> <agent_type>
|
||||||
#
|
#
|
||||||
# agent_type: linux | proxmox | homeassistant
|
# agent_type: linux | proxmox | homeassistant
|
||||||
# Example: curl -sk https://jarvis.orbishosting.com/install-agent.sh | bash -s myserver linux
|
# Example: curl -sk http://jarvis.orbishosting.com:1972/agent/install.sh | bash -s myserver linux
|
||||||
|
#
|
||||||
|
# On the LAN, set JARVIS_URL to the direct internal address instead (faster,
|
||||||
|
# doesn't hairpin through Cloudflare): JARVIS_URL=http://10.48.200.211 curl ... | bash -s ...
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
HOSTNAME_ARG="${1:-$(hostname -s)}"
|
HOSTNAME_ARG="${1:-$(hostname -s)}"
|
||||||
AGENT_TYPE="${2:-linux}"
|
AGENT_TYPE="${2:-linux}"
|
||||||
JARVIS_URL="https://165.22.1.228"
|
# Fixed 2026-07-07: jarvis.orbishosting.com on the default port isn't reachable
|
||||||
JARVIS_HOST="jarvis.orbishosting.com"
|
# from outside the LAN at all (no FortiGate VIP forwards it) — :1972 is the
|
||||||
|
# confirmed-working external path (same fix as the GitHub webhook and the
|
||||||
|
# Windows agent installer).
|
||||||
|
JARVIS_URL="${JARVIS_URL:-http://jarvis.orbishosting.com:1972}"
|
||||||
|
JARVIS_HOST=""
|
||||||
INSTALL_DIR="/opt/jarvis-agent"
|
INSTALL_DIR="/opt/jarvis-agent"
|
||||||
CONFIG_DIR="/etc/jarvis-agent"
|
CONFIG_DIR="/etc/jarvis-agent"
|
||||||
STATE_DIR="/var/lib/jarvis-agent"
|
STATE_DIR="/var/lib/jarvis-agent"
|
||||||
REG_KEY="f846a9aaf7ce9a61742c63c87c4186052a71d2a580c65518"
|
REG_KEY="${JARVIS_REG_KEY:-}"
|
||||||
|
if [ -z "$REG_KEY" ] && [ -r /dev/tty ]; then
|
||||||
|
read -rp "Enter JARVIS registration key: " REG_KEY </dev/tty
|
||||||
|
fi
|
||||||
|
if [ -z "$REG_KEY" ]; then
|
||||||
|
echo "ERROR: registration key required (set JARVIS_REG_KEY env var or enter at prompt)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
SERVICE_FILE="/etc/systemd/system/jarvis-agent.service"
|
SERVICE_FILE="/etc/systemd/system/jarvis-agent.service"
|
||||||
|
|
||||||
echo "=== JARVIS Agent Installer v3.0 ==="
|
echo "=== JARVIS Agent Installer v3.0 ==="
|
||||||
@@ -38,7 +52,7 @@ mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$STATE_DIR"
|
|||||||
|
|
||||||
# ── Download agent ─────────────────────────────────────────────────────────────
|
# ── Download agent ─────────────────────────────────────────────────────────────
|
||||||
echo "Downloading agent..."
|
echo "Downloading agent..."
|
||||||
curl -sk -H "Host: $JARVIS_HOST" "$JARVIS_URL/agent/jarvis-agent.py" -o "$INSTALL_DIR/jarvis-agent.py"
|
curl -sk "$JARVIS_URL/agent/jarvis-agent.py" -o "$INSTALL_DIR/jarvis-agent.py"
|
||||||
cp "$INSTALL_DIR/jarvis-agent.py" /usr/local/bin/jarvis-agent.py
|
cp "$INSTALL_DIR/jarvis-agent.py" /usr/local/bin/jarvis-agent.py
|
||||||
chmod +x "$INSTALL_DIR/jarvis-agent.py" /usr/local/bin/jarvis-agent.py
|
chmod +x "$INSTALL_DIR/jarvis-agent.py" /usr/local/bin/jarvis-agent.py
|
||||||
|
|
||||||
@@ -50,7 +64,7 @@ else
|
|||||||
{
|
{
|
||||||
"jarvis_url": "$JARVIS_URL",
|
"jarvis_url": "$JARVIS_URL",
|
||||||
"host_header": "$JARVIS_HOST",
|
"host_header": "$JARVIS_HOST",
|
||||||
"ssl_verify": false,
|
"ssl_verify": true,
|
||||||
"registration_key": "$REG_KEY",
|
"registration_key": "$REG_KEY",
|
||||||
"hostname": "$HOSTNAME_ARG",
|
"hostname": "$HOSTNAME_ARG",
|
||||||
"agent_type": "$AGENT_TYPE",
|
"agent_type": "$AGENT_TYPE",
|
||||||
|
|||||||
+23
-2
@@ -1,20 +1,39 @@
|
|||||||
<?php
|
<?php
|
||||||
ini_set('session.cache_limiter', '');
|
ini_set('session.cache_limiter', '');
|
||||||
header('Cache-Control: no-store, no-cache, must-revalidate, no-transform');
|
header('Cache-Control: no-store, no-cache, must-revalidate, no-transform');
|
||||||
|
require_once __DIR__ . '/../api/config.php';
|
||||||
session_start();
|
session_start();
|
||||||
if (!empty($_SESSION['jarvis_token'])) { header('Location: /'); exit; }
|
if (!empty($_SESSION['jarvis_token'])) { header('Location: /'); exit; }
|
||||||
$error = '';
|
$error = '';
|
||||||
|
// ── Login rate limiting (Redis, per client IP) ────────────────────────────────
|
||||||
|
// Blocks brute force: 10 failed attempts within 15 min -> locked out for 15 min.
|
||||||
|
$clientIp = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
||||||
|
$clientIp = trim(explode(',', $clientIp)[0]);
|
||||||
|
$rl = null;
|
||||||
|
try {
|
||||||
|
$rl = new Redis();
|
||||||
|
$rl->connect('127.0.0.1', 6379, 1.5);
|
||||||
|
} catch (Throwable $e) { $rl = null; } // fail open if Redis is down
|
||||||
|
$rlKey = 'login_fail:' . $clientIp;
|
||||||
|
$RL_MAX = 10; $RL_WINDOW = 900;
|
||||||
|
|
||||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||||
|
$fails = ($rl && $rl->exists($rlKey)) ? (int)$rl->get($rlKey) : 0;
|
||||||
|
if ($fails >= $RL_MAX) {
|
||||||
|
$error = 'TOO MANY ATTEMPTS — LOCKED';
|
||||||
|
} else {
|
||||||
$u = trim($_POST['username'] ?? '');
|
$u = trim($_POST['username'] ?? '');
|
||||||
$p = $_POST['password'] ?? '';
|
$p = $_POST['password'] ?? '';
|
||||||
if ($u && $p) {
|
if ($u && $p) {
|
||||||
$pdo = new PDO('mysql:host=localhost;dbname=jarvis_db;charset=utf8mb4',
|
$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
|
||||||
'jarvis_user', 'J4rv1s_Pr0t0c0l_2026!',
|
DB_USER, DB_PASS,
|
||||||
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||||
$row = $pdo->prepare('SELECT * FROM users WHERE username=? LIMIT 1');
|
$row = $pdo->prepare('SELECT * FROM users WHERE username=? LIMIT 1');
|
||||||
$row->execute([$u]);
|
$row->execute([$u]);
|
||||||
$user = $row->fetch(PDO::FETCH_ASSOC);
|
$user = $row->fetch(PDO::FETCH_ASSOC);
|
||||||
if ($user && password_verify($p, $user['password_hash'])) {
|
if ($user && password_verify($p, $user['password_hash'])) {
|
||||||
|
if ($rl) $rl->del($rlKey);
|
||||||
|
session_regenerate_id(true);
|
||||||
$token = bin2hex(random_bytes(32));
|
$token = bin2hex(random_bytes(32));
|
||||||
$_SESSION['jarvis_token'] = $token;
|
$_SESSION['jarvis_token'] = $token;
|
||||||
$_SESSION['jarvis_user_id'] = $user['id'];
|
$_SESSION['jarvis_user_id'] = $user['id'];
|
||||||
@@ -23,8 +42,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|||||||
header('Location: /');
|
header('Location: /');
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
if ($rl) { $rl->incr($rlKey); $rl->expire($rlKey, $RL_WINDOW); }
|
||||||
$error = 'ACCESS DENIED';
|
$error = 'ACCESS DENIED';
|
||||||
} else { $error = 'ENTER CREDENTIALS'; }
|
} else { $error = 'ENTER CREDENTIALS'; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
?><!DOCTYPE html>
|
?><!DOCTYPE html>
|
||||||
<html lang="en"><head>
|
<html lang="en"><head>
|
||||||
|
|||||||
Reference in New Issue
Block a user