@pi-kode/model-discoverer 0.0.0-stage → 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/README.md +109 -2
- package/package.json +33 -4
- package/src/configure-model.ts +138 -0
- package/src/discovery.ts +124 -0
- package/src/index.ts +82 -0
- package/src/models-json.ts +61 -0
- package/src/refresh-hook.ts +66 -0
- package/src/refresh.ts +46 -0
- package/src/validate.ts +24 -0
package/README.md
CHANGED
|
@@ -1,3 +1,110 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pi-kode/model-discoverer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Pi extension that discovers, refreshes, and configures model catalogs using authentication already configured for a provider — a `/login` credential or a `models.json` `apiKey`. Targets **Earendil Pi 1.5.2+** and its native provider APIs; older Mario Zechner Pi releases are not supported.
|
|
4
|
+
|
|
5
|
+
## Capabilities
|
|
6
|
+
|
|
7
|
+
- **Built-in provider discovery** — Refreshes catalogs for authenticated native Pi providers by delegating to Pi's native refresh pipeline (handling API keys, OAuth renewal, provider endpoints, and persistence without reading `auth.json` directly).
|
|
8
|
+
- **Custom provider discovery (`models.json`)** — Opt any OpenAI-compatible (`openai-completions`, `openai-responses`) or Anthropic-compatible (`anthropic-messages`) provider into live `/models` discovery with `"discoverModels": true`, including per-model API overrides (`modelApis`) and Anthropic cursor pagination (`has_more` / `last_id`).
|
|
9
|
+
- **Automatic session-start refresh & lifecycle safety** — Runs a non-forced refresh on `session_start` (reusing Pi's startup refresh when fresh), guards against overlapping refreshes, enforces a 30-second timeout, and aborts in-flight requests on `session_shutdown`.
|
|
10
|
+
- **On-demand catalog refresh (`/discover-models`)** — Force-refresh all authenticated dynamic providers or a single provider by exact ID, with per-provider status summaries.
|
|
11
|
+
- **Interactive capability overrides (`/configure-model`)** — Interactively edit `reasoning`, `contextWindow`, and `maxTokens` for discovered models and persist them under `modelOverrides` in `models.json` so overrides survive future catalog refreshes.
|
|
12
|
+
- **Offline persistence & fallback** — Persists discovered catalogs through Pi's model store so models are restored before any network fetch; failed refreshes retain the previous catalog and any handwritten fallback `models`.
|
|
13
|
+
- **Security-first networking** — Requires HTTPS (or HTTP on loopback only), blocks HTTP redirects, enforces same-origin endpoints across config reloads, rejects non-API-key credentials for custom endpoints, and sanitizes all error messages so credentials, headers, and upstream response bodies are never leaked.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
Install from npm (requires Earendil Pi 1.5.2+):
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pi install npm:@pi-kode/model-discoverer
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Restart Pi or run `/reload`. For a one-off trial, use:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pi -e npm:@pi-kode/model-discoverer
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
To remove the npm-installed extension, run `pi remove npm:@pi-kode/model-discoverer` (for local installs, use the source shown by `pi list`) and reload. `models.json` entries and `/login` credentials are left untouched; delete any `discoverModels` keys you no longer want honored.
|
|
30
|
+
|
|
31
|
+
## Commands
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
/discover-models [provider-id]
|
|
35
|
+
/configure-model [provider-id]
|
|
36
|
+
/model
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### `/discover-models [provider-id]`
|
|
40
|
+
|
|
41
|
+
Force-refreshes all authenticated providers that support discovery, or one exact provider ID (matching `[a-z0-9][a-z0-9._-]{0,99}`).
|
|
42
|
+
|
|
43
|
+
- Does not select a model or change your default model.
|
|
44
|
+
- Discovery also runs automatically on `session_start` (without forcing a network fetch when Pi already refreshed).
|
|
45
|
+
- After a new `/login`, run `/discover-models`; the extension does not intercept Pi's login command.
|
|
46
|
+
|
|
47
|
+
### `/configure-model [provider-id]`
|
|
48
|
+
|
|
49
|
+
Interactively edits per-model capability overrides for a `discoverModels` provider in an interactive Pi session:
|
|
50
|
+
|
|
51
|
+
- `reasoning`: `true`, `false`, or remove override
|
|
52
|
+
- `contextWindow`: positive integer token limit, or clear (`""`, `-`, `remove`, `inherit`, `default`)
|
|
53
|
+
- `maxTokens`: positive integer token limit, or clear
|
|
54
|
+
|
|
55
|
+
Values are merged into `modelOverrides` in `~/.pi/agent/models.json` (empty override objects are automatically pruned). A backup is saved as `models.json.bak` before writing; note that rewriting drops JSON comments and custom formatting in `models.json`. Run `/reload` afterwards to apply.
|
|
56
|
+
|
|
57
|
+
Overrides sit at Pi's topmost configuration layer, so they survive every catalog refresh. Once a model is marked `reasoning: true`, use Pi's built-in `/thinking` (or `Shift+Tab`) to choose reasoning effort at runtime.
|
|
58
|
+
|
|
59
|
+
## Built-in providers
|
|
60
|
+
|
|
61
|
+
No configuration is needed. The extension delegates to Pi's **native refresh pipeline**, which handles stored API keys, OAuth renewal, provider-specific endpoints, filtering, and catalog persistence. It never reads `auth.json` directly and does not replace built-in providers.
|
|
62
|
+
|
|
63
|
+
A refreshed catalog is **not proof of account entitlement**. Some native providers refresh metadata from Pi's public catalog rather than querying an account-specific endpoint; others keep a static list. Providers without a refresh implementation are reported as unsupported for native discovery and retain their existing models. Actual availability remains subject to Pi's provider policy and the upstream service.
|
|
64
|
+
|
|
65
|
+
This extension does not invent `/models` endpoints for subscription OAuth providers or send subscription tokens to generic API endpoints.
|
|
66
|
+
|
|
67
|
+
## Discovering a custom provider (`models.json`)
|
|
68
|
+
|
|
69
|
+
Opt a provider into discovery with the custom key **`discoverModels: true`** in its `~/.pi/agent/models.json` entry (JSONC `//` comments and trailing commas are supported):
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"providers": {
|
|
74
|
+
"mws": {
|
|
75
|
+
"baseUrl": "https://gpt.example.com/projects/abc/openai/v1",
|
|
76
|
+
"api": "openai-completions",
|
|
77
|
+
"apiKey": "$MWS_API_KEY",
|
|
78
|
+
"discoverModels": true
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Pi itself ignores `discoverModels`; this extension reads `models.json` at startup and registers a discovery hook for each opted-in provider. Credentials stay with Pi: the provider's `apiKey` (literal, `$ENV_VAR`, or `${ENV_VAR}`) or a key stored via `/login <provider>` is resolved by Pi's auth layer and passed to the hook. If both exist, the stored `/login` credential wins. Never put discovery-only keys anywhere else.
|
|
85
|
+
|
|
86
|
+
Reload with `/reload` after editing `models.json`, then run `/discover-models mws` and pick a model with `/model`.
|
|
87
|
+
|
|
88
|
+
### Provider fields
|
|
89
|
+
|
|
90
|
+
- `discoverModels`: `true` opts the provider into discovery. This is the extension's custom key.
|
|
91
|
+
- `baseUrl`: API base URL (required). HTTPS only, except HTTP on `localhost`, `127.0.0.1`, or `[::1]`.
|
|
92
|
+
- `api`: `openai-completions`, `openai-responses`, or `anthropic-messages` (required for discovery).
|
|
93
|
+
- `modelsUrl`: optional complete catalog URL; defaults to `{baseUrl}/models`. Must share `baseUrl`'s origin. URL credentials, query strings, and fragments are rejected.
|
|
94
|
+
- `modelApis`: optional per-model API overrides, e.g. `{ "model-a": "openai-responses" }`. Unmatched models use the provider `api`.
|
|
95
|
+
- `apiKey`, `headers`, `models`, `modelOverrides`, `compat`: ordinary Pi `models.json` fields, applied as usual. Handwritten `models` remain as offline fallback when discovery fails.
|
|
96
|
+
|
|
97
|
+
Only configure trusted origins: discovery necessarily sends the resolved API key to the configured endpoint. Redirects are blocked. If `models.json` changes the effective `baseUrl` origin after models were discovered, discovery refuses rather than sending the credential to the new origin.
|
|
98
|
+
|
|
99
|
+
### Catalog format
|
|
100
|
+
|
|
101
|
+
Custom endpoints must return a JSON object with `data: [{ "id": "chat-model" }]`.
|
|
102
|
+
|
|
103
|
+
- **Authentication & pagination**: OpenAI-protocol providers (`openai-completions`, `openai-responses`) send `Authorization: Bearer <key>`. Anthropic (`anthropic-messages`) sends `x-api-key` plus `anthropic-version: 2023-06-01` and supports `has_more` / `last_id` cursor pagination via `after_id`. Other pagination schemes fail rather than silently installing an incomplete catalog.
|
|
104
|
+
- **Metadata & defaults**: Optional fields recognized per model are `name` or `display_name`, `context_window` or `context_length`, `max_tokens` or `max_output_tokens`, boolean `reasoning`, and `input: ["text", "image"]`. Absent capabilities default to text-only, `reasoning: false`, `128000` context window, and `16384` max tokens (clamped to `contextWindow`). Costs are zero placeholders (unknown, **not necessarily free**).
|
|
105
|
+
- **Filtering & limits**: Entries with an explicit non-chat `type` (anything other than `"model"` or `"chat"`) are excluded; an untyped `/models` response is assumed to contain chat models. Requests are bounded to 4 MiB per page, 20 pages, and 10000 models. Duplicate IDs are collapsed. Invalid responses fail without replacing the previous catalog. An explicitly empty successful list clears the discovered catalog.
|
|
106
|
+
- **Persistence**: Discovered catalogs are **persisted through Pi's model store**, so they are available offline on the next start and restored before any network fetch. A failed refresh retains the previous catalog. No credentials, headers, or complete upstream responses are logged or stored by this extension.
|
|
107
|
+
|
|
108
|
+
## Contributing & Development
|
|
109
|
+
|
|
110
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for local setup, running tests and type checks, architecture guidelines, and the release process.
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pi-kode/model-discoverer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Discover models using Pi's existing /login credentials",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/pi-kode/model-discoverer.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/pi-kode/model-discoverer#readme",
|
|
11
|
+
"bugs": "https://github.com/pi-kode/model-discoverer/issues",
|
|
12
|
+
"keywords": ["pi-package"],
|
|
13
|
+
"files": ["src", "README.md"],
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"pi": { "extensions": ["./src/index.ts"] },
|
|
18
|
+
"engines": { "node": ">=22" },
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "tsx --test test/*.test.ts",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"prepublishOnly": "npm test && npm run typecheck"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@earendil-works/pi-ai": "*",
|
|
26
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
30
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
31
|
+
"@types/node": "^22.0.0",
|
|
32
|
+
"tsx": "^4.20.0",
|
|
33
|
+
"typescript": "^5.9.0"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { copyFile, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import type { ExtensionCommandContext, ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { record } from "./validate.ts";
|
|
4
|
+
import { stripJsonComments, type DiscoveryEntry } from "./models-json.ts";
|
|
5
|
+
|
|
6
|
+
/** `null` removes the key from the override; `undefined` leaves it untouched. */
|
|
7
|
+
export interface OverridePatch {
|
|
8
|
+
reasoning?: boolean | null;
|
|
9
|
+
contextWindow?: number | null;
|
|
10
|
+
maxTokens?: number | null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const PATCH_KEYS = ["reasoning", "contextWindow", "maxTokens"] as const;
|
|
14
|
+
|
|
15
|
+
function fail(): never {
|
|
16
|
+
// Never echo config values: a mistaken configuration may contain a secret.
|
|
17
|
+
throw new Error("Cannot update models.json; check its syntax and the provider id.");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Return parent[key] as a mutable record, creating it if absent; fail on non-object values. */
|
|
21
|
+
function childRecord(parent: Record<string, unknown>, key: string): Record<string, unknown> {
|
|
22
|
+
const value = parent[key];
|
|
23
|
+
if (value !== undefined && !record(value)) fail();
|
|
24
|
+
const child = record(value) ? value : {};
|
|
25
|
+
parent[key] = child;
|
|
26
|
+
return child;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Merge a modelOverride patch into raw models.json text and return the updated text. */
|
|
30
|
+
export function applyModelOverride(content: string, providerId: string, modelId: string, patch: OverridePatch): string {
|
|
31
|
+
let parsed: unknown;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(stripJsonComments(content.replace(/^/, "")));
|
|
34
|
+
} catch {
|
|
35
|
+
fail();
|
|
36
|
+
}
|
|
37
|
+
if (!record(parsed) || !record(parsed.providers) || parsed.providers[providerId] === undefined) fail();
|
|
38
|
+
const provider = childRecord(parsed.providers, providerId);
|
|
39
|
+
const overrides = childRecord(provider, "modelOverrides");
|
|
40
|
+
const model = childRecord(overrides, modelId);
|
|
41
|
+
for (const key of PATCH_KEYS) {
|
|
42
|
+
const value = patch[key];
|
|
43
|
+
if (value === undefined) continue;
|
|
44
|
+
if (value === null) delete model[key];
|
|
45
|
+
else model[key] = value;
|
|
46
|
+
}
|
|
47
|
+
if (Object.keys(model).length === 0) delete overrides[modelId];
|
|
48
|
+
if (Object.keys(overrides).length === 0) delete provider.modelOverrides;
|
|
49
|
+
return JSON.stringify(parsed, null, 2) + "\n";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseLimit(raw: string | undefined): number | null | undefined {
|
|
53
|
+
if (raw === undefined) return undefined; // cancelled
|
|
54
|
+
const trimmed = raw.trim();
|
|
55
|
+
if (trimmed === "" || /^(-|remove|inherit|default)$/i.test(trimmed)) return null;
|
|
56
|
+
if (!/^[1-9][0-9]{0,8}$/.test(trimmed)) return undefined;
|
|
57
|
+
return Number(trimmed);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Interactive /configure-model flow: pick provider and model, edit capability overrides. */
|
|
61
|
+
export async function configureModel(
|
|
62
|
+
entries: DiscoveryEntry[],
|
|
63
|
+
args: string,
|
|
64
|
+
ctx: ExtensionCommandContext,
|
|
65
|
+
modelsJsonPath: string,
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
if (!ctx.hasUI) {
|
|
68
|
+
throw new Error("/configure-model needs interactive UI; edit modelOverrides in models.json directly instead.");
|
|
69
|
+
}
|
|
70
|
+
if (entries.length === 0) {
|
|
71
|
+
ctx.ui.notify('No discoverModels providers in models.json.', "warning");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const requested = args.trim();
|
|
75
|
+
let entry = requested ? entries.find((candidate) => candidate.id === requested) : undefined;
|
|
76
|
+
if (requested && !entry) {
|
|
77
|
+
ctx.ui.notify(`Unknown discoverModels provider "${requested}". Configured: ${entries.map((e) => e.id).join(", ")}`, "warning");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!entry) {
|
|
81
|
+
const picked = await ctx.ui.select("Configure which provider?", entries.map((e) => e.id));
|
|
82
|
+
if (!picked) return;
|
|
83
|
+
entry = entries.find((candidate) => candidate.id === picked)!;
|
|
84
|
+
}
|
|
85
|
+
const models = listModels(ctx.modelRegistry, entry.id);
|
|
86
|
+
if (models.length === 0) {
|
|
87
|
+
ctx.ui.notify(`Provider ${entry.id} has no models. Run /discover-models ${entry.id} first.`, "warning");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const modelLabel = await ctx.ui.select(`Configure which ${entry.id} model?`, models.map(
|
|
91
|
+
(m) => `${m.id} — context ${m.contextWindow}, max ${m.maxTokens}${m.reasoning ? ", reasoning" : ""}`,
|
|
92
|
+
));
|
|
93
|
+
if (!modelLabel) return;
|
|
94
|
+
const modelId = modelLabel.split(" — ")[0];
|
|
95
|
+
|
|
96
|
+
const patch: OverridePatch = {};
|
|
97
|
+
let dirty = false;
|
|
98
|
+
for (;;) {
|
|
99
|
+
const field = await ctx.ui.select(`Edit ${modelId}`, [
|
|
100
|
+
`reasoning: ${display(patch.reasoning)}`,
|
|
101
|
+
`contextWindow: ${display(patch.contextWindow)}`,
|
|
102
|
+
`maxTokens: ${display(patch.maxTokens)}`,
|
|
103
|
+
dirty ? "save and exit" : "exit without changes",
|
|
104
|
+
]);
|
|
105
|
+
if (!field || field.startsWith("exit")) return;
|
|
106
|
+
if (field.startsWith("save")) break;
|
|
107
|
+
if (field.startsWith("reasoning")) {
|
|
108
|
+
const value = await ctx.ui.select("reasoning", ["true", "false", "remove override"]);
|
|
109
|
+
if (value === undefined) continue;
|
|
110
|
+
patch.reasoning = value === "remove override" ? null : value === "true";
|
|
111
|
+
} else {
|
|
112
|
+
const key = field.startsWith("contextWindow") ? "contextWindow" : "maxTokens";
|
|
113
|
+
const raw = await ctx.ui.input(`New ${key} (tokens, or "remove" to clear the override)`);
|
|
114
|
+
const value = parseLimit(raw);
|
|
115
|
+
if (value === undefined) {
|
|
116
|
+
if (raw !== undefined) ctx.ui.notify("Enter a positive whole number of tokens, or \"remove\".", "warning");
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
patch[key] = value;
|
|
120
|
+
}
|
|
121
|
+
dirty = true;
|
|
122
|
+
}
|
|
123
|
+
const updated = applyModelOverride(await readFile(modelsJsonPath, "utf8"), entry.id, modelId, patch);
|
|
124
|
+
// One-time backup: rewriting drops comments/formatting from the original file.
|
|
125
|
+
await copyFile(modelsJsonPath, modelsJsonPath + ".bak").catch(() => {});
|
|
126
|
+
await writeFile(modelsJsonPath, updated, "utf8");
|
|
127
|
+
ctx.ui.notify(`Saved overrides for ${entry.id}/${modelId} to models.json. Run /reload to apply.`, "info");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function display(value: boolean | number | null | undefined): string {
|
|
131
|
+
if (value === undefined) return "unchanged";
|
|
132
|
+
if (value === null) return "override removed";
|
|
133
|
+
return String(value);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function listModels(registry: ModelRegistry, providerId: string) {
|
|
137
|
+
return registry.getProvider(providerId)?.getModels() ?? [];
|
|
138
|
+
}
|
package/src/discovery.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { Api, Model, RefreshModelsContext } from "@earendil-works/pi-ai";
|
|
2
|
+
import { endpointUrl, record } from "./validate.ts";
|
|
3
|
+
import type { DiscoveryEntry } from "./models-json.ts";
|
|
4
|
+
|
|
5
|
+
const MAX_BYTES = 4 * 1024 * 1024;
|
|
6
|
+
const MAX_MODELS = 10000;
|
|
7
|
+
const DEFAULT_CONTEXT_WINDOW = 128000;
|
|
8
|
+
const DEFAULT_MAX_TOKENS = 16384;
|
|
9
|
+
const positive = (value: unknown, fallback: number): number =>
|
|
10
|
+
typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : fallback;
|
|
11
|
+
|
|
12
|
+
export function parseModels(payload: unknown, id: string, api: Api, baseUrl: string, modelApis?: Record<string, Api>): Model<Api>[] {
|
|
13
|
+
if (!record(payload) || !Array.isArray(payload.data) || payload.data.length > MAX_MODELS) {
|
|
14
|
+
throw new Error("Invalid model catalog.");
|
|
15
|
+
}
|
|
16
|
+
const models = new Map<string, Model<Api>>();
|
|
17
|
+
for (const item of payload.data) {
|
|
18
|
+
if (!record(item) || typeof item.id !== "string" || !item.id.trim() ||
|
|
19
|
+
item.id.length > 256 || /[\u0000-\u001f\u007f]/.test(item.id)) {
|
|
20
|
+
throw new Error("Invalid model catalog entry.");
|
|
21
|
+
}
|
|
22
|
+
// Explicitly non-chat entries must not become selectable chat models.
|
|
23
|
+
if (item.type !== undefined && item.type !== "model" && item.type !== "chat") continue;
|
|
24
|
+
const contextWindow = positive(item.context_window ?? item.context_length, DEFAULT_CONTEXT_WINDOW);
|
|
25
|
+
const maxTokens = Math.min(contextWindow, positive(item.max_tokens ?? item.max_output_tokens, DEFAULT_MAX_TOKENS));
|
|
26
|
+
const name = typeof item.name === "string" ? item.name : item.display_name;
|
|
27
|
+
models.set(item.id, {
|
|
28
|
+
id: item.id,
|
|
29
|
+
name: typeof name === "string" && name.length <= 256 && !/[\u0000-\u001f\u007f]/.test(name) ? name : item.id,
|
|
30
|
+
provider: id,
|
|
31
|
+
api: modelApis?.[item.id] ?? api,
|
|
32
|
+
baseUrl,
|
|
33
|
+
reasoning: item.reasoning === true,
|
|
34
|
+
input: Array.isArray(item.input) && item.input.includes("image") ? ["text", "image"] : ["text"],
|
|
35
|
+
contextWindow,
|
|
36
|
+
maxTokens,
|
|
37
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return [...models.values()];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readJson(response: Response): Promise<unknown> {
|
|
44
|
+
if (!response.body) throw new Error("Empty model catalog response.");
|
|
45
|
+
const reader = response.body.getReader();
|
|
46
|
+
const chunks: Uint8Array[] = [];
|
|
47
|
+
let size = 0;
|
|
48
|
+
try {
|
|
49
|
+
for (;;) {
|
|
50
|
+
const { value, done } = await reader.read();
|
|
51
|
+
if (done) break;
|
|
52
|
+
size += value.byteLength;
|
|
53
|
+
if (size > MAX_BYTES) throw new Error("Model catalog response is too large.");
|
|
54
|
+
chunks.push(value);
|
|
55
|
+
}
|
|
56
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
57
|
+
} finally {
|
|
58
|
+
await reader.cancel().catch(() => {});
|
|
59
|
+
reader.releaseLock();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function discover(
|
|
64
|
+
id: string,
|
|
65
|
+
entry: DiscoveryEntry,
|
|
66
|
+
context: RefreshModelsContext,
|
|
67
|
+
fetcher: typeof fetch = fetch,
|
|
68
|
+
): Promise<Model<Api>[]> {
|
|
69
|
+
// OAuth is provider-specific. Never treat a subscription token as a generic key.
|
|
70
|
+
if (context.credential?.type !== "api_key" || !context.credential.key) {
|
|
71
|
+
throw new Error("Custom discovery requires an API key credential.");
|
|
72
|
+
}
|
|
73
|
+
const base = endpointUrl(context.baseUrl ?? entry.baseUrl);
|
|
74
|
+
// A later configuration change must not redirect a credential to another origin.
|
|
75
|
+
if (base.origin !== endpointUrl(entry.baseUrl).origin) throw new Error("Discovery endpoint origin changed.");
|
|
76
|
+
const url = endpointUrl(entry.modelsUrl ?? `${base.href.replace(/\/$/, "")}/models`);
|
|
77
|
+
if (url.origin !== base.origin) throw new Error("Discovery endpoint origin changed.");
|
|
78
|
+
const signal = context.signal;
|
|
79
|
+
const models = new Map<string, Model<Api>>();
|
|
80
|
+
const cursors = new Set<string>();
|
|
81
|
+
try {
|
|
82
|
+
// Header validation errors can include the invalid value, so sanitize them too.
|
|
83
|
+
const headers = new Headers({ accept: "application/json" });
|
|
84
|
+
if (entry.api === "anthropic-messages") {
|
|
85
|
+
headers.set("x-api-key", context.credential.key);
|
|
86
|
+
headers.set("anthropic-version", "2023-06-01");
|
|
87
|
+
} else {
|
|
88
|
+
headers.set("authorization", `Bearer ${context.credential.key}`);
|
|
89
|
+
}
|
|
90
|
+
for (let page = 0; page < 20; page++) {
|
|
91
|
+
signal.throwIfAborted();
|
|
92
|
+
const response = await fetcher(url, { headers, signal, redirect: "error" });
|
|
93
|
+
if (!response.ok) {
|
|
94
|
+
await response.body?.cancel();
|
|
95
|
+
throw new DiscoveryError(`HTTP ${response.status}`);
|
|
96
|
+
}
|
|
97
|
+
const payload = await readJson(response);
|
|
98
|
+
for (const model of parseModels(payload, id, entry.api, base.href.replace(/\/$/, ""), entry.modelApis)) {
|
|
99
|
+
models.set(model.id, model);
|
|
100
|
+
}
|
|
101
|
+
if (models.size > MAX_MODELS) throw new DiscoveryError("too many models");
|
|
102
|
+
if (!record(payload) || payload.has_more !== true) return [...models.values()];
|
|
103
|
+
if (entry.api !== "anthropic-messages" || typeof payload.last_id !== "string" ||
|
|
104
|
+
!payload.last_id || cursors.has(payload.last_id)) throw new DiscoveryError("unsupported pagination");
|
|
105
|
+
cursors.add(payload.last_id);
|
|
106
|
+
url.searchParams.set("after_id", payload.last_id);
|
|
107
|
+
}
|
|
108
|
+
throw new DiscoveryError("too many pages");
|
|
109
|
+
} catch (error) {
|
|
110
|
+
// Fetch errors and provider bodies may contain credentials or sensitive URLs.
|
|
111
|
+
if (signal.aborted) throw new Error("Model discovery cancelled or timed out.");
|
|
112
|
+
if (error instanceof DiscoveryError) {
|
|
113
|
+
throw new Error(`Model discovery failed: ${error.reason}.`);
|
|
114
|
+
}
|
|
115
|
+
// Node fetch failures carry a safe machine-readable code (ENOTFOUND, ECONNREFUSED, ...).
|
|
116
|
+
const code = (error as { cause?: { code?: unknown } })?.cause?.code;
|
|
117
|
+
const suffix = typeof code === "string" && /^[A-Z0-9_]+$/.test(code) ? `: network ${code}` : "";
|
|
118
|
+
throw new Error(`Model discovery failed${suffix}.`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
class DiscoveryError extends Error {
|
|
123
|
+
constructor(readonly reason: string) { super(reason); }
|
|
124
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { configureModel } from "./configure-model.ts";
|
|
5
|
+
import { parseDiscoveryProviders, type DiscoveryEntry } from "./models-json.ts";
|
|
6
|
+
import { refreshModelsFor } from "./refresh-hook.ts";
|
|
7
|
+
import { refreshCatalogs } from "./refresh.ts";
|
|
8
|
+
|
|
9
|
+
const REFRESH_TIMEOUT_MS = 30000;
|
|
10
|
+
|
|
11
|
+
export default async function modelDiscoverer(pi: ExtensionAPI): Promise<void> {
|
|
12
|
+
// Providers opt into discovery with "discoverModels": true in models.json.
|
|
13
|
+
// Pi ignores that unknown key; this extension reads the file itself.
|
|
14
|
+
let entries: DiscoveryEntry[];
|
|
15
|
+
const modelsJsonPath = join(getAgentDir(), "models.json");
|
|
16
|
+
try {
|
|
17
|
+
entries = parseDiscoveryProviders(await readFile(modelsJsonPath, "utf8"));
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
20
|
+
throw new Error("Cannot read models.json for model discovery; check its syntax.");
|
|
21
|
+
}
|
|
22
|
+
entries = [];
|
|
23
|
+
}
|
|
24
|
+
const discoveredIds: string[] = [];
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
// Legacy registration composes above the models.json provider layer: Pi keeps
|
|
27
|
+
// the provider's baseUrl/apiKey/auth and streams through the configured API.
|
|
28
|
+
pi.registerProvider(entry.id, {
|
|
29
|
+
refreshModels: (context) => refreshModelsFor(entry, context),
|
|
30
|
+
});
|
|
31
|
+
discoveredIds.push(entry.id);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const lifetime = new AbortController();
|
|
35
|
+
let running = false;
|
|
36
|
+
|
|
37
|
+
async function refresh(ctx: ExtensionContext, requested?: string, force = false): Promise<void> {
|
|
38
|
+
if (running) {
|
|
39
|
+
if (ctx.hasUI) ctx.ui.notify("Model discovery is already running.", "info");
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
running = true;
|
|
43
|
+
try {
|
|
44
|
+
const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(REFRESH_TIMEOUT_MS)]);
|
|
45
|
+
// No explicit id list: refreshes every authenticated provider with a refresh hook,
|
|
46
|
+
// including native Pi providers and our discoverModels providers.
|
|
47
|
+
const lines = await refreshCatalogs(ctx.modelRegistry, discoveredIds, requested, signal, force);
|
|
48
|
+
if (ctx.hasUI && !lifetime.signal.aborted) ctx.ui.notify(lines.join("\n"), "info");
|
|
49
|
+
} catch {
|
|
50
|
+
if (ctx.hasUI && !lifetime.signal.aborted) {
|
|
51
|
+
ctx.ui.notify("Model discovery failed. Check authentication, configuration, and connectivity.", "warning");
|
|
52
|
+
}
|
|
53
|
+
} finally {
|
|
54
|
+
running = false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pi.registerCommand("discover-models", {
|
|
59
|
+
description: "Refresh model catalogs using existing /login credentials (optional provider ID)",
|
|
60
|
+
async handler(args, ctx) {
|
|
61
|
+
const id = args.trim();
|
|
62
|
+
if (id && !/^[a-z0-9][a-z0-9._-]{0,99}$/.test(id)) {
|
|
63
|
+
ctx.ui.notify("Usage: /discover-models [provider-id]", "warning");
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
await ctx.waitForIdle();
|
|
67
|
+
await refresh(ctx, id || undefined, true);
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
pi.registerCommand("configure-model", {
|
|
71
|
+
description: "Edit capability overrides (reasoning, contextWindow, maxTokens) for a discovered model",
|
|
72
|
+
async handler(args, ctx) {
|
|
73
|
+
await ctx.waitForIdle();
|
|
74
|
+
await configureModel(entries, args, ctx, modelsJsonPath);
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
78
|
+
// Pi already refreshed during startup; only force-fetch on explicit command.
|
|
79
|
+
await refresh(ctx, undefined, false);
|
|
80
|
+
});
|
|
81
|
+
pi.on("session_shutdown", () => { lifetime.abort(); });
|
|
82
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { endpointUrl, record } from "./validate.ts";
|
|
2
|
+
|
|
3
|
+
export const APIS = ["openai-completions", "openai-responses", "anthropic-messages"] as const;
|
|
4
|
+
export type DiscoveryApi = (typeof APIS)[number];
|
|
5
|
+
|
|
6
|
+
export interface DiscoveryEntry {
|
|
7
|
+
id: string;
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
modelsUrl?: string;
|
|
10
|
+
api: DiscoveryApi;
|
|
11
|
+
modelApis?: Record<string, DiscoveryApi>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fail(): never {
|
|
15
|
+
// Never echo config values: a mistaken configuration may contain a secret.
|
|
16
|
+
throw new Error("Invalid discoverModels provider in models.json; see the README configuration reference.");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Strip `//` comments and trailing commas, leaving string literals untouched (matches Pi's models.json parsing). */
|
|
20
|
+
export function stripJsonComments(input: string): string {
|
|
21
|
+
return input
|
|
22
|
+
.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : ""))
|
|
23
|
+
.replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m, tail) => tail ?? (m[0] === '"' ? m : ""));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Extract providers opted into discovery with `discoverModels: true` from raw models.json text. */
|
|
27
|
+
export function parseDiscoveryProviders(content: string): DiscoveryEntry[] {
|
|
28
|
+
let parsed: unknown;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(stripJsonComments(content.replace(/^/, "")));
|
|
31
|
+
} catch {
|
|
32
|
+
return fail();
|
|
33
|
+
}
|
|
34
|
+
if (!record(parsed) || parsed.providers === undefined) return [];
|
|
35
|
+
if (!record(parsed.providers)) fail();
|
|
36
|
+
const entries: DiscoveryEntry[] = [];
|
|
37
|
+
for (const [id, provider] of Object.entries(parsed.providers)) {
|
|
38
|
+
if (!record(provider)) fail();
|
|
39
|
+
if (provider.discoverModels !== true) continue;
|
|
40
|
+
if (!APIS.includes(provider.api as DiscoveryApi)) fail();
|
|
41
|
+
const base = endpointUrl(provider.baseUrl);
|
|
42
|
+
const modelsUrl = provider.modelsUrl === undefined ? undefined : endpointUrl(provider.modelsUrl);
|
|
43
|
+
if (modelsUrl && modelsUrl.origin !== base.origin) fail();
|
|
44
|
+
const modelApis: Record<string, DiscoveryApi> = {};
|
|
45
|
+
if (provider.modelApis !== undefined) {
|
|
46
|
+
if (!record(provider.modelApis)) fail();
|
|
47
|
+
for (const [modelId, api] of Object.entries(provider.modelApis)) {
|
|
48
|
+
if (!APIS.includes(api as DiscoveryApi)) fail();
|
|
49
|
+
modelApis[modelId] = api as DiscoveryApi;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
entries.push({
|
|
53
|
+
id,
|
|
54
|
+
baseUrl: base.href.replace(/\/$/, ""),
|
|
55
|
+
modelsUrl: modelsUrl?.href,
|
|
56
|
+
api: provider.api as DiscoveryApi,
|
|
57
|
+
modelApis: Object.keys(modelApis).length ? modelApis : undefined,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return entries;
|
|
61
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { getModelType, type AnyModel, type Model, type Api, type RefreshModelsContext } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { discover } from "./discovery.ts";
|
|
4
|
+
import type { DiscoveryEntry } from "./models-json.ts";
|
|
5
|
+
|
|
6
|
+
function apiFor(entry: DiscoveryEntry, id: string): Api {
|
|
7
|
+
return entry.modelApis?.[id] ?? entry.api;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Project a discovered model into the extension model-definition shape Pi composes.
|
|
12
|
+
* Pi's extensionModelFromDefinition requires api and baseUrl on every definition;
|
|
13
|
+
* the models.json layer does not supply them for extension-provided models.
|
|
14
|
+
*/
|
|
15
|
+
function toModelConfig(entry: DiscoveryEntry, model: Model<Api>): ProviderModelConfig {
|
|
16
|
+
return {
|
|
17
|
+
id: model.id,
|
|
18
|
+
name: model.name,
|
|
19
|
+
api: model.api,
|
|
20
|
+
baseUrl: entry.baseUrl,
|
|
21
|
+
reasoning: model.reasoning,
|
|
22
|
+
input: model.input,
|
|
23
|
+
cost: model.cost,
|
|
24
|
+
contextWindow: model.contextWindow,
|
|
25
|
+
maxTokens: model.maxTokens,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function restoreModelConfig(entry: DiscoveryEntry, model: AnyModel): ProviderModelConfig {
|
|
30
|
+
if (getModelType(model) !== "chat") {
|
|
31
|
+
throw new Error("Persisted catalog contains a non-chat model.");
|
|
32
|
+
}
|
|
33
|
+
const chat = model as Model<Api>;
|
|
34
|
+
// Drop stored endpoint fields: current models.json api/baseUrl always wins.
|
|
35
|
+
return {
|
|
36
|
+
id: chat.id,
|
|
37
|
+
name: chat.name,
|
|
38
|
+
api: apiFor(entry, chat.id),
|
|
39
|
+
baseUrl: entry.baseUrl,
|
|
40
|
+
reasoning: chat.reasoning === true,
|
|
41
|
+
input: Array.isArray(chat.input) && chat.input.includes("image") ? ["text", "image"] : ["text"],
|
|
42
|
+
cost: chat.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
43
|
+
contextWindow: chat.contextWindow,
|
|
44
|
+
maxTokens: chat.maxTokens,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Legacy extension refresh hook composed above the models.json provider layer.
|
|
50
|
+
* Pi resolves the effective /login or models.json credential into context.credential.
|
|
51
|
+
*/
|
|
52
|
+
export async function refreshModelsFor(
|
|
53
|
+
entry: DiscoveryEntry,
|
|
54
|
+
context: RefreshModelsContext,
|
|
55
|
+
fetcher: typeof fetch = fetch,
|
|
56
|
+
): Promise<ProviderModelConfig[]> {
|
|
57
|
+
if (!context.allowNetwork) {
|
|
58
|
+
// Cache-only phase: restore the last persisted catalog without network access.
|
|
59
|
+
return (context.stored?.models ?? []).map((model) => restoreModelConfig(entry, model));
|
|
60
|
+
}
|
|
61
|
+
const models = await discover(entry.id, entry, context, fetcher);
|
|
62
|
+
context.signal.throwIfAborted();
|
|
63
|
+
// Persist the catalog for offline startup; Pi applies generation checks.
|
|
64
|
+
await context.publish({ persist: { models, checkedAt: Date.now() } });
|
|
65
|
+
return models.map((model) => toModelConfig(entry, model));
|
|
66
|
+
}
|
package/src/refresh.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export type Registry = Pick<ModelRegistry,
|
|
4
|
+
"getAll" | "getRegisteredProviderIds" | "getProvider" | "getProviderAuthStatus" | "refresh" | "getError">;
|
|
5
|
+
|
|
6
|
+
export async function refreshCatalogs(
|
|
7
|
+
registry: Registry,
|
|
8
|
+
knownIds: readonly string[],
|
|
9
|
+
requested: string | undefined,
|
|
10
|
+
signal: AbortSignal,
|
|
11
|
+
force = true,
|
|
12
|
+
): Promise<string[]> {
|
|
13
|
+
const ids = requested ? [requested] : [...new Set([
|
|
14
|
+
...knownIds, ...registry.getRegisteredProviderIds(), ...registry.getAll().map((model) => model.provider),
|
|
15
|
+
])].sort();
|
|
16
|
+
const lines: string[] = [];
|
|
17
|
+
const selected: string[] = [];
|
|
18
|
+
for (const id of ids) {
|
|
19
|
+
const provider = registry.getProvider(id);
|
|
20
|
+
if (!provider) {
|
|
21
|
+
if (requested) lines.push("Unknown provider. Use its exact /login provider ID.");
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (!registry.getProviderAuthStatus(id).configured) {
|
|
25
|
+
if (requested) lines.push(`${id}: no configured authentication; use /login.`);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (!provider.refreshModels) {
|
|
29
|
+
lines.push(`${id}: no native discovery; keeping existing catalog.`);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
selected.push(id);
|
|
33
|
+
}
|
|
34
|
+
if (selected.length) {
|
|
35
|
+
const result = await registry.refresh({ providers: selected, allowNetwork: true, force, signal });
|
|
36
|
+
for (const id of selected) {
|
|
37
|
+
if (result.errors.has(id)) lines.push(`${id}: refresh failed; keeping previous catalog. Check authentication and connectivity.`);
|
|
38
|
+
else if (result.aborted) lines.push(`${id}: refresh interrupted; catalog may be unchanged.`);
|
|
39
|
+
// Pi may silently supersede a provider refresh; absence of errors is not
|
|
40
|
+
// evidence that this invocation published a new catalog.
|
|
41
|
+
else lines.push(`${id}: refresh finished; current catalog: ${registry.getProvider(id)?.getModels().length ?? 0} chat models.`);
|
|
42
|
+
}
|
|
43
|
+
if (registry.getError()) lines.push("Pi reported a models.json error; check that configuration.");
|
|
44
|
+
}
|
|
45
|
+
return lines.length ? lines : ["No authenticated providers to discover. Run /login first."];
|
|
46
|
+
}
|
package/src/validate.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function record(value: unknown): value is Record<string, unknown> {
|
|
2
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
/** Parse and validate an endpoint URL: HTTPS, or HTTP on loopback only; no credentials/query/fragment. Throws a sanitized error. */
|
|
6
|
+
export function endpointUrl(value: unknown): URL {
|
|
7
|
+
if (typeof value !== "string") fail();
|
|
8
|
+
let url: URL;
|
|
9
|
+
try {
|
|
10
|
+
url = new URL(value as string);
|
|
11
|
+
} catch {
|
|
12
|
+
fail();
|
|
13
|
+
}
|
|
14
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
15
|
+
if (
|
|
16
|
+
(url.protocol !== "https:" && !(url.protocol === "http:" && local)) ||
|
|
17
|
+
url.username || url.password || url.search || url.hash
|
|
18
|
+
) fail();
|
|
19
|
+
return url;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function fail(): never {
|
|
23
|
+
throw new Error("Invalid discovery endpoint URL; see the README configuration reference.");
|
|
24
|
+
}
|