param(
[string]$Token = ""
)
$taskName = "CortexAgent"
$agentRoot = "C:\CortexAgent"
$pythonPath = "$agentRoot\venv\Scripts\python.exe"
$mainPath = "$agentRoot\src\agent_node\main.py"
$logPath = "$agentRoot\agent.log"
$configPath = "$agentRoot\agent_config.yaml"
$ghostRoot = "$env:USERPROFILE\.cortex\agent-node"
$ghostBat = "$ghostRoot\start_agent.bat"
$ghostConfig = "$ghostRoot\agent_config.yaml"
Write-Host "[1/6] Killing all Python processes..."
Get-Process -Name python, python3 -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Seconds 2
Write-Host "[2/6] Disabling ghost startup bat (if present)..."
if (Test-Path $ghostBat) {
Rename-Item -Path $ghostBat -NewName "start_agent.bat.disabled" -Force
Write-Host " Renamed $ghostBat -> start_agent.bat.disabled"
}
Write-Host "[3/6] Syncing ghost config from authoritative config..."
if ((Test-Path $configPath) -and (Test-Path $ghostRoot)) {
Copy-Item -Path $configPath -Destination $ghostConfig -Force
Write-Host " Copied $configPath -> $ghostConfig"
}
Write-Host "[4/6] Updating auth token (if -Token provided)..."
if ($Token -ne "") {
# Update the authoritative config
if (Test-Path $configPath) {
$content = Get-Content $configPath -Raw
$content = $content -replace '(?m)^(\s*(?:auth_token|invite_token)\s*:\s*).*$', "`${1}$Token"
Set-Content -Path $configPath -Value $content -NoNewline
Write-Host " Updated token in $configPath"
}
# Update the ghost config too
if (Test-Path $ghostConfig) {
$content = Get-Content $ghostConfig -Raw
$content = $content -replace '(?m)^(\s*(?:auth_token|invite_token)\s*:\s*).*$', "`${1}$Token"
Set-Content -Path $ghostConfig -Value $content -NoNewline
Write-Host " Updated token in $ghostConfig"
}
}
Write-Host "[5/6] Re-registering Scheduled Task with auto-restart..."
$action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c `"$pythonPath $mainPath >> $logPath 2>&1`""
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-RestartCount 3 `
-RestartInterval (New-TimeSpan -Minutes 1)
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Settings $settings
Start-ScheduledTask -TaskName $taskName
Write-Host "[6/6] Verifying startup (waiting 5s)..."
Start-Sleep -Seconds 5
$running = Get-ScheduledTask -TaskName $taskName | Select-Object -ExpandProperty State
$procs = (Get-Process -Name python -ErrorAction SilentlyContinue).Count
Write-Host ""
Write-Host "=== Result ==="
Write-Host " Task state : $running"
Write-Host " Python PIDs: $procs"
if ($running -eq "Running") {
Write-Host " [OK] CortexAgent is running."
} else {
Write-Host " [WARN] Task is not in Running state. Check $logPath for errors."
}