@xynogen/pix-core 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.
@@ -0,0 +1,362 @@
1
+ /**
2
+ * models.ts โ€” enhanced /models command with benchlm rank + score
3
+ *
4
+ * Replaces (or supplements) the built-in /model selector by registering
5
+ * /models (plural). Each row shows:
6
+ * <name> <provider> ยท <ctx> ยท <cost> ยท ๐Ÿ… #rank score
7
+ *
8
+ * Sorted by benchlm rank when available (best first), then alphabetical.
9
+ */
10
+
11
+ import type {
12
+ ExtensionAPI,
13
+ ExtensionContext,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { DynamicBorder } from "@earendil-works/pi-coding-agent";
16
+ import {
17
+ Container,
18
+ fuzzyFilter,
19
+ Input,
20
+ matchesKey,
21
+ type SelectItem,
22
+ SelectList,
23
+ Text,
24
+ visibleWidth,
25
+ } from "@earendil-works/pi-tui";
26
+ import { lookupModelsDev, lookupBenchmark } from "../../lib/data";
27
+
28
+ // โ”€โ”€โ”€ Pure logic (exported for tests) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
29
+
30
+ export function fmtCtx(n: number): string {
31
+ if (!n || n < 1_000) return `${n}`;
32
+ if (n >= 1_000_000) {
33
+ const m = n / 1_000_000;
34
+ return `${Number.isInteger(m) ? m.toFixed(0) : m.toFixed(1).replace(/\.0$/, "")}M`;
35
+ }
36
+ return `${Math.round(n / 1_000)}k`;
37
+ }
38
+
39
+ export function fmtCost(
40
+ entry: { cost?: { input?: number; output?: number } } | undefined,
41
+ ): string {
42
+ if (!entry?.cost) return "\u2014";
43
+ const i = entry.cost.input ?? 0;
44
+ const o = entry.cost.output ?? 0;
45
+ if (i === 0 && o === 0) return "free";
46
+ return `${i.toFixed(2)}/${o.toFixed(2)}`;
47
+ }
48
+
49
+ export function benchStars(score: number | null | undefined): {
50
+ filled: number;
51
+ empty: number;
52
+ } {
53
+ const total = 5;
54
+ let filled = 1;
55
+ if (typeof score === "number") {
56
+ if (score >= 90) filled = 5;
57
+ else if (score >= 80) filled = 4;
58
+ else if (score >= 70) filled = 3;
59
+ else if (score >= 50) filled = 2;
60
+ }
61
+ return { filled, empty: total - filled };
62
+ }
63
+
64
+ export type SortableModel = {
65
+ provider: string;
66
+ id: string;
67
+ name?: string;
68
+ score?: number | null;
69
+ };
70
+
71
+ export function sortModels<T extends SortableModel>(models: T[]): T[] {
72
+ return [...models].sort((a, b) => {
73
+ const sa = a.score ?? -1;
74
+ const sb = b.score ?? -1;
75
+ if (sa !== sb) return sb - sa;
76
+ return (a.name ?? a.id).localeCompare(b.name ?? b.id);
77
+ });
78
+ }
79
+
80
+ export async function showEnhancedPicker(
81
+ pi: ExtensionAPI,
82
+ ctx: ExtensionContext,
83
+ ): Promise<void> {
84
+ // Mirror the built-in /model selector, which calls refresh() then awaits
85
+ // getAvailable() (see model-selector.js). Without refresh(), this extension
86
+ // reads whatever `this.models` was last loaded into โ€” which, depending on
87
+ // extension load order vs oauth/auth resolution, can omit oauth providers
88
+ // whose models were registered as built-ins but resolved after the last
89
+ // load (notably `openai-codex`). 9router survives because it's registered
90
+ // as a custom provider with an env-key apiKey. refresh() rebuilds the model
91
+ // list (resetOAuthProviders โ†’ loadModels โ†’ re-apply registered providers)
92
+ // so oauth-backed codex models reappear, exactly as the built-in does.
93
+ //
94
+ // The public ExtensionContext type narrows modelRegistry to a sync
95
+ // getAvailable() only; at runtime ctx.modelRegistry is the full
96
+ // ModelRegistry instance (verified in runner.js) with refresh() and an
97
+ // async-capable getAvailable(). Reach through the narrowed type.
98
+ type AvailableModels = ReturnType<typeof ctx.modelRegistry.getAvailable>;
99
+ const registry = ctx.modelRegistry as unknown as {
100
+ refresh?: () => void;
101
+ getAvailable(): AvailableModels | Promise<AvailableModels>;
102
+ };
103
+ registry.refresh?.();
104
+ const available = await registry.getAvailable();
105
+ if (available.length === 0) {
106
+ ctx.ui.notify("No models with configured auth.", "warning");
107
+ return;
108
+ }
109
+
110
+ const current = ctx.model;
111
+
112
+ // Build items with benchmark data
113
+ type Row = {
114
+ m: (typeof available)[number];
115
+ dev: ReturnType<typeof lookupModelsDev>;
116
+ bench: ReturnType<typeof lookupBenchmark>;
117
+ };
118
+ const rows: Row[] = available.map((m) => ({
119
+ m,
120
+ dev: lookupModelsDev(m.provider, m.id),
121
+ bench: lookupBenchmark(m.name ?? m.id),
122
+ }));
123
+
124
+ // Sort: by score desc (highest first), unscored last alphabetical
125
+ rows.sort((a, b) => {
126
+ const sa = a.bench?.overallScore ?? -1;
127
+ const sb = b.bench?.overallScore ?? -1;
128
+ if (sa !== sb) return sb - sa;
129
+ return (a.m.name ?? a.m.id).localeCompare(b.m.name ?? b.m.id);
130
+ });
131
+
132
+ // Show all models (no deduplication)
133
+ const dedupedRows = rows;
134
+
135
+ // items built inside the custom() factory so we have theme access for colors
136
+
137
+ const result = await ctx.ui.custom<string | null>(
138
+ (_tui, theme, _kb, done) => {
139
+ const container = new Container();
140
+ const accent = "accent";
141
+
142
+ // Find max rank width across all benchmarked rows for # padding
143
+ const maxRankWidth = Math.max(
144
+ ...dedupedRows.map((r) => (r.bench ? String(r.bench.rank).length : 0)),
145
+ 1,
146
+ );
147
+
148
+ // Mute low-info parts (separators, padding, #, โ˜†) so the actual values pop.
149
+ const mute = (s: string) => theme.fg("muted", s);
150
+ const sep = mute(" ยท ");
151
+
152
+ // Track rank per item value so fuzzy results can prioritize ranked models.
153
+ const rankByValue = new Map<string, number>();
154
+ for (const { m, bench } of dedupedRows) {
155
+ if (bench) rankByValue.set(`${m.provider}/${m.id}`, bench.rank);
156
+ }
157
+
158
+ const items: SelectItem[] = dedupedRows.map(({ m, dev, bench }) => {
159
+ const isCurrent =
160
+ current && m.provider === current.provider && m.id === current.id;
161
+
162
+ // Label: marker + muted '#' + bright rank + accent-colored model name
163
+ const marker = isCurrent ? theme.fg(accent, "โ–ถ") : " ";
164
+ let rankPrefix: string;
165
+ if (bench) {
166
+ const rankStr = String(bench.rank).padEnd(maxRankWidth);
167
+ rankPrefix = mute("#") + theme.fg("warning", rankStr);
168
+ } else {
169
+ rankPrefix = " ".repeat(maxRankWidth + 1);
170
+ }
171
+ // Display model id only; m.provider is routing provider, not part of id.
172
+ const idColored = theme.fg(accent, m.id);
173
+ const label = `${marker} ${rankPrefix} ${idColored}`;
174
+
175
+ // Description: ctx ยท cost ยท score stars
176
+ // Colors: ctx muted ยท cost success (free muted) ยท score+stars warning
177
+ const ctxRaw = fmtCtx(dev?.limit?.context ?? 0);
178
+ const ctxStr = mute(ctxRaw.padStart(4));
179
+ const rawCost = fmtCost(dev);
180
+ let costSeg: string;
181
+ if (rawCost === "โ€”") {
182
+ costSeg = theme.fg("dim", "โ€”".padEnd(10));
183
+ } else if (rawCost === "free") {
184
+ costSeg = mute("free".padEnd(10));
185
+ } else {
186
+ costSeg = theme.fg("success", rawCost.padEnd(10));
187
+ }
188
+ let benchSeg = "";
189
+ if (bench) {
190
+ const score = bench.overallScore ?? "?";
191
+ const s = bench.overallScore;
192
+ let filled = 1;
193
+ if (typeof s === "number") {
194
+ if (s >= 90) filled = 5;
195
+ else if (s >= 80) filled = 4;
196
+ else if (s >= 70) filled = 3;
197
+ else if (s >= 50) filled = 2;
198
+ }
199
+ const starBar =
200
+ theme.fg("warning", "โ˜…".repeat(filled)) +
201
+ mute("โ˜†".repeat(5 - filled));
202
+ benchSeg = `โšก${theme.fg("warning", String(score))} ${starBar}`;
203
+ }
204
+ const desc = [ctxStr, costSeg, benchSeg].filter(Boolean).join(sep);
205
+
206
+ return {
207
+ value: `${m.provider}/${m.id}`,
208
+ label,
209
+ description: desc,
210
+ };
211
+ });
212
+
213
+ const currentIdx = current
214
+ ? items.findIndex(
215
+ (it) => it.value === `${current.provider}/${current.id}`,
216
+ )
217
+ : 0;
218
+
219
+ container.addChild(new DynamicBorder((s) => theme.fg(accent, s)));
220
+ container.addChild(
221
+ new Text(theme.fg(accent, theme.bold("๓ฐšฉ Select model"))),
222
+ );
223
+ container.addChild(
224
+ new Text(
225
+ theme.fg(
226
+ "dim",
227
+ "context & pricing from models.dev ยท ranks from benchlm.ai",
228
+ ),
229
+ ),
230
+ );
231
+
232
+ // Widest label (visible width, ANSI-stripped) so the model name
233
+ // column never truncates to "โ€ฆ". Add gap headroom.
234
+ const widestLabel = items.reduce(
235
+ (w, it) => Math.max(w, visibleWidth(it.label)),
236
+ 0,
237
+ );
238
+
239
+ const search = new Input();
240
+ const list = new SelectList(
241
+ items,
242
+ Math.min(items.length, 14),
243
+ {
244
+ selectedPrefix: (t) => theme.fg(accent, t),
245
+ selectedText: (t) => theme.fg(accent, t),
246
+ description: (t) => t, // raw โ€” per-segment colors set in items.map
247
+ scrollInfo: (t) => theme.fg("dim", t),
248
+ noMatch: (t) => theme.fg("warning", t),
249
+ },
250
+ {
251
+ minPrimaryColumnWidth: widestLabel + 2,
252
+ maxPrimaryColumnWidth: widestLabel + 2,
253
+ },
254
+ );
255
+ if (currentIdx >= 0) list.setSelectedIndex(currentIdx);
256
+
257
+ list.onSelect = (item) => done(item.value);
258
+ list.onCancel = () => done(null);
259
+ search.onEscape = () => done(null);
260
+
261
+ const applyFuzzy = (query: string) => {
262
+ const internal = list as unknown as {
263
+ items: SelectItem[];
264
+ filteredItems: SelectItem[];
265
+ selectedIndex: number;
266
+ invalidate(): void;
267
+ };
268
+ const q = query.trim();
269
+ let next: SelectItem[];
270
+ if (q.length === 0) {
271
+ next = internal.items;
272
+ } else if (/^\d+$/.test(q)) {
273
+ // Pure number โ†’ match by benchlm rank, not name.
274
+ const wanted = Number(q);
275
+ next = internal.items.filter(
276
+ (it) => rankByValue.get(it.value) === wanted,
277
+ );
278
+ } else {
279
+ next = fuzzyFilter(
280
+ internal.items,
281
+ q,
282
+ (it) => `${it.label} ${it.description ?? ""}`,
283
+ );
284
+ // Stable sort: ranked models (by rank asc) before unranked.
285
+ next = next
286
+ .map((it, i) => ({ it, i }))
287
+ .sort((a, b) => {
288
+ const ra = rankByValue.get(a.it.value) ?? Infinity;
289
+ const rb = rankByValue.get(b.it.value) ?? Infinity;
290
+ if (ra !== rb) return ra - rb;
291
+ return a.i - b.i;
292
+ })
293
+ .map(({ it }) => it);
294
+ }
295
+ internal.filteredItems = next;
296
+ internal.selectedIndex = 0;
297
+ internal.invalidate();
298
+ };
299
+
300
+ container.addChild(new Text(theme.fg("muted", "Search:")));
301
+ container.addChild(search);
302
+ container.addChild(list);
303
+ container.addChild(
304
+ new Text(
305
+ theme.fg(
306
+ "dim",
307
+ "fuzzy search ยท โ†‘โ†“ navigate ยท enter select ยท esc cancel",
308
+ ),
309
+ ),
310
+ );
311
+ container.addChild(new DynamicBorder((s) => theme.fg(accent, s)));
312
+
313
+ return {
314
+ render(w: number) {
315
+ return container.render(w);
316
+ },
317
+ invalidate() {
318
+ container.invalidate();
319
+ },
320
+ handleInput(data: string) {
321
+ // Detect keys via pi-tui's own parser โ€” the same recognition
322
+ // SelectList uses. Arrows arrive as named keys ("up"/"down"),
323
+ // not raw escape sequences, so string-equality checks fail.
324
+ const isNav = matchesKey(data, "up") || matchesKey(data, "down");
325
+ if (isNav || matchesKey(data, "enter")) {
326
+ list.handleInput?.(data);
327
+ } else if (matchesKey(data, "escape")) {
328
+ done(null);
329
+ } else {
330
+ search.handleInput?.(data);
331
+ applyFuzzy(search.getValue?.() ?? "");
332
+ }
333
+ container.invalidate();
334
+ },
335
+ };
336
+ },
337
+ );
338
+
339
+ if (!result) return;
340
+
341
+ // Apply selection
342
+ const [provider, ...rest] = result.split("/");
343
+ const id = rest.join("/");
344
+ const picked = available.find((m) => m.provider === provider && m.id === id);
345
+ if (!picked) {
346
+ ctx.ui.notify(`Model not found: ${result}`, "error");
347
+ return;
348
+ }
349
+ const ok = await pi.setModel(picked);
350
+ if (ok) ctx.ui.notify(`Switched to ${picked.name ?? picked.id}`, "info");
351
+ else ctx.ui.notify(`Failed to switch to ${picked.id}`, "error");
352
+ }
353
+
354
+ export default function modelPickerExtension(pi: ExtensionAPI) {
355
+ const handler = async (_args: unknown, ctx: ExtensionContext) => {
356
+ await showEnhancedPicker(pi, ctx);
357
+ };
358
+ pi.registerCommand("models", {
359
+ description: "Enhanced model picker โ€” shows benchlm rank + score",
360
+ handler,
361
+ });
362
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Smoke tests for the command extensions merged from pix-tools.
3
+ * Each default export must be a registrable (pi) => void function.
4
+ */
5
+
6
+ import { describe, expect, it } from "bun:test";
7
+
8
+ describe("merged pix-tools commands", () => {
9
+ for (const name of ["lg", "yeet", "copy-all", "diff"]) {
10
+ it(`${name} exports a register function`, async () => {
11
+ const mod = await import(`./${name}/${name}.ts`);
12
+ expect(mod.default).toBeFunction();
13
+ });
14
+ }
15
+ });
@@ -0,0 +1,112 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import {
3
+ isTransient,
4
+ commandFor,
5
+ formatUpdateSummary,
6
+ PACKAGE_NAME,
7
+ type InstallMethod,
8
+ } from "./update.ts";
9
+
10
+ describe("isTransient", () => {
11
+ it("matches network errors", () => {
12
+ expect(isTransient("ETIMEDOUT")).toBe(true);
13
+ expect(isTransient("ECONNRESET")).toBe(true);
14
+ expect(isTransient("ECONNREFUSED")).toBe(true);
15
+ expect(isTransient("socket hang up")).toBe(true);
16
+ expect(isTransient("network error occurred")).toBe(true);
17
+ });
18
+
19
+ it("matches HTTP status codes", () => {
20
+ expect(isTransient("Error 429: Too many requests")).toBe(true);
21
+ expect(isTransient("502 Bad Gateway")).toBe(true);
22
+ expect(isTransient("503 Service Unavailable")).toBe(true);
23
+ expect(isTransient("504 Gateway Timeout")).toBe(true);
24
+ });
25
+
26
+ it("matches timeout/temporary", () => {
27
+ expect(isTransient("Request timeout after 30s")).toBe(true);
28
+ expect(isTransient("temporary failure")).toBe(true);
29
+ expect(isTransient("EAI_AGAIN")).toBe(true);
30
+ });
31
+
32
+ it("returns false for permanent errors", () => {
33
+ expect(isTransient("permission denied")).toBe(false);
34
+ expect(isTransient("command not found")).toBe(false);
35
+ expect(isTransient("syntax error")).toBe(false);
36
+ expect(isTransient("")).toBe(false);
37
+ });
38
+
39
+ it("is case-insensitive", () => {
40
+ expect(isTransient("NETWORK FAILURE")).toBe(true);
41
+ expect(isTransient("Timeout after 30s")).toBe(true);
42
+ });
43
+ });
44
+
45
+ describe("commandFor", () => {
46
+ it("returns correct command for each method", () => {
47
+ const methods: InstallMethod[] = ["vp", "bun", "npm", "brew"];
48
+ for (const m of methods) {
49
+ const spec = commandFor(m);
50
+ expect(spec).toBeDefined();
51
+ expect(spec!.command).toBeTruthy();
52
+ expect(spec!.label).toBeTruthy();
53
+ }
54
+ });
55
+
56
+ it("vp uses vp add -g", () => {
57
+ const spec = commandFor("vp")!;
58
+ expect(spec.command).toBe("vp");
59
+ expect(spec.args).toContain(PACKAGE_NAME + "@latest");
60
+ });
61
+
62
+ it("bun uses bun add -g", () => {
63
+ const spec = commandFor("bun")!;
64
+ expect(spec.command).toBe("bun");
65
+ expect(spec.args).toContain(PACKAGE_NAME + "@latest");
66
+ });
67
+
68
+ it("npm uses npm install -g", () => {
69
+ const spec = commandFor("npm")!;
70
+ expect(spec.command).toBe("npm");
71
+ expect(spec.args).toContain("-g");
72
+ expect(spec.args).toContain(PACKAGE_NAME + "@latest");
73
+ });
74
+
75
+ it("brew uses sh -lc", () => {
76
+ const spec = commandFor("brew")!;
77
+ expect(spec.command).toBe("/bin/sh");
78
+ expect(spec.label).toContain("brew upgrade");
79
+ });
80
+
81
+ it("native returns undefined", () => {
82
+ expect(commandFor("native")).toBeUndefined();
83
+ });
84
+ });
85
+
86
+ describe("formatUpdateSummary", () => {
87
+ it("shows updated message when version changed", () => {
88
+ const msg = formatUpdateSummary("0.75.0", "0.76.0", 1);
89
+ expect(msg).toContain("0.75.0 โ†’ 0.76.0");
90
+ });
91
+
92
+ it("shows up-to-date when version unchanged", () => {
93
+ const msg = formatUpdateSummary("0.76.0", "0.76.0", 1);
94
+ expect(msg).toContain("up to date");
95
+ expect(msg).toContain("0.76.0");
96
+ });
97
+
98
+ it("shows retry count when attempts > 1", () => {
99
+ const msg = formatUpdateSummary("0.75.0", "0.76.0", 3);
100
+ expect(msg).toContain("Retried 2 transient failure");
101
+ });
102
+
103
+ it("no retry mention when attempts = 1", () => {
104
+ const msg = formatUpdateSummary("0.75.0", "0.76.0", 1);
105
+ expect(msg).not.toContain("Retried");
106
+ });
107
+
108
+ it("handles unknown versions gracefully", () => {
109
+ const msg = formatUpdateSummary("unknown", "unknown", 1);
110
+ expect(msg).toContain("up to date");
111
+ });
112
+ });