@maheidem/model-discovery 0.7.0 → 0.8.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) 2026 maheidem
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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @maheidem/model-discovery
2
2
 
3
- Interactive TUI for discovering and managing local AI model endpoints. Works with llama.cpp, oMLX, Ollama, vLLM, SGLang, LM Studio, and other OpenAI-compatible servers.
3
+ A responsive, hierarchical Pi wizard for discovering and managing local AI model sources. It works with llama.cpp, oMLX, Ollama, vLLM, SGLang, LM Studio, and other OpenAI-compatible servers, with useful status and diagnostics in TUI, RPC, JSON, and print modes.
4
4
 
5
5
  ## Features
6
6
 
@@ -18,6 +18,8 @@ Interactive TUI for discovering and managing local AI model endpoints. Works wit
18
18
  - **Authenticated endpoints** — enroll, replace, validate, or clear bearer API keys through masked TUI input
19
19
  - **Multi-endpoint management** — add, rename, scan, and remove local model sources
20
20
  - **LLM-callable tool** — the `discover_models` tool can register endpoints on the agent's behalf
21
+ - **Shared Pi UX** — responsive bordered wizard steps, searchable lists, injected keybindings, scrolling previews, cancellable loaders, and masked secrets
22
+ - **Headless command surface** — stable status, diagnostics, paths, source listing, and explicit add/remove actions for RPC and scripts
21
23
  - **Persistent storage** in `~/.pi/agent/model-discovery.json`
22
24
 
23
25
  ## Installation
@@ -27,27 +29,54 @@ Interactive TUI for discovering and managing local AI model endpoints. Works wit
27
29
  pi install npm:@maheidem/model-discovery
28
30
 
29
31
  # Via git
30
- pi install git:github.com/Maheidem/model-discovery@v0.7.0
32
+ pi install git:github.com/Maheidem/model-discovery
31
33
  ```
32
34
 
33
35
  ## Usage
34
36
 
35
- Run `/discover` in Pi to open the management TUI:
37
+ Run bare `/discover` in TUI mode to open the source wizard:
36
38
 
37
- - **Add endpoint** — enter a URL, choose anonymous or API-key authentication, probe it, review models, and register
38
- - **Re-scan** refresh models reported by an existing endpoint
39
+ ```text
40
+ Sources source details model details presets and adaptive routing
41
+ ↘ add / scan / authentication / diagnostics
42
+ ```
43
+
44
+ The home screen shows source and cached-model health before offering the primary actions. Every list supports Pi's configured navigation/confirm/cancel bindings and type-to-filter. Escape returns to the logical parent. Long diagnostics and exact-request previews use a scrolling secondary view rather than clipping the footer.
45
+
46
+ From the wizard you can:
47
+
48
+ - **Add source** — enter a URL, choose anonymous or API-key authentication, probe it, review models, and register
49
+ - **Re-scan** — refresh one source or every source while retaining last known-good catalogues on failure
39
50
  - **Edit model** — override context, max output, reasoning, or vision support
40
- - **Manage profiles** — create, edit, rename, or delete named variants
51
+ - **Manage presets** — create, clone, edit, rename, preview, route, or delete named variants
41
52
  - **Rename source** — change the provider name shown by `/model`
42
- - **Remove** — unregister and delete an endpoint
53
+ - **Authentication** — add, replace, validate, or clear a bearer credential through masked input
54
+ - **Diagnostics** — inspect storage, source health, authentication state, and cached catalogue state without exposing secrets
55
+ - **Remove source** — unregister it and delete its saved configuration after confirmation
56
+
57
+ The same root command has a scriptable surface. Bare `/discover` prints status outside TUI instead of silently doing nothing:
58
+
59
+ ```text
60
+ /discover
61
+ /discover status
62
+ /discover doctor
63
+ /discover paths
64
+ /discover source list
65
+ /discover source add http://192.168.1.100:8080
66
+ /discover source add http://192.168.1.100:8080 --name my-llama
67
+ /discover source remove my-llama --yes
68
+ /discover help
69
+ ```
43
70
 
44
- You can jump directly into adding an endpoint:
71
+ The original direct-add shorthand remains compatible:
45
72
 
46
73
  ```text
47
74
  /discover http://192.168.1.100:8080
48
75
  ```
49
76
 
50
- Enrollment explicitly asks whether the endpoint is anonymous or requires an API key. API-key input is masked and is sent as `Authorization: Bearer <key>` for both `/v1/models` discovery and inference. The key is stored unencrypted in `~/.pi/agent/model-discovery.json`; the extension writes that file atomically with owner-only (`0600`) permissions. Use **Authentication** on an existing endpoint to replace, validate, or clear its key without losing the cached catalogue.
77
+ In TUI mode, add commands enter the full enrollment wizard. Outside TUI, source add probes and registers an anonymous source using server-reported/default values. Configure credentials through the masked TUI rather than command arguments. Source removal requires confirmation in TUI and requires explicit `--yes` outside TUI.
78
+
79
+ Enrollment explicitly asks whether the source is anonymous or requires an API key. API-key input is masked and is sent as `Authorization: Bearer <key>` for both `/v1/models` discovery and inference. The key is stored unencrypted in `~/.pi/agent/model-discovery.json`; the extension writes that file atomically with owner-only (`0600`) permissions. Use **Authentication** on an existing source to replace, validate, or clear its key without losing the cached catalogue.
51
80
 
52
81
  The LLM-callable tool remains available:
53
82
 
@@ -207,6 +236,68 @@ If Pi has an `enabledModels` scope, press **Tab** in `/model` to switch from sco
207
236
 
208
237
  Profiles are retained if a model temporarily disappears during a re-scan.
209
238
 
239
+ ## Tool-schema repair (local endpoints)
240
+
241
+ llama.cpp's JSON-schema→grammar converter — the one behind llama.cpp, llama-swap, LM
242
+ Studio, and LiteLLM routes that forward to them — resolves `$ref` pointers **only
243
+ against the root of a tool schema document**. MCP servers that build schemas by nesting
244
+ Pydantic `model_json_schema()` output inside a hand-written parent routinely leave
245
+ `$defs` on an inner node while the `$ref`s inside it stay root-relative:
246
+
247
+ ```jsonc
248
+ { "properties": { "patch": {
249
+ "$defs": { "GuidelineMetricInput": { /* ... */ } }, // defs live here
250
+ "properties": { "metrics": { "items": { "$ref": "#/$defs/GuidelineMetricInput" } } }
251
+ }}}
252
+ ```
253
+
254
+ The pointer resolves against the document root, where `$defs` is not — so the server
255
+ rejects the **entire request**:
256
+
257
+ ```text
258
+ HTTP 400 {"code":400,"message":"JSON schema conversion failed:
259
+ Error resolving ref #/$defs/GuidelineMetricInput: $defs not in {...}"}
260
+ ```
261
+
262
+ Because the offending tool rides along in every tool list, *every* message in the
263
+ session fails, which looks like a broken endpoint, proxy, or model discovery rather
264
+ than a bad upstream schema.
265
+
266
+ A second llama.cpp b10612 bug was verified independently: `maxLength: 2000` below
267
+ an array's `items` schema produces `Failed to initialize samplers: failed to parse
268
+ grammar`, while 1999, 2001, and even 65536 all compile. This affected the
269
+ `okto_pulse_move_card` tool even before any `$ref` repair.
270
+
271
+ For self-hosted endpoints (private/loopback URL, or a detected local engine) the
272
+ extension normalises outgoing tool schemas in `before_provider_request`:
273
+
274
+ - `$defs` / `definitions` found at any depth are hoisted to a root registry, with
275
+ collisions de-duplicated and local refs rewritten to match;
276
+ - every `$ref` is inlined iteratively, so refs-to-refs collapse;
277
+ - unresolvable or recursive `$ref`s become permissive nodes instead of a hard 400;
278
+ - `$ref` / `$defs` never reach the wire, and annotation siblings (`description`,
279
+ `title`) are preserved;
280
+ - the exact nested-array `maxLength: 2000` failure is sent as 2001. This is the
281
+ least-permissive working neighbour; the MCP server still validates its real 2000 limit.
282
+
283
+ Cloud APIs and clean payloads are left byte-identical (the payload object's identity is
284
+ returned, no cloning). Repairing a 521-tool catalogue costs ~1.5 ms. Opt out per
285
+ provider with `"repairToolSchemas": false` in `~/.pi/agent/model-discovery.json`, or
286
+ globally with `PI_MODEL_DISCOVERY_NO_SCHEMA_REPAIR=1`. Each distinct repair is logged
287
+ once as `[model-discovery] <provider>: repaired N local tool schema(s): …`.
288
+
289
+ Live verification against llama-swap v251 → llama.cpp b10612: the raw 521-tool MCP
290
+ catalogue returned HTTP 400; all 16 affected schemas were repaired in flight; the same
291
+ request then returned HTTP 200 with no residual `$ref`/`$defs` on the wire.
292
+
293
+ Verification:
294
+
295
+ ```bash
296
+ npm test # includes schema-repair.test.ts
297
+ node --experimental-strip-types scripts/live-schema-repair-check.ts http://HOST
298
+ node --experimental-strip-types scripts/bisect-grammar.ts http://HOST MODEL FILTER
299
+ ```
300
+
210
301
  ## Offline resilience
211
302
 
212
303
  Every successful live scan atomically persists the raw model catalogue as the source's last known-good cache. Saved sources are scanned independently and concurrently at startup. If one source is offline, times out, rejects its credentials, or returns a malformed response:
@@ -223,24 +314,32 @@ Legacy implicit routing created by early v0.6 development builds is migrated onc
223
314
 
224
315
  ## Storage
225
316
 
226
- Discovered providers, cached catalogues, model overrides, presets, and explicit routing maps are persisted in:
317
+ Discovered providers, cached catalogues, model overrides, presets, credentials, and explicit routing maps are persisted atomically with owner-only (`0600`) permissions in:
227
318
 
228
319
  ```text
229
320
  ~/.pi/agent/model-discovery.json
230
321
  ```
231
322
 
323
+ If this JSON is corrupt, startup falls back to an empty source list and preserves the unreadable file beside it as `model-discovery.json.corrupt-<timestamp>` instead of overwriting the evidence. Existing profile-routing schema migrations remain automatic.
324
+
232
325
  ## Requirements
233
326
 
234
327
  - Pi coding agent **0.84.0 or newer** (`samplingParams` support is required for model aliases)
235
- - TUI support
236
- - Network access to an OpenAI-compatible model server
328
+ - TUI mode for interactive enrollment, masked credentials, and profile editing
329
+ - Network access to an OpenAI-compatible model server for live discovery (cached status/configuration remains available offline)
237
330
 
238
331
  ## Development
239
332
 
333
+ All suites run with isolated temporary `HOME` directories:
334
+
240
335
  ```bash
336
+ npm run typecheck
241
337
  npm test
338
+ npm pack --dry-run
242
339
  ```
243
340
 
341
+ `prepack` runs strict typechecking and the complete offline suite automatically. Provider detection, enrichment, profile semantics, routing, schema repair, storage, application actions, responsive wizard components, command modes, and adapter registration all have regression coverage.
342
+
244
343
  ## License
245
344
 
246
345
  MIT
package/application.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { ModelProfile, ModelProfileRouting } from "./profiles.ts";
2
+ import {
3
+ deleteModelProfile,
4
+ deleteModelProfileRouting,
5
+ deleteProvider,
6
+ getModelProfileRouting,
7
+ getModelProfiles,
8
+ loadProviders,
9
+ renameProvider,
10
+ saveModelProfile,
11
+ saveModelProfileRouting,
12
+ upsertProvider,
13
+ type DiscoveredProvider,
14
+ } from "./storage.ts";
15
+
16
+ export interface DiscoveryRepository {
17
+ list(): DiscoveredProvider[];
18
+ save(provider: DiscoveredProvider): void;
19
+ remove(name: string): void;
20
+ rename(oldName: string, newName: string): boolean;
21
+ }
22
+
23
+ export interface RenameSourceResult {
24
+ ok: boolean;
25
+ oldName: string;
26
+ newName: string;
27
+ reason?: "missing" | "duplicate" | "invalid";
28
+ }
29
+
30
+ export interface DiscoveryApplication {
31
+ listSources(): DiscoveredProvider[];
32
+ findSource(name: string): DiscoveredProvider | undefined;
33
+ saveSource(provider: DiscoveredProvider): void;
34
+ removeSource(name: string): boolean;
35
+ renameSource(provider: DiscoveredProvider, newName: string): RenameSourceResult;
36
+ setCredential(provider: DiscoveredProvider, apiKey: string | undefined): void;
37
+ profiles(provider: DiscoveredProvider, modelId: string): ModelProfile[];
38
+ profileRouting(provider: DiscoveredProvider, modelId: string): ModelProfileRouting | undefined;
39
+ saveProfile(provider: DiscoveredProvider, modelId: string, profile: ModelProfile, previousSlug?: string): void;
40
+ removeProfile(provider: DiscoveredProvider, modelId: string, slug: string): void;
41
+ saveRouting(provider: DiscoveredProvider, modelId: string, routing: ModelProfileRouting): void;
42
+ removeRouting(provider: DiscoveredProvider, modelId: string): void;
43
+ }
44
+
45
+ export const fileDiscoveryRepository: DiscoveryRepository = {
46
+ list: loadProviders,
47
+ save: upsertProvider,
48
+ remove: deleteProvider,
49
+ rename: renameProvider,
50
+ };
51
+
52
+ export function createDiscoveryApplication(
53
+ repository: DiscoveryRepository = fileDiscoveryRepository,
54
+ ): DiscoveryApplication {
55
+ return {
56
+ listSources: () => repository.list(),
57
+ findSource: (name) => repository.list().find((provider) => provider.name === name),
58
+ saveSource: (provider) => repository.save(provider),
59
+ removeSource: (name) => {
60
+ if (!repository.list().some((provider) => provider.name === name)) return false;
61
+ repository.remove(name);
62
+ return true;
63
+ },
64
+ renameSource: (provider, rawName) => {
65
+ const oldName = provider.name;
66
+ const newName = rawName.trim();
67
+ if (!newName) return { ok: false, oldName, newName, reason: "invalid" };
68
+ const providers = repository.list();
69
+ if (!providers.some((candidate) => candidate.name === oldName)) {
70
+ return { ok: false, oldName, newName, reason: "missing" };
71
+ }
72
+ if (providers.some((candidate) => candidate.name === newName && candidate.name !== oldName)) {
73
+ return { ok: false, oldName, newName, reason: "duplicate" };
74
+ }
75
+ if (newName !== oldName && !repository.rename(oldName, newName)) {
76
+ return { ok: false, oldName, newName, reason: "duplicate" };
77
+ }
78
+ provider.name = newName;
79
+ return { ok: true, oldName, newName };
80
+ },
81
+ setCredential: (provider, apiKey) => {
82
+ provider.apiKey = apiKey;
83
+ repository.save(provider);
84
+ },
85
+ profiles: (provider, modelId) => getModelProfiles(provider, modelId),
86
+ profileRouting: (provider, modelId) => getModelProfileRouting(provider, modelId),
87
+ saveProfile: (provider, modelId, profile, previousSlug) => {
88
+ saveModelProfile(provider, modelId, profile, previousSlug);
89
+ repository.save(provider);
90
+ },
91
+ removeProfile: (provider, modelId, slug) => {
92
+ deleteModelProfile(provider, modelId, slug);
93
+ repository.save(provider);
94
+ },
95
+ saveRouting: (provider, modelId, routing) => {
96
+ saveModelProfileRouting(provider, modelId, routing);
97
+ repository.save(provider);
98
+ },
99
+ removeRouting: (provider, modelId) => {
100
+ deleteModelProfileRouting(provider, modelId);
101
+ repository.save(provider);
102
+ },
103
+ };
104
+ }
package/commands.ts ADDED
@@ -0,0 +1,70 @@
1
+ export type DiscoveryIntent =
2
+ | { kind: "open" }
3
+ | { kind: "status" }
4
+ | { kind: "doctor" }
5
+ | { kind: "paths" }
6
+ | { kind: "help" }
7
+ | { kind: "add"; url?: string; providerName?: string }
8
+ | { kind: "remove"; name: string; confirmed: boolean }
9
+ | { kind: "invalid"; message: string };
10
+
11
+ export const DISCOVER_USAGE = [
12
+ "/discover open the source wizard (status outside TUI)",
13
+ "/discover <url> add a source (existing shorthand)",
14
+ "/discover status show source and catalogue health",
15
+ "/discover doctor show actionable diagnostics",
16
+ "/discover paths show the configuration path",
17
+ "/discover source list list configured sources",
18
+ "/discover source add <url> add an unauthenticated source or open its TUI wizard",
19
+ "/discover source remove <name> remove with TUI confirmation",
20
+ "/discover source remove <name> --yes remove non-interactively",
21
+ "/discover help show this help",
22
+ ].join("\n");
23
+
24
+ const URL_SHORTHAND = /^(?:https?:\/\/|localhost(?::|\/|$)|\[[0-9a-f:]+\]:\d+|(?:\d{1,3}\.){3}\d{1,3}(?::|\/|$)|(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d+)?(?:\/|$)|[^\s/:]+:\d+)/i;
25
+
26
+ export function parseDiscoverArgs(args?: string): DiscoveryIntent {
27
+ const raw = (args ?? "").trim();
28
+ if (!raw) return { kind: "open" };
29
+ if (raw === "status" || raw === "source list") return { kind: "status" };
30
+ if (raw === "doctor") return { kind: "doctor" };
31
+ if (raw === "paths") return { kind: "paths" };
32
+ if (raw === "help") return { kind: "help" };
33
+ if (raw === "source add") return { kind: "add" };
34
+ if (raw.startsWith("source add ")) {
35
+ const tokens = raw.slice("source add ".length).trim().split(/\s+/);
36
+ const url = tokens.shift();
37
+ if (!url) return { kind: "invalid", message: "Missing source URL." };
38
+ if (!tokens.length) return { kind: "add", url };
39
+ if (tokens[0] === "--name" && tokens[1] && tokens.length === 2) {
40
+ return { kind: "add", url, providerName: tokens[1] };
41
+ }
42
+ return { kind: "invalid", message: `Invalid source add arguments: ${tokens.join(" ")}` };
43
+ }
44
+ if (raw === "source remove") return { kind: "invalid", message: "Missing source name." };
45
+ if (raw.startsWith("source remove ")) {
46
+ let specification = raw.slice("source remove ".length).trim();
47
+ const confirmed = specification.endsWith(" --yes");
48
+ if (confirmed) specification = specification.slice(0, -" --yes".length).trim();
49
+ if (!specification) return { kind: "invalid", message: "Missing source name." };
50
+ return { kind: "remove", name: specification, confirmed };
51
+ }
52
+ if (URL_SHORTHAND.test(raw)) return { kind: "add", url: raw };
53
+ return { kind: "invalid", message: `Unknown /discover input: ${raw}` };
54
+ }
55
+
56
+ export function completeDiscoverArgs(prefix: string, sourceNames: readonly string[]): Array<{ value: string; label: string }> | null {
57
+ const values = [
58
+ "status",
59
+ "doctor",
60
+ "paths",
61
+ "help",
62
+ "source list",
63
+ "source add ",
64
+ "source remove ",
65
+ ...sourceNames.map((name) => `source remove ${name}`),
66
+ ...sourceNames.map((name) => `source remove ${name} --yes`),
67
+ ];
68
+ const matches = values.filter((value) => value.startsWith(prefix));
69
+ return matches.length ? matches.map((value) => ({ value, label: value })) : null;
70
+ }