Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(pm2): stop PortOS's own PM2 config leaking into apps it launches

Adam Eivy71e4f7a3f2b0
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index ae90eb13ee..9917803e39 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -244,6 +244,7 @@ export async function startLlamaServer(options = {}) {
await execPm2(['delete', LLAMA_APP]).catch(() => {});
clearJlistCache();
+ console.log(`🦙 llama-server starting on ${host}:${port} (model ${model}${draftPath ? `, drafter ${draftPath}` : ''})`);
await execPm2([
'start', binaryPath,
'--name', LLAMA_APP,
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index e2f208e555..9f8a1caf92 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -11,6 +11,7 @@ import * as processEnv from '../lib/processEnv.js';
import * as commandExistsModule from '../lib/commandExists.js';
import * as childProcess from '../lib/childProcess.js';
import * as platform from '../lib/platform.js';
+import * as openAiModelsProbe from '../lib/openAiModelsProbe.js';
import * as pm2Module from './pm2.js';
import { PORTS } from '../lib/ports.js';
import { EventEmitter } from 'events';
@@ -64,6 +65,12 @@ describe('llamaServerManager', () => {
// especially common), so lifecycle tests pin the port-discovery result.
vi.spyOn(platform, 'isPortInUse').mockResolvedValue(false);
+ // Status and start both probe the endpoint over the network. On a developer
+ // machine that is running PortOS's own llama-server the probe answers for
+ // real on :5568 and every lifecycle test reports "already running", so pin
+ // it unreachable for the same reason the port probe above is pinned.
+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });
+
vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {
execPm2Calls.push(args);
const action = args[0];
diff --git a/server/services/pm2.js b/server/services/pm2.js
index b2971a0a16..840aacf81a 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -41,6 +41,27 @@ function isJsScript(script) {
return /\.(?:js|mjs|cjs|ts)$/i.test(script);
}
+/**
+ * PM2 exports a managed process's own `pm2_env` into that process's environment
+ * as lowercase config keys, and the PM2 CLI reads those keys back as config —
+ * where they outrank an explicit CLI flag. Since PortOS itself runs under PM2,
+ * every `pm2 start` it spawns would otherwise inherit *portos-server's* config.
+ *
+ * That is how a loaded, serving llama-server kept dying: it was handed
+ * portos-server's 4GB `max_memory_restart`, so PM2's memory watchdog (which
+ * fires regardless of `--no-autorestart`) killed the 25GB model process seconds
+ * after every successful load, forever. `exec_mode` and `watch` leak the same
+ * way — verified by starting a process with each key set in the environment.
+ */
+const INHERITED_PM2_CONFIG_KEYS = ['max_memory_restart', 'exec_mode', 'watch'];
+
+/** Drop the PM2 config keys PM2 injected into our own environment. */
+function withoutInheritedPm2Config(env) {
+ const clean = { ...env };
+ for (const key of INHERITED_PM2_CONFIG_KEYS) delete clean[key];
+ return clean;
+}
+
/**
* Spawn PM2 CLI via local binary (node pm2/bin/pm2).
* Always uses the local PM2 binary to avoid depending on a global pm2 install.
@@ -60,7 +81,12 @@ function isJsScript(script) {
export function spawnPm2(pm2Args, opts = {}) {
// windowsHide comes from lib/childProcess.js. Re-asserting it here would also
// outrank a caller's explicit opt-out, which the wrapper deliberately honors.
- const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], opts);
+ // The env sanitize applies to a caller-supplied env too — it inherits
+ // `process.env`, so it carries the same injected keys.
+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], {
+ ...opts,
+ env: withoutInheritedPm2Config(opts.env || process.env),
+ });
// Default error handler — prevents an uncaught EventEmitter 'error' crash
// when no caller attaches its own handler. Callers that do attach their own
// 'error' listener receive the event too (multiple listeners are additive).
diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.js
index 614b9007dc..cfa3f9aa76 100644
--- a/server/services/pm2.launch.test.js
+++ b/server/services/pm2.launch.test.js
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { EventEmitter } from 'events';
const mockPm2 = vi.hoisted(() => ({
@@ -15,7 +15,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => ({
spawn: mockSpawn,
}));
-import { startApp, startWithCommand } from './pm2.js';
+import { startApp, startWithCommand, execPm2 } from './pm2.js';
// Fake child_process.spawn result: closes with the given exit code on next tick.
function fakeChild(exitCode = 0) {
@@ -68,6 +68,42 @@ describe('PM2 command launch interpreters', () => {
}), expect.any(Function));
});
+ // PortOS itself runs under PM2, which exports its pm2_env into our
+ // environment as lowercase config keys — and the PM2 CLI reads those keys
+ // back as config, outranking explicit flags. Unstripped, portos-server's own
+ // 4GB `max_memory_restart` reached every app it launched: PM2's memory
+ // watchdog then killed a fully loaded 25GB llama-server seconds after each
+ // successful start, in a loop that read as "the server won't start".
+ describe('inherited PM2 config in the environment', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('strips PM2\'s own config keys before spawning the CLI', async () => {
+ vi.stubEnv('max_memory_restart', '4294967296');
+ vi.stubEnv('exec_mode', 'cluster_mode');
+ vi.stubEnv('watch', 'true');
+
+ await execPm2(['start', '/usr/local/bin/llama-server', '--name', 'portos-llama-server']);
+
+ const [, , spawnOpts] = mockSpawn.mock.calls[0];
+ expect(spawnOpts.env).not.toHaveProperty('max_memory_restart');
+ expect(spawnOpts.env).not.toHaveProperty('exec_mode');
+ expect(spawnOpts.env).not.toHaveProperty('watch');
+ expect(spawnOpts.env.PATH).toBe(process.env.PATH);
+ });
+
+ it('strips them from a caller-supplied env too, which inherits the same keys', async () => {
+ vi.stubEnv('max_memory_restart', '4294967296');
+
+ await execPm2(['jlist'], { env: { ...process.env, PM2_HOME: '/tmp/example-pm2' } });
+
+ const [, , spawnOpts] = mockSpawn.mock.calls[0];
+ expect(spawnOpts.env).not.toHaveProperty('max_memory_restart');
+ expect(spawnOpts.env.PM2_HOME).toBe('/tmp/example-pm2');
+ });
+ });
+
describe('with a custom pm2Home', () => {
it('starts via the PM2 CLI (not the default-daemon Node API) so the process is visible to CLI-based status/log/delete calls targeting the same home', async () => {
const result = await startWithCommand(