@dylanhalstead/pi-model-switch-guard 0.0.0-stage → 0.1.1

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/package.json +39 -3
  4. package/src/index.ts +231 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dylan Halstead
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 CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # Model switch guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Confirm the first prompt after a mid-session model switch, or undo the pending
4
+ switch before sending anything.
5
+
6
+ I usually want to stay on the same model for the whole session. Switching models
7
+ means loading, and paying, for the re-reading of a sessions. In this case, 90%
8
+ of the time I prefer making a handoff document, so this is a sanity check to
9
+ make sure I truely want to do this.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pi install npm:@dylanhalstead/pi-model-switch-guard
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Select models freely before the first turn starts. After that, changing models
20
+ shows a status warning. Sending the next non-empty interactive prompt asks
21
+ whether to use the new model:
22
+
23
+ - Choose Yes to send the prompt and confirm the switch.
24
+ - Choose No or cancel to restore the original model and keep the prompt text in
25
+ the editor without sending it.
26
+ - If restoration fails, the extension shows an error and asks again on the next
27
+ submission.
28
+
29
+ Use `/model-undo` or `ctrl+alt+m` to undo an unconfirmed switch without sending a
30
+ prompt. Undo only applies to pending switches; it does not provide model history.
31
+ Switching back to the original model clears the warning.
32
+
33
+ No configuration is needed. Use Pi's model selector as usual.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@dylanhalstead/pi-model-switch-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Confirm mid-session model switches before sending the next Pi prompt.",
5
+ "keywords": [
6
+ "pi-extension",
7
+ "pi-package"
8
+ ],
9
+ "homepage": "https://github.com/DylanHalstead/pi-extensions/tree/main/extensions/model-switch-guard#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/DylanHalstead/pi-extensions/issues"
12
+ },
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/DylanHalstead/pi-extensions.git",
17
+ "directory": "extensions/model-switch-guard"
18
+ },
19
+ "files": [
20
+ "src/index.ts",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "type": "module",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-ai": "*",
30
+ "@earendil-works/pi-coding-agent": "*"
31
+ },
32
+ "pi": {
33
+ "extensions": [
34
+ "./src/index.ts"
35
+ ]
36
+ },
37
+ "scripts": {
38
+ "check": "vp -C ../.. check extensions/model-switch-guard",
39
+ "typecheck": "vp check --no-fmt --no-lint .",
40
+ "test": "vp -C ../.. test extensions/model-switch-guard/src"
41
+ }
6
42
  }
package/src/index.ts ADDED
@@ -0,0 +1,231 @@
1
+ import { modelsAreEqual, type Api, type Model } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI, ExtensionContext, InputEvent } from "@earendil-works/pi-coding-agent";
3
+
4
+ function modelLabel(model: Pick<Model<Api>, "provider" | "id">): string {
5
+ return `${model.provider}/${model.id}`;
6
+ }
7
+
8
+ interface PendingSwitch {
9
+ from: Model<Api>;
10
+ to: Model<Api>;
11
+ }
12
+
13
+ interface SwitchOperation {
14
+ change: PendingSwitch;
15
+ generation: number;
16
+ }
17
+
18
+ interface Confirmation extends SwitchOperation {
19
+ controller: AbortController;
20
+ }
21
+
22
+ export default function modelSwitchGuard(pi: ExtensionAPI): void {
23
+ let pendingSwitch: PendingSwitch | undefined;
24
+ let reverting: SwitchOperation | undefined;
25
+ let confirmation: Confirmation | undefined;
26
+ let generation = 0;
27
+ let hasHadTurn = false;
28
+
29
+ function isCurrent(operation: SwitchOperation): boolean {
30
+ return generation === operation.generation;
31
+ }
32
+
33
+ function notify(
34
+ ctx: ExtensionContext,
35
+ message: string,
36
+ type: "info" | "warning" | "error",
37
+ ): void {
38
+ try {
39
+ ctx.ui.notify(message, type);
40
+ } catch {
41
+ // Pi invalidates a replaced session's context while asynchronous work settles.
42
+ }
43
+ }
44
+
45
+ function updateStatus(ctx: ExtensionContext): void {
46
+ if (ctx.mode !== "tui") return;
47
+ try {
48
+ ctx.ui.setStatus(
49
+ "model-switch-guard",
50
+ pendingSwitch
51
+ ? `⇄ model: ${modelLabel(pendingSwitch.from)} → ${modelLabel(pendingSwitch.to)} (ctrl+alt+m to revert)`
52
+ : undefined,
53
+ );
54
+ } catch {
55
+ // The lifecycle handlers can race session replacement after their event is delivered.
56
+ }
57
+ }
58
+
59
+ function invalidate(): void {
60
+ generation += 1;
61
+ confirmation?.controller.abort();
62
+ confirmation = undefined;
63
+ reverting = undefined;
64
+ }
65
+
66
+ function resetSession(_event: unknown, ctx: ExtensionContext): void {
67
+ invalidate();
68
+ pendingSwitch = undefined;
69
+ hasHadTurn = ctx.sessionManager
70
+ .getBranch()
71
+ .some((entry) => entry.type === "message" && entry.message.role === "assistant");
72
+ updateStatus(ctx);
73
+ }
74
+
75
+ async function revertModel(ctx: ExtensionContext): Promise<void> {
76
+ const change = pendingSwitch;
77
+ if (!change || reverting) return;
78
+
79
+ const operation = { change, generation };
80
+ reverting = operation;
81
+ try {
82
+ const restored = await pi.setModel(change.from);
83
+ if (!isCurrent(operation) || reverting !== operation) return;
84
+ if (!restored) {
85
+ notify(
86
+ ctx,
87
+ `Could not revert to ${modelLabel(change.from)}. Check provider authentication; the switch remains pending.`,
88
+ "error",
89
+ );
90
+ return;
91
+ }
92
+
93
+ // setModel normally emits model_select; this also handles hosts that have already updated ctx.model.
94
+ const isRestored = modelsAreEqual(ctx.model, change.from);
95
+ if (pendingSwitch === change && isRestored) pendingSwitch = undefined;
96
+ updateStatus(ctx);
97
+ if (isRestored) notify(ctx, `Reverted to ${modelLabel(change.from)}`, "info");
98
+ } catch (error) {
99
+ if (!isCurrent(operation) || reverting !== operation) return;
100
+ notify(
101
+ ctx,
102
+ `Could not revert to ${modelLabel(change.from)}: ${error instanceof Error ? error.message : String(error)}`,
103
+ "error",
104
+ );
105
+ } finally {
106
+ if (reverting === operation) reverting = undefined;
107
+ }
108
+ }
109
+
110
+ function restorePrompt(
111
+ event: InputEvent,
112
+ ctx: ExtensionContext,
113
+ operation: SwitchOperation,
114
+ ): void {
115
+ if (!isCurrent(operation)) return;
116
+ try {
117
+ // Pi supplies the current input-chain text, not the original before other transformations.
118
+ ctx.ui.setEditorText(event.text);
119
+ } catch {
120
+ return;
121
+ }
122
+ notify(
123
+ ctx,
124
+ event.images?.length
125
+ ? "Prompt text restored. Reattach images before resubmitting; Pi's editor API cannot restore attachments."
126
+ : "Your prompt was restored to the editor.",
127
+ event.images?.length ? "warning" : "info",
128
+ );
129
+ }
130
+
131
+ async function undoSwitch(ctx: ExtensionContext): Promise<void> {
132
+ if (ctx.mode !== "tui") return;
133
+ if (!pendingSwitch) {
134
+ notify(ctx, "No pending model switch to revert", "info");
135
+ return;
136
+ }
137
+ await revertModel(ctx);
138
+ }
139
+
140
+ pi.on("session_start", resetSession);
141
+ pi.on("session_tree", resetSession);
142
+ pi.on("session_shutdown", () => {
143
+ invalidate();
144
+ pendingSwitch = undefined;
145
+ });
146
+ pi.on("turn_start", () => {
147
+ hasHadTurn = true;
148
+ });
149
+
150
+ pi.on("model_select", (event, ctx) => {
151
+ if (ctx.mode !== "tui" || event.source === "restore" || !hasHadTurn || !event.previousModel)
152
+ return;
153
+ if (modelsAreEqual(event.previousModel, event.model)) return;
154
+ pendingSwitch =
155
+ pendingSwitch && modelsAreEqual(event.model, pendingSwitch.from)
156
+ ? undefined
157
+ : { from: pendingSwitch?.from ?? event.previousModel, to: event.model };
158
+ updateStatus(ctx);
159
+ });
160
+
161
+ pi.registerShortcut("ctrl+alt+m", {
162
+ description: "Undo a pending model switch",
163
+ handler: undoSwitch,
164
+ });
165
+ pi.registerCommand("model-undo", {
166
+ description: "Revert an unconfirmed switch to its original model",
167
+ handler: (_args, ctx) => undoSwitch(ctx),
168
+ });
169
+
170
+ pi.on("input", async (event, ctx) => {
171
+ const change = pendingSwitch;
172
+ if (ctx.mode !== "tui" || event.source !== "interactive" || !change || !event.text.trim()) {
173
+ return { action: "continue" };
174
+ }
175
+
176
+ const operation = { change, generation };
177
+ if (reverting || confirmation) {
178
+ restorePrompt(event, ctx, operation);
179
+ return { action: "handled" };
180
+ }
181
+
182
+ const controller = new AbortController();
183
+ const activeConfirmation = { ...operation, controller };
184
+ confirmation = activeConfirmation;
185
+ let proceed = false;
186
+ try {
187
+ proceed = await ctx.ui.confirm(
188
+ "Model was just changed",
189
+ `Send this prompt using ${modelLabel(change.to)}?\n\nPrevious model: ${modelLabel(change.from)}\n\nChoose No to revert and keep your prompt in the editor.`,
190
+ { signal: controller.signal },
191
+ );
192
+ } catch (error) {
193
+ if (isCurrent(activeConfirmation) && confirmation === activeConfirmation) {
194
+ notify(
195
+ ctx,
196
+ `Could not confirm the model switch: ${error instanceof Error ? error.message : String(error)}`,
197
+ "error",
198
+ );
199
+ restorePrompt(event, ctx, activeConfirmation);
200
+ }
201
+ return { action: "handled" };
202
+ } finally {
203
+ if (confirmation === activeConfirmation) confirmation = undefined;
204
+ }
205
+
206
+ if (
207
+ !isCurrent(activeConfirmation) ||
208
+ pendingSwitch !== change ||
209
+ reverting ||
210
+ !modelsAreEqual(ctx.model, change.to)
211
+ ) {
212
+ restorePrompt(event, ctx, activeConfirmation);
213
+ if (isCurrent(activeConfirmation)) {
214
+ notify(
215
+ ctx,
216
+ "The model changed while confirming. Review it before resubmitting.",
217
+ "warning",
218
+ );
219
+ }
220
+ return { action: "handled" };
221
+ }
222
+ if (proceed) {
223
+ pendingSwitch = undefined;
224
+ updateStatus(ctx);
225
+ return { action: "continue" };
226
+ }
227
+ await revertModel(ctx);
228
+ restorePrompt(event, ctx, activeConfirmation);
229
+ return { action: "handled" };
230
+ });
231
+ }