pi-model-costs 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) 2025 Maurizio Faedda
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,54 @@
1
+ # model-costs
2
+
3
+ Pricing-aware model picker for **pi** (https://pi.dev). The built-in `/model`
4
+ selector does not show pricing — this extension adds a model picker that shows
5
+ the real cost of each model before you switch.
6
+
7
+ ## Features
8
+
9
+ - **`/model-cost [query]`** — model picker with:
10
+ - per-1M-token input/output cost
11
+ - context window and max output tokens
12
+ - cache read/write rates and pricing tiers
13
+ - reasoning support and modality (text / text+image)
14
+ - same flow as `/model`: arrows to navigate, type to fuzzy-filter, `Tab`
15
+ toggles all/scoped (when scoped models are configured), `Enter` selects,
16
+ `Esc` cancels
17
+ - **Footer status** — pricing of the currently active model in the footer
18
+ (disable it by setting `SHOW_STATUS = false` in the source).
19
+
20
+ The current model is marked with a ✓ and sorted to the top.
21
+
22
+ ![model-cost picker](images/model-cost.png)
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ # from npm (recommended)
28
+ pi install npm:pi-model-costs
29
+
30
+ # from the gallery or a git repo
31
+ pi install git:github.com/MaurizioFaeddaDev/model-costs
32
+
33
+ # or, to try without installing:
34
+ pi -e npm:pi-model-costs
35
+ ```
36
+
37
+ > Only interactive (`tui`) mode supports the custom picker. In print/RPC mode
38
+ > the command notifies you that it is unavailable.
39
+
40
+ ## Usage
41
+
42
+ ```bash
43
+ /model-cost # browse all models
44
+ /model-cost claude # fuzzy-filter by provider/id/name
45
+ /model-cost $0.00 # fuzzy-filter by cost
46
+ ```
47
+
48
+ `/model-cost` extends the built-in `/model` selector; the actual model switch
49
+ still goes through pi's normal `setModel` path, so API keys are resolved the
50
+ same way.
51
+
52
+ ## License
53
+
54
+ MIT
package/model-costs.ts ADDED
@@ -0,0 +1,362 @@
1
+ /**
2
+ * Model Costs — pricing-aware model picker.
3
+ *
4
+ * The built-in /model selector does not show pricing. This extension adds:
5
+ *
6
+ * /model-cost [query] — model picker with $/1M-token pricing, context
7
+ * window, cache rates, tiers and reasoning support.
8
+ * Same flow as /model: arrows to navigate, type to
9
+ * fuzzy-filter, Tab toggles all/scoped (when scoped
10
+ * models are configured), Enter selects, Esc cancels.
11
+ *
12
+ * Footer status — pricing of the currently active model
13
+ * (set SHOW_STATUS = false below to disable).
14
+ */
15
+
16
+ import type { Api, Model, ModelCostTier, ThinkingLevel } from "@earendil-works/pi-ai";
17
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
18
+ import { DynamicBorder } from "@earendil-works/pi-coding-agent";
19
+ import { Container, type Focusable, fuzzyFilter, Input, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
20
+
21
+ const SHOW_STATUS = true;
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Formatting helpers
25
+ // ---------------------------------------------------------------------------
26
+
27
+ function trimZeros(s: string): string {
28
+ return s.includes(".") ? s.replace(/0+$/, "").replace(/\.$/, "") : s;
29
+ }
30
+
31
+ /** Cost rates are USD per 1M tokens. */
32
+ function money(n: number): string {
33
+ if (n === 0) return "0";
34
+ if (n >= 100) return n.toFixed(0);
35
+ if (n >= 1) return trimZeros(n.toFixed(2));
36
+ return trimZeros(n.toFixed(3));
37
+ }
38
+
39
+ function tokens(n: number): string {
40
+ if (n >= 1_000_000) return `${trimZeros((n / 1_000_000).toFixed(1))}M`;
41
+ if (n >= 1_000) return `${(n / 1_000).toFixed(0)}k`;
42
+ return `${n}`;
43
+ }
44
+
45
+ function isFree(model: Model<Api>): boolean {
46
+ const c = model.cost;
47
+ return c.input === 0 && c.output === 0 && c.cacheRead === 0 && c.cacheWrite === 0 && !c.tiers?.length;
48
+ }
49
+
50
+ /** Compact "$in/$out" used in list rows. */
51
+ function compactCost(model: Model<Api>): string {
52
+ if (isFree(model)) return "free";
53
+ return `$${money(model.cost.input)}/$${money(model.cost.output)}`;
54
+ }
55
+
56
+ function sameModel(a: Model<Api> | undefined, b: Model<Api>): boolean {
57
+ return !!a && a.provider === b.provider && a.id === b.id;
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Picker component
62
+ // ---------------------------------------------------------------------------
63
+
64
+ interface ModelItem {
65
+ model: Model<Api>;
66
+ thinkingLevel?: ThinkingLevel;
67
+ }
68
+
69
+ interface Picked {
70
+ model: Model<Api>;
71
+ thinkingLevel?: ThinkingLevel;
72
+ }
73
+
74
+ class ModelCostPicker extends Container implements Focusable {
75
+ private searchInput = new Input();
76
+ private listContainer = new Container();
77
+ private detailContainer = new Container();
78
+
79
+ // Focusable: propagate focus to the embedded input for IME positioning
80
+ private _focused = false;
81
+ get focused(): boolean {
82
+ return this._focused;
83
+ }
84
+ set focused(value: boolean) {
85
+ this._focused = value;
86
+ this.searchInput.focused = value;
87
+ }
88
+
89
+ private allItems: ModelItem[];
90
+ private scopedItems: ModelItem[];
91
+ private activeItems: ModelItem[];
92
+ private filtered: ModelItem[];
93
+ private selectedIndex = 0;
94
+ private scope: "all" | "scoped";
95
+ private scopeText: Text | undefined;
96
+
97
+ constructor(
98
+ private tui: import("@earendil-works/pi-tui").TUI,
99
+ private theme: Theme,
100
+ private currentModel: Model<Api> | undefined,
101
+ scopedModels: readonly { model: Model<Api>; thinkingLevel?: ThinkingLevel }[],
102
+ availableModels: readonly Model<Api>[],
103
+ initialQuery: string | undefined,
104
+ private done: (value: Picked | null) => void,
105
+ ) {
106
+ super();
107
+
108
+ this.allItems = this.sortItems(availableModels.map((model) => ({ model })));
109
+ this.scopedItems = this.sortItems([...scopedModels]);
110
+ this.scope = this.scopedItems.length > 0 ? "scoped" : "all";
111
+ this.activeItems = this.scope === "scoped" ? this.scopedItems : this.allItems;
112
+ this.filtered = this.activeItems;
113
+
114
+ this.addChild(new DynamicBorder((s) => theme.fg("accent", s)));
115
+ this.addChild(new Spacer(1));
116
+
117
+ if (this.scopedItems.length > 0) {
118
+ this.scopeText = new Text(this.renderScopeText(), 0, 0);
119
+ this.addChild(this.scopeText);
120
+ } else {
121
+ this.addChild(
122
+ new Text(theme.fg("muted", " Only configured providers are shown. Use /login to add more."), 0, 0),
123
+ );
124
+ }
125
+
126
+ this.searchInput.onSubmit = () => {
127
+ const item = this.filtered[this.selectedIndex];
128
+ if (item) this.select(item);
129
+ };
130
+ if (initialQuery) this.searchInput.setValue(initialQuery);
131
+ this.addChild(this.searchInput);
132
+ this.addChild(new Spacer(1));
133
+
134
+ this.addChild(this.listContainer);
135
+ this.addChild(this.detailContainer);
136
+
137
+ this.addChild(new Spacer(1));
138
+ this.addChild(new Text(theme.fg("dim", " ↑↓ navigate · Enter select · Esc cancel · prices per 1M tokens"), 0, 0));
139
+ this.addChild(new DynamicBorder((s) => theme.fg("accent", s)));
140
+
141
+ const currentIndex = this.activeItems.findIndex((item) => sameModel(this.currentModel, item.model));
142
+ this.selectedIndex = currentIndex >= 0 ? currentIndex : 0;
143
+ this.applyFilter(initialQuery ?? "");
144
+ }
145
+
146
+ private sortItems(items: ModelItem[]): ModelItem[] {
147
+ const sorted = [...items];
148
+ sorted.sort((a, b) => {
149
+ const aCurrent = sameModel(this.currentModel, a.model);
150
+ const bCurrent = sameModel(this.currentModel, b.model);
151
+ if (aCurrent && !bCurrent) return -1;
152
+ if (!aCurrent && bCurrent) return 1;
153
+ const byProvider = a.model.provider.localeCompare(b.model.provider);
154
+ return byProvider !== 0 ? byProvider : a.model.id.localeCompare(b.model.id);
155
+ });
156
+ return sorted;
157
+ }
158
+
159
+ private renderScopeText(): string {
160
+ const all = this.scope === "all" ? this.theme.fg("accent", "all") : this.theme.fg("muted", "all");
161
+ const scoped = this.scope === "scoped" ? this.theme.fg("accent", "scoped") : this.theme.fg("muted", "scoped");
162
+ return `${this.theme.fg("muted", " Scope: ")}${all}${this.theme.fg("muted", " | ")}${scoped}${this.theme.fg("dim", " (Tab to toggle)")}`;
163
+ }
164
+
165
+ private applyFilter(query: string): void {
166
+ if (query) {
167
+ this.filtered = fuzzyFilter(this.activeItems, query, (item) =>
168
+ `${item.model.provider}/${item.model.id} ${item.model.name} ${compactCost(item.model)}`,
169
+ );
170
+ this.selectedIndex = 0;
171
+ } else {
172
+ this.filtered = this.activeItems;
173
+ this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filtered.length - 1));
174
+ }
175
+ this.updateList();
176
+ }
177
+
178
+ private updateList(): void {
179
+ const theme = this.theme;
180
+ this.listContainer.clear();
181
+ this.detailContainer.clear();
182
+
183
+ if (this.filtered.length === 0) {
184
+ this.listContainer.addChild(new Text(theme.fg("muted", " No matching models"), 0, 0));
185
+ return;
186
+ }
187
+
188
+ const maxVisible = 10;
189
+ const startIndex = Math.max(
190
+ 0,
191
+ Math.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filtered.length - maxVisible),
192
+ );
193
+ const endIndex = Math.min(startIndex + maxVisible, this.filtered.length);
194
+
195
+ for (let i = startIndex; i < endIndex; i++) {
196
+ const item = this.filtered[i];
197
+ if (!item) continue;
198
+ const isSelected = i === this.selectedIndex;
199
+ const isCurrent = sameModel(this.currentModel, item.model);
200
+
201
+ const prefix = isSelected ? theme.fg("accent", "→ ") : " ";
202
+ const idText = isSelected ? theme.fg("accent", item.model.id) : item.model.id;
203
+ const providerBadge = theme.fg("muted", ` [${item.model.provider}]`);
204
+ const cost = isFree(item.model)
205
+ ? theme.fg("success", "free")
206
+ : theme.fg("warning", `$${money(item.model.cost.input)}/$${money(item.model.cost.output)}`);
207
+ const ctx = theme.fg("dim", ` · ${tokens(item.model.contextWindow)} ctx`);
208
+ const check = isCurrent ? theme.fg("success", " ✓") : "";
209
+
210
+ this.listContainer.addChild(new Text(`${prefix}${idText}${providerBadge} ${cost}${ctx}${check}`, 0, 0));
211
+ }
212
+
213
+ if (startIndex > 0 || endIndex < this.filtered.length) {
214
+ this.listContainer.addChild(
215
+ new Text(theme.fg("dim", ` (${this.selectedIndex + 1}/${this.filtered.length})`), 0, 0),
216
+ );
217
+ }
218
+
219
+ this.renderDetails(this.filtered[this.selectedIndex]?.model);
220
+ }
221
+
222
+ private renderDetails(model: Model<Api> | undefined): void {
223
+ if (!model) return;
224
+ const theme = this.theme;
225
+ const c = model.cost;
226
+
227
+ this.detailContainer.addChild(new Spacer(1));
228
+
229
+ if (isFree(model)) {
230
+ this.detailContainer.addChild(new Text(theme.fg("success", ` free — no per-token cost`), 0, 0));
231
+ } else {
232
+ let line = ` ${theme.fg("warning", `$${money(c.input)}`)} in · ${theme.fg("warning", `$${money(c.output)}`)} out`;
233
+ if (c.cacheRead > 0 || c.cacheWrite > 0) {
234
+ line += theme.fg("muted", ` · cache $${money(c.cacheRead)} read / $${money(c.cacheWrite)} write`);
235
+ }
236
+ this.detailContainer.addChild(new Text(line, 0, 0));
237
+
238
+ for (const tier of c.tiers ?? []) {
239
+ this.detailContainer.addChild(
240
+ new Text(
241
+ theme.fg(
242
+ "muted",
243
+ ` above ${tokens((tier as ModelCostTier).inputTokensAbove)} input tok: $${money(tier.input)}/$${money(tier.output)} · cache $${money(tier.cacheRead)}/$${money(tier.cacheWrite)}`,
244
+ ),
245
+ 0,
246
+ 0,
247
+ ),
248
+ );
249
+ }
250
+ }
251
+
252
+ const tags: string[] = [];
253
+ if (model.reasoning) tags.push("reasoning");
254
+ tags.push(model.input.includes("image") ? "text+image" : "text");
255
+ this.detailContainer.addChild(
256
+ new Text(
257
+ theme.fg(
258
+ "muted",
259
+ ` ${model.name} · ${tokens(model.contextWindow)} ctx · ${tokens(model.maxTokens)} max out · ${tags.join(" · ")}`,
260
+ ),
261
+ 0,
262
+ 0,
263
+ ),
264
+ );
265
+ }
266
+
267
+ private select(item: ModelItem): void {
268
+ this.done({ model: item.model, thinkingLevel: item.thinkingLevel });
269
+ }
270
+
271
+ handleInput(data: string): void {
272
+ if (matchesKey(data, "tab") && this.scopedItems.length > 0) {
273
+ this.scope = this.scope === "all" ? "scoped" : "all";
274
+ this.activeItems = this.scope === "scoped" ? this.scopedItems : this.allItems;
275
+ const currentIndex = this.activeItems.findIndex((item) => sameModel(this.currentModel, item.model));
276
+ this.selectedIndex = currentIndex >= 0 ? currentIndex : 0;
277
+ if (this.scopeText) this.scopeText.setText(this.renderScopeText());
278
+ this.applyFilter(this.searchInput.getValue());
279
+ } else if (matchesKey(data, "up")) {
280
+ if (this.filtered.length === 0) return;
281
+ this.selectedIndex = this.selectedIndex === 0 ? this.filtered.length - 1 : this.selectedIndex - 1;
282
+ this.updateList();
283
+ } else if (matchesKey(data, "down")) {
284
+ if (this.filtered.length === 0) return;
285
+ this.selectedIndex = this.selectedIndex === this.filtered.length - 1 ? 0 : this.selectedIndex + 1;
286
+ this.updateList();
287
+ } else if (matchesKey(data, "return")) {
288
+ const item = this.filtered[this.selectedIndex];
289
+ if (item) this.select(item);
290
+ return;
291
+ } else if (matchesKey(data, "escape")) {
292
+ this.done(null);
293
+ return;
294
+ } else {
295
+ this.searchInput.handleInput(data);
296
+ this.applyFilter(this.searchInput.getValue());
297
+ }
298
+ this.tui.requestRender();
299
+ }
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // Extension
304
+ // ---------------------------------------------------------------------------
305
+
306
+ export default function (pi: ExtensionAPI) {
307
+ const statusText = (model: Model<Api> | undefined): string | undefined => {
308
+ if (!model) return undefined;
309
+ if (isFree(model)) return `${model.id} · free`;
310
+ return `${model.id} · $${money(model.cost.input)}/$${money(model.cost.output)} per 1M`;
311
+ };
312
+
313
+ if (SHOW_STATUS) {
314
+ pi.on("session_start", async (_event, ctx) => {
315
+ ctx.ui.setStatus("model-costs", statusText(ctx.model));
316
+ });
317
+
318
+ pi.on("model_select", async (event, ctx) => {
319
+ ctx.ui.setStatus("model-costs", statusText(event.model));
320
+ });
321
+ }
322
+
323
+ pi.registerCommand("model-cost", {
324
+ description: "Select a model with per-1M-token pricing, context window and cache rates",
325
+ handler: async (args, ctx) => {
326
+ if (ctx.mode !== "tui") {
327
+ ctx.ui.notify("/model-cost is only available in interactive mode", "warning");
328
+ return;
329
+ }
330
+
331
+ const models = ctx.modelRegistry.getAvailable();
332
+ if (models.length === 0) {
333
+ ctx.ui.notify("No models available — check /login", "warning");
334
+ return;
335
+ }
336
+
337
+ const query = args.trim() || undefined;
338
+ const picked = await ctx.ui.custom<Picked | null>((tui, theme, _kb, done) =>
339
+ new ModelCostPicker(tui, theme, ctx.model, ctx.scopedModels, models, query, done),
340
+ );
341
+
342
+ if (!picked) return;
343
+
344
+ const success = await pi.setModel(picked.model);
345
+ if (!success) {
346
+ ctx.ui.notify(`No API key configured for provider "${picked.model.provider}"`, "error");
347
+ return;
348
+ }
349
+ if (picked.thinkingLevel) {
350
+ pi.setThinkingLevel(picked.thinkingLevel);
351
+ }
352
+
353
+ const c = picked.model.cost;
354
+ ctx.ui.notify(
355
+ isFree(picked.model)
356
+ ? `${picked.model.id} — free`
357
+ : `${picked.model.id} — $${money(c.input)} in / $${money(c.output)} out per 1M tokens`,
358
+ "info",
359
+ );
360
+ },
361
+ });
362
+ }
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "pi-model-costs",
3
+ "displayName": "model-costs",
4
+ "version": "1.0.0",
5
+ "description": "Pricing-aware model picker for pi: select models with per-1M-token cost, context window, cache rates, tiers and reasoning support.",
6
+ "type": "module",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi",
10
+ "extension",
11
+ "model",
12
+ "pricing",
13
+ "cost"
14
+ ],
15
+ "license": "MIT",
16
+ "author": {
17
+ "name": "Maurizio Faedda"
18
+ },
19
+ "peerDependencies": {
20
+ "@earendil-works/pi-ai": "*",
21
+ "@earendil-works/pi-coding-agent": "*",
22
+ "@earendil-works/pi-tui": "*",
23
+ "typebox": "*"
24
+ },
25
+ "files": [
26
+ "model-costs.ts"
27
+ ],
28
+ "pi": {
29
+ "extensions": [
30
+ "./model-costs.ts"
31
+ ],
32
+ "image": "https://raw.githubusercontent.com/MaurizioFaeddaDev/model-costs/main/images/model-cost.png"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/MaurizioFaeddaDev/model-costs.git"
37
+ }
38
+ }