@xynogen/pix-data 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 +21 -0
- package/README.md +31 -0
- package/package.json +36 -0
- package/src/data.test.ts +196 -0
- package/src/data.ts +285 -0
- package/src/index.ts +16 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 xynogen
|
|
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,31 @@
|
|
|
1
|
+
# pix-data
|
|
2
|
+
|
|
3
|
+
Pi coding agent extension — shared model data layer. Fetches and caches [models.dev](https://models.dev) metadata and [BenchLM](https://benchlm.ai) leaderboard data to `~/.cache/pi/` on session start, so other extensions can read them synchronously without redundant network calls.
|
|
4
|
+
|
|
5
|
+
## What's included
|
|
6
|
+
|
|
7
|
+
| Export | Description |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `modelsDev` | `DataSource<ModelsDevApi>` — models.dev metadata (context, cost, modalities). TTL 24h → `~/.cache/pi/models.json` |
|
|
10
|
+
| `benchmark` | `DataSource<BenchmarkEntry[]>` — BenchLM leaderboard (rank, score, pricing). TTL 24h → `~/.cache/pi/benchlm.json` |
|
|
11
|
+
| `DataSource` | Generic cached data source class |
|
|
12
|
+
| `CACHE_DIR` | Resolved cache directory (`~/.cache/pi`) |
|
|
13
|
+
| `buildModelsDevIndex` | Build a lookup `Map` from a `ModelsDevApi` response |
|
|
14
|
+
| `lookupInIndex` | Fuzzy-match a router model id against the index |
|
|
15
|
+
| `lookupModelsDev` | Sync lookup by provider + id from in-memory cache |
|
|
16
|
+
| `lookupBenchmark` | Fuzzy lookup a model by name from BenchLM cache |
|
|
17
|
+
| `fetchModelsDevIndex` | Async — fetch models.dev and return built index |
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pi install git:github.com/xynogen/pix-data
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
On session start the extension fires two parallel background fetches (`modelsDev.get()` + `benchmark.get()`). If the cache is fresh the fetches are skipped. Both cache files live in `~/.cache/pi/` — any Pi extension using the same `DataSource` + cache paths will share data automatically.
|
|
28
|
+
|
|
29
|
+
## License
|
|
30
|
+
|
|
31
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@xynogen/pix-data",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi extension — shared model data layer (models.dev + BenchLM), cached at ~/.cache/pi",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "bun test"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"pi": {
|
|
16
|
+
"extensions": ["src/index.ts"]
|
|
17
|
+
},
|
|
18
|
+
"keywords": ["pi", "pi-package", "pi-extension", "models.dev", "benchlm"],
|
|
19
|
+
"author": "xynogen",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/xynogen/pix-mono.git",
|
|
24
|
+
"directory": "packages/pix-data"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://github.com/xynogen/pix-mono/tree/main/packages/pix-data#readme",
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/xynogen/pix-mono/issues"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/data.test.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
buildModelsDevIndex,
|
|
4
|
+
lookupInIndex,
|
|
5
|
+
lookupModelsDev,
|
|
6
|
+
lookupBenchmark,
|
|
7
|
+
modelsDev,
|
|
8
|
+
benchmark,
|
|
9
|
+
type ModelsDevApi,
|
|
10
|
+
type ModelsDevModel,
|
|
11
|
+
type BenchmarkEntry,
|
|
12
|
+
} from "./data.ts";
|
|
13
|
+
|
|
14
|
+
// ── buildModelsDevIndex ──────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
describe("buildModelsDevIndex", () => {
|
|
17
|
+
const api: ModelsDevApi = {
|
|
18
|
+
anthropic: {
|
|
19
|
+
models: {
|
|
20
|
+
"claude-sonnet-4-5": { id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5" },
|
|
21
|
+
"claude-opus-4": { id: "claude-opus-4", name: "Claude Opus 4", reasoning: true },
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
openai: {
|
|
25
|
+
models: {
|
|
26
|
+
"gpt-4o": { id: "gpt-4o", name: "GPT-4o", modalities: { input: ["text", "image"] } },
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
it("indexes all models by exact id", () => {
|
|
32
|
+
const idx = buildModelsDevIndex(api);
|
|
33
|
+
expect(idx.has("claude-sonnet-4-5")).toBe(true);
|
|
34
|
+
expect(idx.has("claude-opus-4")).toBe(true);
|
|
35
|
+
expect(idx.has("gpt-4o")).toBe(true);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("indexes normalized id (strip date suffix)", () => {
|
|
39
|
+
const a: ModelsDevApi = {
|
|
40
|
+
anthropic: {
|
|
41
|
+
models: {
|
|
42
|
+
"claude-sonnet-4-5-20250514": { id: "claude-sonnet-4-5-20250514", name: "Claude Sonnet 4.5" },
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
const idx = buildModelsDevIndex(a);
|
|
47
|
+
expect(idx.has("claude-sonnet-4-5")).toBe(true);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("handles empty api", () => {
|
|
51
|
+
expect(buildModelsDevIndex({}).size).toBe(0);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("handles provider with no models key", () => {
|
|
55
|
+
expect(buildModelsDevIndex({ anthropic: {} }).size).toBe(0);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("preserves first-seen on id collision", () => {
|
|
59
|
+
const a: ModelsDevApi = {
|
|
60
|
+
a: { models: { "gpt-4o": { id: "gpt-4o", name: "First" } } },
|
|
61
|
+
b: { models: { "gpt-4o": { id: "gpt-4o", name: "Second" } } },
|
|
62
|
+
};
|
|
63
|
+
expect(buildModelsDevIndex(a).get("gpt-4o")?.name).toBe("First");
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// ── lookupInIndex ────────────────────────────────────────────────────────────
|
|
68
|
+
|
|
69
|
+
describe("lookupInIndex", () => {
|
|
70
|
+
let index: Map<string, ModelsDevModel>;
|
|
71
|
+
|
|
72
|
+
beforeEach(() => {
|
|
73
|
+
index = buildModelsDevIndex({
|
|
74
|
+
anthropic: {
|
|
75
|
+
models: {
|
|
76
|
+
"claude-sonnet-4-5": { id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5" },
|
|
77
|
+
"claude-opus-4": { id: "claude-opus-4", name: "Claude Opus 4" },
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
openai: {
|
|
81
|
+
models: {
|
|
82
|
+
"gpt-4o": { id: "gpt-4o", name: "GPT-4o" },
|
|
83
|
+
"o3-mini": { id: "o3-mini", name: "o3 mini" },
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("finds exact match", () => {
|
|
90
|
+
expect(lookupInIndex("claude-sonnet-4-5", index)?.name).toBe("Claude Sonnet 4.5");
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("strips provider prefix (provider/model)", () => {
|
|
94
|
+
expect(lookupInIndex("anthropic/claude-opus-4", index)?.name).toBe("Claude Opus 4");
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("strips deep prefix (cc/model)", () => {
|
|
98
|
+
expect(lookupInIndex("cc/claude-opus-4", index)?.name).toBe("Claude Opus 4");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("strips date suffix", () => {
|
|
102
|
+
expect(lookupInIndex("claude-sonnet-4-5-20250514", index)?.name).toBe("Claude Sonnet 4.5");
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("strips provider prefix + date suffix", () => {
|
|
106
|
+
expect(lookupInIndex("anthropic/claude-sonnet-4-5-20250514", index)?.name).toBe("Claude Sonnet 4.5");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("returns undefined for unknown model", () => {
|
|
110
|
+
expect(lookupInIndex("nonexistent-xyz", index)).toBeUndefined();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("finds o3-mini", () => {
|
|
114
|
+
expect(lookupInIndex("o3-mini", index)?.name).toBe("o3 mini");
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// ── lookupModelsDev ───────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
describe("lookupModelsDev", () => {
|
|
121
|
+
beforeEach(() => {
|
|
122
|
+
// Seed in-memory cache directly
|
|
123
|
+
(modelsDev as any)._mem = {
|
|
124
|
+
anthropic: {
|
|
125
|
+
models: {
|
|
126
|
+
"claude-sonnet-4-5": { id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5" },
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
openai: {
|
|
130
|
+
models: {
|
|
131
|
+
"gpt-4o": { id: "gpt-4o", name: "GPT-4o" },
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
afterEach(() => {
|
|
138
|
+
(modelsDev as any)._mem = null;
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("finds by exact provider + id", () => {
|
|
142
|
+
expect(lookupModelsDev("anthropic", "claude-sonnet-4-5")?.name).toBe("Claude Sonnet 4.5");
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("falls back across providers when provider miss", () => {
|
|
146
|
+
expect(lookupModelsDev("unknown-provider", "gpt-4o")?.name).toBe("GPT-4o");
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("strips path prefix from id", () => {
|
|
150
|
+
expect(lookupModelsDev("anthropic", "anthropic/claude-sonnet-4-5")?.name).toBe(
|
|
151
|
+
"Claude Sonnet 4.5",
|
|
152
|
+
);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it("returns undefined for unknown model", () => {
|
|
156
|
+
expect(lookupModelsDev("anthropic", "nonexistent-xyz")).toBeUndefined();
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// ── lookupBenchmark ───────────────────────────────────────────────────────────
|
|
161
|
+
|
|
162
|
+
describe("lookupBenchmark", () => {
|
|
163
|
+
const entries: BenchmarkEntry[] = [
|
|
164
|
+
{ rank: 1, model: "Claude Sonnet 4.5", creator: "Anthropic", overallScore: 95, inputPrice: 3, outputPrice: 15 },
|
|
165
|
+
{ rank: 2, model: "GPT-4o", creator: "OpenAI", overallScore: 90, inputPrice: 5, outputPrice: 15 },
|
|
166
|
+
{ rank: 3, model: "Gemini 1.5 Pro", creator: "Google", overallScore: 88, inputPrice: 3.5, outputPrice: 10.5 },
|
|
167
|
+
];
|
|
168
|
+
|
|
169
|
+
beforeEach(() => {
|
|
170
|
+
(benchmark as any)._mem = entries;
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
afterEach(() => {
|
|
174
|
+
(benchmark as any)._mem = null;
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("finds exact match (case-insensitive, normalized)", () => {
|
|
178
|
+
expect(lookupBenchmark("claude sonnet 4.5")?.rank).toBe(1);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("finds with dashes normalized", () => {
|
|
182
|
+
expect(lookupBenchmark("claude-sonnet-4-5")?.rank).toBe(1);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("finds partial match (needle in model)", () => {
|
|
186
|
+
expect(lookupBenchmark("gpt-4o")?.rank).toBe(2);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("finds partial match (model in needle)", () => {
|
|
190
|
+
expect(lookupBenchmark("gemini 1.5 pro latest")?.rank).toBe(3);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it("returns undefined for unknown model", () => {
|
|
194
|
+
expect(lookupBenchmark("nonexistent-model-xyz")).toBeUndefined();
|
|
195
|
+
});
|
|
196
|
+
});
|
package/src/data.ts
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* data.ts — shared Pi model data layer
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for:
|
|
5
|
+
* - models.dev metadata (context, cost, modalities) → ~/.cache/pi/models.json TTL 24h
|
|
6
|
+
* - BenchLM leaderboard (rank, score, pricing) → ~/.cache/pi/benchlm.json TTL 24h
|
|
7
|
+
*
|
|
8
|
+
* Cache files are shared across all Pi extensions — whichever extension loads
|
|
9
|
+
* first populates the cache; subsequent extensions read from disk.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* import { modelsDev, benchmark } from "./data.ts";
|
|
13
|
+
*
|
|
14
|
+
* const models = await modelsDev.get(); // async, fetches if stale
|
|
15
|
+
* const entries = await benchmark.get();
|
|
16
|
+
*
|
|
17
|
+
* const models = modelsDev.getCached(); // sync, disk-only, no fetch
|
|
18
|
+
* const entries = benchmark.getCached();
|
|
19
|
+
*
|
|
20
|
+
* import { lookupModelsDev, lookupBenchmark } from "./data.ts";
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
24
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { dirname, join } from "node:path";
|
|
27
|
+
|
|
28
|
+
// ── Types ────────────────────────────────────────────────────────────────────
|
|
29
|
+
|
|
30
|
+
export interface ModelsDevModel {
|
|
31
|
+
id: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
reasoning?: boolean;
|
|
34
|
+
modalities?: { input?: string[]; output?: string[] };
|
|
35
|
+
limit?: { context?: number; output?: number };
|
|
36
|
+
cost?: {
|
|
37
|
+
input?: number;
|
|
38
|
+
output?: number;
|
|
39
|
+
cache_read?: number;
|
|
40
|
+
cache_write?: number;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type ModelsDevApi = Record<
|
|
45
|
+
string,
|
|
46
|
+
{ models?: Record<string, ModelsDevModel> }
|
|
47
|
+
>;
|
|
48
|
+
|
|
49
|
+
export interface BenchmarkEntry {
|
|
50
|
+
rank: number;
|
|
51
|
+
model: string;
|
|
52
|
+
creator: string;
|
|
53
|
+
sourceType?: string;
|
|
54
|
+
overallScore: number | null;
|
|
55
|
+
categoryScores?: Record<string, number | null>;
|
|
56
|
+
inputPrice: number | null;
|
|
57
|
+
outputPrice: number | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface BenchmarkResponse {
|
|
61
|
+
lastUpdated?: string;
|
|
62
|
+
mode?: string;
|
|
63
|
+
models: BenchmarkEntry[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ── DataSource ───────────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
interface DataSourceOptions<T> {
|
|
69
|
+
url: string | (() => string);
|
|
70
|
+
headers?: () => Record<string, string> | undefined;
|
|
71
|
+
cachePath: string;
|
|
72
|
+
ttlMs?: number;
|
|
73
|
+
timeoutMs?: number;
|
|
74
|
+
parse: (raw: unknown) => T;
|
|
75
|
+
parseCache: (data: unknown) => T;
|
|
76
|
+
empty: T;
|
|
77
|
+
label: string;
|
|
78
|
+
skip?: () => boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export class DataSource<T> {
|
|
82
|
+
private _mem: T | null = null;
|
|
83
|
+
private _inflight: Promise<T> | null = null;
|
|
84
|
+
private readonly opts: Required<DataSourceOptions<T>>;
|
|
85
|
+
|
|
86
|
+
constructor(opts: DataSourceOptions<T>) {
|
|
87
|
+
this.opts = {
|
|
88
|
+
ttlMs: 24 * 60 * 60 * 1000,
|
|
89
|
+
timeoutMs: 10_000,
|
|
90
|
+
headers: () => undefined,
|
|
91
|
+
skip: () => false,
|
|
92
|
+
...opts,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async get(): Promise<T> {
|
|
97
|
+
if (this._inflight) return this._inflight;
|
|
98
|
+
this._inflight = this._load().finally(() => {
|
|
99
|
+
this._inflight = null;
|
|
100
|
+
});
|
|
101
|
+
return this._inflight;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
getCached(): T {
|
|
105
|
+
if (this._mem) return this._mem;
|
|
106
|
+
try {
|
|
107
|
+
if (existsSync(this.opts.cachePath)) {
|
|
108
|
+
const raw = JSON.parse(readFileSync(this.opts.cachePath, "utf-8")) as {
|
|
109
|
+
data: unknown;
|
|
110
|
+
};
|
|
111
|
+
this._mem = this.opts.parseCache(raw.data);
|
|
112
|
+
return this._mem;
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// No cache file or parse error — return empty, not fatal
|
|
116
|
+
}
|
|
117
|
+
return this.opts.empty;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private async _load(): Promise<T> {
|
|
121
|
+
if (this.opts.skip()) {
|
|
122
|
+
this._mem = this.opts.empty;
|
|
123
|
+
return this.opts.empty;
|
|
124
|
+
}
|
|
125
|
+
const cached = await this._readCache();
|
|
126
|
+
if (cached !== undefined && Date.now() - cached.ts < this.opts.ttlMs) {
|
|
127
|
+
const val = this.opts.parseCache(cached.data);
|
|
128
|
+
this._mem = val;
|
|
129
|
+
return val;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const url =
|
|
133
|
+
typeof this.opts.url === "function" ? this.opts.url() : this.opts.url;
|
|
134
|
+
const response = await fetchWithTimeout(url, this.opts.timeoutMs, this.opts.headers());
|
|
135
|
+
if (!response.ok)
|
|
136
|
+
throw new Error(`${this.opts.label} fetch failed: ${response.status}`);
|
|
137
|
+
const raw = await response.json();
|
|
138
|
+
const val = this.opts.parse(raw);
|
|
139
|
+
this._mem = val;
|
|
140
|
+
void this._writeCache(raw);
|
|
141
|
+
return val;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
144
|
+
if (cached !== undefined) {
|
|
145
|
+
console.warn(`${this.opts.label} fetch failed, using stale cache: ${msg}`);
|
|
146
|
+
const val = this.opts.parseCache(cached.data);
|
|
147
|
+
this._mem = val;
|
|
148
|
+
return val;
|
|
149
|
+
}
|
|
150
|
+
console.warn(`${this.opts.label} unavailable: ${msg}`);
|
|
151
|
+
return this.opts.empty;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async _readCache(): Promise<{ ts: number; data: unknown } | undefined> {
|
|
156
|
+
try {
|
|
157
|
+
const raw = await readFile(this.opts.cachePath, "utf8");
|
|
158
|
+
const parsed = JSON.parse(raw) as { ts: number; data: unknown };
|
|
159
|
+
if (typeof parsed.ts !== "number") return undefined;
|
|
160
|
+
return parsed;
|
|
161
|
+
} catch {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private async _writeCache(data: unknown): Promise<void> {
|
|
167
|
+
try {
|
|
168
|
+
await mkdir(dirname(this.opts.cachePath), { recursive: true });
|
|
169
|
+
await writeFile(this.opts.cachePath, JSON.stringify({ ts: Date.now(), data }));
|
|
170
|
+
} catch {
|
|
171
|
+
// Write failure is non-fatal — stale cache used on next run
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function fetchWithTimeout(
|
|
177
|
+
url: string,
|
|
178
|
+
timeoutMs: number,
|
|
179
|
+
headers?: Record<string, string>,
|
|
180
|
+
): Promise<Response> {
|
|
181
|
+
const controller = new AbortController();
|
|
182
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
183
|
+
return fetch(url, { signal: controller.signal, headers }).finally(() =>
|
|
184
|
+
clearTimeout(timer),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ── Cache dir ─────────────────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
export const CACHE_DIR = join(
|
|
191
|
+
process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
|
|
192
|
+
"pi",
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
// ── Data sources ──────────────────────────────────────────────────────────────
|
|
196
|
+
|
|
197
|
+
export const modelsDev = new DataSource<ModelsDevApi>({
|
|
198
|
+
label: "models.dev",
|
|
199
|
+
url: "https://models.dev/api.json",
|
|
200
|
+
cachePath: join(CACHE_DIR, "models.json"),
|
|
201
|
+
parse: (raw) => raw as ModelsDevApi,
|
|
202
|
+
parseCache: (data) => (data as ModelsDevApi) ?? {},
|
|
203
|
+
empty: {},
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
export const benchmark = new DataSource<BenchmarkEntry[]>({
|
|
207
|
+
label: "benchlm",
|
|
208
|
+
url: "https://benchlm.ai/api/data/leaderboard",
|
|
209
|
+
cachePath: join(CACHE_DIR, "benchlm.json"),
|
|
210
|
+
parse: (raw) => (raw as BenchmarkResponse).models ?? [],
|
|
211
|
+
parseCache: (data) => (data as BenchmarkResponse)?.models ?? [],
|
|
212
|
+
empty: [],
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// ── Lookup helpers ─────────────────────────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
function normalize(id: string): string {
|
|
218
|
+
return id
|
|
219
|
+
.toLowerCase()
|
|
220
|
+
.replace(/[:@].*$/, "")
|
|
221
|
+
.replace(/-\d{8}$/, "");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function stripPrefix(id: string): string {
|
|
225
|
+
const i = id.lastIndexOf("/");
|
|
226
|
+
return i >= 0 ? id.slice(i + 1) : id;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function buildModelsDevIndex(api: ModelsDevApi): Map<string, ModelsDevModel> {
|
|
230
|
+
const index = new Map<string, ModelsDevModel>();
|
|
231
|
+
for (const provider of Object.values(api)) {
|
|
232
|
+
if (!provider?.models) continue;
|
|
233
|
+
for (const [modelId, model] of Object.entries(provider.models)) {
|
|
234
|
+
const m: ModelsDevModel = { ...model, id: modelId };
|
|
235
|
+
if (!index.has(modelId)) index.set(modelId, m);
|
|
236
|
+
const norm = normalize(modelId);
|
|
237
|
+
if (!index.has(norm)) index.set(norm, m);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return index;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function lookupInIndex(
|
|
244
|
+
id: string,
|
|
245
|
+
index: Map<string, ModelsDevModel>,
|
|
246
|
+
): ModelsDevModel | undefined {
|
|
247
|
+
const stripped = stripPrefix(id);
|
|
248
|
+
const direct = index.get(stripped) ?? index.get(normalize(stripped));
|
|
249
|
+
if (direct) return direct;
|
|
250
|
+
const norm = normalize(stripped);
|
|
251
|
+
for (const [key, model] of index) {
|
|
252
|
+
if (key.startsWith(norm) || norm.startsWith(key)) return model;
|
|
253
|
+
}
|
|
254
|
+
return undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function lookupModelsDev(provider: string, id: string): ModelsDevModel | undefined {
|
|
258
|
+
const data = modelsDev.getCached();
|
|
259
|
+
const canonical = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
|
|
260
|
+
const exact = data[provider]?.models?.[canonical];
|
|
261
|
+
if (exact) return exact;
|
|
262
|
+
for (const p of Object.keys(data)) {
|
|
263
|
+
const hit = data[p]?.models?.[canonical];
|
|
264
|
+
if (hit) return hit;
|
|
265
|
+
}
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export async function fetchModelsDevIndex(): Promise<Map<string, ModelsDevModel>> {
|
|
270
|
+
return buildModelsDevIndex(await modelsDev.get());
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function normBench(s: string): string {
|
|
274
|
+
return s.toLowerCase().replace(/[-_.]+/g, " ").replace(/\s+/g, " ").trim();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function lookupBenchmark(modelName: string): BenchmarkEntry | undefined {
|
|
278
|
+
const entries = benchmark.getCached();
|
|
279
|
+
const needle = normBench(modelName);
|
|
280
|
+
return (
|
|
281
|
+
entries.find((e) => normBench(e.model) === needle) ??
|
|
282
|
+
entries.find((e) => normBench(e.model).includes(needle)) ??
|
|
283
|
+
entries.find((e) => needle.includes(normBench(e.model)))
|
|
284
|
+
);
|
|
285
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pix-data — Pi extension
|
|
3
|
+
*
|
|
4
|
+
* Warms the shared model data cache on session start so other extensions
|
|
5
|
+
* (pix-9router, models picker, footer) can read from ~/.cache/pi/* synchronously.
|
|
6
|
+
*
|
|
7
|
+
* Fetches in parallel, non-blocking — Pi session starts immediately.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { modelsDev, benchmark } from "./data.ts";
|
|
12
|
+
|
|
13
|
+
export default function (_pi: ExtensionAPI): void {
|
|
14
|
+
void modelsDev.get();
|
|
15
|
+
void benchmark.get();
|
|
16
|
+
}
|