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.
@@ -1,53 +1,53 @@
1
- {
2
- "server": {
3
- "host": "127.0.0.1",
4
- "port": 8080,
5
- "healthTimeout": 60,
6
- "portReleaseTimeout": 15
7
- },
8
- "defaultModel": "qwen",
9
- "models": {
10
- "qwen": {
11
- "name": "Qwen3.6 35B-A3B",
12
- "description": "Coding/Reasoning",
13
- "env": { "GGML_OP_OFFLOAD_MIN_BATCH": "64" },
14
- "command": [
15
- "~/llama.cpp/llama-server",
16
- "-m", "~/models/qwen/Qwen3.6-35B-A3B.gguf",
17
- "-ngl", "999",
18
- "--flash-attn", "on",
19
- "--cache-type-k", "q8_0",
20
- "--cache-type-v", "q8_0",
21
- "--ctx-size", "8192",
22
- "--parallel", "1",
23
- "--host", "127.0.0.1",
24
- "--port", "8080"
25
- ],
26
- "vision": false,
27
- "contextWindow": 8192,
28
- "maxTokens": 4096,
29
- "tags": ["coding", "reasoning"]
30
- },
31
- "gemma4b": {
32
- "name": "Gemma 4 E4B",
33
- "description": "Fast/Vision/Audio",
34
- "command": [
35
- "~/llama.cpp/llama-server",
36
- "-m", "~/models/gemma/gemma-4-E4B.gguf",
37
- "--mmproj", "~/models/gemma/mmproj.gguf",
38
- "-ngl", "99",
39
- "--flash-attn", "on",
40
- "--cache-type-k", "q8_0",
41
- "--cache-type-v", "q8_0",
42
- "--ctx-size", "131072",
43
- "--parallel", "1",
44
- "--host", "127.0.0.1",
45
- "--port", "8080"
46
- ],
47
- "vision": true,
48
- "contextWindow": 131072,
49
- "maxTokens": 4096,
50
- "tags": ["fast", "vision", "audio"]
51
- }
52
- }
53
- }
1
+ {
2
+ "server": {
3
+ "host": "127.0.0.1",
4
+ "port": 8080,
5
+ "healthTimeout": 60,
6
+ "portReleaseTimeout": 15
7
+ },
8
+ "defaultModel": "qwen",
9
+ "models": {
10
+ "qwen": {
11
+ "name": "Qwen3.6 35B-A3B",
12
+ "description": "Coding/Reasoning",
13
+ "env": { "GGML_OP_OFFLOAD_MIN_BATCH": "64" },
14
+ "command": [
15
+ "~/llama.cpp/llama-server",
16
+ "-m", "~/models/qwen/Qwen3.6-35B-A3B.gguf",
17
+ "-ngl", "999",
18
+ "--flash-attn", "on",
19
+ "--cache-type-k", "q8_0",
20
+ "--cache-type-v", "q8_0",
21
+ "--ctx-size", "8192",
22
+ "--parallel", "1",
23
+ "--host", "127.0.0.1",
24
+ "--port", "8080"
25
+ ],
26
+ "vision": false,
27
+ "contextWindow": 8192,
28
+ "maxTokens": 4096,
29
+ "tags": ["coding", "reasoning"]
30
+ },
31
+ "gemma4b": {
32
+ "name": "Gemma 4 E4B",
33
+ "description": "Fast/Vision/Audio",
34
+ "command": [
35
+ "~/llama.cpp/llama-server",
36
+ "-m", "~/models/gemma/gemma-4-E4B.gguf",
37
+ "--mmproj", "~/models/gemma/mmproj.gguf",
38
+ "-ngl", "99",
39
+ "--flash-attn", "on",
40
+ "--cache-type-k", "q8_0",
41
+ "--cache-type-v", "q8_0",
42
+ "--ctx-size", "131072",
43
+ "--parallel", "1",
44
+ "--host", "127.0.0.1",
45
+ "--port", "8080"
46
+ ],
47
+ "vision": true,
48
+ "contextWindow": 131072,
49
+ "maxTokens": 4096,
50
+ "tags": ["fast", "vision", "audio"]
51
+ }
52
+ }
53
+ }
package/package.json CHANGED
@@ -1,41 +1,44 @@
1
- {
2
- "name": "pi-llama-switch",
3
- "version": "1.0.2",
4
- "description": "Restart llama-server with different model configurations. For single-model setups where models need different flags (context size, vision projector, sampling params).",
5
- "keywords": [
6
- "pi",
7
- "pi-package",
8
- "pi-extension",
9
- "llama",
10
- "llama-cpp",
11
- "vllm",
12
- "local-llm",
13
- "model-switch",
14
- "gpu",
15
- "vram"
16
- ],
17
- "author": "Carlos Duplar",
18
- "license": "MIT",
19
- "repository": {
20
- "type": "git",
21
- "url": "git+https://github.com/carlosduplar/pi-llama-switch.git"
22
- },
23
- "homepage": "https://github.com/carlosduplar/pi-llama-switch#readme",
24
- "bugs": {
25
- "url": "https://github.com/carlosduplar/pi-llama-switch/issues"
26
- },
27
- "pi": {
28
- "extensions": [
29
- "./src/index.ts"
30
- ]
31
- },
32
- "peerDependencies": {
33
- "@earendil-works/pi-coding-agent": "*"
34
- },
35
- "dependencies": {
36
- "@sinclair/typebox": "^0.34.49"
37
- },
38
- "devDependencies": {
39
- "typescript": "^5.9.3"
40
- }
41
- }
1
+ {
2
+ "name": "pi-llama-switch",
3
+ "version": "1.0.3",
4
+ "description": "Restart llama-server with different model configurations. For single-model setups where models need different flags (context size, vision projector, sampling params).",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "llama",
10
+ "llama-cpp",
11
+ "vllm",
12
+ "local-llm",
13
+ "model-switch",
14
+ "gpu",
15
+ "vram"
16
+ ],
17
+ "author": "Carlos Duplar",
18
+ "license": "MIT",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/carlosduplar/pi-llama-switch.git"
22
+ },
23
+ "homepage": "https://github.com/carlosduplar/pi-llama-switch#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/carlosduplar/pi-llama-switch/issues"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./src/index.ts"
30
+ ]
31
+ },
32
+ "peerDependencies": {
33
+ "@earendil-works/pi-coding-agent": "*"
34
+ },
35
+ "dependencies": {
36
+ "@sinclair/typebox": "^0.34.49"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.9.3"
40
+ },
41
+ "scripts": {
42
+ "test": "tsc --module nodenext --moduleResolution nodenext --outDir .test-dist --declaration false --sourceMap false && node --test test/fixes.test.cjs"
43
+ }
44
+ }
package/src/config.ts CHANGED
@@ -1,123 +1,170 @@
1
- import { readFileSync, existsSync } from "node:fs";
2
- import { resolve, join } from "node:path";
3
- import { homedir } from "node:os";
4
-
5
- export interface ServerConfig {
6
- host: string;
7
- port: number;
8
- healthTimeout: number;
9
- portReleaseTimeout: number;
10
- }
11
-
12
- export interface ModelConfig {
13
- name: string;
14
- description: string;
15
- command: string[];
16
- env?: Record<string, string>;
17
- vision: boolean;
18
- contextWindow: number;
19
- maxTokens: number;
20
- tags: string[];
21
- }
22
-
23
- export interface SwitcherConfig {
24
- server: ServerConfig;
25
- defaultModel: string;
26
- models: Record<string, ModelConfig>;
27
- }
28
-
29
- const CONFIG_FILENAME = "model-switcher.json";
30
-
31
- function expandTilde(p: string): string {
32
- // Handle --arg=~/path pattern
33
- const eqMatch = p.match(/^(--\w[\w-]*=)(~\/.*)$/);
34
- if (eqMatch) {
35
- return eqMatch[1] + join(homedir(), eqMatch[2].slice(2));
36
- }
37
- // Handle standalone ~/path
38
- if (p.startsWith("~/")) {
39
- return join(homedir(), p.slice(2));
40
- }
41
- return p;
42
- }
43
-
44
- function expandCommand(command: string[]): string[] {
45
- return command.map((arg) => expandTilde(arg));
46
- }
47
-
48
- function validateConfig(raw: any): SwitcherConfig {
49
- if (!raw || typeof raw !== "object") {
50
- throw new Error("Config must be a JSON object");
51
- }
52
-
53
- if (!raw.server || typeof raw.server !== "object") {
54
- throw new Error("Config must have a 'server' object");
55
- }
56
-
57
- if (typeof raw.server.host !== "string") {
58
- throw new Error("server.host must be a string");
59
- }
60
-
61
- if (typeof raw.server.port !== "number") {
62
- throw new Error("server.port must be a number");
63
- }
64
-
65
- if (!raw.models || typeof raw.models !== "object") {
66
- throw new Error("Config must have a 'models' object");
67
- }
68
-
69
- for (const [key, model] of Object.entries(raw.models)) {
70
- const m = model as any;
71
- if (!m.name || typeof m.name !== "string") {
72
- throw new Error(`models.${key}.name must be a string`);
73
- }
74
- if (!m.description || typeof m.description !== "string") {
75
- throw new Error(`models.${key}.description must be a string`);
76
- }
77
- if (!Array.isArray(m.command) || m.command.length === 0) {
78
- throw new Error(`models.${key}.command must be a non-empty array`);
79
- }
80
- }
81
-
82
- const server: ServerConfig = {
83
- host: raw.server.host,
84
- port: raw.server.port,
85
- healthTimeout: raw.server.healthTimeout ?? 60,
86
- portReleaseTimeout: raw.server.portReleaseTimeout ?? 30,
87
- };
88
-
89
- const models: Record<string, ModelConfig> = {};
90
- for (const [key, model] of Object.entries(raw.models) as [string, any][]) {
91
- models[key] = {
92
- name: model.name,
93
- description: model.description,
94
- command: expandCommand(model.command),
95
- env: model.env && typeof model.env === "object" ? model.env : undefined,
96
- vision: model.vision ?? false,
97
- contextWindow: model.contextWindow ?? 8192,
98
- maxTokens: model.maxTokens ?? 4096,
99
- tags: model.tags ?? [],
100
- };
101
- }
102
-
103
- return {
104
- server,
105
- defaultModel: raw.defaultModel ?? Object.keys(models)[0] ?? "",
106
- models,
107
- };
108
- }
109
-
110
- export function getConfigPath(): string {
111
- return join(homedir(), ".pi", "agent", CONFIG_FILENAME);
112
- }
113
-
114
- export function loadConfig(configPath?: string): SwitcherConfig | null {
115
- const path = configPath ?? getConfigPath();
116
-
117
- if (!existsSync(path)) {
118
- return null;
119
- }
120
-
121
- const raw = JSON.parse(readFileSync(path, "utf-8"));
122
- return validateConfig(raw);
123
- }
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { resolve, join } from "node:path";
3
+ import { homedir } from "node:os";
4
+
5
+ export interface ServerConfig {
6
+ host: string;
7
+ port: number;
8
+ healthTimeout: number;
9
+ portReleaseTimeout: number;
10
+ }
11
+
12
+ export interface ModelConfig {
13
+ name: string;
14
+ description: string;
15
+ command: string[];
16
+ env?: Record<string, string>;
17
+ modelId?: string;
18
+ vision: boolean;
19
+ contextWindow: number;
20
+ maxTokens: number;
21
+ tags: string[];
22
+ }
23
+
24
+ export interface SwitcherConfig {
25
+ server: ServerConfig;
26
+ defaultModel: string;
27
+ models: Record<string, ModelConfig>;
28
+ }
29
+
30
+ const CONFIG_FILENAME = "model-switcher.json";
31
+
32
+ /**
33
+ * Formats a host for use inside a URL authority. IPv6 literals must be
34
+ * bracketed (http://[::1]:8080), while already-bracketed hosts are left alone.
35
+ */
36
+ export function formatHostForUrl(host: string): string {
37
+ if (host.startsWith("[") && host.endsWith("]")) {
38
+ return host;
39
+ }
40
+ if (host.includes(":")) {
41
+ return `[${host}]`;
42
+ }
43
+ return host;
44
+ }
45
+
46
+ export function formatServerUrl(
47
+ host: string,
48
+ port: number,
49
+ path = ""
50
+ ): string {
51
+ return `http://${formatHostForUrl(host)}:${port}${path}`;
52
+ }
53
+
54
+ /**
55
+ * node:net's socket.connect(port, host) expects an unbracketed IPv6 address.
56
+ */
57
+ export function normalizeHostForSocket(host: string): string {
58
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
59
+ }
60
+
61
+ function expandTilde(p: string): string {
62
+ // Handle --arg=~/path pattern
63
+ const eqMatch = p.match(/^(--\w[\w-]*=)(~\/.*)$/);
64
+ if (eqMatch) {
65
+ return eqMatch[1] + join(homedir(), eqMatch[2].slice(2));
66
+ }
67
+ // Handle standalone ~/path
68
+ if (p.startsWith("~/")) {
69
+ return join(homedir(), p.slice(2));
70
+ }
71
+ return p;
72
+ }
73
+
74
+ function expandCommand(command: string[]): string[] {
75
+ return command.map((arg) => expandTilde(arg));
76
+ }
77
+
78
+ function validateConfig(raw: any): SwitcherConfig {
79
+ if (!raw || typeof raw !== "object") {
80
+ throw new Error("Config must be a JSON object");
81
+ }
82
+
83
+ if (!raw.server || typeof raw.server !== "object") {
84
+ throw new Error("Config must have a 'server' object");
85
+ }
86
+
87
+ if (typeof raw.server.host !== "string") {
88
+ throw new Error("server.host must be a string");
89
+ }
90
+
91
+ if (typeof raw.server.port !== "number") {
92
+ throw new Error("server.port must be a number");
93
+ }
94
+
95
+ if (!raw.models || typeof raw.models !== "object") {
96
+ throw new Error("Config must have a 'models' object");
97
+ }
98
+
99
+ for (const [key, model] of Object.entries(raw.models)) {
100
+ const m = model as any;
101
+ if (!m.name || typeof m.name !== "string") {
102
+ throw new Error(`models.${key}.name must be a string`);
103
+ }
104
+ if (!m.description || typeof m.description !== "string") {
105
+ throw new Error(`models.${key}.description must be a string`);
106
+ }
107
+ if (!Array.isArray(m.command) || m.command.length === 0) {
108
+ throw new Error(`models.${key}.command must be a non-empty array`);
109
+ }
110
+ if (
111
+ m.modelId !== undefined &&
112
+ (typeof m.modelId !== "string" || m.modelId.trim().length === 0)
113
+ ) {
114
+ throw new Error(`models.${key}.modelId must be a non-empty string`);
115
+ }
116
+ }
117
+
118
+ const server: ServerConfig = {
119
+ host: raw.server.host,
120
+ port: raw.server.port,
121
+ healthTimeout: raw.server.healthTimeout ?? 60,
122
+ portReleaseTimeout: raw.server.portReleaseTimeout ?? 30,
123
+ };
124
+
125
+ const models: Record<string, ModelConfig> = {};
126
+ for (const [key, model] of Object.entries(raw.models) as [string, any][]) {
127
+ models[key] = {
128
+ name: model.name,
129
+ description: model.description,
130
+ command: expandCommand(model.command),
131
+ env: model.env && typeof model.env === "object" ? model.env : undefined,
132
+ modelId: model.modelId?.trim() || undefined,
133
+ vision: model.vision ?? false,
134
+ contextWindow: model.contextWindow ?? 8192,
135
+ maxTokens: model.maxTokens ?? 4096,
136
+ tags: model.tags ?? [],
137
+ };
138
+ }
139
+
140
+ if (raw.defaultModel !== undefined && typeof raw.defaultModel !== "string") {
141
+ throw new Error("defaultModel must be a string");
142
+ }
143
+ const requestedDefault =
144
+ typeof raw.defaultModel === "string" ? raw.defaultModel.trim() : "";
145
+ const defaultModel = requestedDefault || Object.keys(models)[0] || "";
146
+ if (defaultModel && !models[defaultModel]) {
147
+ throw new Error(`defaultModel '${defaultModel}' not found in models`);
148
+ }
149
+
150
+ return {
151
+ server,
152
+ defaultModel,
153
+ models,
154
+ };
155
+ }
156
+
157
+ export function getConfigPath(): string {
158
+ return join(homedir(), ".pi", "agent", CONFIG_FILENAME);
159
+ }
160
+
161
+ export function loadConfig(configPath?: string): SwitcherConfig | null {
162
+ const path = configPath ?? getConfigPath();
163
+
164
+ if (!existsSync(path)) {
165
+ return null;
166
+ }
167
+
168
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
169
+ return validateConfig(raw);
170
+ }
package/src/health.ts CHANGED
@@ -1,17 +1,20 @@
1
- import type { ServerConfig } from "./config.js";
1
+ import { formatServerUrl, type ServerConfig } from "./config.js";
2
2
 
3
3
  export interface HealthStatus {
4
4
  status: "ok" | "loading" | "error" | "unknown";
5
5
  error?: string;
6
6
  }
7
7
 
8
+ // Cap a single health attempt so a stalled server cannot consume the whole timeout.
9
+ const MAX_ATTEMPT_TIMEOUT_MS = 5000;
10
+
8
11
  async function fetchHealth(
9
12
  host: string,
10
13
  port: number,
11
14
  signal?: AbortSignal
12
15
  ): Promise<HealthStatus> {
13
16
  try {
14
- const res = await fetch(`http://${host}:${port}/health`, {
17
+ const res = await fetch(formatServerUrl(host, port, "/health"), {
15
18
  signal,
16
19
  headers: { Accept: "application/json" },
17
20
  });
@@ -43,6 +46,9 @@ async function fetchHealth(
43
46
 
44
47
  return { status: s ?? "unknown" };
45
48
  } catch (err: any) {
49
+ if (err.name === "TimeoutError") {
50
+ return { status: "unknown", error: "request timed out" };
51
+ }
46
52
  if (err.name === "AbortError") {
47
53
  return { status: "unknown", error: "aborted" };
48
54
  }
@@ -55,21 +61,55 @@ export type HealthProgressCallback = (
55
61
  lastStatus: HealthStatus
56
62
  ) => void;
57
63
 
64
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
65
+ return new Promise((resolve, reject) => {
66
+ if (signal?.aborted) {
67
+ reject(new Error("Health check aborted"));
68
+ return;
69
+ }
70
+
71
+ const onAbort = () => {
72
+ clearTimeout(timer);
73
+ reject(new Error("Health check aborted"));
74
+ };
75
+ const timer = setTimeout(() => {
76
+ signal?.removeEventListener("abort", onAbort);
77
+ resolve();
78
+ }, ms);
79
+ signal?.addEventListener("abort", onAbort, { once: true });
80
+ });
81
+ }
82
+
58
83
  export async function waitForHealth(
59
84
  server: ServerConfig,
60
85
  onProgress?: HealthProgressCallback,
61
86
  signal?: AbortSignal
62
87
  ): Promise<HealthStatus> {
63
88
  const { host, port, healthTimeout } = server;
64
- const deadline = Date.now() + healthTimeout * 1000;
89
+ const startTime = Date.now();
90
+ const deadline = startTime + healthTimeout * 1000;
65
91
  let lastStatus: HealthStatus = { status: "unknown" };
66
92
 
67
- while (Date.now() < deadline) {
93
+ while (true) {
68
94
  if (signal?.aborted) {
69
95
  throw new Error("Health check aborted");
70
96
  }
71
97
 
72
- lastStatus = await fetchHealth(host, port, signal);
98
+ const remainingMs = deadline - Date.now();
99
+ if (remainingMs <= 0) break;
100
+
101
+ const attemptTimeout = AbortSignal.timeout(
102
+ Math.min(remainingMs, MAX_ATTEMPT_TIMEOUT_MS)
103
+ );
104
+ const requestSignal = signal
105
+ ? AbortSignal.any([signal, attemptTimeout])
106
+ : attemptTimeout;
107
+
108
+ lastStatus = await fetchHealth(host, port, requestSignal);
109
+
110
+ if (signal?.aborted) {
111
+ throw new Error("Health check aborted");
112
+ }
73
113
 
74
114
  if (lastStatus.status === "ok") {
75
115
  return lastStatus;
@@ -81,9 +121,12 @@ export async function waitForHealth(
81
121
  );
82
122
  }
83
123
 
84
- onProgress?.(Math.floor((Date.now() - (deadline - healthTimeout * 1000)) / 1000), lastStatus);
124
+ onProgress?.(Math.floor((Date.now() - startTime) / 1000), lastStatus);
85
125
 
86
- await new Promise((r) => setTimeout(r, 1000));
126
+ const sleepMs = Math.min(1000, Math.max(0, deadline - Date.now()));
127
+ if (sleepMs > 0) {
128
+ await abortableSleep(sleepMs, signal);
129
+ }
87
130
  }
88
131
 
89
132
  throw new Error(
@@ -93,8 +136,9 @@ export async function waitForHealth(
93
136
 
94
137
  export async function checkHealth(
95
138
  host: string,
96
- port: number
139
+ port: number,
140
+ timeoutMs = 5000
97
141
  ): Promise<boolean> {
98
- const status = await fetchHealth(host, port);
142
+ const status = await fetchHealth(host, port, AbortSignal.timeout(timeoutMs));
99
143
  return status.status === "ok";
100
144
  }