@evomap/evolver-cli 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/dist/antiGeneBenchmark.d.ts +9 -0
- package/dist/antiGeneBenchmark.js +173 -0
- package/dist/antiGeneRollout.d.ts +14 -0
- package/dist/antiGeneRollout.js +276 -0
- package/dist/atp.d.ts +122 -0
- package/dist/atp.js +413 -0
- package/dist/atpAutoDeliver.d.ts +53 -0
- package/dist/atpAutoDeliver.js +197 -0
- package/dist/atpAutobuyPrompt.d.ts +48 -0
- package/dist/atpAutobuyPrompt.js +109 -0
- package/dist/autoDistillAntiGene.d.ts +63 -0
- package/dist/autoDistillAntiGene.js +396 -0
- package/dist/autoDistillLlm.d.ts +94 -0
- package/dist/autoDistillLlm.js +510 -0
- package/dist/autoDistillTranscript.d.ts +87 -0
- package/dist/autoDistillTranscript.js +364 -0
- package/dist/autoRecall.d.ts +25 -0
- package/dist/autoRecall.js +80 -0
- package/dist/autoexec.d.ts +237 -0
- package/dist/autoexec.js +1041 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +7 -0
- package/dist/cliContracts.d.ts +72 -0
- package/dist/cliContracts.js +815 -0
- package/dist/commands.d.ts +9 -0
- package/dist/commands.js +10 -0
- package/dist/cursorRewrite.d.ts +42 -0
- package/dist/cursorRewrite.js +65 -0
- package/dist/cycleConsumer.d.ts +42 -0
- package/dist/cycleConsumer.js +519 -0
- package/dist/daemonLoop.d.ts +33 -0
- package/dist/daemonLoop.js +72 -0
- package/dist/dispatch.d.ts +10 -0
- package/dist/dispatch.js +75 -0
- package/dist/distillObserver.d.ts +33 -0
- package/dist/distillObserver.js +146 -0
- package/dist/distillPrimitives.d.ts +48 -0
- package/dist/distillPrimitives.js +142 -0
- package/dist/doctor.d.ts +54 -0
- package/dist/doctor.js +931 -0
- package/dist/geneValue.d.ts +37 -0
- package/dist/geneValue.js +97 -0
- package/dist/index.d.ts +193 -0
- package/dist/index.js +1135 -0
- package/dist/lifecycle.d.ts +75 -0
- package/dist/lifecycle.js +859 -0
- package/dist/login.d.ts +10 -0
- package/dist/login.js +38 -0
- package/dist/migrate/divergenceAudit.d.ts +29 -0
- package/dist/migrate/divergenceAudit.js +37 -0
- package/dist/migrate/fieldMap.d.ts +18 -0
- package/dist/migrate/fieldMap.js +68 -0
- package/dist/migrate/v1Import.d.ts +16 -0
- package/dist/migrate/v1Import.js +118 -0
- package/dist/phub.d.ts +18 -0
- package/dist/phub.js +284 -0
- package/dist/recall.d.ts +26 -0
- package/dist/recall.js +162 -0
- package/dist/recipe.d.ts +61 -0
- package/dist/recipe.js +564 -0
- package/dist/reflectionObserver.d.ts +8 -0
- package/dist/reflectionObserver.js +6 -0
- package/dist/reuse.d.ts +48 -0
- package/dist/reuse.js +300 -0
- package/dist/reuseReport.d.ts +20 -0
- package/dist/reuseReport.js +255 -0
- package/dist/reviewFilter.d.ts +4 -0
- package/dist/reviewFilter.js +6 -0
- package/dist/runtimeSessionSource.d.ts +9 -0
- package/dist/runtimeSessionSource.js +29 -0
- package/dist/setupHooks.d.ts +2 -0
- package/dist/setupHooks.js +410 -0
- package/dist/skill2gep.d.ts +144 -0
- package/dist/skill2gep.js +321 -0
- package/dist/skillDistill.d.ts +75 -0
- package/dist/skillDistill.js +342 -0
- package/dist/solo/breaker.d.ts +14 -0
- package/dist/solo/breaker.js +21 -0
- package/dist/solo/gitGuard.d.ts +17 -0
- package/dist/solo/gitGuard.js +62 -0
- package/dist/solo/mode.d.ts +12 -0
- package/dist/solo/mode.js +55 -0
- package/dist/thesis.d.ts +43 -0
- package/dist/thesis.js +179 -0
- package/dist/trajectoryExport.d.ts +1 -0
- package/dist/trajectoryExport.js +895 -0
- package/dist/valueDigest.d.ts +33 -0
- package/dist/valueDigest.js +94 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +14 -0
- package/package.json +38 -0
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { spawn, execFileSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { basename, dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
8
|
+
const requireFromHere = createRequire(import.meta.url);
|
|
9
|
+
const DEFAULT_DAEMON_NAME = 'evolver-proxy';
|
|
10
|
+
const DEFAULT_LABEL = 'com.evomap.evolver-proxy';
|
|
11
|
+
const DEFAULT_HEALTH_TIMEOUT_MS = 700;
|
|
12
|
+
const DEFAULT_WATCH_INTERVAL_MS = 120_000;
|
|
13
|
+
export function runLifecycleCommand(argv, deps = {}) {
|
|
14
|
+
return runLifecycleCommandInner(argv, deps).catch((err) => {
|
|
15
|
+
const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
|
|
16
|
+
stderr(`${err instanceof Error ? err.message : String(err)}\n`);
|
|
17
|
+
return 1;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async function runLifecycleCommandInner(argv, deps) {
|
|
21
|
+
const action = argv[0];
|
|
22
|
+
const env = deps.env ?? process.env;
|
|
23
|
+
const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
|
|
24
|
+
const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
|
|
25
|
+
const flags = parseFlags(argv.slice(1));
|
|
26
|
+
const paths = lifecyclePaths(env);
|
|
27
|
+
switch (action) {
|
|
28
|
+
case 'start': {
|
|
29
|
+
const result = await startLifecycle(paths, env);
|
|
30
|
+
stdout(`${JSON.stringify(result)}\n`);
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
case 'stop': {
|
|
34
|
+
const result = stopLifecycle(paths);
|
|
35
|
+
stdout(`${JSON.stringify(result)}\n`);
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
case 'restart': {
|
|
39
|
+
stopLifecycle(paths);
|
|
40
|
+
const result = await startLifecycle(paths, env);
|
|
41
|
+
stdout(`${JSON.stringify({ ...result, status: result.status === 'started' ? 'restarted' : result.status })}\n`);
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
case 'status': {
|
|
45
|
+
const status = await lifecycleStatus(paths, env);
|
|
46
|
+
stdout(`${JSON.stringify(status, null, 2)}\n`);
|
|
47
|
+
return status.running ? 0 : 1;
|
|
48
|
+
}
|
|
49
|
+
case 'check': {
|
|
50
|
+
const status = await lifecycleStatus(paths, env);
|
|
51
|
+
stdout(`${JSON.stringify(status, null, 2)}\n`);
|
|
52
|
+
if (!status.healthy) {
|
|
53
|
+
stderr(`[Lifecycle] unhealthy reason=${status.reason ?? 'unknown'}; restarting\n`);
|
|
54
|
+
stopLifecycle(paths);
|
|
55
|
+
const result = await startLifecycle(paths, env);
|
|
56
|
+
stdout(`${JSON.stringify(result)}\n`);
|
|
57
|
+
const next = await lifecycleStatus(paths, env);
|
|
58
|
+
stdout(`${JSON.stringify({ after_restart: lifecycleStatusForOperator(next), log: 'inspect EVOLVER_LIFECYCLE_LOG_FILE or EVOLVER_LIFECYCLE_LOG_DIR' }, null, 2)}\n`);
|
|
59
|
+
if (!next.healthy) {
|
|
60
|
+
stderr(`[Lifecycle] restart did not become healthy reason=${next.reason ?? 'unknown'}; inspect EVOLVER_LIFECYCLE_LOG_FILE or EVOLVER_LIFECYCLE_LOG_DIR\n`);
|
|
61
|
+
return 1;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
case 'watch':
|
|
67
|
+
return runWatch(paths, env, flags, stdout, stderr);
|
|
68
|
+
case 'install-service': {
|
|
69
|
+
const target = serviceTarget(flags);
|
|
70
|
+
const result = installService(target, flags, env, deps.argv1 ?? process.argv[1]);
|
|
71
|
+
stdout(`${JSON.stringify(result, null, 2)}\n`);
|
|
72
|
+
return 0;
|
|
73
|
+
}
|
|
74
|
+
default:
|
|
75
|
+
stderr('用法: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows>\n');
|
|
76
|
+
return action === undefined ? 0 : 1;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function lifecycleStatusForOperator(status) {
|
|
80
|
+
const { logFile: _logFile, ...safe } = status;
|
|
81
|
+
return safe;
|
|
82
|
+
}
|
|
83
|
+
export async function maybeAutoRestartProxyForSessionStart(env = process.env, argv1 = process.argv[1], deps = {}) {
|
|
84
|
+
if (!sessionAutoRestartEnabled(env))
|
|
85
|
+
return;
|
|
86
|
+
if (!proxyExpected(env))
|
|
87
|
+
return;
|
|
88
|
+
const paths = lifecyclePaths(env);
|
|
89
|
+
const verbose = sessionStartHookVerboseEnabled(env);
|
|
90
|
+
const stderr = verbose
|
|
91
|
+
? (deps.stderr ?? ((text) => { process.stderr.write(text); }))
|
|
92
|
+
: undefined;
|
|
93
|
+
const status = await lifecycleStatus(paths, env, { timeoutMs: 250, quietSettingsReadError: !verbose, stderr });
|
|
94
|
+
if (status.healthy)
|
|
95
|
+
return;
|
|
96
|
+
if ((deps.platform ?? process.platform) === 'win32') {
|
|
97
|
+
stderr?.(`[evolver-session-start] proxy daemon unhealthy (${status.reason ?? 'unknown'}); scheduled task/service manager should restart it on Windows.\n`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const cliPath = argv1 && argv1.trim() ? argv1 : resolveCurrentCliPath();
|
|
101
|
+
const spawnDetached = deps.spawnDetached ?? spawn;
|
|
102
|
+
const child = spawnDetached(process.execPath, [cliPath, 'lifecycle', 'start'], {
|
|
103
|
+
detached: true,
|
|
104
|
+
stdio: 'ignore',
|
|
105
|
+
env: { ...process.env, ...env },
|
|
106
|
+
windowsHide: true,
|
|
107
|
+
});
|
|
108
|
+
child.once('error', (err) => {
|
|
109
|
+
stderr?.(`[evolver-session-start] background restart spawn failed: ${err.message}\n`);
|
|
110
|
+
});
|
|
111
|
+
child.unref();
|
|
112
|
+
stderr?.(`[evolver-session-start] proxy daemon unhealthy (${status.reason ?? 'unknown'}); attempted background restart (PID ${child.pid}).\n`);
|
|
113
|
+
}
|
|
114
|
+
export async function startLifecycle(paths, env = process.env) {
|
|
115
|
+
loadEnvFileFromEnv(env);
|
|
116
|
+
mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
|
|
117
|
+
mkdirSync(paths.logDir, { recursive: true, mode: 0o700 });
|
|
118
|
+
const current = await lifecycleStatus(paths, env);
|
|
119
|
+
if (current.healthy && current.pid)
|
|
120
|
+
return { status: 'already_running', pid: current.pid, logFile: paths.logFile };
|
|
121
|
+
if (current.pid && current.running)
|
|
122
|
+
stopLifecycle(paths);
|
|
123
|
+
else
|
|
124
|
+
rmSync(paths.pidFile, { force: true });
|
|
125
|
+
const command = resolveDaemonCommand(env);
|
|
126
|
+
const cwd = env['EVOLVER_LIFECYCLE_CWD'] || process.cwd();
|
|
127
|
+
const out = openSync(paths.logFile, 'a');
|
|
128
|
+
const err = openSync(paths.logFile, 'a');
|
|
129
|
+
const child = spawn(command.command, command.args, {
|
|
130
|
+
cwd,
|
|
131
|
+
detached: true,
|
|
132
|
+
stdio: ['ignore', out, err],
|
|
133
|
+
env: { ...env },
|
|
134
|
+
windowsHide: true,
|
|
135
|
+
});
|
|
136
|
+
child.once('error', (err) => {
|
|
137
|
+
process.stderr.write(`[Lifecycle] failed to spawn ${command.command}: ${err.message}\n`);
|
|
138
|
+
});
|
|
139
|
+
child.unref();
|
|
140
|
+
if (!child.pid)
|
|
141
|
+
throw new Error('failed to determine lifecycle daemon pid');
|
|
142
|
+
writePidFile(paths.pidFile, {
|
|
143
|
+
owner: 'evolver-lifecycle',
|
|
144
|
+
pid: child.pid,
|
|
145
|
+
parentPid: process.pid,
|
|
146
|
+
command: command.command,
|
|
147
|
+
args: command.args,
|
|
148
|
+
cwd,
|
|
149
|
+
createdAt: new Date().toISOString(),
|
|
150
|
+
});
|
|
151
|
+
return { status: 'started', pid: child.pid, logFile: paths.logFile };
|
|
152
|
+
}
|
|
153
|
+
export function stopLifecycle(paths, deps = {}) {
|
|
154
|
+
const pidFile = readPidFile(paths.pidFile);
|
|
155
|
+
const pid = pidFile.pid;
|
|
156
|
+
if (!pid || !isPidRunning(pid)) {
|
|
157
|
+
rmSync(paths.pidFile, { force: true });
|
|
158
|
+
return { status: 'not_running' };
|
|
159
|
+
}
|
|
160
|
+
if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity)) {
|
|
161
|
+
return { status: 'not_owned', pid, reason: 'pidfile_owner_unconfirmed' };
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
process.kill(pid, 'SIGTERM');
|
|
165
|
+
}
|
|
166
|
+
catch (err) {
|
|
167
|
+
return { status: 'stop_failed', pid, reason: err instanceof Error ? err.message : String(err) };
|
|
168
|
+
}
|
|
169
|
+
const stopped = waitForExit(pid, 5_000);
|
|
170
|
+
if (!stopped)
|
|
171
|
+
forceKill(pid);
|
|
172
|
+
rmSync(paths.pidFile, { force: true });
|
|
173
|
+
return { status: 'stopped', pids: [pid] };
|
|
174
|
+
}
|
|
175
|
+
export async function lifecycleStatus(paths, env = process.env, options = {}) {
|
|
176
|
+
const settings = readProxySettings(paths.settingsFile, {
|
|
177
|
+
quietReadError: options.quietSettingsReadError === true,
|
|
178
|
+
stderr: options.stderr,
|
|
179
|
+
});
|
|
180
|
+
const pidFile = readPidFile(paths.pidFile);
|
|
181
|
+
const pid = pidFile.pid;
|
|
182
|
+
if (!pid || !isPidRunning(pid)) {
|
|
183
|
+
if (pid)
|
|
184
|
+
rmSync(paths.pidFile, { force: true });
|
|
185
|
+
const settingsStatus = await lifecycleStatusFromSettings(settings, paths, options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS);
|
|
186
|
+
if (settingsStatus)
|
|
187
|
+
return settingsStatus;
|
|
188
|
+
return { running: false, healthy: false, reason: 'not_running', logFile: paths.logFile };
|
|
189
|
+
}
|
|
190
|
+
if (!pidFile.owned || !pidFileRecordMatchesProcess(pidFile)) {
|
|
191
|
+
const settingsStatus = await lifecycleStatusFromSettings(settings, paths, options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS);
|
|
192
|
+
if (settingsStatus)
|
|
193
|
+
return settingsStatus;
|
|
194
|
+
return { running: false, pid, healthy: false, reason: 'pidfile_owner_unconfirmed', logFile: paths.logFile };
|
|
195
|
+
}
|
|
196
|
+
if (env['EVOLVER_LIFECYCLE_REQUIRE_PROXY_STATUS'] === '0') {
|
|
197
|
+
return { running: true, pid, healthy: true, logFile: paths.logFile };
|
|
198
|
+
}
|
|
199
|
+
if (!settings.url || !settings.token) {
|
|
200
|
+
return { running: true, pid, healthy: false, reason: 'proxy_settings_missing', logFile: paths.logFile };
|
|
201
|
+
}
|
|
202
|
+
if (settings.pid && settings.pid !== pid && !isPidRunning(settings.pid)) {
|
|
203
|
+
return { running: true, pid, healthy: false, reason: 'proxy_settings_stale_pid', logFile: paths.logFile };
|
|
204
|
+
}
|
|
205
|
+
const ok = await proxyStatusOk(settings, options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS);
|
|
206
|
+
return {
|
|
207
|
+
running: true,
|
|
208
|
+
pid,
|
|
209
|
+
healthy: ok,
|
|
210
|
+
...(ok ? {} : { reason: 'proxy_unreachable' }),
|
|
211
|
+
logFile: paths.logFile,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
export function lifecyclePaths(env = process.env) {
|
|
215
|
+
const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
|
|
216
|
+
const stateDir = env['EVOLVER_LIFECYCLE_STATE_DIR'] ?? join(home, 'lifecycle');
|
|
217
|
+
const logDir = env['EVOLVER_LIFECYCLE_LOG_DIR'] ?? join(home, 'logs');
|
|
218
|
+
const name = env['EVOLVER_LIFECYCLE_NAME'] ?? DEFAULT_DAEMON_NAME;
|
|
219
|
+
const settingsHome = env['EVOLVER_SETTINGS_DIR'] ?? join(homedir(), '.evolver');
|
|
220
|
+
return {
|
|
221
|
+
home,
|
|
222
|
+
stateDir,
|
|
223
|
+
logDir,
|
|
224
|
+
pidFile: env['EVOLVER_LIFECYCLE_PID_FILE'] ?? join(stateDir, `${name}.pid`),
|
|
225
|
+
logFile: env['EVOLVER_LIFECYCLE_LOG_FILE'] ?? join(logDir, `${name}.log`),
|
|
226
|
+
settingsFile: env['EVOLVER_PROXY_SETTINGS_FILE'] ?? join(settingsHome, 'settings.json'),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
export function renderSystemdUnit(opts = {}) {
|
|
230
|
+
return [
|
|
231
|
+
'# Linux systemd user unit -- ~/.config/systemd/user/evolver-proxy.service',
|
|
232
|
+
'[Unit]',
|
|
233
|
+
'Description=EvoMap Evolver Proxy Daemon',
|
|
234
|
+
'After=network-online.target',
|
|
235
|
+
'Wants=network-online.target',
|
|
236
|
+
'StartLimitBurst=5',
|
|
237
|
+
'StartLimitIntervalSec=120s',
|
|
238
|
+
'',
|
|
239
|
+
'[Service]',
|
|
240
|
+
'Type=simple',
|
|
241
|
+
`WorkingDirectory=${opts.workingDirectory ?? '%h'}`,
|
|
242
|
+
...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
|
|
243
|
+
`ExecStart=${opts.execStart ?? defaultServiceExecStart()}`,
|
|
244
|
+
'Restart=on-failure',
|
|
245
|
+
'RestartSec=5s',
|
|
246
|
+
'RestartPreventExitStatus=0',
|
|
247
|
+
'RestartForceExitStatus=78',
|
|
248
|
+
'TimeoutStopSec=30s',
|
|
249
|
+
'StandardOutput=journal',
|
|
250
|
+
'StandardError=journal',
|
|
251
|
+
'SyslogIdentifier=evolver-proxy',
|
|
252
|
+
'NoNewPrivileges=true',
|
|
253
|
+
'PrivateTmp=true',
|
|
254
|
+
'',
|
|
255
|
+
'[Install]',
|
|
256
|
+
'WantedBy=default.target',
|
|
257
|
+
'',
|
|
258
|
+
].join('\n');
|
|
259
|
+
}
|
|
260
|
+
export function renderLaunchdPlist(opts = {}) {
|
|
261
|
+
const workingDirectory = opts.workingDirectory ?? '/Users/YOU/your-project';
|
|
262
|
+
const nodePath = opts.nodePath ?? '/usr/local/bin/node';
|
|
263
|
+
const proxyBin = opts.proxyBin ?? '/Users/YOU/your-project/node_modules/@evomap/evolver-proxy/dist/bin/evolver-proxy.js';
|
|
264
|
+
const logDir = opts.logDir ?? '/Users/YOU/Library/Logs';
|
|
265
|
+
const envFileBlock = opts.envFile ? ` <key>EVOLVER_ENV_FILE</key>\n <string>${escapeXml(opts.envFile)}</string>\n` : '';
|
|
266
|
+
return [
|
|
267
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
268
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
269
|
+
'<plist version="1.0">',
|
|
270
|
+
'<dict>',
|
|
271
|
+
' <key>Label</key>',
|
|
272
|
+
` <string>${DEFAULT_LABEL}</string>`,
|
|
273
|
+
' <key>ProgramArguments</key>',
|
|
274
|
+
' <array>',
|
|
275
|
+
` <string>${escapeXml(nodePath)}</string>`,
|
|
276
|
+
` <string>${escapeXml(proxyBin)}</string>`,
|
|
277
|
+
' </array>',
|
|
278
|
+
' <key>WorkingDirectory</key>',
|
|
279
|
+
` <string>${escapeXml(workingDirectory)}</string>`,
|
|
280
|
+
' <key>EnvironmentVariables</key>',
|
|
281
|
+
' <dict>',
|
|
282
|
+
envFileBlock.trimEnd(),
|
|
283
|
+
' <key>PATH</key>',
|
|
284
|
+
' <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>',
|
|
285
|
+
' </dict>',
|
|
286
|
+
' <key>RunAtLoad</key>',
|
|
287
|
+
' <true/>',
|
|
288
|
+
' <key>KeepAlive</key>',
|
|
289
|
+
' <dict>',
|
|
290
|
+
' <key>SuccessfulExit</key>',
|
|
291
|
+
' <false/>',
|
|
292
|
+
' </dict>',
|
|
293
|
+
' <key>ThrottleInterval</key>',
|
|
294
|
+
' <integer>5</integer>',
|
|
295
|
+
' <key>StandardOutPath</key>',
|
|
296
|
+
` <string>${escapeXml(join(logDir, 'evolver-proxy.log'))}</string>`,
|
|
297
|
+
' <key>StandardErrorPath</key>',
|
|
298
|
+
` <string>${escapeXml(join(logDir, 'evolver-proxy.err.log'))}</string>`,
|
|
299
|
+
' <key>ProcessType</key>',
|
|
300
|
+
' <string>Standard</string>',
|
|
301
|
+
' <key>LowPriorityIO</key>',
|
|
302
|
+
' <false/>',
|
|
303
|
+
' <key>LowPriorityBackgroundIO</key>',
|
|
304
|
+
' <false/>',
|
|
305
|
+
'</dict>',
|
|
306
|
+
'</plist>',
|
|
307
|
+
'',
|
|
308
|
+
].filter((line) => line !== '').join('\n');
|
|
309
|
+
}
|
|
310
|
+
export function renderWindowsInstaller() {
|
|
311
|
+
return String.raw `param(
|
|
312
|
+
[switch]$Install,
|
|
313
|
+
[switch]$Uninstall,
|
|
314
|
+
[string]$TaskName = 'EvoMapEvolverProxyDaemon',
|
|
315
|
+
[string]$NodePath,
|
|
316
|
+
[string]$ProxyBin,
|
|
317
|
+
[string]$EnvFile
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
$ErrorActionPreference = 'Stop'
|
|
321
|
+
|
|
322
|
+
if (-not ($Install -or $Uninstall)) {
|
|
323
|
+
Write-Host 'Usage: install-evolver-proxy-windows.ps1 -Install [-NodePath ...] [-ProxyBin ...] [-EnvFile ...]'
|
|
324
|
+
Write-Host ' install-evolver-proxy-windows.ps1 -Uninstall [-TaskName ...]'
|
|
325
|
+
exit 1
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if ($Uninstall) {
|
|
329
|
+
$existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
|
|
330
|
+
if ($existing) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false }
|
|
331
|
+
$launcher = Join-Path $env:LOCALAPPDATA 'EvoMap\evolver-proxy-task-launcher.vbs'
|
|
332
|
+
if (Test-Path $launcher) { Remove-Item $launcher -Force -ErrorAction SilentlyContinue }
|
|
333
|
+
exit 0
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (-not $NodePath) {
|
|
337
|
+
$cmd = Get-Command node -ErrorAction SilentlyContinue
|
|
338
|
+
if (-not $cmd) { Write-Error 'node.exe not on PATH; pass -NodePath explicitly.'; exit 1 }
|
|
339
|
+
$NodePath = $cmd.Source
|
|
340
|
+
}
|
|
341
|
+
if (-not $ProxyBin) { Write-Error 'Pass -ProxyBin pointing at evolver-proxy.js.'; exit 1 }
|
|
342
|
+
if (-not (Test-Path $ProxyBin)) { Write-Error "Proxy bin not found at $ProxyBin"; exit 1 }
|
|
343
|
+
|
|
344
|
+
$launcherDir = Join-Path $env:LOCALAPPDATA 'EvoMap'
|
|
345
|
+
if (-not (Test-Path $launcherDir)) { New-Item -ItemType Directory -Path $launcherDir | Out-Null }
|
|
346
|
+
$launcherPath = Join-Path $launcherDir 'evolver-proxy-task-launcher.vbs'
|
|
347
|
+
|
|
348
|
+
$nodeEsc = $NodePath.Replace('"', '""')
|
|
349
|
+
$proxyEsc = $ProxyBin.Replace('"', '""')
|
|
350
|
+
$envEsc = if ($EnvFile) { $EnvFile.Replace('"', '""') } else { '' }
|
|
351
|
+
|
|
352
|
+
$launcherBody = @"
|
|
353
|
+
' AUTO-GENERATED by install-evolver-proxy-windows.ps1 -- do not edit.
|
|
354
|
+
' wscript.exe is a Windows-subsystem host. WshShell.Run(..., 0, True)
|
|
355
|
+
' launches node.exe hidden and waits so Task Scheduler sees the exit code.
|
|
356
|
+
Dim WshShell, env, cmd, rc
|
|
357
|
+
Set WshShell = CreateObject("WScript.Shell")
|
|
358
|
+
Set env = WshShell.Environment("PROCESS")
|
|
359
|
+
If "$envEsc" <> "" Then env("EVOLVER_ENV_FILE") = "$envEsc"
|
|
360
|
+
cmd = """$nodeEsc"" ""$proxyEsc"""
|
|
361
|
+
rc = WshShell.Run(cmd, 0, True)
|
|
362
|
+
WScript.Quit rc
|
|
363
|
+
"@
|
|
364
|
+
Set-Content -Path $launcherPath -Value $launcherBody -Encoding Unicode
|
|
365
|
+
|
|
366
|
+
$action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('"{0}"' -f $launcherPath)
|
|
367
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
368
|
+
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
|
|
369
|
+
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 2) -ExecutionTimeLimit (New-TimeSpan -Days 0)
|
|
370
|
+
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
371
|
+
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal
|
|
372
|
+
Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
|
|
373
|
+
Write-Host "Installed scheduled task '$TaskName' using hidden wscript launcher $launcherPath."
|
|
374
|
+
`;
|
|
375
|
+
}
|
|
376
|
+
function parseFlags(argv) {
|
|
377
|
+
const out = {};
|
|
378
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
379
|
+
const arg = argv[i];
|
|
380
|
+
if (!arg?.startsWith('--'))
|
|
381
|
+
continue;
|
|
382
|
+
const raw = arg.slice(2);
|
|
383
|
+
const eq = raw.indexOf('=');
|
|
384
|
+
if (eq >= 0)
|
|
385
|
+
out[raw.slice(0, eq)] = raw.slice(eq + 1);
|
|
386
|
+
else if (argv[i + 1] && !argv[i + 1].startsWith('--'))
|
|
387
|
+
out[raw] = argv[++i];
|
|
388
|
+
else
|
|
389
|
+
out[raw] = true;
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
function serviceTarget(flags) {
|
|
394
|
+
const value = typeof flags['target'] === 'string' ? flags['target'] : '';
|
|
395
|
+
if (value === 'launchd' || value === 'systemd' || value === 'windows')
|
|
396
|
+
return value;
|
|
397
|
+
throw new Error('missing or invalid --target (expected: launchd|systemd|windows)');
|
|
398
|
+
}
|
|
399
|
+
function installService(target, flags, env, argv1) {
|
|
400
|
+
const dryRun = flags['dry-run'] === true;
|
|
401
|
+
const envFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : env['EVOLVER_ENV_FILE'];
|
|
402
|
+
if (target === 'systemd') {
|
|
403
|
+
const path = expandHome('~/.config/systemd/user/evolver-proxy.service');
|
|
404
|
+
const unit = renderSystemdUnit({ envFile, workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined });
|
|
405
|
+
if (!dryRun)
|
|
406
|
+
writeTextFile(path, unit, 0o644);
|
|
407
|
+
return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'systemd-user' };
|
|
408
|
+
}
|
|
409
|
+
if (target === 'launchd') {
|
|
410
|
+
const path = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
|
|
411
|
+
const plist = renderLaunchdPlist({
|
|
412
|
+
envFile,
|
|
413
|
+
workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : process.cwd(),
|
|
414
|
+
nodePath: resolveStableNodePath(),
|
|
415
|
+
proxyBin: resolveProxyBinPath() ?? (argv1?.startsWith('/') ? argv1 : undefined) ?? '/ABSOLUTE/PATH/TO/evolver-proxy.js',
|
|
416
|
+
logDir: join(homedir(), 'Library', 'Logs'),
|
|
417
|
+
});
|
|
418
|
+
if (!dryRun)
|
|
419
|
+
writeTextFile(path, plist, 0o644);
|
|
420
|
+
return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'launchd' };
|
|
421
|
+
}
|
|
422
|
+
const path = expandHome('~/install-evolver-proxy-windows.ps1');
|
|
423
|
+
const script = renderWindowsInstaller();
|
|
424
|
+
if (!dryRun)
|
|
425
|
+
writeTextFile(path, script, 0o644);
|
|
426
|
+
return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'windows-scheduled-task' };
|
|
427
|
+
}
|
|
428
|
+
async function runWatch(paths, env, flags, stdout, stderr) {
|
|
429
|
+
const once = flags['once'] === true;
|
|
430
|
+
const intervalMs = positiveInt(env['EVOLVER_WATCH_INTERVAL_MS'], DEFAULT_WATCH_INTERVAL_MS);
|
|
431
|
+
let prevWall = Date.now();
|
|
432
|
+
let prevMono = process.hrtime.bigint();
|
|
433
|
+
let skippedLastTick = false;
|
|
434
|
+
const tick = async () => {
|
|
435
|
+
const nowWall = Date.now();
|
|
436
|
+
const nowMono = process.hrtime.bigint();
|
|
437
|
+
const wallDelta = nowWall - prevWall;
|
|
438
|
+
const monoDeltaMs = Number((nowMono - prevMono) / 1000000n);
|
|
439
|
+
const status = await lifecycleStatus(paths, env);
|
|
440
|
+
const clockJumped = (wallDelta - monoDeltaMs) > 60_000 && !skippedLastTick;
|
|
441
|
+
if (status.healthy) {
|
|
442
|
+
stdout(`[Watch] ${new Date().toISOString()} healthy pid=${status.pid ?? '-'}\n`);
|
|
443
|
+
skippedLastTick = false;
|
|
444
|
+
}
|
|
445
|
+
else if (clockJumped && status.reason === 'stagnation') {
|
|
446
|
+
stdout(`[Watch] wall-clock jump detected; skipping one stagnation restart\n`);
|
|
447
|
+
skippedLastTick = true;
|
|
448
|
+
}
|
|
449
|
+
else {
|
|
450
|
+
stdout(`[Watch] ${new Date().toISOString()} unhealthy reason=${status.reason ?? 'unknown'} restarting...\n`);
|
|
451
|
+
stopLifecycle(paths);
|
|
452
|
+
const result = await startLifecycle(paths, env);
|
|
453
|
+
stdout(`[Watch] restart result: ${JSON.stringify(result)}\n`);
|
|
454
|
+
skippedLastTick = false;
|
|
455
|
+
}
|
|
456
|
+
prevWall = nowWall;
|
|
457
|
+
prevMono = nowMono;
|
|
458
|
+
};
|
|
459
|
+
await tick().catch((err) => { stderr(`[Watch] tick error: ${err instanceof Error ? err.message : String(err)}\n`); });
|
|
460
|
+
if (once)
|
|
461
|
+
return 0;
|
|
462
|
+
setInterval(() => {
|
|
463
|
+
void tick().catch((err) => { stderr(`[Watch] tick error: ${err instanceof Error ? err.message : String(err)}\n`); });
|
|
464
|
+
}, intervalMs);
|
|
465
|
+
stdout(`[Watch] Supervisor running every ${Math.round(intervalMs / 1000)}s. Ctrl-C to stop.\n`);
|
|
466
|
+
return new Promise(() => { });
|
|
467
|
+
}
|
|
468
|
+
function resolveDaemonCommand(env) {
|
|
469
|
+
const explicit = env['EVOLVER_LIFECYCLE_COMMAND']?.trim();
|
|
470
|
+
if (explicit) {
|
|
471
|
+
const parsed = repairUnquotedWindowsExePath(explicit, parseCommandLine(explicit));
|
|
472
|
+
if (parsed.length === 0)
|
|
473
|
+
throw new Error('EVOLVER_LIFECYCLE_COMMAND is empty');
|
|
474
|
+
return { command: parsed[0], args: parsed.slice(1), display: explicit };
|
|
475
|
+
}
|
|
476
|
+
const proxyBin = resolveProxyBinPath();
|
|
477
|
+
if (proxyBin)
|
|
478
|
+
return { command: process.execPath, args: [proxyBin], display: `${process.execPath} ${proxyBin}` };
|
|
479
|
+
return { command: DEFAULT_DAEMON_NAME, args: [], display: DEFAULT_DAEMON_NAME };
|
|
480
|
+
}
|
|
481
|
+
export function resolveProxyBinPath() {
|
|
482
|
+
try {
|
|
483
|
+
const entry = requireFromHere.resolve('@evomap/evolver-proxy');
|
|
484
|
+
const candidate = join(dirname(entry), 'bin', 'evolver-proxy.js');
|
|
485
|
+
return existsSync(candidate) ? candidate : undefined;
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
const local = fileURLToPath(new URL('../../evolver-proxy/dist/bin/evolver-proxy.js', import.meta.url));
|
|
489
|
+
return existsSync(local) ? local : undefined;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
export function resolveStableNodePath() {
|
|
493
|
+
const pathNode = resolvePathCommand('node');
|
|
494
|
+
if (pathNode)
|
|
495
|
+
return pathNode;
|
|
496
|
+
for (const candidate of ['/opt/homebrew/bin/node', '/usr/local/bin/node', '/usr/bin/node']) {
|
|
497
|
+
if (existsSync(candidate))
|
|
498
|
+
return candidate;
|
|
499
|
+
}
|
|
500
|
+
return process.execPath;
|
|
501
|
+
}
|
|
502
|
+
function defaultServiceExecStart() {
|
|
503
|
+
const proxyBin = resolveProxyBinPath();
|
|
504
|
+
if (!proxyBin)
|
|
505
|
+
return `${quoteSystemdArg(resolveStableNodePath())} /ABSOLUTE/PATH/TO/evolver-proxy.js`;
|
|
506
|
+
return `${quoteSystemdArg(resolveStableNodePath())} ${quoteSystemdArg(proxyBin)}`;
|
|
507
|
+
}
|
|
508
|
+
function resolvePathCommand(command) {
|
|
509
|
+
try {
|
|
510
|
+
const out = execFileSync('/bin/sh', ['-lc', `command -v ${command}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
511
|
+
return out.startsWith('/') ? out : undefined;
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function writePidFile(path, record) {
|
|
518
|
+
writeFileSync(path, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
519
|
+
}
|
|
520
|
+
function readPidFile(path) {
|
|
521
|
+
try {
|
|
522
|
+
const raw = readFileSync(path, 'utf8').trim();
|
|
523
|
+
if (raw.startsWith('{')) {
|
|
524
|
+
const parsed = JSON.parse(raw);
|
|
525
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
526
|
+
return { owned: false, legacy: false };
|
|
527
|
+
const record = parsed;
|
|
528
|
+
const rawPid = record['pid'];
|
|
529
|
+
const pid = typeof rawPid === 'number' && Number.isInteger(rawPid) && rawPid > 0 ? rawPid : undefined;
|
|
530
|
+
const args = record['args'];
|
|
531
|
+
const command = record['command'];
|
|
532
|
+
const cwd = record['cwd'];
|
|
533
|
+
const owner = record['owner'];
|
|
534
|
+
const createdAt = record['createdAt'];
|
|
535
|
+
const parentPid = record['parentPid'];
|
|
536
|
+
if (owner === 'evolver-lifecycle'
|
|
537
|
+
&& pid !== undefined
|
|
538
|
+
&& (parentPid === undefined || (typeof parentPid === 'number' && Number.isInteger(parentPid) && parentPid > 0))
|
|
539
|
+
&& typeof command === 'string'
|
|
540
|
+
&& Array.isArray(args)
|
|
541
|
+
&& args.every((arg) => typeof arg === 'string')
|
|
542
|
+
&& typeof cwd === 'string'
|
|
543
|
+
&& typeof createdAt === 'string') {
|
|
544
|
+
return {
|
|
545
|
+
pid,
|
|
546
|
+
owned: true,
|
|
547
|
+
legacy: false,
|
|
548
|
+
record: { owner, pid, ...(parentPid ? { parentPid } : {}), command, args, cwd, createdAt },
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
return { pid, owned: false, legacy: false };
|
|
552
|
+
}
|
|
553
|
+
const pid = Number(raw);
|
|
554
|
+
return { pid: Number.isInteger(pid) && pid > 0 ? pid : undefined, owned: false, legacy: true };
|
|
555
|
+
}
|
|
556
|
+
catch (err) {
|
|
557
|
+
if (err.code === 'ENOENT')
|
|
558
|
+
return { owned: false, legacy: false };
|
|
559
|
+
return { owned: false, legacy: false };
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
function pidFileRecordMatchesProcess(pidFile, readCommandLine = processCommandLine, readIdentity = processIdentity) {
|
|
563
|
+
if (!pidFile.owned || !pidFile.record)
|
|
564
|
+
return false;
|
|
565
|
+
const record = pidFile.record;
|
|
566
|
+
const commandLine = readCommandLine(record.pid);
|
|
567
|
+
if (commandLine && commandLine.includes(basename(record.command)))
|
|
568
|
+
return record.args.every((arg) => commandLine.includes(arg));
|
|
569
|
+
return processIdentityMatchesRecord(record, readIdentity(record.pid));
|
|
570
|
+
}
|
|
571
|
+
function waitForPidFileRecordMatch(pidFile, timeoutMs, readCommandLine = processCommandLine, readIdentity = processIdentity) {
|
|
572
|
+
const start = Date.now();
|
|
573
|
+
while (Date.now() - start < timeoutMs) {
|
|
574
|
+
if (pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity))
|
|
575
|
+
return true;
|
|
576
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
577
|
+
}
|
|
578
|
+
return pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity);
|
|
579
|
+
}
|
|
580
|
+
function processCommandLine(pid) {
|
|
581
|
+
if (process.platform === 'win32') {
|
|
582
|
+
try {
|
|
583
|
+
const script = `$p=Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; if ($p) { $p.CommandLine }`;
|
|
584
|
+
return execFileSync('powershell.exe', ['-NoProfile', '-Command', script], {
|
|
585
|
+
encoding: 'utf8',
|
|
586
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
587
|
+
windowsHide: true,
|
|
588
|
+
}).trim() || undefined;
|
|
589
|
+
}
|
|
590
|
+
catch {
|
|
591
|
+
return undefined;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
try {
|
|
595
|
+
return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || undefined;
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
return undefined;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function processIdentity(pid) {
|
|
602
|
+
if (process.platform === 'win32') {
|
|
603
|
+
try {
|
|
604
|
+
const script = [
|
|
605
|
+
`$p=Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"`,
|
|
606
|
+
'if (-not $p) { exit 1 }',
|
|
607
|
+
'$path=$p.ExecutablePath',
|
|
608
|
+
'$start=if ($p.CreationDate) { ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() } else { "" }',
|
|
609
|
+
'$parent=if ($p.ParentProcessId) { $p.ParentProcessId } else { "" }',
|
|
610
|
+
'Write-Output $path',
|
|
611
|
+
'Write-Output $start',
|
|
612
|
+
'Write-Output $parent',
|
|
613
|
+
].join('; ');
|
|
614
|
+
const [executable, rawStartedAt, rawParentPid] = execFileSync('powershell.exe', ['-NoProfile', '-Command', script], {
|
|
615
|
+
encoding: 'utf8',
|
|
616
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
617
|
+
windowsHide: true,
|
|
618
|
+
}).split(/\r?\n/).map((line) => line.trim());
|
|
619
|
+
const startedAt = rawStartedAt ? Number(rawStartedAt) : undefined;
|
|
620
|
+
const parentPid = rawParentPid ? Number(rawParentPid) : undefined;
|
|
621
|
+
return {
|
|
622
|
+
...(executable ? { executable } : {}),
|
|
623
|
+
...(parentPid && Number.isInteger(parentPid) && parentPid > 0 ? { parentPid } : {}),
|
|
624
|
+
...(startedAt && Number.isFinite(startedAt) ? { startedAt } : {}),
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
return undefined;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
return undefined;
|
|
632
|
+
}
|
|
633
|
+
function processIdentityMatchesRecord(record, identity) {
|
|
634
|
+
if (!identity?.executable || !identity.parentPid || !identity.startedAt)
|
|
635
|
+
return false;
|
|
636
|
+
if (record.parentPid !== undefined && record.parentPid !== identity.parentPid)
|
|
637
|
+
return false;
|
|
638
|
+
if (normalizeFsIdentity(identity.executable) !== normalizeFsIdentity(record.command))
|
|
639
|
+
return false;
|
|
640
|
+
const recordStartedAt = Date.parse(record.createdAt);
|
|
641
|
+
return Number.isFinite(recordStartedAt) && Math.abs(identity.startedAt - recordStartedAt) <= 30_000;
|
|
642
|
+
}
|
|
643
|
+
function normalizeFsIdentity(value) {
|
|
644
|
+
const normalized = value.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
645
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
646
|
+
}
|
|
647
|
+
function isPidRunning(pid) {
|
|
648
|
+
try {
|
|
649
|
+
process.kill(pid, 0);
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
catch (err) {
|
|
653
|
+
return err.code === 'EPERM';
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
function waitForExit(pid, timeoutMs) {
|
|
657
|
+
const start = Date.now();
|
|
658
|
+
while (Date.now() - start < timeoutMs) {
|
|
659
|
+
if (!isPidRunning(pid))
|
|
660
|
+
return true;
|
|
661
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
662
|
+
}
|
|
663
|
+
return !isPidRunning(pid);
|
|
664
|
+
}
|
|
665
|
+
function forceKill(pid) {
|
|
666
|
+
if (process.platform === 'win32') {
|
|
667
|
+
try {
|
|
668
|
+
execFileSync('taskkill', ['/F', '/PID', String(pid)], { stdio: 'ignore', windowsHide: true });
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
catch (err) {
|
|
672
|
+
process.stderr.write(`[Lifecycle] taskkill failed for PID ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
process.kill(pid, 'SIGKILL');
|
|
677
|
+
}
|
|
678
|
+
catch (err) {
|
|
679
|
+
process.stderr.write(`[Lifecycle] SIGKILL failed for PID ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function readProxySettings(path, options = {}) {
|
|
683
|
+
try {
|
|
684
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
685
|
+
const proxy = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed['proxy'] : undefined;
|
|
686
|
+
if (!proxy || typeof proxy !== 'object' || Array.isArray(proxy))
|
|
687
|
+
return {};
|
|
688
|
+
const record = proxy;
|
|
689
|
+
return {
|
|
690
|
+
...(typeof record['url'] === 'string' ? { url: record['url'] } : {}),
|
|
691
|
+
...(typeof record['token'] === 'string' ? { token: record['token'] } : {}),
|
|
692
|
+
...(typeof record['pid'] === 'number' ? { pid: record['pid'] } : {}),
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
catch (err) {
|
|
696
|
+
if (!options.quietReadError && err.code !== 'ENOENT') {
|
|
697
|
+
const stderr = options.stderr ?? ((text) => { process.stderr.write(text); });
|
|
698
|
+
stderr(`[Lifecycle] failed to read proxy settings: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
699
|
+
}
|
|
700
|
+
return {};
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
async function proxyStatusOk(settings, timeoutMs) {
|
|
704
|
+
if (!settings.url || !settings.token)
|
|
705
|
+
return false;
|
|
706
|
+
const controller = new AbortController();
|
|
707
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
708
|
+
try {
|
|
709
|
+
const url = `${settings.url.replace(/\/+$/, '')}/proxy/status`;
|
|
710
|
+
const res = await fetch(url, { headers: { authorization: `Bearer ${settings.token}` }, signal: controller.signal });
|
|
711
|
+
if (!res.ok)
|
|
712
|
+
return false;
|
|
713
|
+
const body = await res.json();
|
|
714
|
+
return Boolean(body && typeof body === 'object' && !Array.isArray(body) && body['status'] === 'running');
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
finally {
|
|
720
|
+
clearTimeout(timeout);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
async function lifecycleStatusFromSettings(settings, paths, timeoutMs) {
|
|
724
|
+
if (!settings.pid || !settings.url || !settings.token || !isPidRunning(settings.pid))
|
|
725
|
+
return undefined;
|
|
726
|
+
const ok = await proxyStatusOk(settings, timeoutMs);
|
|
727
|
+
if (!ok)
|
|
728
|
+
return undefined;
|
|
729
|
+
return { running: true, pid: settings.pid, healthy: true, logFile: paths.logFile };
|
|
730
|
+
}
|
|
731
|
+
function sessionAutoRestartEnabled(env) {
|
|
732
|
+
const value = env['EVOLVER_SESSION_AUTO_RESTART']?.trim().toLowerCase();
|
|
733
|
+
return value !== '0' && value !== 'false' && value !== 'off';
|
|
734
|
+
}
|
|
735
|
+
export function sessionStartHookVerboseEnabled(env = process.env) {
|
|
736
|
+
const value = env['EVOLVER_HOOK_VERBOSE']?.trim().toLowerCase();
|
|
737
|
+
return value === '1' || value === 'true' || value === 'yes' || value === 'on';
|
|
738
|
+
}
|
|
739
|
+
export function proxyExpected(env = process.env) {
|
|
740
|
+
if (env['EVOLVER_PROXY_EXPECTED'] === '1')
|
|
741
|
+
return true;
|
|
742
|
+
if (env['EVOMAP_PROXY'] === '1')
|
|
743
|
+
return true;
|
|
744
|
+
if (env['A2A_TRANSPORT']?.toLowerCase() === 'mailbox')
|
|
745
|
+
return true;
|
|
746
|
+
if (isLoopbackUrl(env['EVOLVER_PROXY_URL']) || isLoopbackUrl(env['ANTHROPIC_BASE_URL']))
|
|
747
|
+
return true;
|
|
748
|
+
return existsSync(lifecyclePaths(env).settingsFile);
|
|
749
|
+
}
|
|
750
|
+
function isLoopbackUrl(value) {
|
|
751
|
+
const raw = value?.trim();
|
|
752
|
+
if (!raw)
|
|
753
|
+
return false;
|
|
754
|
+
try {
|
|
755
|
+
const parsed = new URL(raw);
|
|
756
|
+
const host = parsed.hostname.toLowerCase();
|
|
757
|
+
return parsed.protocol === 'http:' && (host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]');
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function repairUnquotedWindowsExePath(value, parsed) {
|
|
764
|
+
if (process.platform !== 'win32' || parsed.length === 0)
|
|
765
|
+
return parsed;
|
|
766
|
+
const first = parsed[0];
|
|
767
|
+
if (/\.exe$/i.test(first))
|
|
768
|
+
return parsed;
|
|
769
|
+
const exeEnd = value.toLowerCase().indexOf('.exe');
|
|
770
|
+
if (exeEnd < 0)
|
|
771
|
+
return parsed;
|
|
772
|
+
const command = value.slice(0, exeEnd + 4).trim();
|
|
773
|
+
if (!/^[A-Za-z]:\\/.test(command) && !command.startsWith('\\\\'))
|
|
774
|
+
return parsed;
|
|
775
|
+
if (!existsSync(command))
|
|
776
|
+
return parsed;
|
|
777
|
+
const rest = value.slice(exeEnd + 4).trim();
|
|
778
|
+
return rest ? [command, ...parseCommandLine(rest)] : [command];
|
|
779
|
+
}
|
|
780
|
+
function parseCommandLine(value) {
|
|
781
|
+
const out = [];
|
|
782
|
+
let current = '';
|
|
783
|
+
let quote = null;
|
|
784
|
+
let escaped = false;
|
|
785
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
786
|
+
const ch = value[i];
|
|
787
|
+
if (escaped) {
|
|
788
|
+
current += ch;
|
|
789
|
+
escaped = false;
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
if (ch === '\\' && quote !== "'") {
|
|
793
|
+
const next = value[i + 1];
|
|
794
|
+
if (next !== undefined && (/\s/.test(next) || next === '"' || next === "'" || next === '\\')) {
|
|
795
|
+
escaped = true;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
current += ch;
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
if ((ch === '"' || ch === "'") && quote === null) {
|
|
802
|
+
quote = ch;
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (ch === quote) {
|
|
806
|
+
quote = null;
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
if (/\s/.test(ch) && quote === null) {
|
|
810
|
+
if (current) {
|
|
811
|
+
out.push(current);
|
|
812
|
+
current = '';
|
|
813
|
+
}
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
current += ch;
|
|
817
|
+
}
|
|
818
|
+
if (quote !== null)
|
|
819
|
+
throw new Error('unterminated quote in EVOLVER_LIFECYCLE_COMMAND');
|
|
820
|
+
if (escaped)
|
|
821
|
+
current += '\\';
|
|
822
|
+
if (current)
|
|
823
|
+
out.push(current);
|
|
824
|
+
return out;
|
|
825
|
+
}
|
|
826
|
+
function positiveInt(value, fallback) {
|
|
827
|
+
const parsed = Number(value);
|
|
828
|
+
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
|
|
829
|
+
}
|
|
830
|
+
function expandHome(path) {
|
|
831
|
+
if (path === '~')
|
|
832
|
+
return homedir();
|
|
833
|
+
if (path.startsWith('~/'))
|
|
834
|
+
return join(homedir(), path.slice(2));
|
|
835
|
+
return path;
|
|
836
|
+
}
|
|
837
|
+
function writeTextFile(path, content, mode) {
|
|
838
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
839
|
+
writeFileSync(path, content, { encoding: 'utf8', mode });
|
|
840
|
+
}
|
|
841
|
+
function escapeXml(value) {
|
|
842
|
+
return value
|
|
843
|
+
.replaceAll('&', '&')
|
|
844
|
+
.replaceAll('<', '<')
|
|
845
|
+
.replaceAll('>', '>')
|
|
846
|
+
.replaceAll('"', '"')
|
|
847
|
+
.replaceAll("'", ''');
|
|
848
|
+
}
|
|
849
|
+
function escapeSystemdEnvValue(value) {
|
|
850
|
+
return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$');
|
|
851
|
+
}
|
|
852
|
+
function quoteSystemdArg(value) {
|
|
853
|
+
return /^[A-Za-z0-9_/:.@%+=,-]+$/.test(value)
|
|
854
|
+
? value
|
|
855
|
+
: `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$')}"`;
|
|
856
|
+
}
|
|
857
|
+
function resolveCurrentCliPath() {
|
|
858
|
+
return fileURLToPath(new URL('./cli.js', import.meta.url));
|
|
859
|
+
}
|