pi-llama-switch 1.0.2 → 1.0.3

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/src/switcher.ts CHANGED
@@ -1,9 +1,22 @@
1
1
  import { spawn, execSync, type ChildProcess } from "node:child_process";
2
- import { readFileSync, writeFileSync, existsSync, unlinkSync, createWriteStream } from "node:fs";
3
- import { join } from "node:path";
2
+ import {
3
+ readFileSync,
4
+ writeFileSync,
5
+ existsSync,
6
+ unlinkSync,
7
+ openSync,
8
+ closeSync,
9
+ mkdirSync,
10
+ } from "node:fs";
11
+ import { basename, dirname, join } from "node:path";
4
12
  import { homedir } from "node:os";
5
13
  import { waitForHealth } from "./health.js";
6
- import type { SwitcherConfig, ModelConfig, ServerConfig } from "./config.js";
14
+ import {
15
+ normalizeHostForSocket,
16
+ type SwitcherConfig,
17
+ type ModelConfig,
18
+ type ServerConfig,
19
+ } from "./config.js";
7
20
 
8
21
  const PID_FILENAME = "llama-switch.pid";
9
22
  const LOG_FILENAME = "llama-switch.log";
@@ -30,6 +43,14 @@ export function updateActiveState(modelKey: string, pid: number): void {
30
43
  writePidFile(pid);
31
44
  }
32
45
 
46
+ /**
47
+ * Clears the active model key without touching the running process. Used when
48
+ * the config reload drops the active model but its server is still up.
49
+ */
50
+ export function clearActiveModelKey(): void {
51
+ state.activeModelKey = null;
52
+ }
53
+
33
54
  function getPidPath(): string {
34
55
  return join(homedir(), ".pi", "agent", PID_FILENAME);
35
56
  }
@@ -66,25 +87,121 @@ export function isProcessAlive(pid: number): boolean {
66
87
  }
67
88
  }
68
89
 
69
- export function isLlamaServer(pid: number): boolean {
90
+ /**
91
+ * Boundary-safe check for a token inside a process command line. Matches whole
92
+ * arguments only, so "8080" does not match "18080" and "python3" matches
93
+ * "/usr/bin/python3".
94
+ */
95
+ export function commandLineHasToken(commandLine: string, token: string): boolean {
96
+ if (!token) return false;
97
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
98
+ const re = new RegExp(
99
+ `(?:^|[\\s"'\`=/\\\\])${escaped}(?=$|[\\s"'\`/\\\\])`
100
+ );
101
+ return re.test(commandLine);
102
+ }
103
+
104
+ /**
105
+ * Returns true when the command line contains an explicit `--port` whose last
106
+ * value equals `port`. `-p` is deliberately ignored: in llama-server it is
107
+ * `--prompt`, not the port.
108
+ */
109
+ export function hasPortArg(commandLine: string, port: number): boolean {
110
+ const re = /(?:^|\s)--port(?:=|\s+)(\d+)(?=\s|$)/g;
111
+ let last: string | null = null;
112
+ for (const match of commandLine.matchAll(re)) {
113
+ last = match[1];
114
+ }
115
+ return last !== null && Number(last) === port;
116
+ }
117
+
118
+ const GENERIC_EXECUTABLES =
119
+ /^(?:python(?:\d+(?:\.\d+)*)?(?:\.exe)?|node(?:\.exe)?|uv|uvx|bash|sh|zsh|env)$/i;
120
+
121
+ function matchesConfiguredCommand(commandLine: string, command: string[]): boolean {
122
+ if (command.length === 0) return false;
123
+
124
+ const executable = basename(command[0]);
125
+ if (!commandLineHasToken(commandLine, executable)) return false;
126
+
127
+ if (!GENERIC_EXECUTABLES.test(executable)) {
128
+ return true;
129
+ }
130
+
131
+ // Generic interpreters (python3, node, ...) need a module/script argument to
132
+ // identify the server; matching the interpreter alone would be a false positive.
133
+ const second = command[1];
134
+ if (!second) return false;
135
+ const identifying = second === "-m" ? command[2] : second;
136
+ if (!identifying || identifying.startsWith("-")) return false;
137
+ return commandLineHasToken(commandLine, basename(identifying));
138
+ }
139
+
140
+ /**
141
+ * Returns true when the command line looks like a managed local LLM server:
142
+ * llama-server, a vLLM OpenAI server, or one of the configured commands.
143
+ */
144
+ export function isManagedServerCommand(
145
+ cmdLine: string,
146
+ config?: SwitcherConfig
147
+ ): boolean {
148
+ if (!cmdLine.trim()) return false;
149
+ if (/\bllama-server\b/.test(cmdLine)) return true;
150
+ if (/\bvllm\.entrypoints\.openai\.api_server\b/.test(cmdLine)) return true;
151
+ if (/\bvllm(?:\s+|$).*?\bserve\b/.test(cmdLine)) return true;
152
+
153
+ if (config) {
154
+ for (const model of Object.values(config.models)) {
155
+ if (matchesConfiguredCommand(cmdLine, model.command)) {
156
+ return true;
157
+ }
158
+ }
159
+ }
160
+
161
+ return false;
162
+ }
163
+
164
+ export function isManagedServer(pid: number, config?: SwitcherConfig): boolean {
165
+ if (!Number.isInteger(pid) || pid <= 0) return false;
70
166
  try {
71
- const comm = execSync(`ps -p ${pid} -o comm=`, { encoding: "utf-8" }).trim();
72
- return comm.includes("llama-server");
167
+ const args = execSync(`ps -p ${pid} -o args=`, {
168
+ encoding: "utf-8",
169
+ timeout: 3000,
170
+ }).trim();
171
+ return isManagedServerCommand(args, config);
73
172
  } catch {
74
173
  return false;
75
174
  }
76
175
  }
77
176
 
78
- export function findLlamaServerPid(port: number): number | null {
177
+ /** @deprecated Use isManagedServer instead. */
178
+ export function isLlamaServer(pid: number): boolean {
179
+ return isManagedServer(pid);
180
+ }
181
+
182
+ /**
183
+ * Finds a managed server PID listening on `port`. Scans full command lines so
184
+ * both llama-server and `python3 -m vllm...` processes are discovered.
185
+ */
186
+ export function findServerPid(
187
+ port: number,
188
+ config?: SwitcherConfig
189
+ ): number | null {
79
190
  try {
80
- const output = execSync("pgrep -af llama-server", { encoding: "utf-8", timeout: 3000 }).trim();
81
- if (!output) return null;
191
+ const output = execSync("ps -eo pid=,args=", {
192
+ encoding: "utf-8",
193
+ timeout: 3000,
194
+ });
195
+
82
196
  for (const line of output.split("\n")) {
83
- const match = line.match(/^(\d+)\s/);
197
+ const match = line.match(/^\s*(\d+)\s+(.*)$/);
84
198
  if (!match) continue;
199
+
85
200
  const pid = parseInt(match[1], 10);
86
- if (isNaN(pid)) continue;
87
- if (line.includes(`--port`) && line.includes(String(port))) {
201
+ if (isNaN(pid) || pid === process.pid) continue;
202
+
203
+ const args = match[2];
204
+ if (isManagedServerCommand(args, config) && hasPortArg(args, port)) {
88
205
  return pid;
89
206
  }
90
207
  }
@@ -94,26 +211,39 @@ export function findLlamaServerPid(port: number): number | null {
94
211
  }
95
212
  }
96
213
 
214
+ /**
215
+ * Sends a signal to a detached child's process group where possible, falling
216
+ * back to the single process so vLLM worker children are also terminated.
217
+ */
218
+ function killProcessTree(pid: number, signal: NodeJS.Signals): void {
219
+ try {
220
+ process.kill(-pid, signal);
221
+ } catch {
222
+ try {
223
+ process.kill(pid, signal);
224
+ } catch {
225
+ // Process already dead
226
+ }
227
+ }
228
+ }
229
+
97
230
  export async function stopServer(
98
231
  serverConfig: ServerConfig,
232
+ config?: SwitcherConfig,
99
233
  gracefulTimeout = 10000
100
234
  ): Promise<void> {
101
235
  let pid = state.activePid;
102
236
 
103
- if (!pid || !isProcessAlive(pid)) {
104
- pid = findLlamaServerPid(serverConfig.port);
237
+ if (!pid || !isProcessAlive(pid) || !isManagedServer(pid, config)) {
238
+ pid = findServerPid(serverConfig.port, config);
105
239
  if (pid) {
106
240
  state.activePid = pid;
107
241
  writePidFile(pid);
108
242
  }
109
243
  }
110
244
 
111
- if (pid && isProcessAlive(pid) && isLlamaServer(pid)) {
112
- try {
113
- process.kill(pid, "SIGTERM");
114
- } catch {
115
- // Process already dead
116
- }
245
+ if (pid && isProcessAlive(pid) && isManagedServer(pid, config)) {
246
+ killProcessTree(pid, "SIGTERM");
117
247
 
118
248
  const deadline = Date.now() + gracefulTimeout;
119
249
  while (Date.now() < deadline && isProcessAlive(pid)) {
@@ -121,11 +251,7 @@ export async function stopServer(
121
251
  }
122
252
 
123
253
  if (isProcessAlive(pid)) {
124
- try {
125
- process.kill(pid, "SIGKILL");
126
- } catch {
127
- // Already dead
128
- }
254
+ killProcessTree(pid, "SIGKILL");
129
255
  // Give OS time to reclaim socket after SIGKILL
130
256
  await new Promise((r) => setTimeout(r, 2000));
131
257
  }
@@ -146,6 +272,7 @@ async function waitForPortRelease(
146
272
  ): Promise<void> {
147
273
  const net = await import("node:net");
148
274
  const deadline = Date.now() + timeout * 1000;
275
+ const socketHost = normalizeHostForSocket(host);
149
276
 
150
277
  while (Date.now() < deadline) {
151
278
  const connected = await new Promise<boolean>((resolve) => {
@@ -162,7 +289,7 @@ async function waitForPortRelease(
162
289
  socket.on("error", () => {
163
290
  resolve(false);
164
291
  });
165
- socket.connect(port, host);
292
+ socket.connect(port, socketHost);
166
293
  });
167
294
 
168
295
  if (!connected) return;
@@ -180,58 +307,73 @@ export interface SwitchProgressCallback {
180
307
  onHealthProgress?: (elapsed: number, status: { status: string; error?: string }) => void;
181
308
  }
182
309
 
310
+ function waitForSpawn(child: ChildProcess, command: string): Promise<void> {
311
+ return new Promise<void>((resolve, reject) => {
312
+ const onSpawn = () => {
313
+ cleanup();
314
+ resolve();
315
+ };
316
+ const onError = (err: Error) => {
317
+ cleanup();
318
+ reject(new Error(`Failed to start ${command}: ${err.message}`));
319
+ };
320
+ const cleanup = () => {
321
+ child.off("spawn", onSpawn);
322
+ child.off("error", onError);
323
+ };
324
+ child.once("spawn", onSpawn);
325
+ child.once("error", onError);
326
+ });
327
+ }
328
+
183
329
  export async function switchModel(
184
330
  config: SwitcherConfig,
185
331
  modelKey: string,
186
332
  progress?: SwitchProgressCallback,
187
333
  signal?: AbortSignal
188
334
  ): Promise<void> {
189
- const model = config.models[modelKey];
190
- if (!model) {
335
+ const serverSnapshot: ServerConfig = { ...config.server };
336
+ const loadedModel = config.models[modelKey];
337
+ if (!loadedModel) {
191
338
  throw new Error(
192
339
  `Model '${modelKey}' not found. Available: ${Object.keys(config.models).join(", ")}`
193
340
  );
194
341
  }
342
+ const modelSnapshot: ModelConfig = {
343
+ ...loadedModel,
344
+ command: [...loadedModel.command],
345
+ env: loadedModel.env ? { ...loadedModel.env } : undefined,
346
+ };
195
347
 
196
348
  if (state.isSwitching) {
197
349
  throw new Error("Switch already in progress");
198
350
  }
199
351
 
200
352
  state.isSwitching = true;
353
+ const childAbort = new AbortController();
201
354
  let child: ChildProcess | null = null;
202
355
 
203
356
  try {
204
357
  progress?.onStatusUpdate?.(`Stopping current server...`);
205
- await stopServer(config.server);
358
+ await stopServer(serverSnapshot, config);
206
359
 
207
- progress?.onStatusUpdate?.(`Starting ${model.name}...`);
360
+ progress?.onStatusUpdate?.(`Starting ${modelSnapshot.name}...`);
208
361
  const logPath = getLogPath();
209
- const logStream = createWriteStream(logPath, { flags: "w" });
210
- await new Promise<void>((resolve, reject) => {
211
- logStream.on("open", () => resolve());
212
- logStream.on("error", reject);
213
- });
214
- child = spawn(model.command[0], model.command.slice(1), {
215
- detached: true,
216
- stdio: ["ignore", "ignore", logStream],
217
- env: { ...process.env, ...(model.env ?? {}) },
218
- });
219
-
220
- if (!child.pid) {
221
- throw new Error("Failed to start llama-server: no PID returned");
362
+ mkdirSync(dirname(logPath), { recursive: true });
363
+ const logFd = openSync(logPath, "w");
364
+ try {
365
+ child = spawn(modelSnapshot.command[0], modelSnapshot.command.slice(1), {
366
+ detached: true,
367
+ stdio: ["ignore", "ignore", logFd],
368
+ env: { ...process.env, ...(modelSnapshot.env ?? {}) },
369
+ });
370
+ } finally {
371
+ // The child holds its own duplicate of the descriptor.
372
+ closeSync(logFd);
222
373
  }
223
374
 
224
- child.unref();
225
-
226
- state.activePid = child.pid;
227
- writePidFile(child.pid);
228
-
229
- // Abort health check if child exits unexpectedly
230
- const childAbort = new AbortController();
231
- const combinedSignal = signal
232
- ? AbortSignal.any([signal, childAbort.signal])
233
- : childAbort.signal;
234
-
375
+ // Attach listeners before awaiting spawn so an ENOENT/EACCES 'error' event
376
+ // is always handled and can never crash the host process.
235
377
  child.on("error", (err) => {
236
378
  console.error(`llama-server process error: ${err.message}`);
237
379
  childAbort.abort();
@@ -252,26 +394,43 @@ export async function switchModel(
252
394
  }
253
395
  });
254
396
 
255
- progress?.onStatusUpdate?.(`Waiting for ${model.name} to be ready...`);
397
+ await waitForSpawn(child, modelSnapshot.command[0]);
398
+
399
+ if (!child.pid) {
400
+ throw new Error(
401
+ `Failed to start ${modelSnapshot.command[0]}: no PID returned`
402
+ );
403
+ }
404
+
405
+ child.unref();
406
+
407
+ state.activePid = child.pid;
408
+ writePidFile(child.pid);
409
+
410
+ const combinedSignal = signal
411
+ ? AbortSignal.any([signal, childAbort.signal])
412
+ : childAbort.signal;
413
+
414
+ progress?.onStatusUpdate?.(`Waiting for ${modelSnapshot.name} to be ready...`);
256
415
  await waitForHealth(
257
- config.server,
416
+ serverSnapshot,
258
417
  (elapsed, status) => {
259
418
  progress?.onHealthProgress?.(elapsed, {
260
419
  status: status.status,
261
420
  error: status.error,
262
421
  });
263
422
  progress?.onStatusUpdate?.(
264
- `Loading ${model.name}... ${elapsed}s (${status.status})`
423
+ `Loading ${modelSnapshot.name}... ${elapsed}s (${status.status})`
265
424
  );
266
425
  },
267
426
  combinedSignal
268
427
  );
269
428
 
270
429
  state.activeModelKey = modelKey;
271
- progress?.onStatusUpdate?.(`Switched to ${model.name}`);
430
+ progress?.onStatusUpdate?.(`Switched to ${modelSnapshot.name}`);
272
431
  } catch (err) {
273
- if (child) {
274
- try { child.kill("SIGKILL"); } catch {}
432
+ if (child?.pid) {
433
+ killProcessTree(child.pid, "SIGKILL");
275
434
  }
276
435
  state.activeModelKey = null;
277
436
  state.activePid = null;