@howaboua/pi-gpt-switcher 0.1.0 → 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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # @howaboua/pi-gpt-switcher
2
+
3
+ ## 0.1.1
4
+
5
+ ### Changes
6
+
7
+ - [#333](https://github.com/IgorWarzocha/howaboua-pi-stuff/pull/333) [`a9143cf`](https://github.com/IgorWarzocha/howaboua-pi-stuff/commit/a9143cfeb802406c2e62b4424e27b69da141b7ae) Thanks [@IgorWarzocha](https://github.com/IgorWarzocha)! - Add configurable session context windows and reasoning defaults for GPT shortcuts.
8
+
9
+ ## 0.1.0
10
+
11
+ ### Changes
12
+
13
+ - [#164](https://github.com/IgorWarzocha/howaboua-pi-stuff/pull/164) [`b8731f6`](https://github.com/IgorWarzocha/howaboua-pi-stuff/commit/b8731f68c8b6cbfb167e29728aad07fb59e560bb) Thanks [@IgorWarzocha](https://github.com/IgorWarzocha)!:
14
+ - Add `/sol`, `/terra`, and `/luna` commands for switching GPT-5.6 Codex models and reasoning levels.
package/README.md CHANGED
@@ -8,8 +8,27 @@ Pi extension adding quick model commands:
8
8
  | `/terra [reasoning]` | `openai-codex/gpt-5.6-terra` |
9
9
  | `/luna [reasoning]` | `openai-codex/gpt-5.6-luna` |
10
10
 
11
- Reasoning defaults to `high`. Valid arguments are `off`, `minimal`, `low`,
12
- `medium`, `high`, `xhigh`, and `max`; for example, `/luna low`.
11
+ An explicit reasoning argument overrides the configured default. Valid arguments
12
+ are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`; for example,
13
+ `/luna low`.
14
+
15
+ ## Defaults
16
+
17
+ On first load, the extension creates `pi-gpt-switcher.json` in Pi's global
18
+ agent directory:
19
+
20
+ ```json
21
+ {
22
+ "sol": { "contextWindow": 272000, "reasoning": "high" },
23
+ "terra": { "contextWindow": 872000, "reasoning": "high" },
24
+ "luna": { "contextWindow": 472000, "reasoning": "xhigh" }
25
+ }
26
+ ```
27
+
28
+ Edit the file to change a shortcut's session context window or default
29
+ reasoning. Changes apply on the next shortcut invocation and do not alter the
30
+ provider catalogue. Context windows may be lowered to 128k but not raised
31
+ above the shortcut's shipped limit.
13
32
 
14
33
  ## Install
15
34
 
@@ -29,8 +48,8 @@ The commands use Pi's model registry and normal provider authentication. If a
29
48
  model is unavailable or the OpenAI Codex credentials are missing, the command
30
49
  reports that instead of changing the current model.
31
50
 
32
- Reasoning defaults to `high`. Pi clamps the requested level automatically if
33
- the selected model supports fewer levels.
51
+ Pi clamps the requested reasoning level automatically if the selected model
52
+ supports fewer levels.
34
53
 
35
54
  ## Local development
36
55
 
package/biome.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.4.16/schema.json",
2
+ "$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
package/changelog.ts ADDED
@@ -0,0 +1,327 @@
1
+ // Generated extension packages copy this file during changelog:extensions.
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ DynamicBorder,
10
+ type ExtensionAPI,
11
+ getAgentDir,
12
+ getMarkdownTheme,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
15
+
16
+ const ENTRY_TYPE = "@howaboua/pi-stuff/changelog";
17
+ const REGISTRATION_CHANNEL = "@howaboua/pi-stuff/changelog/register/v1";
18
+ const STATE_FILENAME = "howaboua-pi-stuff-changelog.json";
19
+ const SUPPRESS_KEY = "suppress";
20
+ const LOCK_STALE_MS = 30_000;
21
+ const LOCK_TIMEOUT_MS = 2_000;
22
+
23
+ interface PackageMetadata {
24
+ name: string;
25
+ version: string;
26
+ }
27
+
28
+ interface PackageRegistration extends PackageMetadata {
29
+ changelogPath: string;
30
+ }
31
+
32
+ interface RegistrationEvent {
33
+ accept: () => void;
34
+ registration: PackageRegistration;
35
+ }
36
+
37
+ interface ChangelogEntry {
38
+ content: string;
39
+ version: string;
40
+ }
41
+
42
+ interface ChangelogEntryData {
43
+ markdown: string;
44
+ }
45
+
46
+ type ChangelogState = Record<string, boolean | string>;
47
+
48
+ function packageRegistration(): PackageRegistration {
49
+ const packageDirectory = fileURLToPath(new URL(".", import.meta.url));
50
+ const metadata = JSON.parse(
51
+ readFileSync(join(packageDirectory, "package.json"), "utf8"),
52
+ ) as Partial<PackageMetadata>;
53
+ if (typeof metadata.name !== "string" || typeof metadata.version !== "string")
54
+ throw new Error(`Invalid package metadata in ${packageDirectory}`);
55
+ return {
56
+ name: metadata.name,
57
+ version: metadata.version,
58
+ changelogPath: join(packageDirectory, "CHANGELOG.md"),
59
+ };
60
+ }
61
+
62
+ function isRegistrationEvent(value: unknown): value is RegistrationEvent {
63
+ if (!value || typeof value !== "object") return false;
64
+ const event = value as Partial<RegistrationEvent>;
65
+ return (
66
+ typeof event.accept === "function" &&
67
+ typeof event.registration?.name === "string" &&
68
+ typeof event.registration.version === "string" &&
69
+ typeof event.registration.changelogPath === "string"
70
+ );
71
+ }
72
+
73
+ function parseChangelog(markdown: string): ChangelogEntry[] {
74
+ const entries: ChangelogEntry[] = [];
75
+ let currentLines: string[] = [];
76
+ let currentVersion: string | undefined;
77
+
78
+ for (const line of markdown.split("\n")) {
79
+ const version = line.match(/^##\s+\[?(\d+\.\d+\.\d+)\]?(?:\s.*)?$/)?.[1];
80
+ if (version) {
81
+ if (currentVersion)
82
+ entries.push({
83
+ content: currentLines.join("\n").trim(),
84
+ version: currentVersion,
85
+ });
86
+ currentVersion = version;
87
+ currentLines = [line];
88
+ } else if (currentVersion) {
89
+ currentLines.push(line);
90
+ }
91
+ }
92
+
93
+ if (currentVersion)
94
+ entries.push({
95
+ content: currentLines.join("\n").trim(),
96
+ version: currentVersion,
97
+ });
98
+ return entries;
99
+ }
100
+
101
+ function compareVersions(left: string, right: string): number {
102
+ const leftParts = left.split(".").map(Number);
103
+ const rightParts = right.split(".").map(Number);
104
+ for (let index = 0; index < 3; index++) {
105
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
106
+ if (difference !== 0) return difference;
107
+ }
108
+ return 0;
109
+ }
110
+
111
+ function isStableVersion(version: string): boolean {
112
+ return /^\d+\.\d+\.\d+$/.test(version);
113
+ }
114
+
115
+ function statePath(): string {
116
+ return join(getAgentDir(), STATE_FILENAME);
117
+ }
118
+
119
+ async function readState(path: string): Promise<ChangelogState> {
120
+ let text: string;
121
+ try {
122
+ text = await readFile(path, "utf8");
123
+ } catch (error) {
124
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
125
+ throw error;
126
+ }
127
+ const parsed = JSON.parse(text) as unknown;
128
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
129
+ throw new Error(`${path} must contain a JSON object`);
130
+ for (const [name, value] of Object.entries(parsed)) {
131
+ if (name === SUPPRESS_KEY) {
132
+ if (typeof value !== "boolean")
133
+ throw new Error(`${path} ${SUPPRESS_KEY} must be a boolean`);
134
+ } else if (typeof value !== "string") {
135
+ throw new Error(`${path} version for ${name} must be a string`);
136
+ }
137
+ }
138
+ return parsed as ChangelogState;
139
+ }
140
+
141
+ async function acquireLock(path: string): Promise<() => Promise<void>> {
142
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
143
+ while (true) {
144
+ try {
145
+ await mkdir(path);
146
+ return () => rm(path, { force: true, recursive: true });
147
+ } catch (error) {
148
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
149
+ const info = await stat(path).catch(() => undefined);
150
+ if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
151
+ await rm(path, { force: true, recursive: true });
152
+ continue;
153
+ }
154
+ if (Date.now() >= deadline)
155
+ throw new Error(`Timed out waiting for ${path}`);
156
+ await new Promise((resolve) => setTimeout(resolve, 20));
157
+ }
158
+ }
159
+ }
160
+
161
+ async function writeState(path: string, state: ChangelogState): Promise<void> {
162
+ await mkdir(dirname(path), { mode: 0o700, recursive: true });
163
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
164
+ try {
165
+ const ordered = Object.fromEntries(
166
+ Object.entries(state).sort(([left], [right]) =>
167
+ left.localeCompare(right),
168
+ ),
169
+ );
170
+ await writeFile(temporaryPath, `${JSON.stringify(ordered, null, 2)}\n`, {
171
+ encoding: "utf8",
172
+ mode: 0o600,
173
+ });
174
+ await rename(temporaryPath, path);
175
+ } catch (error) {
176
+ await rm(temporaryPath, { force: true });
177
+ throw error;
178
+ }
179
+ }
180
+
181
+ function packageMarkdown(
182
+ registration: PackageRegistration,
183
+ entries: ChangelogEntry[],
184
+ ): string {
185
+ return [
186
+ `## ${registration.name}`,
187
+ ...entries.map((entry) => entry.content.replace(/^##\s+/, "### ")),
188
+ ].join("\n\n");
189
+ }
190
+
191
+ async function claimUpdates(
192
+ registrations: Iterable<PackageRegistration>,
193
+ ): Promise<{ errors: string[]; markdown?: string }> {
194
+ const stableRegistrations = [...registrations]
195
+ .filter((registration) => isStableVersion(registration.version))
196
+ .sort((left, right) => left.name.localeCompare(right.name));
197
+ if (stableRegistrations.length === 0) return { errors: [] };
198
+ const path = statePath();
199
+ await mkdir(dirname(path), { mode: 0o700, recursive: true });
200
+ const release = await acquireLock(`${path}.lock`);
201
+ try {
202
+ const state = await readState(path);
203
+ const errors: string[] = [];
204
+ const sections: string[] = [];
205
+ let changed = false;
206
+ if (state[SUPPRESS_KEY] === true) {
207
+ for (const registration of stableRegistrations) {
208
+ const seenVersion = state[registration.name];
209
+ if (
210
+ typeof seenVersion !== "string" ||
211
+ compareVersions(registration.version, seenVersion) > 0
212
+ ) {
213
+ state[registration.name] = registration.version;
214
+ changed = true;
215
+ }
216
+ }
217
+ if (changed) await writeState(path, state);
218
+ return { errors };
219
+ }
220
+ for (const registration of stableRegistrations) {
221
+ const seenVersion = state[registration.name];
222
+ if (
223
+ typeof seenVersion === "string" &&
224
+ compareVersions(registration.version, seenVersion) <= 0
225
+ )
226
+ continue;
227
+ try {
228
+ const entries = parseChangelog(
229
+ await readFile(registration.changelogPath, "utf8"),
230
+ ).filter(
231
+ (entry) =>
232
+ compareVersions(entry.version, registration.version) <= 0 &&
233
+ (typeof seenVersion === "string"
234
+ ? compareVersions(entry.version, seenVersion) > 0
235
+ : entry.version === registration.version),
236
+ );
237
+ if (entries.length === 0) {
238
+ errors.push(
239
+ `No ${registration.version} changelog entry found for ${registration.name}`,
240
+ );
241
+ continue;
242
+ }
243
+ sections.push(packageMarkdown(registration, entries));
244
+ state[registration.name] = registration.version;
245
+ changed = true;
246
+ } catch (error) {
247
+ errors.push(
248
+ `Could not read the ${registration.name} changelog: ${error instanceof Error ? error.message : String(error)}`,
249
+ );
250
+ }
251
+ }
252
+ if (changed) await writeState(path, state);
253
+ return {
254
+ errors,
255
+ ...(sections.length > 0 ? { markdown: sections.join("\n\n") } : {}),
256
+ };
257
+ } finally {
258
+ await release();
259
+ }
260
+ }
261
+
262
+ function registerCoordinator(
263
+ pi: ExtensionAPI,
264
+ registration: PackageRegistration,
265
+ ): void {
266
+ let accepted = false;
267
+ pi.events.emit(REGISTRATION_CHANNEL, {
268
+ registration,
269
+ accept: () => {
270
+ accepted = true;
271
+ },
272
+ } satisfies RegistrationEvent);
273
+ if (accepted) return;
274
+
275
+ const registrations = new Map([[registration.name, registration]]);
276
+ pi.events.on(REGISTRATION_CHANNEL, (value) => {
277
+ if (!isRegistrationEvent(value)) return;
278
+ registrations.set(value.registration.name, value.registration);
279
+ value.accept();
280
+ });
281
+ pi.registerEntryRenderer<ChangelogEntryData>(
282
+ ENTRY_TYPE,
283
+ (entry, _options, theme) => {
284
+ if (!entry.data) return undefined;
285
+ const container = new Container();
286
+ container.addChild(new DynamicBorder());
287
+ container.addChild(
288
+ new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0),
289
+ );
290
+ container.addChild(new Spacer(1));
291
+ container.addChild(
292
+ new Markdown(entry.data.markdown.trim(), 1, 0, getMarkdownTheme()),
293
+ );
294
+ container.addChild(new Spacer(1));
295
+ container.addChild(new DynamicBorder());
296
+ return container;
297
+ },
298
+ );
299
+ pi.on("session_start", async (event, ctx) => {
300
+ if (event.reason === "reload" || ctx.mode !== "tui") return;
301
+ if (
302
+ ctx.sessionManager
303
+ .getEntries()
304
+ .some((entry) =>
305
+ ["branch_summary", "compaction", "message"].includes(entry.type),
306
+ )
307
+ )
308
+ return;
309
+ try {
310
+ const update = await claimUpdates(registrations.values());
311
+ if (update.markdown)
312
+ pi.appendEntry<ChangelogEntryData>(ENTRY_TYPE, {
313
+ markdown: update.markdown,
314
+ });
315
+ for (const error of update.errors) ctx.ui.notify(error, "warning");
316
+ } catch (error) {
317
+ ctx.ui.notify(
318
+ `Could not update Howaboua changelog state: ${error instanceof Error ? error.message : String(error)}`,
319
+ "warning",
320
+ );
321
+ }
322
+ });
323
+ }
324
+
325
+ export default function howabouaPackageChangelog(pi: ExtensionAPI): void {
326
+ registerCoordinator(pi, packageRegistration());
327
+ }
@@ -5,6 +5,14 @@
5
5
  */
6
6
 
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ ensureGptSwitcherConfig,
10
+ type GptSwitcherConfig,
11
+ readGptSwitcherConfig,
12
+ type ShortcutAlias,
13
+ THINKING_LEVELS,
14
+ type ThinkingLevel,
15
+ } from "./config.js";
8
16
 
9
17
  const MODELS = {
10
18
  sol: "gpt-5.6-sol",
@@ -12,41 +20,32 @@ const MODELS = {
12
20
  luna: "gpt-5.6-luna",
13
21
  } as const;
14
22
 
15
- type Alias = keyof typeof MODELS;
16
- type ThinkingLevel =
17
- | "off"
18
- | "minimal"
19
- | "low"
20
- | "medium"
21
- | "high"
22
- | "xhigh"
23
- | "max";
23
+ type Alias = keyof typeof MODELS & ShortcutAlias;
24
24
 
25
- const DEFAULT_THINKING_LEVEL: ThinkingLevel = "high";
26
- const THINKING_LEVELS = new Set<ThinkingLevel>([
27
- "off",
28
- "minimal",
29
- "low",
30
- "medium",
31
- "high",
32
- "xhigh",
33
- "max",
34
- ]);
35
-
36
- function parseThinkingLevel(args: string): ThinkingLevel | undefined {
25
+ function parseThinkingLevel(
26
+ args: string,
27
+ defaultThinkingLevel: ThinkingLevel,
28
+ ): ThinkingLevel | undefined {
37
29
  const requested = args.trim().toLowerCase();
38
- if (requested === "") return DEFAULT_THINKING_LEVEL;
30
+ if (requested === "") return defaultThinkingLevel;
39
31
  return THINKING_LEVELS.has(requested as ThinkingLevel)
40
32
  ? (requested as ThinkingLevel)
41
33
  : undefined;
42
34
  }
43
35
 
44
- export default function (pi: ExtensionAPI) {
36
+ export default function (
37
+ pi: ExtensionAPI,
38
+ options: { getConfig?: () => GptSwitcherConfig } = {},
39
+ ) {
40
+ const getConfig = options.getConfig ?? readGptSwitcherConfig;
41
+ if (!options.getConfig) ensureGptSwitcherConfig();
42
+
45
43
  for (const alias of Object.keys(MODELS) as Alias[]) {
46
44
  pi.registerCommand(alias, {
47
45
  description: `Switch to GPT-5.6 ${alias.charAt(0).toUpperCase()}${alias.slice(1)}`,
48
46
  handler: async (args, ctx) => {
49
- const thinkingLevel = parseThinkingLevel(args);
47
+ const defaults = getConfig()[alias];
48
+ const thinkingLevel = parseThinkingLevel(args, defaults.reasoning);
50
49
  if (!thinkingLevel) {
51
50
  ctx.ui.notify(
52
51
  `Usage: /${alias} [off|minimal|low|medium|high|xhigh|max]`,
@@ -63,12 +62,18 @@ export default function (pi: ExtensionAPI) {
63
62
  return;
64
63
  }
65
64
 
65
+ const selectedModel = {
66
+ ...model,
67
+ contextWindow: defaults.contextWindow,
68
+ };
66
69
  const alreadySelected =
67
- ctx.model?.provider === "openai-codex" && ctx.model.id === modelId;
70
+ ctx.model?.provider === "openai-codex" &&
71
+ ctx.model.id === modelId &&
72
+ ctx.model.contextWindow === defaults.contextWindow;
68
73
  if (!alreadySelected) {
69
74
  let switched: boolean;
70
75
  try {
71
- switched = await pi.setModel(model);
76
+ switched = await pi.setModel(selectedModel);
72
77
  } catch (error) {
73
78
  ctx.ui.notify(
74
79
  `Could not switch to ${model.name}: ${error instanceof Error ? error.message : String(error)}`,
package/config.ts ADDED
@@ -0,0 +1,158 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ export const SHORTCUT_ALIASES = ["sol", "terra", "luna"] as const;
6
+ export type ShortcutAlias = (typeof SHORTCUT_ALIASES)[number];
7
+ export type ThinkingLevel =
8
+ | "off"
9
+ | "minimal"
10
+ | "low"
11
+ | "medium"
12
+ | "high"
13
+ | "xhigh"
14
+ | "max";
15
+
16
+ export const THINKING_LEVELS = new Set<ThinkingLevel>([
17
+ "off",
18
+ "minimal",
19
+ "low",
20
+ "medium",
21
+ "high",
22
+ "xhigh",
23
+ "max",
24
+ ]);
25
+
26
+ export type ShortcutDefaults = {
27
+ contextWindow: number;
28
+ reasoning: ThinkingLevel;
29
+ };
30
+
31
+ export type GptSwitcherConfig = Record<ShortcutAlias, ShortcutDefaults>;
32
+
33
+ export const DEFAULT_GPT_SWITCHER_CONFIG: GptSwitcherConfig = {
34
+ sol: { contextWindow: 272_000, reasoning: "high" },
35
+ terra: { contextWindow: 872_000, reasoning: "high" },
36
+ luna: { contextWindow: 472_000, reasoning: "xhigh" },
37
+ };
38
+
39
+ const CONFIG_BASENAME = "pi-gpt-switcher.json";
40
+ const MIN_CONTEXT_WINDOW = 128_000;
41
+
42
+ function isObject(value: unknown): value is Record<string, unknown> {
43
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44
+ }
45
+
46
+ function configurationError(message: string): void {
47
+ console.warn(`[pi-gpt-switcher] ${message}`);
48
+ }
49
+
50
+ function normalizeContextWindow(
51
+ value: unknown,
52
+ fallback: number,
53
+ alias: ShortcutAlias,
54
+ ): number {
55
+ if (value === undefined) return fallback;
56
+ if (
57
+ typeof value === "number" &&
58
+ Number.isSafeInteger(value) &&
59
+ value >= MIN_CONTEXT_WINDOW &&
60
+ value <= fallback
61
+ )
62
+ return value;
63
+ configurationError(
64
+ `${alias}.contextWindow must be an integer from ${MIN_CONTEXT_WINDOW} to ${fallback}; using the default`,
65
+ );
66
+ return fallback;
67
+ }
68
+
69
+ function normalizeReasoning(
70
+ value: unknown,
71
+ fallback: ThinkingLevel,
72
+ alias: ShortcutAlias,
73
+ ): ThinkingLevel {
74
+ if (value === undefined) return fallback;
75
+ if (typeof value === "string") {
76
+ const normalized = value.trim().toLowerCase();
77
+ if (THINKING_LEVELS.has(normalized as ThinkingLevel))
78
+ return normalized as ThinkingLevel;
79
+ }
80
+ configurationError(
81
+ `${alias}.reasoning must be a supported Pi thinking level; using the default`,
82
+ );
83
+ return fallback;
84
+ }
85
+
86
+ export function normalizeGptSwitcherConfig(value: unknown): GptSwitcherConfig {
87
+ if (!isObject(value)) {
88
+ configurationError("configuration must be a JSON object; using defaults");
89
+ return structuredClone(DEFAULT_GPT_SWITCHER_CONFIG);
90
+ }
91
+
92
+ return Object.fromEntries(
93
+ SHORTCUT_ALIASES.map((alias) => {
94
+ const defaults = DEFAULT_GPT_SWITCHER_CONFIG[alias];
95
+ const configured = value[alias];
96
+ if (configured === undefined) return [alias, { ...defaults }];
97
+ if (!isObject(configured)) {
98
+ configurationError(`${alias} must be an object; using defaults`);
99
+ return [alias, { ...defaults }];
100
+ }
101
+ return [
102
+ alias,
103
+ {
104
+ contextWindow: normalizeContextWindow(
105
+ configured["contextWindow"],
106
+ defaults.contextWindow,
107
+ alias,
108
+ ),
109
+ reasoning: normalizeReasoning(
110
+ configured["reasoning"],
111
+ defaults.reasoning,
112
+ alias,
113
+ ),
114
+ },
115
+ ];
116
+ }),
117
+ ) as GptSwitcherConfig;
118
+ }
119
+
120
+ export function getGptSwitcherConfigPath(
121
+ agentDir: string = getAgentDir(),
122
+ ): string {
123
+ return join(agentDir, CONFIG_BASENAME);
124
+ }
125
+
126
+ export function ensureGptSwitcherConfig(
127
+ configPath: string = getGptSwitcherConfigPath(),
128
+ ): void {
129
+ if (existsSync(configPath)) return;
130
+ try {
131
+ mkdirSync(dirname(configPath), { recursive: true, mode: 0o700 });
132
+ writeFileSync(
133
+ configPath,
134
+ `${JSON.stringify(DEFAULT_GPT_SWITCHER_CONFIG, null, 2)}\n`,
135
+ { encoding: "utf8", mode: 0o600, flag: "wx" },
136
+ );
137
+ } catch (error) {
138
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return;
139
+ configurationError(
140
+ `could not create ${configPath}: ${error instanceof Error ? error.message : String(error)}`,
141
+ );
142
+ }
143
+ }
144
+
145
+ export function readGptSwitcherConfig(
146
+ configPath: string = getGptSwitcherConfigPath(),
147
+ ): GptSwitcherConfig {
148
+ try {
149
+ return normalizeGptSwitcherConfig(
150
+ JSON.parse(readFileSync(configPath, "utf8")) as unknown,
151
+ );
152
+ } catch (error) {
153
+ configurationError(
154
+ `could not read ${configPath}: ${error instanceof Error ? error.message : String(error)}; using defaults`,
155
+ );
156
+ return structuredClone(DEFAULT_GPT_SWITCHER_CONFIG);
157
+ }
158
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-gpt-switcher",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Quick Pi commands for switching between GPT-5.6 Codex models and reasoning levels.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,18 +31,23 @@
31
31
  "files": [
32
32
  "index.ts",
33
33
  "codex-model-shortcuts.ts",
34
+ "config.ts",
34
35
  "README.md",
35
36
  "LICENSE",
36
37
  "tsconfig.json",
37
- "biome.json"
38
+ "biome.json",
39
+ "changelog.ts",
40
+ "CHANGELOG.md"
38
41
  ],
39
42
  "pi": {
40
43
  "extensions": [
44
+ "./changelog.ts",
41
45
  "./index.ts"
42
46
  ]
43
47
  },
44
48
  "peerDependencies": {
45
- "@earendil-works/pi-coding-agent": ">=0.80.6"
49
+ "@earendil-works/pi-coding-agent": ">=0.80.6",
50
+ "@earendil-works/pi-tui": "*"
46
51
  },
47
52
  "devDependencies": {
48
53
  "@biomejs/biome": "^2.4.16",