pi-llama-switch 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Duplar Mello
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,216 @@
1
+ # pi-llama-switch
2
+
3
+ <div align="center">
4
+
5
+ <!-- Add a cover image: docs/cover.png -->
6
+ Restart local LLM servers with different model configurations. For single-model setups where each model needs different flags -- context size, vision projector, sampling params, GPU offload. Works with [llama.cpp](https://github.com/ggml-org/llama.cpp) and [vLLM](https://github.com/vllm-project/vllm) (experimental).
7
+
8
+ [![npm version](https://img.shields.io/npm/v/pi-llama-switch.svg)](https://www.npmjs.com/package/pi-llama-switch)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
+
11
+ </div>
12
+
13
+ ## Features
14
+
15
+ - **`/switch` command** -- interactive model picker or direct switch with `/switch qwen`
16
+ - **`model_switch` tool** -- the LLM can request a switch programmatically
17
+ - **Health checking** -- polls `/health` endpoint with progress updates
18
+ - **Provider registration** -- after switch, Pi natively knows the active model via `/model` and `Ctrl+P`
19
+ - **PID tracking** -- clean process lifecycle management with graceful shutdown
20
+ - **Stderr logging** -- captures startup failures to `~/.pi/agent/llama-switch.log`
21
+ - **Auto-reconnect** -- reconnects to a running server on Pi restart
22
+ - **Multi-backend** -- works with llama.cpp and vLLM (experimental)
23
+
24
+ ## Who is this for
25
+
26
+ You have a single GPU and multiple local models, but each model needs different server flags. Instead of maintaining separate terminals or scripts, you switch between them with `/switch`.
27
+
28
+ **Common setups:**
29
+
30
+ - **Coding vs general-purpose:** Qwen3.6 for code (small context, fast) and Gemma 4 for general tasks (vision, larger context) -- each needs different `--ctx-size` and `--mmproj` flags.
31
+ - **Fast vs powerful:** A small E4B model for quick tasks and a 35B model for complex reasoning -- the small model loads in seconds, the large one needs 60+ seconds and more VRAM.
32
+ - **Text vs multimodal:** A text-only model for coding and a vision model for image analysis -- the vision model needs `--mmproj` which adds VRAM overhead.
33
+
34
+ If you only run one model at a time and don't change server flags between models, you don't need this extension.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pi install npm:pi-llama-switch
40
+ ```
41
+
42
+ Then restart your Pi session.
43
+
44
+ ## Config
45
+
46
+ Copy `examples/model-switcher.json` to `~/.pi/agent/model-switcher.json` and edit:
47
+
48
+ ```json
49
+ {
50
+ "server": {
51
+ "host": "127.0.0.1",
52
+ "port": 8080,
53
+ "healthTimeout": 60,
54
+ "portReleaseTimeout": 15
55
+ },
56
+ "defaultModel": "qwen",
57
+ "models": {
58
+ "qwen": {
59
+ "name": "Qwen3.6 35B-A3B",
60
+ "description": "Coding/Reasoning",
61
+ "command": [
62
+ "llama-server",
63
+ "-m", "~/models/qwen/Qwen3.6-35B-A3B.gguf",
64
+ "-ngl", "999",
65
+ "--flash-attn", "on",
66
+ "--cache-type-k", "q8_0",
67
+ "--cache-type-v", "q8_0",
68
+ "--ctx-size", "8192",
69
+ "--parallel", "1",
70
+ "--host", "127.0.0.1",
71
+ "--port", "8080"
72
+ ],
73
+ "vision": false,
74
+ "contextWindow": 8192,
75
+ "maxTokens": 4096,
76
+ "tags": ["coding", "reasoning"]
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ ### vLLM
83
+
84
+ The extension should also work with vLLM. See `examples/model-switcher-vllm.json` for a full example:
85
+
86
+ ```json
87
+ {
88
+ "server": {
89
+ "host": "127.0.0.1",
90
+ "port": 8000,
91
+ "healthTimeout": 120,
92
+ "portReleaseTimeout": 15
93
+ },
94
+ "defaultModel": "qwen",
95
+ "models": {
96
+ "qwen": {
97
+ "name": "Qwen3.6-35B-A3B",
98
+ "description": "Coding/Reasoning",
99
+ "command": [
100
+ "python3", "-m", "vllm.entrypoints.openai.api_server",
101
+ "--model", "~/models/qwen/Qwen3.6-35B-A3B",
102
+ "--tensor-parallel-size", "1",
103
+ "--gpu-memory-utilization", "0.9",
104
+ "--max-model-len", "8192",
105
+ "--host", "127.0.0.1",
106
+ "--port", "8000"
107
+ ],
108
+ "vision": false,
109
+ "contextWindow": 8192,
110
+ "maxTokens": 4096,
111
+ "tags": ["coding", "reasoning"]
112
+ }
113
+ }
114
+ }
115
+ ```
116
+
117
+ > [!NOTE]
118
+ > vLLM support is verified against docs but not tested end-to-end. The health endpoint and OpenAI-compatible API are standard. Report issues if you test this.
119
+
120
+ ### Config fields
121
+
122
+ | Field | Required | Description |
123
+ |---|---|---|
124
+ | `server.host` | yes | Server bind address |
125
+ | `server.port` | yes | Server port |
126
+ | `server.healthTimeout` | no | Seconds to wait for `/health` (default: 60) |
127
+ | `server.portReleaseTimeout` | no | Seconds to wait for port release after stop (default: 30) |
128
+ | `defaultModel` | no | Model key active on startup (default: first model) |
129
+ | `models.<key>.name` | yes | Display name |
130
+ | `models.<key>.description` | yes | Short description |
131
+ | `models.<key>.command` | yes | Array-style command (no shell parsing needed) |
132
+ | `models.<key>.vision` | no | Whether model supports images (default: false) |
133
+ | `models.<key>.contextWindow` | no | Max context tokens for Pi (default: 8192) |
134
+ | `models.<key>.maxTokens` | no | Max output tokens for Pi (default: 4096) |
135
+ | `models.<key>.tags` | no | Tags for filtering (default: []) |
136
+
137
+ ## Commands
138
+
139
+ | Command | Description |
140
+ |---|---|
141
+ | `/switch` | Interactive model picker |
142
+ | `/switch qwen` | Switch directly to model key |
143
+ | `/switch list` | Print all available models |
144
+ | `/switch status` | Show active model + server health |
145
+ | `/switch reload` | Re-read config file |
146
+ | `/switch logs` | Tail the last 50 lines of the log |
147
+
148
+ ## Tool
149
+
150
+ The `model_switch` tool lets the LLM switch models programmatically:
151
+
152
+ ```typescript
153
+ model_switch({
154
+ model: "qwen", // model key from config
155
+ dryRun: false // optional: print command without executing
156
+ })
157
+ ```
158
+
159
+ ### Schema
160
+
161
+ ```ts
162
+ model_switch({
163
+ model: string, // required: model key
164
+ dryRun?: boolean, // optional: preview mode
165
+ })
166
+ ```
167
+
168
+ Returns:
169
+
170
+ ```ts
171
+ {
172
+ content: [{ type: "text", text: string }],
173
+ details: {
174
+ switched: boolean,
175
+ model: string,
176
+ name: string,
177
+ contextWindow: number,
178
+ error?: string,
179
+ }
180
+ }
181
+ ```
182
+
183
+ ## How it works
184
+
185
+ 1. Stops the current server via `SIGTERM` (tracked PID, not `pkill`)
186
+ 2. Waits for the port to be released
187
+ 3. Spawns a new server with the model's command array
188
+ 4. Polls `/health` until `status === "ok"` (or errors immediately on `status: "error"`)
189
+ 5. Registers the new model with Pi's provider system
190
+
191
+ ## Troubleshooting
192
+
193
+ **Startup timeout:** Increase `server.healthTimeout` in your config. Large models on low VRAM can take 60+ seconds to load. vLLM models may need even longer for initial weight loading.
194
+
195
+ **Logs:** Check `~/.pi/agent/llama-switch.log` for stderr output:
196
+ ```bash
197
+ # From Pi
198
+ /switch logs
199
+
200
+ # From terminal
201
+ tail -50 ~/.pi/agent/llama-switch.log
202
+ tail -f ~/.pi/agent/llama-switch.log # follow in real time
203
+ ```
204
+
205
+ **Port still in use after stop:** Increase `server.portReleaseTimeout` (default: 30s). Large context sizes take longer to flush KV cache.
206
+
207
+ **Switch failed, server still running:** The extension kills orphaned processes on failure. If something slips through:
208
+ ```bash
209
+ lsof -ti:8080 | xargs kill -9
210
+ ```
211
+
212
+ **Config not reloading:** Run `/switch reload` after editing `~/.pi/agent/model-switcher.json`. Verify JSON validity first.
213
+
214
+ ## License
215
+
216
+ MIT
@@ -0,0 +1,61 @@
1
+ {
2
+ "server": {
3
+ "host": "127.0.0.1",
4
+ "port": 8000,
5
+ "healthTimeout": 120,
6
+ "portReleaseTimeout": 15
7
+ },
8
+ "defaultModel": "qwen",
9
+ "models": {
10
+ "qwen": {
11
+ "name": "Qwen3.6-35B-A3B",
12
+ "description": "Coding/Reasoning",
13
+ "command": [
14
+ "python3",
15
+ "-m",
16
+ "vllm.entrypoints.openai.api_server",
17
+ "--model",
18
+ "~/models/qwen/Qwen3.6-35B-A3B",
19
+ "--tensor-parallel-size",
20
+ "1",
21
+ "--gpu-memory-utilization",
22
+ "0.9",
23
+ "--max-model-len",
24
+ "8192",
25
+ "--host",
26
+ "127.0.0.1",
27
+ "--port",
28
+ "8000"
29
+ ],
30
+ "vision": false,
31
+ "contextWindow": 8192,
32
+ "maxTokens": 4096,
33
+ "tags": ["coding", "reasoning"]
34
+ },
35
+ "llama": {
36
+ "name": "Llama 4 Scout",
37
+ "description": "General purpose",
38
+ "command": [
39
+ "python3",
40
+ "-m",
41
+ "vllm.entrypoints.openai.api_server",
42
+ "--model",
43
+ "~/models/meta-llama/Llama-4-Scout-17B-16E-Instruct",
44
+ "--tensor-parallel-size",
45
+ "2",
46
+ "--gpu-memory-utilization",
47
+ "0.95",
48
+ "--max-model-len",
49
+ "16384",
50
+ "--host",
51
+ "127.0.0.1",
52
+ "--port",
53
+ "8000"
54
+ ],
55
+ "vision": false,
56
+ "contextWindow": 16384,
57
+ "maxTokens": 8192,
58
+ "tags": ["general"]
59
+ }
60
+ }
61
+ }
@@ -0,0 +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
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "pi-llama-switch",
3
+ "version": "1.0.0",
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
+ }
package/src/config.ts ADDED
@@ -0,0 +1,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
+ 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
+ }
package/src/health.ts ADDED
@@ -0,0 +1,100 @@
1
+ import type { ServerConfig } from "./config.js";
2
+
3
+ export interface HealthStatus {
4
+ status: "ok" | "loading" | "error" | "unknown";
5
+ error?: string;
6
+ }
7
+
8
+ async function fetchHealth(
9
+ host: string,
10
+ port: number,
11
+ signal?: AbortSignal
12
+ ): Promise<HealthStatus> {
13
+ try {
14
+ const res = await fetch(`http://${host}:${port}/health`, {
15
+ signal,
16
+ headers: { Accept: "application/json" },
17
+ });
18
+
19
+ // 503 means server is alive but unhealthy (vLLM engine dead)
20
+ if (res.status === 503) {
21
+ return { status: "error", error: "server returned 503" };
22
+ }
23
+
24
+ if (!res.ok) {
25
+ return { status: "unknown", error: `HTTP ${res.status}` };
26
+ }
27
+
28
+ // Try parsing JSON body (llama.cpp returns { status: "ok" })
29
+ // vLLM returns 200 with empty body — treat as healthy
30
+ const text = await res.text();
31
+ if (!text) {
32
+ return { status: "ok" };
33
+ }
34
+
35
+ const data = JSON.parse(text);
36
+ const s = data?.status;
37
+
38
+ if (s === "ok") return { status: "ok" };
39
+ if (s === "error") return { status: "error", error: "server reported error" };
40
+ if (typeof s === "string" && s.includes("loading")) {
41
+ return { status: "loading" };
42
+ }
43
+
44
+ return { status: s ?? "unknown" };
45
+ } catch (err: any) {
46
+ if (err.name === "AbortError") {
47
+ return { status: "unknown", error: "aborted" };
48
+ }
49
+ return { status: "unknown", error: err.message ?? String(err) };
50
+ }
51
+ }
52
+
53
+ export type HealthProgressCallback = (
54
+ elapsed: number,
55
+ lastStatus: HealthStatus
56
+ ) => void;
57
+
58
+ export async function waitForHealth(
59
+ server: ServerConfig,
60
+ onProgress?: HealthProgressCallback,
61
+ signal?: AbortSignal
62
+ ): Promise<HealthStatus> {
63
+ const { host, port, healthTimeout } = server;
64
+ const deadline = Date.now() + healthTimeout * 1000;
65
+ let lastStatus: HealthStatus = { status: "unknown" };
66
+
67
+ while (Date.now() < deadline) {
68
+ if (signal?.aborted) {
69
+ throw new Error("Health check aborted");
70
+ }
71
+
72
+ lastStatus = await fetchHealth(host, port, signal);
73
+
74
+ if (lastStatus.status === "ok") {
75
+ return lastStatus;
76
+ }
77
+
78
+ if (lastStatus.status === "error") {
79
+ throw new Error(
80
+ `Server reported error status: ${lastStatus.error ?? "unknown"}`
81
+ );
82
+ }
83
+
84
+ onProgress?.(Math.floor((Date.now() - (deadline - healthTimeout * 1000)) / 1000), lastStatus);
85
+
86
+ await new Promise((r) => setTimeout(r, 1000));
87
+ }
88
+
89
+ throw new Error(
90
+ `Health check timed out after ${healthTimeout}s. Last status: ${lastStatus.status} (${lastStatus.error ?? "no error"})`
91
+ );
92
+ }
93
+
94
+ export async function checkHealth(
95
+ host: string,
96
+ port: number
97
+ ): Promise<boolean> {
98
+ const status = await fetchHealth(host, port);
99
+ return status.status === "ok";
100
+ }
package/src/index.ts ADDED
@@ -0,0 +1,401 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { readFileSync } from "node:fs";
4
+ import { execSync } from "node:child_process";
5
+ import { join } from "node:path";
6
+ import { homedir } from "node:os";
7
+ import { loadConfig, type SwitcherConfig } from "./config.js";
8
+ import {
9
+ getState,
10
+ readPidFile,
11
+ writePidFile,
12
+ isProcessAlive,
13
+ isLlamaServer,
14
+ findLlamaServerPid,
15
+ switchModel,
16
+ disconnectState,
17
+ deletePidFile,
18
+ updateActiveState,
19
+ } from "./switcher.js";
20
+ import { checkHealth } from "./health.js";
21
+ import { buildProviderModels, getModelForProvider } from "./provider.js";
22
+
23
+ const PROVIDER_ID = "llama-local";
24
+
25
+ export default async function (pi: ExtensionAPI) {
26
+ let config = loadConfig();
27
+
28
+ if (!config) {
29
+ console.warn(
30
+ "[pi-llama-switch] No config found at ~/.pi/agent/model-switcher.json"
31
+ );
32
+ return;
33
+ }
34
+
35
+ // Register provider from default model
36
+ registerProvider(pi, config, config.defaultModel);
37
+
38
+ // Register /switch command
39
+ pi.registerCommand("switch", {
40
+ description: "Switch to a different local LLM model",
41
+ handler: async (args, ctx) => {
42
+ const subcommand = args?.trim();
43
+
44
+ if (!subcommand) {
45
+ return await handleInteractiveSwitch(pi, config, ctx);
46
+ }
47
+
48
+ if (subcommand === "list") {
49
+ return handleList(config, ctx);
50
+ }
51
+
52
+ if (subcommand === "status") {
53
+ return handleStatus(config, ctx);
54
+ }
55
+
56
+ if (subcommand === "reload") {
57
+ return handleReload(pi, config, ctx);
58
+ }
59
+
60
+ if (subcommand === "logs") {
61
+ return handleLogs(ctx);
62
+ }
63
+
64
+ if (subcommand === "--help" || subcommand === "-h") {
65
+ ctx.ui.notify(
66
+ "Usage: /switch [model_key|list|status|reload|logs]",
67
+ "info"
68
+ );
69
+ return;
70
+ }
71
+
72
+ // Direct switch to model key
73
+ if (config.models[subcommand]) {
74
+ return await handleDirectSwitch(pi, config, subcommand, ctx);
75
+ }
76
+
77
+ ctx.ui.notify(
78
+ `Unknown model or subcommand: '${subcommand}'. Available: ${Object.keys(config.models).join(", ")}`,
79
+ "error"
80
+ );
81
+ },
82
+ });
83
+
84
+ // Register model_switch tool
85
+ pi.registerTool({
86
+ name: "model_switch",
87
+ label: "Switch Model",
88
+ description:
89
+ "Switch to a different local LLM model. Each model requires different server flags.",
90
+ promptSnippet: "Switch between local LLM models with different capabilities",
91
+ promptGuidelines: [
92
+ "Use model_switch when the user explicitly asks to switch models or needs a capability (vision, audio, reasoning) not supported by the current model.",
93
+ "model_switch stops the current llama-server and restarts with a new configuration. This takes 10-60 seconds depending on model size.",
94
+ ],
95
+ parameters: Type.Object({
96
+ model: Type.String({
97
+ description: "Model key from the config (e.g. 'qwen', 'ornith', 'gemma4b')",
98
+ }),
99
+ dryRun: Type.Optional(
100
+ Type.Boolean({
101
+ description:
102
+ "If true, print the command that would be run without executing it",
103
+ })
104
+ ),
105
+ }),
106
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
107
+ const modelKey = params.model;
108
+ const dryRun = params.dryRun ?? false;
109
+
110
+ if (!config.models[modelKey]) {
111
+ const available = Object.keys(config.models).join(", ");
112
+ return {
113
+ content: [
114
+ {
115
+ type: "text",
116
+ text: `Model '${modelKey}' not found. Available: ${available}`,
117
+ },
118
+ ],
119
+ details: { error: "model_not_found", available: Object.keys(config.models) },
120
+ };
121
+ }
122
+
123
+ if (dryRun) {
124
+ const model = config.models[modelKey];
125
+ return {
126
+ content: [
127
+ {
128
+ type: "text",
129
+ text: `Dry run: would execute:\n${model.command.join(" ")}`,
130
+ },
131
+ ],
132
+ details: { dryRun: true, command: model.command },
133
+ } as any;
134
+ }
135
+
136
+ onUpdate?.({
137
+ content: [{ type: "text", text: `Switching to ${config.models[modelKey].name}...` }],
138
+ details: { phase: "switching", model: modelKey },
139
+ });
140
+
141
+ try {
142
+ await switchModel(config, modelKey, {
143
+ onStatusUpdate: (msg) => {
144
+ onUpdate?.({ content: [{ type: "text", text: msg }], details: { phase: "switching", model: modelKey } });
145
+ },
146
+ }, signal);
147
+
148
+ registerProvider(pi, config, modelKey);
149
+
150
+ const model = config.models[modelKey];
151
+ return {
152
+ content: [
153
+ {
154
+ type: "text",
155
+ text: `Switched to ${model.name} (${model.description}). Context window: ${model.contextWindow} tokens.`,
156
+ },
157
+ ],
158
+ details: {
159
+ switched: true,
160
+ model: modelKey,
161
+ name: model.name,
162
+ contextWindow: model.contextWindow,
163
+ },
164
+ } as any;
165
+ } catch (err: any) {
166
+ return {
167
+ content: [
168
+ {
169
+ type: "text",
170
+ text: `Failed to switch to '${modelKey}': ${err.message}\nCheck logs: ~/.pi/agent/llama-switch.log`,
171
+ },
172
+ ],
173
+ details: { error: err.message },
174
+ isError: true,
175
+ } as any;
176
+ }
177
+ },
178
+ });
179
+
180
+ // session_start: reconnect to existing server
181
+ pi.on("session_start", async (_event, ctx) => {
182
+ let pid = readPidFile();
183
+ if (!pid || !isProcessAlive(pid) || !isLlamaServer(pid)) {
184
+ pid = findLlamaServerPid(config.server.port);
185
+ if (pid) {
186
+ writePidFile(pid);
187
+ }
188
+ }
189
+ if (pid && isProcessAlive(pid) && isLlamaServer(pid)) {
190
+ const alive = await checkHealth(config.server.host, config.server.port);
191
+ if (alive) {
192
+ const modelKey = detectModelFromPid(config, pid);
193
+ const activeKey = modelKey ?? config.defaultModel;
194
+ updateActiveState(activeKey, pid);
195
+ registerProvider(pi, config, activeKey);
196
+ const model = config.models[activeKey];
197
+ ctx.ui.setStatus("llama-switch", `⚡ ${model?.name ?? activeKey}`);
198
+ return;
199
+ }
200
+ }
201
+
202
+ deletePidFile();
203
+ ctx.ui.setStatus("llama-switch", "no model loaded");
204
+ });
205
+
206
+ // session_shutdown: clean up in-memory state
207
+ pi.on("session_shutdown", async (event) => {
208
+ if (event.reason === "reload") return;
209
+ disconnectState();
210
+ });
211
+
212
+ // before_agent_start: inject model identity
213
+ pi.on("before_agent_start", async (event, _ctx) => {
214
+ const state = getState();
215
+ if (state.activeModelKey) {
216
+ const model = config.models[state.activeModelKey];
217
+ if (model) {
218
+ return {
219
+ systemPrompt:
220
+ event.systemPrompt +
221
+ `\n\nCurrent LLM: ${model.name} (${model.description}). Context window: ${model.contextWindow} tokens.`,
222
+ };
223
+ }
224
+ }
225
+ });
226
+ }
227
+
228
+ function registerProvider(
229
+ pi: ExtensionAPI,
230
+ config: SwitcherConfig,
231
+ modelKey: string
232
+ ): void {
233
+ const models = buildProviderModels(config);
234
+ const activeModel = models.find((m) => m.id === modelKey);
235
+ if (!activeModel) return;
236
+
237
+ pi.registerProvider(PROVIDER_ID, {
238
+ baseUrl: `http://${config.server.host}:${config.server.port}/v1`,
239
+ apiKey: "no-key",
240
+ api: "openai-completions",
241
+ models: models.map((m) => ({
242
+ ...m,
243
+ reasoning: m.id === modelKey ? (activeModel.reasoning ?? false) : false,
244
+ })),
245
+ });
246
+ }
247
+
248
+ async function handleInteractiveSwitch(
249
+ pi: ExtensionAPI,
250
+ config: SwitcherConfig,
251
+ ctx: any
252
+ ): Promise<void> {
253
+ const state = getState();
254
+ const entries = Object.entries(config.models).map(([key, model]) => {
255
+ const isCurrent = state.activeModelKey === key;
256
+ const vision = model.vision ? " [vision]" : "";
257
+ const tags = model.tags?.length ? ` (${model.tags.join(", ")})` : "";
258
+ return {
259
+ label: `${isCurrent ? "► " : " "}${key} - ${model.name}${vision}${tags}`,
260
+ value: key,
261
+ description: model.description,
262
+ };
263
+ });
264
+
265
+ const choice = await ctx.ui.select(
266
+ "Switch to model:",
267
+ entries.map((e) => e.label)
268
+ );
269
+
270
+ if (!choice) return;
271
+
272
+ const selectedEntry = entries.find((e) => e.label === choice);
273
+ if (!selectedEntry) return;
274
+
275
+ const modelKey = selectedEntry.value;
276
+
277
+ if (state.activeModelKey === modelKey) {
278
+ ctx.ui.notify(`Already using ${config.models[modelKey].name}`, "info");
279
+ return;
280
+ }
281
+
282
+ try {
283
+ ctx.ui.notify(`Switching to ${config.models[modelKey].name}...`, "info");
284
+ await switchModel(config, modelKey, {
285
+ onStatusUpdate: (msg) => {
286
+ ctx.ui.notify(msg, "info");
287
+ },
288
+ });
289
+
290
+ registerProvider(pi, config, modelKey);
291
+ ctx.ui.notify(`Switched to ${config.models[modelKey].name}`, "info");
292
+ } catch (err: any) {
293
+ ctx.ui.notify(`Switch failed: ${err.message}`, "error");
294
+ }
295
+ }
296
+
297
+ async function handleDirectSwitch(
298
+ pi: ExtensionAPI,
299
+ config: SwitcherConfig,
300
+ modelKey: string,
301
+ ctx: any
302
+ ): Promise<void> {
303
+ const state = getState();
304
+ if (state.activeModelKey === modelKey) {
305
+ ctx.ui.notify(`Already using ${config.models[modelKey].name}`, "info");
306
+ return;
307
+ }
308
+
309
+ try {
310
+ ctx.ui.notify(`Switching to ${config.models[modelKey].name}...`, "info");
311
+ await switchModel(config, modelKey, {
312
+ onStatusUpdate: (msg) => {
313
+ ctx.ui.notify(msg, "info");
314
+ },
315
+ });
316
+
317
+ registerProvider(pi, config, modelKey);
318
+ ctx.ui.notify(`Switched to ${config.models[modelKey].name}`, "info");
319
+ } catch (err: any) {
320
+ ctx.ui.notify(`Switch failed: ${err.message}`, "error");
321
+ }
322
+ }
323
+
324
+ function handleList(config: SwitcherConfig, ctx: any): void {
325
+ const state = getState();
326
+ const lines = Object.entries(config.models).map(([key, model]) => {
327
+ const isCurrent = state.activeModelKey === key;
328
+ const icon = isCurrent ? "►" : " ";
329
+ const vision = model.vision ? " [vision]" : "";
330
+ const tags = model.tags?.length ? ` (${model.tags.join(", ")})` : "";
331
+ return `${icon} ${key} - ${model.name}${vision}${tags}\n ${model.description} | ctx: ${model.contextWindow}`;
332
+ });
333
+
334
+ ctx.ui.notify(
335
+ `Models:\n${lines.join("\n\n")}`,
336
+ "info"
337
+ );
338
+ }
339
+
340
+ function handleStatus(config: SwitcherConfig, ctx: any): void {
341
+ const state = getState();
342
+ if (state.activeModelKey) {
343
+ const model = config.models[state.activeModelKey];
344
+ ctx.ui.notify(
345
+ `Active: ${model.name} (${model.description})\n` +
346
+ `Context: ${model.contextWindow} tokens\n` +
347
+ `PID: ${state.activePid ?? "unknown"}\n` +
348
+ `Server: http://${config.server.host}:${config.server.port}`,
349
+ "info"
350
+ );
351
+ } else {
352
+ ctx.ui.notify("No model currently loaded", "info");
353
+ }
354
+ }
355
+
356
+ function handleReload(pi: ExtensionAPI, config: SwitcherConfig, ctx: any): void {
357
+ const newConfig = loadConfig();
358
+ if (!newConfig) {
359
+ ctx.ui.notify("Failed to reload config: file not found", "error");
360
+ return;
361
+ }
362
+ Object.assign(config, newConfig);
363
+ const state = getState();
364
+ registerProvider(pi, config, state.activeModelKey ?? config.defaultModel);
365
+ ctx.ui.notify(
366
+ `Reloaded config: ${Object.keys(newConfig.models).length} models`,
367
+ "info"
368
+ );
369
+ }
370
+
371
+ function handleLogs(ctx: any): void {
372
+ const logPath = join(homedir(), ".pi", "agent", "llama-switch.log");
373
+
374
+ try {
375
+ const content = readFileSync(logPath, "utf-8");
376
+ const lines = content.split("\n").slice(-50).join("\n");
377
+ ctx.ui.notify(`Last 50 lines of ${logPath}:\n${lines}`, "info");
378
+ } catch {
379
+ ctx.ui.notify(`No log file found at ${logPath}`, "info");
380
+ }
381
+ }
382
+
383
+ function detectModelFromPid(config: SwitcherConfig, pid: number): string | null {
384
+ try {
385
+ const args = execSync(`ps -p ${pid} -o args=`, {
386
+ encoding: "utf-8",
387
+ timeout: 1000,
388
+ }).trim();
389
+
390
+ for (const [key, model] of Object.entries(config.models)) {
391
+ const ggufArg = model.command.find((arg) => arg.endsWith(".gguf"));
392
+ if (ggufArg && args.includes(ggufArg)) {
393
+ return key;
394
+ }
395
+ }
396
+ } catch {
397
+ // ps not available or other error
398
+ }
399
+
400
+ return config.defaultModel || null;
401
+ }
@@ -0,0 +1,43 @@
1
+ import type { SwitcherConfig, ModelConfig } from "./config.js";
2
+
3
+ export interface ProviderModel {
4
+ id: string;
5
+ name: string;
6
+ reasoning: boolean;
7
+ input: ("text" | "image")[];
8
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
9
+ contextWindow: number;
10
+ maxTokens: number;
11
+ }
12
+
13
+ export function buildProviderModels(
14
+ config: SwitcherConfig
15
+ ): ProviderModel[] {
16
+ return Object.entries(config.models).map(([key, model]) => ({
17
+ id: key,
18
+ name: model.name,
19
+ reasoning: model.tags?.includes("reasoning") ?? false,
20
+ input: model.vision ? ["text", "image"] : ["text"],
21
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
22
+ contextWindow: model.contextWindow,
23
+ maxTokens: model.maxTokens,
24
+ }));
25
+ }
26
+
27
+ export function getModelForProvider(
28
+ config: SwitcherConfig,
29
+ modelKey: string
30
+ ): ProviderModel | null {
31
+ const model = config.models[modelKey];
32
+ if (!model) return null;
33
+
34
+ return {
35
+ id: modelKey,
36
+ name: model.name,
37
+ reasoning: model.tags?.includes("reasoning") ?? false,
38
+ input: model.vision ? ["text", "image"] : ["text"],
39
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
40
+ contextWindow: model.contextWindow,
41
+ maxTokens: model.maxTokens,
42
+ };
43
+ }
@@ -0,0 +1,285 @@
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";
4
+ import { homedir } from "node:os";
5
+ import { waitForHealth } from "./health.js";
6
+ import type { SwitcherConfig, ModelConfig, ServerConfig } from "./config.js";
7
+
8
+ const PID_FILENAME = "llama-switch.pid";
9
+ const LOG_FILENAME = "llama-switch.log";
10
+
11
+ export interface SwitcherState {
12
+ activeModelKey: string | null;
13
+ activePid: number | null;
14
+ isSwitching: boolean;
15
+ }
16
+
17
+ const state: SwitcherState = {
18
+ activeModelKey: null,
19
+ activePid: null,
20
+ isSwitching: false,
21
+ };
22
+
23
+ export function getState(): Readonly<SwitcherState> {
24
+ return state;
25
+ }
26
+
27
+ export function updateActiveState(modelKey: string, pid: number): void {
28
+ state.activeModelKey = modelKey;
29
+ state.activePid = pid;
30
+ writePidFile(pid);
31
+ }
32
+
33
+ function getPidPath(): string {
34
+ return join(homedir(), ".pi", "agent", PID_FILENAME);
35
+ }
36
+
37
+ function getLogPath(): string {
38
+ return join(homedir(), ".pi", "agent", LOG_FILENAME);
39
+ }
40
+
41
+ export function readPidFile(): number | null {
42
+ const path = getPidPath();
43
+ if (!existsSync(path)) return null;
44
+ const raw = readFileSync(path, "utf-8").trim();
45
+ const pid = parseInt(raw, 10);
46
+ return isNaN(pid) ? null : pid;
47
+ }
48
+
49
+ export function writePidFile(pid: number): void {
50
+ writeFileSync(getPidPath(), String(pid), "utf-8");
51
+ }
52
+
53
+ export function deletePidFile(): void {
54
+ const path = getPidPath();
55
+ if (existsSync(path)) {
56
+ unlinkSync(path);
57
+ }
58
+ }
59
+
60
+ export function isProcessAlive(pid: number): boolean {
61
+ try {
62
+ process.kill(pid, 0);
63
+ return true;
64
+ } catch (err: any) {
65
+ return err?.code === "EPERM";
66
+ }
67
+ }
68
+
69
+ export function isLlamaServer(pid: number): boolean {
70
+ try {
71
+ const comm = execSync(`ps -p ${pid} -o comm=`, { encoding: "utf-8" }).trim();
72
+ return comm.includes("llama-server");
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ export function findLlamaServerPid(port: number): number | null {
79
+ try {
80
+ const output = execSync("pgrep -af llama-server", { encoding: "utf-8", timeout: 3000 }).trim();
81
+ if (!output) return null;
82
+ for (const line of output.split("\n")) {
83
+ const match = line.match(/^(\d+)\s/);
84
+ if (!match) continue;
85
+ const pid = parseInt(match[1], 10);
86
+ if (isNaN(pid)) continue;
87
+ if (line.includes(`--port`) && line.includes(String(port))) {
88
+ return pid;
89
+ }
90
+ }
91
+ return null;
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ export async function stopServer(
98
+ serverConfig: ServerConfig,
99
+ gracefulTimeout = 10000
100
+ ): Promise<void> {
101
+ let pid = state.activePid;
102
+
103
+ if (!pid || !isProcessAlive(pid)) {
104
+ pid = findLlamaServerPid(serverConfig.port);
105
+ if (pid) {
106
+ state.activePid = pid;
107
+ writePidFile(pid);
108
+ }
109
+ }
110
+
111
+ if (pid && isProcessAlive(pid) && isLlamaServer(pid)) {
112
+ try {
113
+ process.kill(pid, "SIGTERM");
114
+ } catch {
115
+ // Process already dead
116
+ }
117
+
118
+ const deadline = Date.now() + gracefulTimeout;
119
+ while (Date.now() < deadline && isProcessAlive(pid)) {
120
+ await new Promise((r) => setTimeout(r, 200));
121
+ }
122
+
123
+ if (isProcessAlive(pid)) {
124
+ try {
125
+ process.kill(pid, "SIGKILL");
126
+ } catch {
127
+ // Already dead
128
+ }
129
+ // Give OS time to reclaim socket after SIGKILL
130
+ await new Promise((r) => setTimeout(r, 2000));
131
+ }
132
+ }
133
+
134
+ // Wait for port release
135
+ await waitForPortRelease(
136
+ serverConfig.host,
137
+ serverConfig.port,
138
+ serverConfig.portReleaseTimeout
139
+ );
140
+ }
141
+
142
+ async function waitForPortRelease(
143
+ host: string,
144
+ port: number,
145
+ timeout: number
146
+ ): Promise<void> {
147
+ const net = await import("node:net");
148
+ const deadline = Date.now() + timeout * 1000;
149
+
150
+ while (Date.now() < deadline) {
151
+ const connected = await new Promise<boolean>((resolve) => {
152
+ const socket = new net.Socket();
153
+ socket.setTimeout(1000);
154
+ socket.on("connect", () => {
155
+ socket.destroy();
156
+ resolve(true);
157
+ });
158
+ socket.on("timeout", () => {
159
+ socket.destroy();
160
+ resolve(false);
161
+ });
162
+ socket.on("error", () => {
163
+ resolve(false);
164
+ });
165
+ socket.connect(port, host);
166
+ });
167
+
168
+ if (!connected) return;
169
+
170
+ await new Promise((r) => setTimeout(r, 500));
171
+ }
172
+
173
+ throw new Error(
174
+ `Port ${port} is still in use after ${timeout}s. Try: lsof -ti:${port}`
175
+ );
176
+ }
177
+
178
+ export interface SwitchProgressCallback {
179
+ onStatusUpdate?: (message: string) => void;
180
+ onHealthProgress?: (elapsed: number, status: { status: string; error?: string }) => void;
181
+ }
182
+
183
+ export async function switchModel(
184
+ config: SwitcherConfig,
185
+ modelKey: string,
186
+ progress?: SwitchProgressCallback,
187
+ signal?: AbortSignal
188
+ ): Promise<void> {
189
+ const model = config.models[modelKey];
190
+ if (!model) {
191
+ throw new Error(
192
+ `Model '${modelKey}' not found. Available: ${Object.keys(config.models).join(", ")}`
193
+ );
194
+ }
195
+
196
+ if (state.isSwitching) {
197
+ throw new Error("Switch already in progress");
198
+ }
199
+
200
+ state.isSwitching = true;
201
+ let child: ChildProcess | null = null;
202
+
203
+ try {
204
+ progress?.onStatusUpdate?.(`Stopping current server...`);
205
+ await stopServer(config.server);
206
+
207
+ progress?.onStatusUpdate?.(`Starting ${model.name}...`);
208
+ const logPath = getLogPath();
209
+ const logStream = createWriteStream(logPath, { flags: "w" });
210
+ child = spawn(model.command[0], model.command.slice(1), {
211
+ detached: true,
212
+ stdio: ["ignore", "ignore", logStream],
213
+ env: { ...process.env, ...(model.env ?? {}) },
214
+ });
215
+
216
+ if (!child.pid) {
217
+ throw new Error("Failed to start llama-server: no PID returned");
218
+ }
219
+
220
+ child.unref();
221
+
222
+ state.activePid = child.pid;
223
+ writePidFile(child.pid);
224
+
225
+ // Abort health check if child exits unexpectedly
226
+ const childAbort = new AbortController();
227
+ const combinedSignal = signal
228
+ ? AbortSignal.any([signal, childAbort.signal])
229
+ : childAbort.signal;
230
+
231
+ child.on("error", (err) => {
232
+ console.error(`llama-server process error: ${err.message}`);
233
+ childAbort.abort();
234
+ state.activeModelKey = null;
235
+ state.activePid = null;
236
+ deletePidFile();
237
+ });
238
+
239
+ child.on("exit", (code) => {
240
+ if (code !== null && code !== 0) {
241
+ console.error(`llama-server exited with code ${code}`);
242
+ }
243
+ childAbort.abort();
244
+ if (child && state.activePid === child.pid) {
245
+ state.activeModelKey = null;
246
+ state.activePid = null;
247
+ deletePidFile();
248
+ }
249
+ });
250
+
251
+ progress?.onStatusUpdate?.(`Waiting for ${model.name} to be ready...`);
252
+ await waitForHealth(
253
+ config.server,
254
+ (elapsed, status) => {
255
+ progress?.onHealthProgress?.(elapsed, {
256
+ status: status.status,
257
+ error: status.error,
258
+ });
259
+ progress?.onStatusUpdate?.(
260
+ `Loading ${model.name}... ${elapsed}s (${status.status})`
261
+ );
262
+ },
263
+ combinedSignal
264
+ );
265
+
266
+ state.activeModelKey = modelKey;
267
+ progress?.onStatusUpdate?.(`Switched to ${model.name}`);
268
+ } catch (err) {
269
+ if (child) {
270
+ try { child.kill("SIGKILL"); } catch {}
271
+ }
272
+ state.activeModelKey = null;
273
+ state.activePid = null;
274
+ deletePidFile();
275
+ throw err;
276
+ } finally {
277
+ state.isSwitching = false;
278
+ }
279
+ }
280
+
281
+ export function disconnectState(): void {
282
+ state.activeModelKey = null;
283
+ state.activePid = null;
284
+ state.isSwitching = false;
285
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "esModuleInterop": true,
7
+ "strict": true,
8
+ "skipLibCheck": true,
9
+ "outDir": "./dist",
10
+ "rootDir": "./src",
11
+ "declaration": true,
12
+ "sourceMap": true,
13
+ "resolveJsonModule": true
14
+ },
15
+ "include": ["src/**/*.ts"],
16
+ "exclude": ["node_modules", "dist"]
17
+ }