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/LICENSE +21 -21
- package/README.md +218 -216
- package/examples/model-switcher-vllm.json +65 -61
- package/examples/model-switcher.json +53 -53
- package/package.json +44 -41
- package/src/config.ts +170 -123
- package/src/health.ts +53 -9
- package/src/index.ts +273 -63
- package/src/provider.ts +76 -2
- package/src/switcher.ts +219 -60
- package/test/fixes.test.cjs +636 -0
- package/tsconfig.json +17 -17
package/src/index.ts
CHANGED
|
@@ -2,36 +2,67 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
2
2
|
import { Type } from "@sinclair/typebox";
|
|
3
3
|
import { readFileSync } from "node:fs";
|
|
4
4
|
import { execSync } from "node:child_process";
|
|
5
|
-
import { join } from "node:path";
|
|
5
|
+
import { basename, join } from "node:path";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
formatServerUrl,
|
|
9
|
+
loadConfig,
|
|
10
|
+
type SwitcherConfig,
|
|
11
|
+
} from "./config.js";
|
|
8
12
|
import {
|
|
9
13
|
getState,
|
|
10
14
|
readPidFile,
|
|
11
15
|
writePidFile,
|
|
12
16
|
isProcessAlive,
|
|
13
|
-
|
|
14
|
-
|
|
17
|
+
isManagedServer,
|
|
18
|
+
findServerPid,
|
|
15
19
|
switchModel,
|
|
16
20
|
disconnectState,
|
|
17
21
|
deletePidFile,
|
|
18
22
|
updateActiveState,
|
|
23
|
+
clearActiveModelKey,
|
|
24
|
+
commandLineHasToken,
|
|
19
25
|
} from "./switcher.js";
|
|
20
26
|
import { checkHealth } from "./health.js";
|
|
21
|
-
import {
|
|
27
|
+
import {
|
|
28
|
+
buildProviderModels,
|
|
29
|
+
findFlagValue,
|
|
30
|
+
resolveApiModelId,
|
|
31
|
+
} from "./provider.js";
|
|
22
32
|
|
|
23
33
|
const PROVIDER_ID = "llama-local";
|
|
24
34
|
|
|
35
|
+
const SECONDARY_MODEL_FLAGS = [
|
|
36
|
+
"--mmproj",
|
|
37
|
+
"--mmproj-url",
|
|
38
|
+
"--lora",
|
|
39
|
+
"--lora-scaled",
|
|
40
|
+
"--draft",
|
|
41
|
+
"-md",
|
|
42
|
+
"--model-draft",
|
|
43
|
+
"--control-vector",
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
const DISTINGUISHING_FLAGS = [
|
|
47
|
+
"--mmproj",
|
|
48
|
+
"--ctx-size",
|
|
49
|
+
"--max-model-len",
|
|
50
|
+
"--alias",
|
|
51
|
+
"--served-model-name",
|
|
52
|
+
];
|
|
53
|
+
|
|
25
54
|
export default async function (pi: ExtensionAPI) {
|
|
26
|
-
|
|
55
|
+
const loadedConfig = loadConfig();
|
|
27
56
|
|
|
28
|
-
if (!
|
|
57
|
+
if (!loadedConfig) {
|
|
29
58
|
console.warn(
|
|
30
59
|
"[pi-llama-switch] No config found at ~/.pi/agent/model-switcher.json"
|
|
31
60
|
);
|
|
32
61
|
return;
|
|
33
62
|
}
|
|
34
63
|
|
|
64
|
+
let config: SwitcherConfig = loadedConfig;
|
|
65
|
+
|
|
35
66
|
// Register provider from default model
|
|
36
67
|
registerProvider(pi, config, config.defaultModel);
|
|
37
68
|
|
|
@@ -54,7 +85,9 @@ export default async function (pi: ExtensionAPI) {
|
|
|
54
85
|
}
|
|
55
86
|
|
|
56
87
|
if (subcommand === "reload") {
|
|
57
|
-
return handleReload(pi,
|
|
88
|
+
return await handleReload(pi, ctx, (next) => {
|
|
89
|
+
config = next;
|
|
90
|
+
});
|
|
58
91
|
}
|
|
59
92
|
|
|
60
93
|
if (subcommand === "logs") {
|
|
@@ -104,11 +137,13 @@ export default async function (pi: ExtensionAPI) {
|
|
|
104
137
|
),
|
|
105
138
|
}),
|
|
106
139
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
140
|
+
const snapshot = config;
|
|
107
141
|
const modelKey = params.model;
|
|
108
142
|
const dryRun = params.dryRun ?? false;
|
|
143
|
+
const model = snapshot.models[modelKey];
|
|
109
144
|
|
|
110
|
-
if (!
|
|
111
|
-
const available = Object.keys(
|
|
145
|
+
if (!model) {
|
|
146
|
+
const available = Object.keys(snapshot.models).join(", ");
|
|
112
147
|
return {
|
|
113
148
|
content: [
|
|
114
149
|
{
|
|
@@ -116,12 +151,11 @@ export default async function (pi: ExtensionAPI) {
|
|
|
116
151
|
text: `Model '${modelKey}' not found. Available: ${available}`,
|
|
117
152
|
},
|
|
118
153
|
],
|
|
119
|
-
details: { error: "model_not_found", available: Object.keys(
|
|
154
|
+
details: { error: "model_not_found", available: Object.keys(snapshot.models) },
|
|
120
155
|
};
|
|
121
156
|
}
|
|
122
157
|
|
|
123
158
|
if (dryRun) {
|
|
124
|
-
const model = config.models[modelKey];
|
|
125
159
|
return {
|
|
126
160
|
content: [
|
|
127
161
|
{
|
|
@@ -134,25 +168,27 @@ export default async function (pi: ExtensionAPI) {
|
|
|
134
168
|
}
|
|
135
169
|
|
|
136
170
|
onUpdate?.({
|
|
137
|
-
content: [{ type: "text", text: `Switching to ${
|
|
171
|
+
content: [{ type: "text", text: `Switching to ${model.name}...` }],
|
|
138
172
|
details: { phase: "switching", model: modelKey },
|
|
139
173
|
});
|
|
140
174
|
|
|
141
175
|
try {
|
|
142
|
-
await switchModel(
|
|
176
|
+
await switchModel(snapshot, modelKey, {
|
|
143
177
|
onStatusUpdate: (msg) => {
|
|
144
178
|
onUpdate?.({ content: [{ type: "text", text: msg }], details: { phase: "switching", model: modelKey } });
|
|
145
179
|
},
|
|
146
180
|
}, signal);
|
|
147
181
|
|
|
148
|
-
|
|
182
|
+
const selected = await activateModel(pi, snapshot, modelKey, ctx);
|
|
183
|
+
const selectionNote = selected
|
|
184
|
+
? ""
|
|
185
|
+
: "\nThe server switched and the provider was updated. If Pi did not select the new model automatically, choose it via /model.";
|
|
149
186
|
|
|
150
|
-
const model = config.models[modelKey];
|
|
151
187
|
return {
|
|
152
188
|
content: [
|
|
153
189
|
{
|
|
154
190
|
type: "text",
|
|
155
|
-
text: `Switched to ${model.name} (${model.description}). Context window: ${model.contextWindow} tokens
|
|
191
|
+
text: `Switched to ${model.name} (${model.description}). Context window: ${model.contextWindow} tokens.${selectionNote}`,
|
|
156
192
|
},
|
|
157
193
|
],
|
|
158
194
|
details: {
|
|
@@ -160,6 +196,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
160
196
|
model: modelKey,
|
|
161
197
|
name: model.name,
|
|
162
198
|
contextWindow: model.contextWindow,
|
|
199
|
+
selectedModel: selected,
|
|
163
200
|
},
|
|
164
201
|
} as any;
|
|
165
202
|
} catch (err: any) {
|
|
@@ -180,21 +217,18 @@ export default async function (pi: ExtensionAPI) {
|
|
|
180
217
|
// session_start: reconnect to existing server
|
|
181
218
|
pi.on("session_start", async (_event, ctx) => {
|
|
182
219
|
let pid = readPidFile();
|
|
183
|
-
if (!pid || !isProcessAlive(pid) || !
|
|
184
|
-
pid =
|
|
220
|
+
if (!pid || !isProcessAlive(pid) || !isManagedServer(pid, config)) {
|
|
221
|
+
pid = findServerPid(config.server.port, config);
|
|
185
222
|
if (pid) {
|
|
186
223
|
writePidFile(pid);
|
|
187
224
|
}
|
|
188
225
|
}
|
|
189
|
-
if (pid && isProcessAlive(pid) &&
|
|
226
|
+
if (pid && isProcessAlive(pid) && isManagedServer(pid, config)) {
|
|
190
227
|
const alive = await checkHealth(config.server.host, config.server.port);
|
|
191
228
|
if (alive) {
|
|
192
|
-
const modelKey = detectModelFromPid(config, pid);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
registerProvider(pi, config, activeKey);
|
|
196
|
-
const model = config.models[activeKey];
|
|
197
|
-
ctx.ui.setStatus("llama-switch", `⚡ ${model?.name ?? activeKey}`);
|
|
229
|
+
const modelKey = detectModelFromPid(config, pid) ?? config.defaultModel;
|
|
230
|
+
updateActiveState(modelKey, pid);
|
|
231
|
+
await activateModel(pi, config, modelKey, ctx);
|
|
198
232
|
return;
|
|
199
233
|
}
|
|
200
234
|
}
|
|
@@ -230,28 +264,57 @@ function registerProvider(
|
|
|
230
264
|
config: SwitcherConfig,
|
|
231
265
|
modelKey: string
|
|
232
266
|
): void {
|
|
267
|
+
const targetModel = config.models[modelKey];
|
|
268
|
+
if (!targetModel) return;
|
|
269
|
+
|
|
233
270
|
const models = buildProviderModels(config);
|
|
234
|
-
const
|
|
271
|
+
const activeApiId = resolveApiModelId(modelKey, targetModel);
|
|
272
|
+
const activeModel = models.find((m) => m.id === activeApiId);
|
|
235
273
|
if (!activeModel) return;
|
|
236
274
|
|
|
237
275
|
pi.registerProvider(PROVIDER_ID, {
|
|
238
|
-
baseUrl:
|
|
276
|
+
baseUrl: formatServerUrl(config.server.host, config.server.port, "/v1"),
|
|
239
277
|
apiKey: "no-key",
|
|
240
278
|
api: "openai-completions",
|
|
241
|
-
models
|
|
242
|
-
...m,
|
|
243
|
-
reasoning: m.id === modelKey ? (activeModel.reasoning ?? false) : false,
|
|
244
|
-
})),
|
|
279
|
+
models,
|
|
245
280
|
});
|
|
246
281
|
}
|
|
247
282
|
|
|
283
|
+
export async function activateModel(
|
|
284
|
+
pi: ExtensionAPI,
|
|
285
|
+
config: SwitcherConfig,
|
|
286
|
+
modelKey: string,
|
|
287
|
+
ctx?: any
|
|
288
|
+
): Promise<boolean> {
|
|
289
|
+
registerProvider(pi, config, modelKey);
|
|
290
|
+
|
|
291
|
+
const model = config.models[modelKey];
|
|
292
|
+
if (!model) return false;
|
|
293
|
+
|
|
294
|
+
const apiModelId = resolveApiModelId(modelKey, model);
|
|
295
|
+
ctx?.ui?.setStatus?.("llama-switch", `⚡ ${model.name}`);
|
|
296
|
+
|
|
297
|
+
if (ctx?.modelRegistry?.find && typeof pi.setModel === "function") {
|
|
298
|
+
const registered = ctx.modelRegistry.find(PROVIDER_ID, apiModelId);
|
|
299
|
+
if (!registered) return false;
|
|
300
|
+
try {
|
|
301
|
+
return await pi.setModel(registered);
|
|
302
|
+
} catch {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
|
|
248
310
|
async function handleInteractiveSwitch(
|
|
249
311
|
pi: ExtensionAPI,
|
|
250
312
|
config: SwitcherConfig,
|
|
251
313
|
ctx: any
|
|
252
314
|
): Promise<void> {
|
|
315
|
+
const snapshot = config;
|
|
253
316
|
const state = getState();
|
|
254
|
-
const entries = Object.entries(
|
|
317
|
+
const entries = Object.entries(snapshot.models).map(([key, model]) => {
|
|
255
318
|
const isCurrent = state.activeModelKey === key;
|
|
256
319
|
const vision = model.vision ? " [vision]" : "";
|
|
257
320
|
const tags = model.tags?.length ? ` (${model.tags.join(", ")})` : "";
|
|
@@ -273,22 +336,27 @@ async function handleInteractiveSwitch(
|
|
|
273
336
|
if (!selectedEntry) return;
|
|
274
337
|
|
|
275
338
|
const modelKey = selectedEntry.value;
|
|
339
|
+
const model = snapshot.models[modelKey];
|
|
340
|
+
if (!model) return;
|
|
276
341
|
|
|
277
342
|
if (state.activeModelKey === modelKey) {
|
|
278
|
-
ctx.ui.notify(`Already using ${
|
|
343
|
+
ctx.ui.notify(`Already using ${model.name}`, "info");
|
|
279
344
|
return;
|
|
280
345
|
}
|
|
281
346
|
|
|
282
347
|
try {
|
|
283
|
-
ctx.ui.notify(`Switching to ${
|
|
284
|
-
await switchModel(
|
|
348
|
+
ctx.ui.notify(`Switching to ${model.name}...`, "info");
|
|
349
|
+
await switchModel(snapshot, modelKey, {
|
|
285
350
|
onStatusUpdate: (msg) => {
|
|
286
351
|
ctx.ui.notify(msg, "info");
|
|
287
352
|
},
|
|
288
353
|
});
|
|
289
354
|
|
|
290
|
-
|
|
291
|
-
ctx.ui.notify(
|
|
355
|
+
const selected = await activateModel(pi, snapshot, modelKey, ctx);
|
|
356
|
+
ctx.ui.notify(
|
|
357
|
+
`Switched to ${model.name}${selected ? "" : " — select it via /model if needed"}`,
|
|
358
|
+
"info"
|
|
359
|
+
);
|
|
292
360
|
} catch (err: any) {
|
|
293
361
|
ctx.ui.notify(`Switch failed: ${err.message}`, "error");
|
|
294
362
|
}
|
|
@@ -300,22 +368,32 @@ async function handleDirectSwitch(
|
|
|
300
368
|
modelKey: string,
|
|
301
369
|
ctx: any
|
|
302
370
|
): Promise<void> {
|
|
371
|
+
const snapshot = config;
|
|
303
372
|
const state = getState();
|
|
373
|
+
const model = snapshot.models[modelKey];
|
|
374
|
+
if (!model) {
|
|
375
|
+
ctx.ui.notify(`Unknown model: '${modelKey}'`, "error");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
304
379
|
if (state.activeModelKey === modelKey) {
|
|
305
|
-
ctx.ui.notify(`Already using ${
|
|
380
|
+
ctx.ui.notify(`Already using ${model.name}`, "info");
|
|
306
381
|
return;
|
|
307
382
|
}
|
|
308
383
|
|
|
309
384
|
try {
|
|
310
|
-
ctx.ui.notify(`Switching to ${
|
|
311
|
-
await switchModel(
|
|
385
|
+
ctx.ui.notify(`Switching to ${model.name}...`, "info");
|
|
386
|
+
await switchModel(snapshot, modelKey, {
|
|
312
387
|
onStatusUpdate: (msg) => {
|
|
313
388
|
ctx.ui.notify(msg, "info");
|
|
314
389
|
},
|
|
315
390
|
});
|
|
316
391
|
|
|
317
|
-
|
|
318
|
-
ctx.ui.notify(
|
|
392
|
+
const selected = await activateModel(pi, snapshot, modelKey, ctx);
|
|
393
|
+
ctx.ui.notify(
|
|
394
|
+
`Switched to ${model.name}${selected ? "" : " — select it via /model if needed"}`,
|
|
395
|
+
"info"
|
|
396
|
+
);
|
|
319
397
|
} catch (err: any) {
|
|
320
398
|
ctx.ui.notify(`Switch failed: ${err.message}`, "error");
|
|
321
399
|
}
|
|
@@ -337,15 +415,25 @@ function handleList(config: SwitcherConfig, ctx: any): void {
|
|
|
337
415
|
);
|
|
338
416
|
}
|
|
339
417
|
|
|
340
|
-
function handleStatus(config: SwitcherConfig, ctx: any): void {
|
|
418
|
+
export function handleStatus(config: SwitcherConfig, ctx: any): void {
|
|
341
419
|
const state = getState();
|
|
342
|
-
|
|
343
|
-
|
|
420
|
+
const model = state.activeModelKey
|
|
421
|
+
? config.models[state.activeModelKey]
|
|
422
|
+
: undefined;
|
|
423
|
+
|
|
424
|
+
if (model) {
|
|
344
425
|
ctx.ui.notify(
|
|
345
426
|
`Active: ${model.name} (${model.description})\n` +
|
|
346
427
|
`Context: ${model.contextWindow} tokens\n` +
|
|
347
428
|
`PID: ${state.activePid ?? "unknown"}\n` +
|
|
348
|
-
`Server:
|
|
429
|
+
`Server: ${formatServerUrl(config.server.host, config.server.port)}`,
|
|
430
|
+
"info"
|
|
431
|
+
);
|
|
432
|
+
} else if (state.activeModelKey || state.activePid) {
|
|
433
|
+
ctx.ui.notify(
|
|
434
|
+
`Active: ${state.activeModelKey ?? "unlisted model"} (not in current config)\n` +
|
|
435
|
+
`PID: ${state.activePid ?? "unknown"}\n` +
|
|
436
|
+
`Server: ${formatServerUrl(config.server.host, config.server.port)}`,
|
|
349
437
|
"info"
|
|
350
438
|
);
|
|
351
439
|
} else {
|
|
@@ -353,19 +441,59 @@ function handleStatus(config: SwitcherConfig, ctx: any): void {
|
|
|
353
441
|
}
|
|
354
442
|
}
|
|
355
443
|
|
|
356
|
-
function handleReload(
|
|
357
|
-
|
|
444
|
+
export async function handleReload(
|
|
445
|
+
pi: ExtensionAPI,
|
|
446
|
+
ctx: any,
|
|
447
|
+
setConfig: (next: SwitcherConfig) => void
|
|
448
|
+
): Promise<void> {
|
|
449
|
+
if (getState().isSwitching) {
|
|
450
|
+
ctx.ui.notify(
|
|
451
|
+
"Cannot reload config while a model switch is in progress",
|
|
452
|
+
"error"
|
|
453
|
+
);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
let newConfig: SwitcherConfig | null;
|
|
458
|
+
try {
|
|
459
|
+
newConfig = loadConfig();
|
|
460
|
+
} catch (err: any) {
|
|
461
|
+
ctx.ui.notify(`Failed to reload config: ${err.message}`, "error");
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
|
|
358
465
|
if (!newConfig) {
|
|
359
466
|
ctx.ui.notify("Failed to reload config: file not found", "error");
|
|
360
467
|
return;
|
|
361
468
|
}
|
|
362
|
-
|
|
469
|
+
|
|
470
|
+
setConfig(newConfig);
|
|
363
471
|
const state = getState();
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
472
|
+
const modelCount = Object.keys(newConfig.models).length;
|
|
473
|
+
|
|
474
|
+
if (state.activeModelKey && !newConfig.models[state.activeModelKey]) {
|
|
475
|
+
const droppedKey = state.activeModelKey;
|
|
476
|
+
clearActiveModelKey();
|
|
477
|
+
|
|
478
|
+
if (newConfig.defaultModel && newConfig.models[newConfig.defaultModel]) {
|
|
479
|
+
registerProvider(pi, newConfig, newConfig.defaultModel);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
ctx.ui.setStatus("llama-switch", "⚠ unlisted model running");
|
|
483
|
+
ctx.ui.notify(
|
|
484
|
+
`Reloaded config: ${modelCount} models. Active model '${droppedKey}' was removed; the current server stays running until the next /switch.`,
|
|
485
|
+
"warning"
|
|
486
|
+
);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if (state.activeModelKey) {
|
|
491
|
+
await activateModel(pi, newConfig, state.activeModelKey, ctx);
|
|
492
|
+
} else if (newConfig.defaultModel && newConfig.models[newConfig.defaultModel]) {
|
|
493
|
+
registerProvider(pi, newConfig, newConfig.defaultModel);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
ctx.ui.notify(`Reloaded config: ${modelCount} models`, "info");
|
|
369
497
|
}
|
|
370
498
|
|
|
371
499
|
function handleLogs(ctx: any): void {
|
|
@@ -380,22 +508,104 @@ function handleLogs(ctx: any): void {
|
|
|
380
508
|
}
|
|
381
509
|
}
|
|
382
510
|
|
|
511
|
+
/**
|
|
512
|
+
* Extracts the primary model identifier from a configured command. Secondary
|
|
513
|
+
* artifacts (--mmproj, --draft, ...) are explicitly skipped so they cannot be
|
|
514
|
+
* mistaken for the main model.
|
|
515
|
+
*/
|
|
516
|
+
export function extractModelMatchTokens(command: string[]): string[] {
|
|
517
|
+
const tokens: string[] = [];
|
|
518
|
+
|
|
519
|
+
const servedName = findFlagValue(command, ["--served-model-name"]);
|
|
520
|
+
if (servedName) tokens.push(servedName);
|
|
521
|
+
|
|
522
|
+
// `python3 -m <module>` uses -m for the module, not the model.
|
|
523
|
+
const pythonModuleFlag =
|
|
524
|
+
command[1] === "-m" && /python/i.test(basename(command[0]));
|
|
525
|
+
const modelFlag = findFlagValue(
|
|
526
|
+
command,
|
|
527
|
+
pythonModuleFlag ? ["--model"] : ["-m", "--model"]
|
|
528
|
+
);
|
|
529
|
+
if (modelFlag) tokens.push(modelFlag);
|
|
530
|
+
|
|
531
|
+
const hfRepo = findFlagValue(command, ["--hf-repo", "-hf"]);
|
|
532
|
+
if (hfRepo) tokens.push(hfRepo);
|
|
533
|
+
|
|
534
|
+
if (tokens.length === 0) {
|
|
535
|
+
const serveIndex = command.indexOf("serve");
|
|
536
|
+
if (serveIndex !== -1) {
|
|
537
|
+
const positional = command[serveIndex + 1];
|
|
538
|
+
if (positional && !positional.startsWith("-")) {
|
|
539
|
+
tokens.push(positional);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (tokens.length === 0) {
|
|
545
|
+
for (let i = 0; i < command.length; i++) {
|
|
546
|
+
const arg = command[i];
|
|
547
|
+
if (SECONDARY_MODEL_FLAGS.includes(arg)) {
|
|
548
|
+
i++;
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
if (SECONDARY_MODEL_FLAGS.some((flag) => arg.startsWith(`${flag}=`))) {
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
if (arg.toLowerCase().endsWith(".gguf")) {
|
|
555
|
+
tokens.push(arg);
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
return tokens;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Identifies which configured model a running process serves. Models sharing a
|
|
566
|
+
* primary model file are disambiguated by secondary flags (--mmproj, --ctx-size,
|
|
567
|
+
* --max-model-len, --alias, --served-model-name).
|
|
568
|
+
*/
|
|
569
|
+
export function detectModelFromArgs(
|
|
570
|
+
config: SwitcherConfig,
|
|
571
|
+
procArgs: string
|
|
572
|
+
): string | null {
|
|
573
|
+
let best: { key: string; score: number } | null = null;
|
|
574
|
+
|
|
575
|
+
for (const [key, model] of Object.entries(config.models)) {
|
|
576
|
+
const tokens = extractModelMatchTokens(model.command);
|
|
577
|
+
if (tokens.length === 0) continue;
|
|
578
|
+
if (!tokens.some((token) => commandLineHasToken(procArgs, token))) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
let score = 0;
|
|
583
|
+
for (const flag of DISTINGUISHING_FLAGS) {
|
|
584
|
+
const value = findFlagValue(model.command, [flag]);
|
|
585
|
+
if (value && commandLineHasToken(procArgs, value)) {
|
|
586
|
+
score++;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (!best || score > best.score) {
|
|
591
|
+
best = { key, score };
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return best?.key ?? null;
|
|
596
|
+
}
|
|
597
|
+
|
|
383
598
|
function detectModelFromPid(config: SwitcherConfig, pid: number): string | null {
|
|
384
599
|
try {
|
|
385
600
|
const args = execSync(`ps -p ${pid} -o args=`, {
|
|
386
601
|
encoding: "utf-8",
|
|
387
|
-
timeout:
|
|
602
|
+
timeout: 3000,
|
|
388
603
|
}).trim();
|
|
389
604
|
|
|
390
|
-
|
|
391
|
-
const ggufArg = model.command.find((arg) => arg.endsWith(".gguf"));
|
|
392
|
-
if (ggufArg && args.includes(ggufArg)) {
|
|
393
|
-
return key;
|
|
394
|
-
}
|
|
395
|
-
}
|
|
605
|
+
return detectModelFromArgs(config, args);
|
|
396
606
|
} catch {
|
|
397
607
|
// ps not available or other error
|
|
398
608
|
}
|
|
399
609
|
|
|
400
|
-
return
|
|
610
|
+
return null;
|
|
401
611
|
}
|
package/src/provider.ts
CHANGED
|
@@ -10,11 +10,85 @@ export interface ProviderModel {
|
|
|
10
10
|
maxTokens: number;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Finds the value of a CLI flag, supporting both `--flag value` and
|
|
15
|
+
* `--flag=value` forms.
|
|
16
|
+
*/
|
|
17
|
+
export function findFlagValue(args: string[], names: string[]): string | undefined {
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
const arg = args[i];
|
|
20
|
+
for (const name of names) {
|
|
21
|
+
if (arg === name) {
|
|
22
|
+
const next = args[i + 1];
|
|
23
|
+
if (next !== undefined && !next.startsWith("-")) {
|
|
24
|
+
return next;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const prefix = `${name}=`;
|
|
28
|
+
if (arg.startsWith(prefix)) {
|
|
29
|
+
const value = arg.slice(prefix.length);
|
|
30
|
+
if (value.length > 0) {
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isVllmCommand(command: string[]): boolean {
|
|
40
|
+
if (command.some((arg) => arg.includes("vllm.entrypoints.openai.api_server"))) {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
const serveIndex = command.indexOf("serve");
|
|
44
|
+
if (serveIndex === -1) return false;
|
|
45
|
+
return command
|
|
46
|
+
.slice(0, serveIndex)
|
|
47
|
+
.some((arg) => arg === "vllm" || arg.replace(/\\/g, "/").endsWith("/vllm"));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function vllmModelId(command: string[]): string | undefined {
|
|
51
|
+
const flagValue = findFlagValue(command, ["--model"]);
|
|
52
|
+
if (flagValue) return flagValue;
|
|
53
|
+
|
|
54
|
+
const serveIndex = command.indexOf("serve");
|
|
55
|
+
if (serveIndex === -1) return undefined;
|
|
56
|
+
const positional = command[serveIndex + 1];
|
|
57
|
+
if (positional && !positional.startsWith("-")) {
|
|
58
|
+
return positional;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolves the model ID sent in OpenAI API requests. Backends may serve a
|
|
65
|
+
* different ID than the config key: llama-server uses `--alias`, vLLM uses
|
|
66
|
+
* `--served-model-name`, and both accept an explicit `modelId` override.
|
|
67
|
+
*/
|
|
68
|
+
export function resolveApiModelId(key: string, model: ModelConfig): string {
|
|
69
|
+
if (model.modelId) {
|
|
70
|
+
return model.modelId;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const servedName = findFlagValue(model.command, ["--served-model-name"]);
|
|
74
|
+
if (servedName) return servedName;
|
|
75
|
+
|
|
76
|
+
const alias = findFlagValue(model.command, ["--alias", "-a"]);
|
|
77
|
+
if (alias) return alias;
|
|
78
|
+
|
|
79
|
+
if (isVllmCommand(model.command)) {
|
|
80
|
+
const modelId = vllmModelId(model.command);
|
|
81
|
+
if (modelId) return modelId;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return key;
|
|
85
|
+
}
|
|
86
|
+
|
|
13
87
|
export function buildProviderModels(
|
|
14
88
|
config: SwitcherConfig
|
|
15
89
|
): ProviderModel[] {
|
|
16
90
|
return Object.entries(config.models).map(([key, model]) => ({
|
|
17
|
-
id: key,
|
|
91
|
+
id: resolveApiModelId(key, model),
|
|
18
92
|
name: model.name,
|
|
19
93
|
reasoning: model.tags?.includes("reasoning") ?? false,
|
|
20
94
|
input: model.vision ? ["text", "image"] : ["text"],
|
|
@@ -32,7 +106,7 @@ export function getModelForProvider(
|
|
|
32
106
|
if (!model) return null;
|
|
33
107
|
|
|
34
108
|
return {
|
|
35
|
-
id: modelKey,
|
|
109
|
+
id: resolveApiModelId(modelKey, model),
|
|
36
110
|
name: model.name,
|
|
37
111
|
reasoning: model.tags?.includes("reasoning") ?? false,
|
|
38
112
|
input: model.vision ? ["text", "image"] : ["text"],
|