pi-model-switcher 0.1.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 elied-dy
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,56 @@
1
+ # pi-model-switcher
2
+
3
+ Switch [Pi](https://pi.dev) models by [`pi-model-alias`](https://www.npmjs.com/package/@zigai/pi-model-alias) alias, with an optional thinking level.
4
+
5
+ ## Install
6
+
7
+ Install and configure the alias package first:
8
+
9
+ ```bash
10
+ pi install npm:@zigai/pi-model-alias
11
+ ```
12
+
13
+ Then install this package:
14
+
15
+ ```bash
16
+ pi install npm:pi-model-switcher
17
+ ```
18
+
19
+ Reload an existing Pi session with `/reload`.
20
+
21
+ ## Usage
22
+
23
+ ```text
24
+ /switch-model <alias> [thinking-level]
25
+ ```
26
+
27
+ Examples:
28
+
29
+ ```text
30
+ /switch-model terra
31
+ /switch-model sonnet high
32
+ ```
33
+
34
+ Valid thinking levels are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`.
35
+
36
+ When the level is omitted, Pi applies its configured default for the selected model. An explicit level affects only the current session and is clamped to the model's supported levels.
37
+
38
+ Aliases come from the active `pi-model-alias` settings:
39
+
40
+ - `~/.pi/agent/extension-settings/pi-model-alias.json`
41
+ - `<project>/.pi/extension-settings/pi-model-alias.json` for a trusted project override
42
+
43
+ Alias matching is exact and case-sensitive. If multiple providers define the same alias, `/switch-model` rejects the ambiguous name rather than guessing.
44
+
45
+ ## Development
46
+
47
+ ```bash
48
+ npm install
49
+ npm test
50
+ npm run typecheck
51
+ npm pack --dry-run
52
+ ```
53
+
54
+ ## License
55
+
56
+ MIT
@@ -0,0 +1,229 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ CONFIG_DIR_NAME,
5
+ getAgentDir,
6
+ type ExtensionAPI,
7
+ } from "@earendil-works/pi-coding-agent";
8
+
9
+ export const THINKING_LEVELS = [
10
+ "off",
11
+ "minimal",
12
+ "low",
13
+ "medium",
14
+ "high",
15
+ "xhigh",
16
+ "max",
17
+ ] as const;
18
+
19
+ export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
20
+
21
+ export interface AliasEntry {
22
+ provider: string;
23
+ model: string;
24
+ alias: string;
25
+ }
26
+
27
+ export interface ParsedCommand {
28
+ alias: string;
29
+ thinkingLevel?: ThinkingLevel;
30
+ }
31
+
32
+ export interface CompletionItem {
33
+ value: string;
34
+ label: string;
35
+ description: string;
36
+ }
37
+
38
+ const USAGE = `Usage: /switch-model <alias> [${THINKING_LEVELS.join("|")}]`;
39
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
40
+ typeof value === "object" && value !== null && !Array.isArray(value);
41
+
42
+ /** Tags parse/validation errors from pi-model-alias settings so loadActiveAliases
43
+ * can distinguish them from I/O errors without matching on message wording. */
44
+ export class AliasSettingsError extends Error {}
45
+
46
+ export function parseCommandArgs(input: string): ParsedCommand {
47
+ const parts = input.trim().split(/\s+/).filter(Boolean);
48
+ if (parts.length < 1 || parts.length > 2) throw new Error(USAGE);
49
+ const [alias, requestedLevel] = parts;
50
+ if (!alias) throw new Error(USAGE);
51
+ if (requestedLevel === undefined) return { alias };
52
+ if (!THINKING_LEVELS.includes(requestedLevel as ThinkingLevel)) {
53
+ throw new Error(`Invalid thinking level "${requestedLevel}". ${USAGE}`);
54
+ }
55
+ return { alias, thinkingLevel: requestedLevel as ThinkingLevel };
56
+ }
57
+
58
+ export function parseAliasSettings(raw: string): AliasEntry[] {
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(raw);
62
+ } catch {
63
+ throw new AliasSettingsError("pi-model-alias settings contain invalid JSON");
64
+ }
65
+ if (!isRecord(parsed) || !Array.isArray(parsed.aliases)) {
66
+ throw new AliasSettingsError("pi-model-alias settings must contain an aliases array");
67
+ }
68
+
69
+ const result = parsed.aliases.map((value, index) => {
70
+ if (!isRecord(value)) throw new AliasSettingsError(`Invalid alias at index ${index}`);
71
+ const provider = typeof value.provider === "string" ? value.provider.trim() : "";
72
+ const model = typeof value.model === "string" ? value.model.trim() : "";
73
+ const alias = typeof value.alias === "string" ? value.alias.trim() : "";
74
+ if (!provider || !model || !alias) throw new AliasSettingsError(`Invalid alias at index ${index}`);
75
+ return { provider, model, alias };
76
+ });
77
+
78
+ const seen = new Set<string>();
79
+ for (const entry of result) {
80
+ const key = `${entry.provider}\0${entry.alias}`;
81
+ if (seen.has(key)) {
82
+ throw new AliasSettingsError(`Duplicate alias "${entry.alias}" for provider "${entry.provider}"`);
83
+ }
84
+ seen.add(key);
85
+ }
86
+ return result;
87
+ }
88
+
89
+ export function selectAliasConfigPath(
90
+ globalPath: string,
91
+ projectPath: string,
92
+ projectTrusted: boolean,
93
+ projectExists: boolean,
94
+ ): string {
95
+ return projectTrusted && projectExists ? projectPath : globalPath;
96
+ }
97
+
98
+ export function loadActiveAliases(cwd: string, projectTrusted: boolean): AliasEntry[] {
99
+ const globalPath = join(getAgentDir(), "extension-settings", "pi-model-alias.json");
100
+ const projectPath = join(cwd, CONFIG_DIR_NAME, "extension-settings", "pi-model-alias.json");
101
+ const path = selectAliasConfigPath(globalPath, projectPath, projectTrusted, existsSync(projectPath));
102
+ try {
103
+ return parseAliasSettings(readFileSync(path, "utf8"));
104
+ } catch (error) {
105
+ if (error instanceof AliasSettingsError) throw error;
106
+ throw new Error(`Cannot read pi-model-alias settings from ${path}`);
107
+ }
108
+ }
109
+
110
+ export function resolveAlias(aliases: readonly AliasEntry[], requested: string): AliasEntry {
111
+ const matches = aliases.filter((entry) => entry.alias === requested);
112
+ if (matches.length === 0) {
113
+ const available = [...new Set(aliases.map((entry) => entry.alias))].sort();
114
+ throw new Error(`Unknown alias "${requested}". Available: ${available.join(", ") || "none"}`);
115
+ }
116
+ if (matches.length > 1) {
117
+ const providers = matches.map((entry) => entry.provider).sort();
118
+ throw new Error(`Ambiguous alias "${requested}". Providers: ${providers.join(", ")}`);
119
+ }
120
+ return matches[0]!;
121
+ }
122
+
123
+ export interface SwitchDependencies<T extends { provider: string; id: string }> {
124
+ findModel(provider: string, alias: string): T | undefined;
125
+ setModel(model: T): Promise<boolean>;
126
+ setThinkingLevel(level: ThinkingLevel): void;
127
+ getThinkingLevel(): ThinkingLevel;
128
+ }
129
+
130
+ export interface SwitchResult {
131
+ provider: string;
132
+ model: string;
133
+ thinkingLevel: ThinkingLevel;
134
+ }
135
+
136
+ export async function switchModel<T extends { provider: string; id: string }>(
137
+ input: string,
138
+ aliases: readonly AliasEntry[],
139
+ dependencies: SwitchDependencies<T>,
140
+ ): Promise<SwitchResult> {
141
+ const command = parseCommandArgs(input);
142
+ const alias = resolveAlias(aliases, command.alias);
143
+ const model = dependencies.findModel(alias.provider, alias.alias);
144
+ if (!model) {
145
+ throw new Error(
146
+ `Alias "${alias.alias}" is not available from Pi; ensure @zigai/pi-model-alias is installed, enabled, and valid`,
147
+ );
148
+ }
149
+
150
+ if (!(await dependencies.setModel(model))) {
151
+ throw new Error(`No authentication configured for ${model.provider}/${model.id}`);
152
+ }
153
+ if (command.thinkingLevel !== undefined) {
154
+ dependencies.setThinkingLevel(command.thinkingLevel);
155
+ }
156
+
157
+ return {
158
+ provider: model.provider,
159
+ model: model.id,
160
+ thinkingLevel: dependencies.getThinkingLevel(),
161
+ };
162
+ }
163
+
164
+ export function completeArguments(input: string, aliases: readonly AliasEntry[]): CompletionItem[] | null {
165
+ const levelMatch = input.match(/^(\S+)\s+(\S*)$/);
166
+ if (levelMatch) {
167
+ const [, alias, levelPrefix] = levelMatch;
168
+ if (!aliases.some((entry) => entry.alias === alias)) return null;
169
+ const items = THINKING_LEVELS
170
+ .filter((level) => level.startsWith(levelPrefix ?? ""))
171
+ .map((level) => ({
172
+ value: `${alias} ${level}`,
173
+ label: level,
174
+ description: "thinking level",
175
+ }));
176
+ return items.length > 0 ? items : null;
177
+ }
178
+
179
+ const items = aliases
180
+ .filter((entry) => entry.alias.startsWith(input))
181
+ .sort((a, b) => a.alias.localeCompare(b.alias) || a.provider.localeCompare(b.provider))
182
+ .map((entry) => ({
183
+ value: entry.alias,
184
+ label: entry.alias,
185
+ description: `${entry.provider}/${entry.model}`,
186
+ }));
187
+ return items.length > 0 ? items : null;
188
+ }
189
+
190
+ export default function switchModelExtension(pi: ExtensionAPI): void {
191
+ let cwd = process.cwd();
192
+ let projectTrusted = false;
193
+
194
+ pi.on("session_start", (_event, ctx) => {
195
+ cwd = ctx.cwd;
196
+ projectTrusted = ctx.isProjectTrusted();
197
+ });
198
+
199
+ pi.registerCommand("switch-model", {
200
+ description: "Switch model by alias with an optional thinking level",
201
+ getArgumentCompletions(input) {
202
+ try {
203
+ return completeArguments(input, loadActiveAliases(cwd, projectTrusted));
204
+ } catch {
205
+ return null;
206
+ }
207
+ },
208
+ async handler(input, ctx) {
209
+ try {
210
+ const result = await switchModel(
211
+ input,
212
+ loadActiveAliases(ctx.cwd, ctx.isProjectTrusted()),
213
+ {
214
+ findModel: (provider, alias) => ctx.modelRegistry.find(provider, alias),
215
+ setModel: (model) => pi.setModel(model),
216
+ setThinkingLevel: (level) => pi.setThinkingLevel(level),
217
+ getThinkingLevel: () => pi.getThinkingLevel(),
218
+ },
219
+ );
220
+ ctx.ui.notify(
221
+ `Switched to ${result.provider}/${result.model} (${result.thinkingLevel})`,
222
+ "info",
223
+ );
224
+ } catch (error) {
225
+ ctx.ui.notify(error instanceof Error ? error.message : "Model switch failed", "error");
226
+ }
227
+ },
228
+ });
229
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "pi-model-switcher",
3
+ "version": "0.1.0",
4
+ "description": "Switch Pi models by pi-model-alias name with an optional thinking level.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-coding-agent",
10
+ "pi-extension",
11
+ "model-alias",
12
+ "model-switcher"
13
+ ],
14
+ "files": [
15
+ "extensions",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test test/*.test.ts",
21
+ "typecheck": "tsc --noEmit"
22
+ },
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-coding-agent": "*"
25
+ },
26
+ "devDependencies": {
27
+ "@earendil-works/pi-coding-agent": "^0.85.1",
28
+ "@types/node": "^26.5.0",
29
+ "typescript": "^7.0.2"
30
+ },
31
+ "pi": {
32
+ "extensions": [
33
+ "./extensions/switch-model.ts"
34
+ ]
35
+ }
36
+ }