@evomap/evolver 1.89.20 → 2.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -564
- package/bin/evolver-llm-proxy.js +3 -0
- package/bin/evolver-mcp.js +2 -0
- package/bin/evolver-proxy.js +3 -0
- package/bin/evolver.js +4 -0
- package/index.js +1 -3586
- package/package.json +32 -62
- package/CONTRIBUTING.md +0 -19
- package/LICENSE +0 -641
- package/README.ja-JP.md +0 -521
- package/README.ko-KR.md +0 -520
- package/README.zh-CN.md +0 -531
- package/SKILL.md +0 -365
- package/assets/cover.png +0 -0
- package/assets/gep/genes.seed.json +0 -496
- package/conformance/savings-core/constants.json +0 -30
- package/conformance/savings-core/golden-vectors.json +0 -333
- package/scripts/a2a_export.js +0 -63
- package/scripts/a2a_ingest.js +0 -79
- package/scripts/a2a_promote.js +0 -118
- package/scripts/analyze_by_skill.js +0 -121
- package/scripts/build_binaries.js +0 -479
- package/scripts/check-changelog.js +0 -166
- package/scripts/extract_log.js +0 -85
- package/scripts/generate_history.js +0 -75
- package/scripts/gep_append_event.js +0 -96
- package/scripts/gep_personality_report.js +0 -234
- package/scripts/human_report.js +0 -147
- package/scripts/recall-verify-report.js +0 -234
- package/scripts/recover_loop.js +0 -61
- package/scripts/refresh_stars_badge.js +0 -168
- package/scripts/seed-merchants.js +0 -91
- package/scripts/skill2recipes.js +0 -118
- package/scripts/suggest_version.js +0 -89
- package/scripts/validate-modules.js +0 -38
- package/scripts/validate-suite.js +0 -78
- package/skills/_meta/SKILL.md +0 -41
- package/skills/index.json +0 -14
- package/src/adapters/claudeCode.js +0 -194
- package/src/adapters/codex.js +0 -216
- package/src/adapters/cursor.js +0 -91
- package/src/adapters/hookAdapter.js +0 -469
- package/src/adapters/kiro.js +0 -195
- package/src/adapters/opencode.js +0 -326
- package/src/adapters/scripts/_lockPaths.js +0 -74
- package/src/adapters/scripts/_memoryFiltering.js +0 -35
- package/src/adapters/scripts/_runtimePaths.js +0 -440
- package/src/adapters/scripts/evolver-session-end.js +0 -321
- package/src/adapters/scripts/evolver-session-start.js +0 -587
- package/src/adapters/scripts/evolver-signal-detect.js +0 -98
- package/src/adapters/scripts/evolver-task-recall.js +0 -173
- package/src/atp/atpExecute.js +0 -283
- package/src/atp/atpTaskPickup.js +0 -233
- package/src/atp/autoBuyer.js +0 -382
- package/src/atp/autoDeliver.js +0 -215
- package/src/atp/cli.js +0 -354
- package/src/atp/cliAutobuyPrompt.js +0 -154
- package/src/atp/consumerAgent.js +0 -157
- package/src/atp/defaultHandler.js +0 -69
- package/src/atp/heartbeatSignalsHandler.js +0 -254
- package/src/atp/hubClient.js +0 -317
- package/src/atp/index.js +0 -38
- package/src/atp/merchantAgent.js +0 -118
- package/src/atp/protocol.js +0 -41
- package/src/atp/questionComposer.js +0 -133
- package/src/atp/serviceHelper.js +0 -92
- package/src/canary.js +0 -13
- package/src/config.js +0 -351
- package/src/evolve/guards.js +0 -1
- package/src/evolve/pipeline/collect.js +0 -1
- package/src/evolve/pipeline/dispatch.js +0 -1
- package/src/evolve/pipeline/enrich.js +0 -1
- package/src/evolve/pipeline/hub.js +0 -1
- package/src/evolve/pipeline/select.js +0 -1
- package/src/evolve/pipeline/signals.js +0 -1
- package/src/evolve/utils.js +0 -1
- package/src/evolve.js +0 -1
- package/src/experiment/agentRunner.js +0 -229
- package/src/experiment/cli.js +0 -159
- package/src/experiment/comparison.js +0 -233
- package/src/experiment/metrics.js +0 -75
- package/src/forceUpdate.js +0 -991
- package/src/gep/a2a.js +0 -173
- package/src/gep/a2aProtocol.js +0 -1
- package/src/gep/analyzer.js +0 -35
- package/src/gep/antiAbuseTelemetry.js +0 -1
- package/src/gep/assetCallLog.js +0 -197
- package/src/gep/assetStore.js +0 -723
- package/src/gep/assets.js +0 -36
- package/src/gep/autoDistillConv.js +0 -1
- package/src/gep/autoDistillLlm.js +0 -1
- package/src/gep/bridge.js +0 -138
- package/src/gep/candidateEval.js +0 -1
- package/src/gep/candidates.js +0 -1
- package/src/gep/claimNudge.js +0 -121
- package/src/gep/cliContracts.js +0 -1190
- package/src/gep/contentHash.js +0 -1
- package/src/gep/conversationDistiller.js +0 -1
- package/src/gep/conversationSniffer.js +0 -1
- package/src/gep/crypto.js +0 -1
- package/src/gep/curriculum.js +0 -1
- package/src/gep/deviceId.js +0 -1
- package/src/gep/directoryClient.js +0 -115
- package/src/gep/envFingerprint.js +0 -1
- package/src/gep/epigenetics.js +0 -1
- package/src/gep/execBridge.js +0 -1
- package/src/gep/executionTrace.js +0 -291
- package/src/gep/explore.js +0 -1
- package/src/gep/featureFlags.js +0 -121
- package/src/gep/gitOps.js +0 -265
- package/src/gep/hash.js +0 -1
- package/src/gep/hostErrorClassifier.js +0 -34
- package/src/gep/hubFetch.js +0 -1
- package/src/gep/hubReview.js +0 -1
- package/src/gep/hubSearch.js +0 -1
- package/src/gep/hubVerify.js +0 -1
- package/src/gep/idleScheduler.js +0 -400
- package/src/gep/issueReporter.js +0 -416
- package/src/gep/learningSignals.js +0 -1
- package/src/gep/llmReview.js +0 -92
- package/src/gep/localStateAwareness.js +0 -243
- package/src/gep/mailboxTransport.js +0 -119
- package/src/gep/memoryGraph.js +0 -1
- package/src/gep/memoryGraphAdapter.js +0 -1
- package/src/gep/mutation.js +0 -1
- package/src/gep/narrativeMemory.js +0 -1
- package/src/gep/oauthLogin.js +0 -181
- package/src/gep/openPRRegistry.js +0 -1
- package/src/gep/paths.js +0 -522
- package/src/gep/personality.js +0 -1
- package/src/gep/policyCheck.js +0 -1
- package/src/gep/portable.js +0 -103
- package/src/gep/privacyClient.js +0 -235
- package/src/gep/prompt.js +0 -1
- package/src/gep/questionGenerator.js +0 -518
- package/src/gep/recallInject.js +0 -1
- package/src/gep/recallVerifier.js +0 -1
- package/src/gep/reflection.js +0 -1
- package/src/gep/sanitize.js +0 -264
- package/src/gep/savingsCore.js +0 -1
- package/src/gep/schemas/capsule.js +0 -170
- package/src/gep/schemas/gene.js +0 -154
- package/src/gep/schemas/index.js +0 -8
- package/src/gep/schemas/protocol.js +0 -51
- package/src/gep/schemas/task.js +0 -74
- package/src/gep/selector.js +0 -1
- package/src/gep/selfPR.js +0 -469
- package/src/gep/signals.js +0 -776
- package/src/gep/skill2gep.js +0 -1056
- package/src/gep/skill2gepAudit.js +0 -303
- package/src/gep/skill2recipes.js +0 -511
- package/src/gep/skillDistiller.js +0 -1
- package/src/gep/skillPublisher.js +0 -358
- package/src/gep/solidify.js +0 -1
- package/src/gep/strategy.js +0 -1
- package/src/gep/taskReceiver.js +0 -575
- package/src/gep/tokenSavings.js +0 -1
- package/src/gep/trajectoryExport.js +0 -1
- package/src/gep/validationReport.js +0 -55
- package/src/gep/validator/index.js +0 -411
- package/src/gep/validator/reporter.js +0 -210
- package/src/gep/validator/sandboxExecutor.js +0 -480
- package/src/gep/validator/stakeBootstrap.js +0 -357
- package/src/gep/workspaceKeychain.js +0 -1
- package/src/ops/cleanup.js +0 -80
- package/src/ops/commentary.js +0 -60
- package/src/ops/health_check.js +0 -104
- package/src/ops/index.js +0 -11
- package/src/ops/innovation.js +0 -67
- package/src/ops/lifecycle.js +0 -798
- package/src/ops/self_repair.js +0 -76
- package/src/ops/skills_monitor.js +0 -147
- package/src/ops/trigger.js +0 -33
- package/src/proxy/clientSettings.js +0 -405
- package/src/proxy/envelope.js +0 -59
- package/src/proxy/extensions/dmHandler.js +0 -45
- package/src/proxy/extensions/sessionHandler.js +0 -141
- package/src/proxy/extensions/skillUpdater.js +0 -64
- package/src/proxy/extensions/traceControl.js +0 -1
- package/src/proxy/index.js +0 -1395
- package/src/proxy/inject.js +0 -1
- package/src/proxy/lifecycle/manager.js +0 -1568
- package/src/proxy/mailbox/state.js +0 -207
- package/src/proxy/mailbox/store.js +0 -590
- package/src/proxy/router/cache_passthrough.js +0 -26
- package/src/proxy/router/features.js +0 -84
- package/src/proxy/router/gemini_route.js +0 -154
- package/src/proxy/router/messages_route.js +0 -535
- package/src/proxy/router/model_router.js +0 -113
- package/src/proxy/router/models_route.js +0 -52
- package/src/proxy/router/ollama_route.js +0 -103
- package/src/proxy/router/responses_route.js +0 -170
- package/src/proxy/router/vertex_route.js +0 -110
- package/src/proxy/server/http.js +0 -363
- package/src/proxy/server/routes.js +0 -558
- package/src/proxy/server/settings.js +0 -115
- package/src/proxy/sync/engine.js +0 -179
- package/src/proxy/sync/inbound.js +0 -211
- package/src/proxy/sync/outbound.js +0 -320
- package/src/proxy/task/monitor.js +0 -131
- package/src/proxy/trace/extractor.js +0 -1
- package/src/proxy/trace/usage.js +0 -1
- package/src/webui/client/clientJs/assets.js +0 -111
- package/src/webui/client/clientJs/bootstrap.js +0 -92
- package/src/webui/client/clientJs/common.js +0 -77
- package/src/webui/client/clientJs/i18n.js +0 -366
- package/src/webui/client/clientJs/index.js +0 -35
- package/src/webui/client/clientJs/interactions.js +0 -351
- package/src/webui/client/clientJs/overview.js +0 -152
- package/src/webui/client/clientJs/personality.js +0 -285
- package/src/webui/client/clientJs/pipelines.js +0 -330
- package/src/webui/client/indexHtml.js +0 -221
- package/src/webui/client/static.js +0 -23
- package/src/webui/client/stylesCss.js +0 -639
- package/src/webui/client/vendor/README.md +0 -15
- package/src/webui/client/vendor/echarts.min.js +0 -45
- package/src/webui/index.js +0 -14
- package/src/webui/observer/assets.js +0 -146
- package/src/webui/observer/index.js +0 -37
- package/src/webui/observer/interactions.js +0 -127
- package/src/webui/observer/jsonl.js +0 -75
- package/src/webui/observer/paths.js +0 -46
- package/src/webui/observer/personality.js +0 -43
- package/src/webui/observer/pipelineEvents.js +0 -58
- package/src/webui/observer/redact.js +0 -63
- package/src/webui/observer/runs.js +0 -356
- package/src/webui/observer/safety.js +0 -57
- package/src/webui/observer/skills.js +0 -70
- package/src/webui/observer/status.js +0 -71
- package/src/webui/server/http.js +0 -138
- package/src/webui/server/routes.js +0 -41
package/src/ops/lifecycle.js
DELETED
|
@@ -1,798 +0,0 @@
|
|
|
1
|
-
// Evolver Lifecycle Manager - Evolver Core Module
|
|
2
|
-
// Provides: start, stop, restart, status, log, health check
|
|
3
|
-
// The loop script to spawn is configurable via EVOLVER_LOOP_SCRIPT env var.
|
|
4
|
-
// Cross-platform: works on Linux/macOS (ps) and Windows (WMI via PowerShell).
|
|
5
|
-
|
|
6
|
-
const fs = require('fs');
|
|
7
|
-
const path = require('path');
|
|
8
|
-
const os = require('os');
|
|
9
|
-
const { execFileSync, execSync, spawn } = require('child_process');
|
|
10
|
-
const { readSettings } = require('../proxy/server/settings');
|
|
11
|
-
// 10 MB — prevents RangeError on large child process output (e.g. git log/diff
|
|
12
|
-
// on large repos). See GHSA reports / issue #451.
|
|
13
|
-
const MAX_EXEC_BUFFER = 10 * 1024 * 1024;
|
|
14
|
-
|
|
15
|
-
const { getRepoRoot, getWorkspaceRoot, getEvolverLogPath } = require('../gep/paths');
|
|
16
|
-
|
|
17
|
-
var WORKSPACE_ROOT = getWorkspaceRoot();
|
|
18
|
-
var LOG_FILE = getEvolverLogPath();
|
|
19
|
-
var PID_FILE = path.join(WORKSPACE_ROOT, 'memory', 'evolver_loop.pid');
|
|
20
|
-
var MAX_SILENCE_MS = require('../config').MAX_SILENCE_MS;
|
|
21
|
-
|
|
22
|
-
function getLoopScript() {
|
|
23
|
-
// External supervisors / wrappers can override via EVOLVER_LOOP_SCRIPT.
|
|
24
|
-
if (process.env.EVOLVER_LOOP_SCRIPT) return process.env.EVOLVER_LOOP_SCRIPT;
|
|
25
|
-
return path.join(getRepoRoot(), 'index.js');
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// --- Portable helpers ---
|
|
29
|
-
|
|
30
|
-
function sleepMs(ms) {
|
|
31
|
-
var delay = Math.max(0, Math.floor(Number(ms) || 0));
|
|
32
|
-
if (delay <= 0) return;
|
|
33
|
-
// Atomics.wait blocks without spawning a subprocess; works on all platforms.
|
|
34
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function execText(command) {
|
|
38
|
-
return execSync(command, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: MAX_EXEC_BUFFER });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function execFileText(file, args) {
|
|
42
|
-
return execFileSync(file, args, {
|
|
43
|
-
encoding: 'utf8',
|
|
44
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
45
|
-
maxBuffer: MAX_EXEC_BUFFER,
|
|
46
|
-
windowsHide: true
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// --- Test-only process-table injection -------------------------------------
|
|
51
|
-
// Lets the lifecycle proxy-health tests run hermetically on a host that already
|
|
52
|
-
// has REAL `node index.js --loop` processes (CI runners, or a live agent box).
|
|
53
|
-
// Without it, getRunningPids()/checkHealth()/stopOwnedLoops() read the actual
|
|
54
|
-
// process table via ps/proc and would (a) fail their "not_running" assertions
|
|
55
|
-
// against unrelated real loops and (b) risk SIGTERM-ing real production loops.
|
|
56
|
-
// Production never installs a table; listProcesses()/getPidCwd()/isPidRunning()
|
|
57
|
-
// consult it only when one has been set. Entries are { pid, args, cwd }.
|
|
58
|
-
var _processTableForTest = null;
|
|
59
|
-
function _setProcessTableForTest(table) {
|
|
60
|
-
_processTableForTest = Array.isArray(table) ? table.map(function (p) {
|
|
61
|
-
return {
|
|
62
|
-
pid: parseInt(p.pid, 10),
|
|
63
|
-
args: String(p.args || ''),
|
|
64
|
-
cwd: p.cwd != null ? String(p.cwd) : null,
|
|
65
|
-
};
|
|
66
|
-
}) : null;
|
|
67
|
-
}
|
|
68
|
-
function _resetProcessTableForTest() { _processTableForTest = null; }
|
|
69
|
-
|
|
70
|
-
function listProcesses() {
|
|
71
|
-
if (_processTableForTest) {
|
|
72
|
-
return _processTableForTest.map(function (p) { return { pid: p.pid, args: p.args }; });
|
|
73
|
-
}
|
|
74
|
-
if (process.platform === 'win32') {
|
|
75
|
-
var out = execFileText('powershell', [
|
|
76
|
-
'-NoProfile',
|
|
77
|
-
'-Command',
|
|
78
|
-
'Get-CimInstance Win32_Process | ForEach-Object { $cmd = if ($_.CommandLine) { $_.CommandLine } else { \'\'}; Write-Output (\'{0}\t{1}\' -f $_.ProcessId, $cmd) }'
|
|
79
|
-
]);
|
|
80
|
-
var procs = [];
|
|
81
|
-
for (var line of out.split(/\r?\n/)) {
|
|
82
|
-
if (!line || !line.trim()) continue;
|
|
83
|
-
var tabIndex = line.indexOf('\t');
|
|
84
|
-
var pidText = tabIndex >= 0 ? line.slice(0, tabIndex).trim() : line.trim();
|
|
85
|
-
var cmdText = tabIndex >= 0 ? line.slice(tabIndex + 1).trim() : '';
|
|
86
|
-
var pid = parseInt(pidText, 10);
|
|
87
|
-
if (!isNaN(pid)) procs.push({ pid: pid, args: cmdText });
|
|
88
|
-
}
|
|
89
|
-
return procs;
|
|
90
|
-
}
|
|
91
|
-
var psOut = execText('ps -e -o pid=,args=');
|
|
92
|
-
var unixProcs = [];
|
|
93
|
-
for (var psLine of psOut.split('\n')) {
|
|
94
|
-
var trimmed = psLine.trim();
|
|
95
|
-
if (!trimmed) continue;
|
|
96
|
-
var parts = trimmed.split(/\s+/);
|
|
97
|
-
var pidUnix = parseInt(parts[0], 10);
|
|
98
|
-
if (isNaN(pidUnix)) continue;
|
|
99
|
-
unixProcs.push({ pid: pidUnix, args: parts.slice(1).join(' ') });
|
|
100
|
-
}
|
|
101
|
-
return unixProcs;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// --- Process Discovery ---
|
|
105
|
-
|
|
106
|
-
function getRunningPids() {
|
|
107
|
-
try {
|
|
108
|
-
var pids = [];
|
|
109
|
-
for (var proc of listProcesses()) {
|
|
110
|
-
var pid = proc.pid;
|
|
111
|
-
var cmd = (proc.args || '').trim();
|
|
112
|
-
if (pid === process.pid) continue;
|
|
113
|
-
var cmdLower = cmd.toLowerCase();
|
|
114
|
-
// Match any `node ... index.js ... --loop` invocation.
|
|
115
|
-
// Wrapper path prefix filters were removed so launchd/plist or direct
|
|
116
|
-
// node invocations are also discovered (fixes #379, #403).
|
|
117
|
-
if (cmdLower.includes('node') && cmdLower.includes('index.js') && cmdLower.includes('--loop')) {
|
|
118
|
-
pids.push(pid);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
return [...new Set(pids)].filter(isPidRunning);
|
|
122
|
-
} catch (e) {
|
|
123
|
-
return [];
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function isPidRunning(pid) {
|
|
128
|
-
if (_processTableForTest) {
|
|
129
|
-
var spRun = parseInt(pid, 10);
|
|
130
|
-
return _processTableForTest.some(function (p) { return p.pid === spRun; });
|
|
131
|
-
}
|
|
132
|
-
try { process.kill(pid, 0); return true; } catch (e) { return false; }
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function boolEnv(value) {
|
|
136
|
-
var raw = String(value || '').trim().toLowerCase();
|
|
137
|
-
return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on';
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function isLoopbackProxyUrl(value) {
|
|
141
|
-
var raw = String(value || '').trim().replace(/\/+$/, '');
|
|
142
|
-
if (!raw) return false;
|
|
143
|
-
try {
|
|
144
|
-
var parsed = new URL(raw);
|
|
145
|
-
if (parsed.protocol !== 'http:') return false;
|
|
146
|
-
var host = parsed.hostname.toLowerCase();
|
|
147
|
-
return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]';
|
|
148
|
-
} catch (_) {
|
|
149
|
-
return false;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function readJsonFile(file) {
|
|
154
|
-
try {
|
|
155
|
-
if (!file || !fs.existsSync(file)) return null;
|
|
156
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
157
|
-
} catch (_) {
|
|
158
|
-
return null;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function getClaudeSettingsFile(env) {
|
|
163
|
-
var e = env || process.env;
|
|
164
|
-
var explicit = String(e.CLAUDE_SETTINGS_FILE || e.EVOMAP_CLAUDE_SETTINGS_FILE || '').trim();
|
|
165
|
-
if (explicit) return explicit;
|
|
166
|
-
var home = e.HOME || os.homedir();
|
|
167
|
-
return home ? path.join(home, '.claude', 'settings.json') : null;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function getCodexConfigFile(env) {
|
|
171
|
-
var e = env || process.env;
|
|
172
|
-
var explicit = String(e.CODEX_CONFIG_FILE || e.EVOMAP_CODEX_CONFIG_FILE || '').trim();
|
|
173
|
-
if (explicit) return explicit;
|
|
174
|
-
var home = e.HOME || os.homedir();
|
|
175
|
-
return home ? path.join(home, '.codex', 'config.toml') : null;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
function stripTomlComment(line) {
|
|
179
|
-
var out = '';
|
|
180
|
-
var quote = null;
|
|
181
|
-
var escaped = false;
|
|
182
|
-
for (var i = 0; i < String(line || '').length; i++) {
|
|
183
|
-
var ch = line[i];
|
|
184
|
-
if (escaped) {
|
|
185
|
-
out += ch;
|
|
186
|
-
escaped = false;
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
if (ch === '\\' && quote === '"') {
|
|
190
|
-
out += ch;
|
|
191
|
-
escaped = true;
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
if ((ch === '"' || ch === "'") && !quote) {
|
|
195
|
-
quote = ch;
|
|
196
|
-
out += ch;
|
|
197
|
-
continue;
|
|
198
|
-
}
|
|
199
|
-
if (ch === quote) {
|
|
200
|
-
quote = null;
|
|
201
|
-
out += ch;
|
|
202
|
-
continue;
|
|
203
|
-
}
|
|
204
|
-
if (ch === '#' && !quote) break;
|
|
205
|
-
out += ch;
|
|
206
|
-
}
|
|
207
|
-
return out.trim();
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
function readTomlStringValue(value) {
|
|
211
|
-
var raw = stripTomlComment(value);
|
|
212
|
-
var match = raw.match(/^(['"])([\s\S]*)\1$/);
|
|
213
|
-
if (match) return match[2];
|
|
214
|
-
return raw.trim();
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
function codexConfigExpectsProxy(env) {
|
|
218
|
-
var file = getCodexConfigFile(env);
|
|
219
|
-
if (!file || !fs.existsSync(file)) return false;
|
|
220
|
-
var selectedProvider = null;
|
|
221
|
-
var section = '';
|
|
222
|
-
var providerUrls = {};
|
|
223
|
-
try {
|
|
224
|
-
var content = fs.readFileSync(file, 'utf8');
|
|
225
|
-
for (var line of content.split(/\r?\n/)) {
|
|
226
|
-
var clean = stripTomlComment(line);
|
|
227
|
-
if (!clean) continue;
|
|
228
|
-
var sectionMatch = clean.match(/^\[([^\]]+)\]$/);
|
|
229
|
-
if (sectionMatch) {
|
|
230
|
-
section = sectionMatch[1].trim();
|
|
231
|
-
continue;
|
|
232
|
-
}
|
|
233
|
-
var kv = clean.match(/^([A-Za-z0-9_.-]+)\s*=\s*([\s\S]+)$/);
|
|
234
|
-
if (!kv) continue;
|
|
235
|
-
var key = kv[1].trim();
|
|
236
|
-
var val = readTomlStringValue(kv[2]);
|
|
237
|
-
if (!section && key === 'model_provider') {
|
|
238
|
-
selectedProvider = val;
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
var providerMatch = section.match(/^model_providers\.([A-Za-z0-9_.-]+)$/);
|
|
242
|
-
if (providerMatch && key === 'base_url') {
|
|
243
|
-
providerUrls[providerMatch[1]] = val;
|
|
244
|
-
continue;
|
|
245
|
-
}
|
|
246
|
-
if (!section && key === 'base_url' && isLoopbackProxyUrl(val)) {
|
|
247
|
-
return true;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
} catch (_) {
|
|
251
|
-
return false;
|
|
252
|
-
}
|
|
253
|
-
if (selectedProvider && isLoopbackProxyUrl(providerUrls[selectedProvider])) return true;
|
|
254
|
-
return Object.keys(providerUrls).some(function(name) {
|
|
255
|
-
return /(?:evomap|proxy)/i.test(name) && isLoopbackProxyUrl(providerUrls[name]);
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function clientSettingsExpectProxy(env) {
|
|
260
|
-
var settings = readJsonFile(getClaudeSettingsFile(env));
|
|
261
|
-
var cfg = settings && settings.env;
|
|
262
|
-
if (!cfg || typeof cfg !== 'object') return false;
|
|
263
|
-
if (isLoopbackProxyUrl(cfg.EVOMAP_PROXY_URL)) return true;
|
|
264
|
-
if (String(cfg.EVOMAP_PROXY_AUTO_INJECTED || '') === '1' && isLoopbackProxyUrl(cfg.ANTHROPIC_BASE_URL)) return true;
|
|
265
|
-
return !!(settings._evomap_proxy_client_env && settings._evomap_proxy_client_env.managed_by === 'evomap-proxy'
|
|
266
|
-
&& isLoopbackProxyUrl(cfg.ANTHROPIC_BASE_URL));
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
function expectsProxy(env) {
|
|
270
|
-
var e = env || process.env;
|
|
271
|
-
if (boolEnv(e.EVOMAP_PROXY)) return true;
|
|
272
|
-
if (String(e.A2A_TRANSPORT || '').trim().toLowerCase() === 'mailbox') return true;
|
|
273
|
-
if (isLoopbackProxyUrl(e.EVOMAP_PROXY_URL) || isLoopbackProxyUrl(e.ANTHROPIC_BASE_URL)) return true;
|
|
274
|
-
if (codexConfigExpectsProxy(e)) return true;
|
|
275
|
-
return clientSettingsExpectProxy(e);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
function prepareStartEnv(env) {
|
|
279
|
-
var next = Object.assign({}, env || process.env);
|
|
280
|
-
if (expectsProxy(next)) {
|
|
281
|
-
next.EVOMAP_PROXY = '1';
|
|
282
|
-
}
|
|
283
|
-
return next;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
function isProxyUrlReachable(url, token) {
|
|
287
|
-
if (!url || !token) return false;
|
|
288
|
-
try {
|
|
289
|
-
execFileSync(process.execPath, ['-e', `
|
|
290
|
-
const fs = require('fs');
|
|
291
|
-
const http = require('http');
|
|
292
|
-
const url = process.argv[1];
|
|
293
|
-
const token = fs.readFileSync(0, 'utf8').trim();
|
|
294
|
-
if (!token) process.exit(1);
|
|
295
|
-
const req = http.get(url.replace(/\\/+$/, '') + '/proxy/status', {
|
|
296
|
-
headers: { Authorization: 'Bearer ' + token },
|
|
297
|
-
}, (res) => {
|
|
298
|
-
let body = '';
|
|
299
|
-
res.setEncoding('utf8');
|
|
300
|
-
res.on('data', (chunk) => {
|
|
301
|
-
body += chunk;
|
|
302
|
-
if (body.length > 1024 * 1024) req.destroy(new Error('response too large'));
|
|
303
|
-
});
|
|
304
|
-
res.on('end', () => {
|
|
305
|
-
if (res.statusCode < 200 || res.statusCode >= 300) process.exit(1);
|
|
306
|
-
let parsed;
|
|
307
|
-
try { parsed = JSON.parse(body); } catch (_) { process.exit(1); }
|
|
308
|
-
if (parsed && parsed.status === 'running' && (parsed.proxy_protocol_version || parsed.schema_version || parsed.node_id != null)) {
|
|
309
|
-
process.exit(0);
|
|
310
|
-
}
|
|
311
|
-
process.exit(1);
|
|
312
|
-
});
|
|
313
|
-
});
|
|
314
|
-
req.setTimeout(800, () => { req.destroy(new Error('timeout')); });
|
|
315
|
-
req.on('error', () => process.exit(1));
|
|
316
|
-
`, url], { input: String(token), stdio: ['pipe', 'ignore', 'ignore'], timeout: 1500, windowsHide: true });
|
|
317
|
-
return true;
|
|
318
|
-
} catch (_) {
|
|
319
|
-
return false;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
function checkProxyHealth(env) {
|
|
324
|
-
if (!expectsProxy(env)) return { healthy: true, expected: false };
|
|
325
|
-
var proxy = readSettings().proxy || {};
|
|
326
|
-
if (!proxy.url) {
|
|
327
|
-
return { healthy: false, expected: true, reason: 'proxy_not_configured' };
|
|
328
|
-
}
|
|
329
|
-
if (proxy.pid && !isPidRunning(proxy.pid)) {
|
|
330
|
-
return { healthy: false, expected: true, reason: 'proxy_pid_stale', proxyPid: proxy.pid, proxyUrl: proxy.url };
|
|
331
|
-
}
|
|
332
|
-
if (!proxy.token) {
|
|
333
|
-
return { healthy: false, expected: true, reason: 'proxy_token_missing', proxyPid: proxy.pid, proxyUrl: proxy.url };
|
|
334
|
-
}
|
|
335
|
-
if (!isProxyUrlReachable(proxy.url, proxy.token)) {
|
|
336
|
-
return { healthy: false, expected: true, reason: 'proxy_unreachable', proxyPid: proxy.pid, proxyUrl: proxy.url };
|
|
337
|
-
}
|
|
338
|
-
return { healthy: true, expected: true, proxyPid: proxy.pid, proxyUrl: proxy.url };
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
function shouldRestartForProxy(pids, env) {
|
|
342
|
-
if (!pids || pids.length === 0) return false;
|
|
343
|
-
var proxyHealth = checkProxyHealth(env);
|
|
344
|
-
return proxyHealth.expected === true && proxyHealth.healthy === false;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
function getCmdLine(pid) {
|
|
348
|
-
try {
|
|
349
|
-
const safePid = parseInt(pid, 10);
|
|
350
|
-
if (isNaN(safePid)) return null;
|
|
351
|
-
var proc = listProcesses().find(function(p) { return p.pid === safePid; });
|
|
352
|
-
return proc ? (proc.args || '').trim() : null;
|
|
353
|
-
} catch (e) {
|
|
354
|
-
return null;
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
function getPidCwd(pid) {
|
|
359
|
-
const safePid = parseInt(pid, 10);
|
|
360
|
-
if (!Number.isFinite(safePid) || safePid <= 0) return null;
|
|
361
|
-
if (_processTableForTest) {
|
|
362
|
-
var cwdEntry = _processTableForTest.find(function (p) { return p.pid === safePid; });
|
|
363
|
-
return cwdEntry ? cwdEntry.cwd : null;
|
|
364
|
-
}
|
|
365
|
-
if (process.platform === 'win32') return null;
|
|
366
|
-
if (process.platform === 'linux') {
|
|
367
|
-
try { return fs.realpathSync('/proc/' + safePid + '/cwd'); } catch (_) {}
|
|
368
|
-
}
|
|
369
|
-
try {
|
|
370
|
-
var lsofOut = execFileSync('lsof', ['-a', '-p', String(safePid), '-d', 'cwd', '-Fn'], {
|
|
371
|
-
encoding: 'utf8',
|
|
372
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
373
|
-
maxBuffer: MAX_EXEC_BUFFER,
|
|
374
|
-
timeout: 1000,
|
|
375
|
-
windowsHide: true
|
|
376
|
-
});
|
|
377
|
-
for (var line of lsofOut.split(/\r?\n/)) {
|
|
378
|
-
if (line && line[0] === 'n') {
|
|
379
|
-
try { return fs.realpathSync(line.slice(1)); } catch (_) { return path.resolve(line.slice(1)); }
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
} catch (_) {}
|
|
383
|
-
try {
|
|
384
|
-
var pwdxOut = execFileText('pwdx', [String(safePid)]).trim();
|
|
385
|
-
var match = pwdxOut.match(/^\d+:\s*(.+)$/);
|
|
386
|
-
if (match) {
|
|
387
|
-
try { return fs.realpathSync(match[1]); } catch (_) { return path.resolve(match[1]); }
|
|
388
|
-
}
|
|
389
|
-
} catch (_) {}
|
|
390
|
-
return null;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
function commandIncludesPath(cmd, targetPath) {
|
|
394
|
-
if (!cmd || !targetPath) return false;
|
|
395
|
-
var cmdNorm = String(cmd).replace(/\\/g, '/');
|
|
396
|
-
var candidates = [targetPath];
|
|
397
|
-
try { candidates.push(fs.realpathSync(targetPath)); } catch (_) {}
|
|
398
|
-
return candidates.some(function(candidate) {
|
|
399
|
-
var normalized = path.resolve(candidate).replace(/\\/g, '/');
|
|
400
|
-
return normalized && cmdNorm.includes(normalized);
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
function splitCommandLine(cmd) {
|
|
405
|
-
var tokens = [];
|
|
406
|
-
var current = '';
|
|
407
|
-
var quote = null;
|
|
408
|
-
var escaped = false;
|
|
409
|
-
var raw = String(cmd || '');
|
|
410
|
-
for (var i = 0; i < raw.length; i++) {
|
|
411
|
-
var ch = raw[i];
|
|
412
|
-
if (escaped) {
|
|
413
|
-
current += ch;
|
|
414
|
-
escaped = false;
|
|
415
|
-
continue;
|
|
416
|
-
}
|
|
417
|
-
if (ch === '\\') {
|
|
418
|
-
escaped = true;
|
|
419
|
-
continue;
|
|
420
|
-
}
|
|
421
|
-
if ((ch === '"' || ch === "'") && !quote) {
|
|
422
|
-
quote = ch;
|
|
423
|
-
continue;
|
|
424
|
-
}
|
|
425
|
-
if (ch === quote) {
|
|
426
|
-
quote = null;
|
|
427
|
-
continue;
|
|
428
|
-
}
|
|
429
|
-
if (/\s/.test(ch) && !quote) {
|
|
430
|
-
if (current) {
|
|
431
|
-
tokens.push(current);
|
|
432
|
-
current = '';
|
|
433
|
-
}
|
|
434
|
-
continue;
|
|
435
|
-
}
|
|
436
|
-
current += ch;
|
|
437
|
-
}
|
|
438
|
-
if (escaped) current += '\\';
|
|
439
|
-
if (current) tokens.push(current);
|
|
440
|
-
return tokens;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
function looksLikeNodeToken(token) {
|
|
444
|
-
var base = path.basename(String(token || '').replace(/\\/g, '/')).toLowerCase();
|
|
445
|
-
return base === 'node' || base === 'node.exe';
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function nodeOptionTakesValue(option) {
|
|
449
|
-
var name = String(option || '').split('=')[0];
|
|
450
|
-
return name === '-r' || name === '--require' ||
|
|
451
|
-
name === '--import' ||
|
|
452
|
-
name === '--loader' || name === '--experimental-loader' ||
|
|
453
|
-
name === '--icu-data-dir' ||
|
|
454
|
-
name === '--openssl-config' ||
|
|
455
|
-
name === '--redirect-warnings';
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
function nodeOptionIsEvalMode(option) {
|
|
459
|
-
var name = String(option || '').split('=')[0];
|
|
460
|
-
return name === '-e' || name === '--eval' ||
|
|
461
|
-
name === '-p' || name === '--print' ||
|
|
462
|
-
name === '-c' || name === '--check';
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
function getNodeScriptToken(tokens) {
|
|
466
|
-
for (var i = 0; i < tokens.length; i++) {
|
|
467
|
-
if (!looksLikeNodeToken(tokens[i])) continue;
|
|
468
|
-
for (var j = i + 1; j < tokens.length; j++) {
|
|
469
|
-
var token = tokens[j];
|
|
470
|
-
if (!token) continue;
|
|
471
|
-
if (token === '--') return tokens[j + 1] || null;
|
|
472
|
-
if (token[0] === '-') {
|
|
473
|
-
if (nodeOptionIsEvalMode(token)) return null;
|
|
474
|
-
if (nodeOptionTakesValue(token) && !token.includes('=')) j++;
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
return token;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return null;
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
function sameRealPath(left, right) {
|
|
484
|
-
try {
|
|
485
|
-
return fs.realpathSync(left) === fs.realpathSync(right);
|
|
486
|
-
} catch (_) {
|
|
487
|
-
return false;
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
function commandUsesCurrentRepoRelativeIndex(cmd, cwd) {
|
|
492
|
-
if (!cwd) return false;
|
|
493
|
-
var script = getNodeScriptToken(splitCommandLine(cmd));
|
|
494
|
-
if (!script || path.isAbsolute(script)) return false;
|
|
495
|
-
if (path.basename(script.replace(/\\/g, '/')).toLowerCase() !== 'index.js') return false;
|
|
496
|
-
return sameRealPath(path.resolve(cwd, script), path.join(getRepoRoot(), 'index.js'));
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
function isCurrentLoopCommand(cmd, cwd) {
|
|
500
|
-
var raw = String(cmd || '');
|
|
501
|
-
var lower = raw.toLowerCase();
|
|
502
|
-
if (!lower.includes('node') || !lower.includes('--loop')) return false;
|
|
503
|
-
if (commandIncludesPath(raw, getLoopScript())) return true;
|
|
504
|
-
if (commandIncludesPath(raw, path.join(getRepoRoot(), 'index.js'))) return true;
|
|
505
|
-
return commandUsesCurrentRepoRelativeIndex(raw, cwd);
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
function readPidFile(file) {
|
|
509
|
-
try {
|
|
510
|
-
if (!file || !fs.existsSync(file)) return null;
|
|
511
|
-
var raw = fs.readFileSync(file, 'utf8').trim();
|
|
512
|
-
var pid = parseInt(raw, 10);
|
|
513
|
-
return Number.isFinite(pid) && pid > 0 ? pid : null;
|
|
514
|
-
} catch (_) {
|
|
515
|
-
return null;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
function getOwnedLoopPids(discoveredPids) {
|
|
520
|
-
var candidates = new Set();
|
|
521
|
-
function addPid(pid) {
|
|
522
|
-
var parsed = parseInt(pid, 10);
|
|
523
|
-
if (Number.isFinite(parsed) && parsed > 0) candidates.add(parsed);
|
|
524
|
-
}
|
|
525
|
-
(discoveredPids || []).forEach(addPid);
|
|
526
|
-
addPid(readPidFile(PID_FILE));
|
|
527
|
-
try {
|
|
528
|
-
var proxyPid = (readSettings().proxy || {}).pid;
|
|
529
|
-
addPid(proxyPid);
|
|
530
|
-
} catch (_) {}
|
|
531
|
-
return Array.from(candidates).filter(function(pid) {
|
|
532
|
-
if (!isPidRunning(pid)) return false;
|
|
533
|
-
var cmd = getCmdLine(pid);
|
|
534
|
-
if (isCurrentLoopCommand(cmd)) return true;
|
|
535
|
-
return isCurrentLoopCommand(cmd, getPidCwd(pid));
|
|
536
|
-
});
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
function stopPids(pids, options) {
|
|
540
|
-
var targets = Array.from(new Set(pids || [])).map(function(pid) {
|
|
541
|
-
return parseInt(pid, 10);
|
|
542
|
-
}).filter(Number.isFinite);
|
|
543
|
-
for (var i = 0; i < targets.length; i++) {
|
|
544
|
-
console.log('[Lifecycle] Stopping PID ' + targets[i] + '...');
|
|
545
|
-
try { process.kill(targets[i], 'SIGTERM'); } catch (e) {}
|
|
546
|
-
}
|
|
547
|
-
var attempts = 0;
|
|
548
|
-
while (targets.some(isPidRunning) && attempts < 10) {
|
|
549
|
-
sleepMs(500);
|
|
550
|
-
attempts++;
|
|
551
|
-
}
|
|
552
|
-
var remaining = targets.filter(isPidRunning);
|
|
553
|
-
for (var j = 0; j < remaining.length; j++) {
|
|
554
|
-
console.log('[Lifecycle] Force-killing PID ' + remaining[j]);
|
|
555
|
-
if (process.platform === 'win32') {
|
|
556
|
-
try { execFileSync('taskkill', ['/F', '/PID', String(remaining[j])], { stdio: 'ignore', windowsHide: true }); } catch (e) {}
|
|
557
|
-
} else {
|
|
558
|
-
try { process.kill(remaining[j], 'SIGKILL'); } catch (e) {}
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
if (options && options.unlinkPidFile) {
|
|
562
|
-
try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
|
|
563
|
-
}
|
|
564
|
-
if (options && options.unlinkLock) {
|
|
565
|
-
var evolverLock = path.join(getRepoRoot(), 'evolver.pid');
|
|
566
|
-
try { if (fs.existsSync(evolverLock)) fs.unlinkSync(evolverLock); } catch (_) {}
|
|
567
|
-
}
|
|
568
|
-
return { status: 'stopped', killed: targets };
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
// --- Lifecycle ---
|
|
572
|
-
|
|
573
|
-
function start(options) {
|
|
574
|
-
var delayMs = (options && options.delayMs) || 0;
|
|
575
|
-
var pids = getRunningPids();
|
|
576
|
-
var ownedPids = getOwnedLoopPids(pids);
|
|
577
|
-
if (ownedPids.length > 0) {
|
|
578
|
-
if (shouldRestartForProxy(ownedPids, process.env)) {
|
|
579
|
-
console.log('[Lifecycle] Loop running but proxy is unhealthy; restarting.');
|
|
580
|
-
stopPids(ownedPids, { unlinkPidFile: true, unlinkLock: true });
|
|
581
|
-
ownedPids = getOwnedLoopPids(getRunningPids());
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
if (ownedPids.length > 0) {
|
|
585
|
-
console.log('[Lifecycle] Already running (PIDs: ' + ownedPids.join(', ') + ').');
|
|
586
|
-
return { status: 'already_running', pids: ownedPids };
|
|
587
|
-
}
|
|
588
|
-
if (delayMs > 0) {
|
|
589
|
-
sleepMs(delayMs);
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
var script = getLoopScript();
|
|
593
|
-
console.log('[Lifecycle] Starting: node ' + path.relative(WORKSPACE_ROOT, script) + ' --loop');
|
|
594
|
-
|
|
595
|
-
var out = fs.openSync(LOG_FILE, 'a');
|
|
596
|
-
var err = fs.openSync(LOG_FILE, 'a');
|
|
597
|
-
|
|
598
|
-
var env = prepareStartEnv(process.env);
|
|
599
|
-
// .npm-global/bin is a Unix-only convention; skip the PATH injection on Windows
|
|
600
|
-
// to avoid polluting the environment with a path that does not exist.
|
|
601
|
-
if (process.platform !== 'win32') {
|
|
602
|
-
var npmGlobal = path.join(os.homedir(), '.npm-global', 'bin');
|
|
603
|
-
if (env.PATH && !env.PATH.includes(npmGlobal)) {
|
|
604
|
-
env.PATH = npmGlobal + ':' + env.PATH;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
var child = spawn(process.execPath, [script, '--loop'], {
|
|
609
|
-
detached: true, stdio: ['ignore', out, err], cwd: WORKSPACE_ROOT, env: env, windowsHide: true
|
|
610
|
-
});
|
|
611
|
-
child.unref();
|
|
612
|
-
fs.writeFileSync(PID_FILE, String(child.pid));
|
|
613
|
-
console.log('[Lifecycle] Started PID ' + child.pid);
|
|
614
|
-
return { status: 'started', pid: child.pid };
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
function stop() {
|
|
618
|
-
var pids = getRunningPids();
|
|
619
|
-
if (pids.length === 0) {
|
|
620
|
-
console.log('[Lifecycle] No running evolver loops found.');
|
|
621
|
-
// Wrap in try/catch: on Windows a concurrently-open file raises EBUSY
|
|
622
|
-
// instead of succeeding silently as on Unix.
|
|
623
|
-
try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
|
|
624
|
-
return { status: 'not_running' };
|
|
625
|
-
}
|
|
626
|
-
// Preserve the existing CLI stop semantics: stop every discoverable loop.
|
|
627
|
-
stopPids(pids, { unlinkPidFile: true, unlinkLock: true });
|
|
628
|
-
console.log('[Lifecycle] All stopped.');
|
|
629
|
-
return { status: 'stopped', killed: pids };
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
function stopOwnedLoops() {
|
|
633
|
-
var ownedPids = getOwnedLoopPids(getRunningPids());
|
|
634
|
-
if (ownedPids.length === 0) {
|
|
635
|
-
try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
|
|
636
|
-
return { status: 'not_running' };
|
|
637
|
-
}
|
|
638
|
-
return stopPids(ownedPids, { unlinkPidFile: true, unlinkLock: true });
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
function restart(options) {
|
|
642
|
-
stopOwnedLoops();
|
|
643
|
-
return start(Object.assign({ delayMs: 2000 }, options || {}));
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
function status() {
|
|
647
|
-
var pids = getRunningPids();
|
|
648
|
-
if (pids.length > 0) {
|
|
649
|
-
return { running: true, pids: pids.map(function(p) { return { pid: p, cmd: getCmdLine(p) }; }), log: path.relative(WORKSPACE_ROOT, LOG_FILE) };
|
|
650
|
-
}
|
|
651
|
-
return { running: false };
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
function tailLog(lines) {
|
|
655
|
-
if (!fs.existsSync(LOG_FILE)) return { error: 'No log file' };
|
|
656
|
-
try {
|
|
657
|
-
const n = parseInt(lines, 10) || 20;
|
|
658
|
-
const fd = fs.openSync(LOG_FILE, 'r');
|
|
659
|
-
var content = '';
|
|
660
|
-
try {
|
|
661
|
-
const stat = fs.fstatSync(fd);
|
|
662
|
-
if (stat.size > 0) {
|
|
663
|
-
const chunkSize = 64 * 1024;
|
|
664
|
-
let position = stat.size;
|
|
665
|
-
let collected = '';
|
|
666
|
-
let lineCount = 0;
|
|
667
|
-
while (position > 0 && lineCount <= n) {
|
|
668
|
-
const readSize = Math.min(chunkSize, position);
|
|
669
|
-
position -= readSize;
|
|
670
|
-
const buf = Buffer.alloc(readSize);
|
|
671
|
-
fs.readSync(fd, buf, 0, readSize, position);
|
|
672
|
-
collected = buf.toString('utf8') + collected;
|
|
673
|
-
lineCount = collected.split('\n').length - 1;
|
|
674
|
-
}
|
|
675
|
-
const rows = collected.split('\n');
|
|
676
|
-
if (rows.length > 0 && rows[rows.length - 1] === '') rows.pop();
|
|
677
|
-
content = rows.slice(-n).join('\n');
|
|
678
|
-
}
|
|
679
|
-
} finally {
|
|
680
|
-
fs.closeSync(fd);
|
|
681
|
-
}
|
|
682
|
-
return {
|
|
683
|
-
file: path.relative(WORKSPACE_ROOT, LOG_FILE),
|
|
684
|
-
content: content
|
|
685
|
-
};
|
|
686
|
-
} catch (e) {
|
|
687
|
-
return { error: e.message };
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
function checkHealth() {
|
|
692
|
-
var pids = getOwnedLoopPids(getRunningPids());
|
|
693
|
-
if (pids.length === 0) return { healthy: false, reason: 'not_running' };
|
|
694
|
-
var proxyHealth = checkProxyHealth(process.env);
|
|
695
|
-
if (!proxyHealth.healthy) {
|
|
696
|
-
return Object.assign({ healthy: false }, proxyHealth);
|
|
697
|
-
}
|
|
698
|
-
if (fs.existsSync(LOG_FILE)) {
|
|
699
|
-
var silenceMs = Date.now() - fs.statSync(LOG_FILE).mtimeMs;
|
|
700
|
-
if (silenceMs > MAX_SILENCE_MS) {
|
|
701
|
-
return { healthy: false, reason: 'stagnation', silenceMinutes: Math.round(silenceMs / 60000) };
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
return { healthy: true, pids: pids };
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
// --- CLI ---
|
|
708
|
-
if (require.main === module) {
|
|
709
|
-
var action = process.argv[2];
|
|
710
|
-
switch (action) {
|
|
711
|
-
case 'start': console.log(JSON.stringify(start())); break;
|
|
712
|
-
case 'stop': console.log(JSON.stringify(stop())); break;
|
|
713
|
-
case 'restart': console.log(JSON.stringify(restart())); break;
|
|
714
|
-
case 'status': console.log(JSON.stringify(status(), null, 2)); break;
|
|
715
|
-
case 'log': var r = tailLog(); console.log(r.content || r.error); break;
|
|
716
|
-
case 'check':
|
|
717
|
-
var health = checkHealth();
|
|
718
|
-
console.log(JSON.stringify(health, null, 2));
|
|
719
|
-
if (!health.healthy) { console.log('[Lifecycle] Restarting...'); restart(); }
|
|
720
|
-
break;
|
|
721
|
-
// watch: continuous self-healing supervisor loop. Checks every
|
|
722
|
-
// EVOLVER_WATCH_INTERVAL_S seconds (default 120) and restarts the
|
|
723
|
-
// daemon if checkHealth() reports unhealthy (not running or log
|
|
724
|
-
// stagnation beyond MAX_SILENCE_MS). Designed to be run as a
|
|
725
|
-
// lightweight companion process or cron job so the daemon self-heals
|
|
726
|
-
// without an external supervisor like pm2/launchd.
|
|
727
|
-
//
|
|
728
|
-
// Usage:
|
|
729
|
-
// node src/ops/lifecycle.js watch # runs until killed
|
|
730
|
-
// node src/ops/lifecycle.js watch --once # one check then exit
|
|
731
|
-
case 'watch':
|
|
732
|
-
var watchOnce = process.argv.slice(3).includes('--once');
|
|
733
|
-
var watchIntervalMs = (parseInt(process.env.EVOLVER_WATCH_INTERVAL_S || '120', 10) || 120) * 1000;
|
|
734
|
-
var prevWall = Date.now();
|
|
735
|
-
var prevMono = process.hrtime.bigint();
|
|
736
|
-
var skippedLastTick = false;
|
|
737
|
-
var watchRun = function () {
|
|
738
|
-
try {
|
|
739
|
-
var nowWall = Date.now();
|
|
740
|
-
var nowMono = process.hrtime.bigint();
|
|
741
|
-
var wallDelta = nowWall - prevWall;
|
|
742
|
-
var monoDeltaMs = Number((nowMono - prevMono) / 1000000n);
|
|
743
|
-
// Wall-clock can jump forward after macOS sleep/resume; monotonic
|
|
744
|
-
// clock does not. If the gap exceeds 60s, skip the stagnation
|
|
745
|
-
// restart this tick to give the daemon a grace period — but only
|
|
746
|
-
// once in a row, so a genuinely stuck daemon still gets restarted.
|
|
747
|
-
var clockJumped = (wallDelta - monoDeltaMs) > 60000 && !skippedLastTick;
|
|
748
|
-
var wh = checkHealth();
|
|
749
|
-
var ts = new Date().toISOString();
|
|
750
|
-
if (wh.healthy) {
|
|
751
|
-
console.log('[Watch] ' + ts + ' healthy pids=' + (wh.pids || []).join(','));
|
|
752
|
-
skippedLastTick = false;
|
|
753
|
-
} else if (clockJumped && wh.reason === 'stagnation') {
|
|
754
|
-
console.log('[watch] wall-clock jump detected (+' + Math.round((wallDelta - monoDeltaMs) / 1000) + 's), skipping stagnation check this cycle to give daemon a grace period');
|
|
755
|
-
skippedLastTick = true;
|
|
756
|
-
} else {
|
|
757
|
-
console.log('[Watch] ' + ts + ' unhealthy reason=' + wh.reason + ' restarting...');
|
|
758
|
-
var res = restart();
|
|
759
|
-
console.log('[Watch] restart result: ' + JSON.stringify(res));
|
|
760
|
-
skippedLastTick = false;
|
|
761
|
-
}
|
|
762
|
-
prevWall = nowWall;
|
|
763
|
-
prevMono = nowMono;
|
|
764
|
-
} catch (e) {
|
|
765
|
-
console.error('[watch] tick error: ' + (e && e.stack || e));
|
|
766
|
-
}
|
|
767
|
-
};
|
|
768
|
-
try { watchRun(); } catch (e) { console.error('[watch] tick error: ' + (e && e.stack || e)); }
|
|
769
|
-
if (!watchOnce) {
|
|
770
|
-
setInterval(function () {
|
|
771
|
-
try { watchRun(); } catch (e) { console.error('[watch] tick error: ' + (e && e.stack || e)); }
|
|
772
|
-
}, watchIntervalMs);
|
|
773
|
-
console.log('[Watch] Supervisor running every ' + Math.round(watchIntervalMs / 1000) + 's. Ctrl-C to stop.');
|
|
774
|
-
}
|
|
775
|
-
break;
|
|
776
|
-
default: console.log('Usage: node lifecycle.js [start|stop|restart|status|log|check|watch]');
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
module.exports = {
|
|
781
|
-
start,
|
|
782
|
-
stop,
|
|
783
|
-
restart,
|
|
784
|
-
status,
|
|
785
|
-
tailLog,
|
|
786
|
-
checkHealth,
|
|
787
|
-
getRunningPids,
|
|
788
|
-
expectsProxy,
|
|
789
|
-
prepareStartEnv,
|
|
790
|
-
checkProxyHealth,
|
|
791
|
-
shouldRestartForProxy,
|
|
792
|
-
isProxyUrlReachable,
|
|
793
|
-
isCurrentLoopCommand,
|
|
794
|
-
getOwnedLoopPids,
|
|
795
|
-
stopOwnedLoops,
|
|
796
|
-
_setProcessTableForTest,
|
|
797
|
-
_resetProcessTableForTest,
|
|
798
|
-
};
|