pi-omlx-picker 0.2.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/.biomeignore ADDED
@@ -0,0 +1 @@
1
+ references/
@@ -0,0 +1,11 @@
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "npm" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "weekly"
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PeachlifeAB
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,41 @@
1
+ # Pi OMLX Picker
2
+
3
+ Pi extension that discovers models from a local [OMLX](https://github.com/Open-Model-Lookup-Exchange) server and registers them as a native Pi provider. Switch models with Pi's built-in `/model` command.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:pi-omlx-picker
9
+ ```
10
+
11
+ ## Configure
12
+
13
+ Set these env vars (or copy `.env-example` to `.env`):
14
+
15
+ ```sh
16
+ export OMLX_BASE_URL="http://127.0.0.1:8008/v1"
17
+ export OMLX_API_KEY="omlx-..."
18
+ ```
19
+
20
+ If either is missing, the provider is skipped and Pi logs a message on startup.
21
+
22
+ Optionally override the model metadata path (default: `~/.omlx/model_settings.json`):
23
+
24
+ ```sh
25
+ export OMLX_MODEL_SETTINGS_PATH="/path/to/model_settings.json"
26
+ ```
27
+
28
+ ## How it works
29
+
30
+ On startup, the extension fetches available models from OMLX, merges local `model_settings.json` metadata, and registers an `omlx` provider in Pi. Thinking controls are applied per-request based on each model's `thinkingDefault`.
31
+
32
+ ## Debugging
33
+
34
+ ```sh
35
+ mise run debug:omlx # OMLX config, model path, template, cache
36
+ mise run debug:pi # Pi install, config, session, log, cache
37
+ mise run verify # Biome + typecheck + unit tests
38
+ mise run smoke:omlx # Live smoke test against a running OMLX server
39
+ ```
40
+
41
+ See [docs/DEBUG.md](docs/DEBUG.md) for triage order.
package/index.ts ADDED
@@ -0,0 +1,94 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { fetchModels, resolveLocalModelSettingsPath, type OmlxModel } from "./src/catalog.ts";
3
+ import { loadConfig, MissingEnvError, type OmlxConfig } from "./src/config.ts";
4
+ import { toProviderConfig } from "./src/provider.ts";
5
+ import { applyOmlxThinkingControls } from "./src/thinking.ts";
6
+
7
+ const PROVIDER = "omlx";
8
+ const EXTENSION_SINGLETON_KEY = Symbol.for("pi-omlx-picker/loaded");
9
+
10
+ interface State {
11
+ config: OmlxConfig | undefined;
12
+ catalog: OmlxModel[];
13
+ registered: boolean;
14
+ lastError: string | undefined;
15
+ lastRefreshAt: string | undefined;
16
+ modelSettingsPath: string | undefined;
17
+ }
18
+
19
+ export default async function (pi: ExtensionAPI): Promise<void> {
20
+ const globalState = globalThis as Record<PropertyKey, unknown>;
21
+ if (globalState[EXTENSION_SINGLETON_KEY]) return;
22
+ globalState[EXTENSION_SINGLETON_KEY] = true;
23
+
24
+ const state: State = {
25
+ config: undefined,
26
+ catalog: [],
27
+ registered: false,
28
+ lastError: undefined,
29
+ lastRefreshAt: undefined,
30
+ modelSettingsPath: undefined,
31
+ };
32
+
33
+ await refreshProvider(pi, state);
34
+
35
+ pi.on("before_provider_request", (event, ctx) => {
36
+ if (ctx.model?.provider !== PROVIDER) return;
37
+ const activeModel = findCatalogModel(state, ctx.model.id);
38
+ return applyOmlxThinkingControls(event.payload, pi.getThinkingLevel(), activeModel?.thinkingDefault);
39
+ });
40
+ }
41
+
42
+ function clearRegisteredProvider(pi: ExtensionAPI, state: State): void {
43
+ if (state.registered) {
44
+ pi.unregisterProvider(PROVIDER);
45
+ }
46
+ state.catalog = [];
47
+ state.registered = false;
48
+ state.config = undefined;
49
+ state.modelSettingsPath = undefined;
50
+ }
51
+
52
+ async function refreshProvider(pi: ExtensionAPI, state: State): Promise<void> {
53
+ let config: OmlxConfig;
54
+ try {
55
+ config = loadConfig();
56
+ } catch (err) {
57
+ state.lastError =
58
+ err instanceof MissingEnvError
59
+ ? `${err.varName} is not set`
60
+ : err instanceof Error
61
+ ? err.message
62
+ : String(err);
63
+ clearRegisteredProvider(pi, state);
64
+ return;
65
+ }
66
+
67
+ const modelSettingsPath = resolveLocalModelSettingsPath(process.env.OMLX_MODEL_SETTINGS_PATH);
68
+
69
+ let models: OmlxModel[];
70
+ try {
71
+ models = await fetchModels(config.apiRoot, process.env.OMLX_API_KEY!, { modelSettingsPath });
72
+ } catch (err) {
73
+ state.lastError = err instanceof Error ? err.message : String(err);
74
+ return;
75
+ }
76
+
77
+ if (models.length === 0) {
78
+ state.lastError = "OMLX returned 0 models";
79
+ clearRegisteredProvider(pi, state);
80
+ return;
81
+ }
82
+
83
+ pi.registerProvider(PROVIDER, toProviderConfig(config.apiRoot, config.apiKeyEnvVar, models));
84
+ state.config = config;
85
+ state.catalog = models;
86
+ state.registered = true;
87
+ state.lastError = undefined;
88
+ state.lastRefreshAt = new Date().toISOString();
89
+ state.modelSettingsPath = modelSettingsPath;
90
+ }
91
+
92
+ function findCatalogModel(state: State, id: string | undefined): OmlxModel | undefined {
93
+ return id ? state.catalog.find((model) => model.id === id) : undefined;
94
+ }
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "pi-omlx-picker",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Pi extension that maps OMLX model settings into native Pi model metadata.",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "test": "node --import tsx --test 'test/*.test.ts'",
9
+ "debug:omlx": "tsx scripts/debug-omlx.ts",
10
+ "debug:pi": "tsx scripts/debug-pi.ts",
11
+ "smoke:omlx": "tsx scripts/smoke-live-omlx.ts",
12
+ "typecheck": "tsc --noEmit"
13
+ },
14
+ "pi": {
15
+ "extensions": [
16
+ "./index.ts"
17
+ ]
18
+ },
19
+ "devDependencies": {
20
+ "@mariozechner/pi-ai": "^0.73.1",
21
+ "@mariozechner/pi-coding-agent": "*",
22
+ "tsx": "^4.7.0",
23
+ "typescript": "^6.0.3"
24
+ }
25
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,548 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ export interface OmlxModel {
6
+ id: string;
7
+ displayName?: string;
8
+ description?: string;
9
+ modelAlias?: string;
10
+ contextWindow?: number;
11
+ maxTokens?: number;
12
+ thinkingDefault?: boolean | null;
13
+ taskBudgetTokens?: number;
14
+ maxToolResultTokens?: number;
15
+ thinkingBudgetTokens?: number;
16
+ thinkingBudgetEnabled?: boolean;
17
+ preserveThinking?: boolean;
18
+ chatTemplateKwargs?: Record<string, unknown>;
19
+ forcedCtKwargs?: string[];
20
+ isDefault?: boolean;
21
+ isPinned?: boolean;
22
+ trustRemoteCode?: boolean;
23
+ ttlSeconds?: number;
24
+ indexCacheFreq?: number;
25
+ reasoningParser?: string;
26
+ activeProfileName?: string;
27
+ modelType?: string | null;
28
+ settingsSummary?: Record<string, unknown>;
29
+ }
30
+
31
+ export interface CatalogDebugEvent {
32
+ kind: string;
33
+ details: Record<string, unknown>;
34
+ }
35
+
36
+ interface OpenAIModelsResponse {
37
+ object: string;
38
+ data: Array<{ id: string; object?: string }>;
39
+ }
40
+
41
+ interface OmlxModelsStatusResponse {
42
+ models: Array<{
43
+ id: string;
44
+ display_name?: string | null;
45
+ description?: string | null;
46
+ model_alias?: string | null;
47
+ max_context_window?: number;
48
+ max_tokens?: number;
49
+ thinking_default?: boolean | null;
50
+ enable_thinking?: boolean | null;
51
+ max_tool_result_tokens?: number;
52
+ thinking_budget_tokens?: number;
53
+ thinking_budget_enabled?: boolean;
54
+ preserve_thinking?: boolean | null;
55
+ chat_template_kwargs?: Record<string, unknown> | null;
56
+ forced_ct_kwargs?: string[];
57
+ is_default?: boolean;
58
+ is_pinned?: boolean;
59
+ pinned?: boolean;
60
+ trust_remote_code?: boolean;
61
+ ttl_seconds?: number;
62
+ index_cache_freq?: number;
63
+ reasoning_parser?: string | null;
64
+ active_profile_name?: string | null;
65
+ model_type?: string | null;
66
+ engine_type?: string | null;
67
+ model_type_override?: string | null;
68
+ }>;
69
+ }
70
+
71
+ export function parseModelsResponse(json: unknown): OmlxModel[] {
72
+ const r = json as OpenAIModelsResponse | undefined;
73
+ if (!r || !Array.isArray(r.data)) {
74
+ throw new Error("OMLX /models response is missing `data` array");
75
+ }
76
+ const seen = new Set<string>();
77
+ const out: OmlxModel[] = [];
78
+ for (const entry of r.data) {
79
+ if (!entry || typeof entry.id !== "string" || !entry.id) continue;
80
+ if (seen.has(entry.id)) continue;
81
+ seen.add(entry.id);
82
+ out.push({ id: entry.id });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ export function parseModelsStatusResponse(json: unknown): OmlxModel[] {
88
+ const r = json as OmlxModelsStatusResponse | undefined;
89
+ if (!r || !Array.isArray(r.models)) {
90
+ throw new Error("OMLX /models/status response is missing `models` array");
91
+ }
92
+ const seen = new Set<string>();
93
+ const out: OmlxModel[] = [];
94
+ for (const entry of r.models) {
95
+ if (!entry || typeof entry.id !== "string" || !entry.id) continue;
96
+ if (seen.has(entry.id)) continue;
97
+ seen.add(entry.id);
98
+ const m: OmlxModel = { id: entry.id };
99
+ if (typeof entry.display_name === "string" && entry.display_name.trim())
100
+ m.displayName = entry.display_name;
101
+ if (typeof entry.description === "string" && entry.description.trim())
102
+ m.description = entry.description;
103
+ if (typeof entry.model_alias === "string" && entry.model_alias.trim())
104
+ m.modelAlias = entry.model_alias;
105
+ if (typeof entry.max_context_window === "number")
106
+ m.contextWindow = entry.max_context_window;
107
+ if (typeof entry.max_tokens === "number") m.maxTokens = entry.max_tokens;
108
+ const chatTemplateKwargs = asRecord(entry.chat_template_kwargs);
109
+ if (chatTemplateKwargs) m.chatTemplateKwargs = chatTemplateKwargs;
110
+ if (typeof entry.enable_thinking === "boolean") {
111
+ m.thinkingDefault = entry.enable_thinking;
112
+ } else if (
113
+ chatTemplateKwargs &&
114
+ typeof chatTemplateKwargs.enable_thinking === "boolean"
115
+ ) {
116
+ m.thinkingDefault = chatTemplateKwargs.enable_thinking;
117
+ } else if ("thinking_default" in entry) {
118
+ m.thinkingDefault = entry.thinking_default ?? null;
119
+ }
120
+ if (typeof entry.max_tool_result_tokens === "number")
121
+ m.maxToolResultTokens = entry.max_tool_result_tokens;
122
+ if (typeof entry.thinking_budget_tokens === "number")
123
+ m.thinkingBudgetTokens = entry.thinking_budget_tokens;
124
+ if (typeof entry.thinking_budget_enabled === "boolean")
125
+ m.thinkingBudgetEnabled = entry.thinking_budget_enabled;
126
+ if (typeof entry.preserve_thinking === "boolean")
127
+ m.preserveThinking = entry.preserve_thinking;
128
+ else if (typeof chatTemplateKwargs?.preserve_thinking === "boolean")
129
+ m.preserveThinking = chatTemplateKwargs.preserve_thinking;
130
+ if (Array.isArray(entry.forced_ct_kwargs)) {
131
+ m.forcedCtKwargs = entry.forced_ct_kwargs.filter(
132
+ (item): item is string => typeof item === "string",
133
+ );
134
+ }
135
+ if (typeof entry.is_default === "boolean") m.isDefault = entry.is_default;
136
+ if (typeof entry.is_pinned === "boolean") m.isPinned = entry.is_pinned;
137
+ else if (typeof entry.pinned === "boolean") m.isPinned = entry.pinned;
138
+ if (typeof entry.trust_remote_code === "boolean")
139
+ m.trustRemoteCode = entry.trust_remote_code;
140
+ if (typeof entry.ttl_seconds === "number") m.ttlSeconds = entry.ttl_seconds;
141
+ if (typeof entry.index_cache_freq === "number")
142
+ m.indexCacheFreq = entry.index_cache_freq;
143
+ if (
144
+ typeof entry.reasoning_parser === "string" &&
145
+ entry.reasoning_parser.trim()
146
+ )
147
+ m.reasoningParser = entry.reasoning_parser;
148
+ if (
149
+ typeof entry.active_profile_name === "string" &&
150
+ entry.active_profile_name.trim()
151
+ )
152
+ m.activeProfileName = entry.active_profile_name;
153
+ const type =
154
+ entry.model_type_override ?? entry.model_type ?? entry.engine_type;
155
+ if (typeof type === "string") m.modelType = type.toLowerCase();
156
+ out.push(m);
157
+ }
158
+ return out;
159
+ }
160
+
161
+ export const DEFAULT_FETCH_TIMEOUT_MS = 15_000;
162
+
163
+ export async function fetchModels(
164
+ apiRoot: string,
165
+ apiKey: string,
166
+ opts: {
167
+ signal?: AbortSignal;
168
+ timeoutMs?: number;
169
+ modelSettingsPath?: string;
170
+ onDebug?: (event: CatalogDebugEvent) => void;
171
+ } = {},
172
+ ): Promise<OmlxModel[]> {
173
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
174
+ let models: OmlxModel[];
175
+
176
+ try {
177
+ const json = await getJson(
178
+ `${apiRoot}/models/status`,
179
+ apiKey,
180
+ opts.signal,
181
+ timeoutMs,
182
+ );
183
+ models = parseModelsStatusResponse(json);
184
+ opts.onDebug?.({
185
+ kind: "catalog_status_loaded",
186
+ details: {
187
+ apiRoot,
188
+ count: models.length,
189
+ documenter: models.find((m) => m.id === "qwen3.6-8b-documenter"),
190
+ },
191
+ });
192
+ return applyLocalModelSettings(
193
+ models,
194
+ apiRoot,
195
+ opts.modelSettingsPath,
196
+ opts.onDebug,
197
+ );
198
+ } catch (err) {
199
+ if (err instanceof Error && err.name === "AbortError") throw err;
200
+ opts.onDebug?.({
201
+ kind: "catalog_status_failed",
202
+ details: {
203
+ apiRoot,
204
+ error: err instanceof Error ? err.message : String(err),
205
+ },
206
+ });
207
+ // Fall through to /models for servers without /models/status.
208
+ }
209
+
210
+ const json = await getJson(
211
+ `${apiRoot}/models`,
212
+ apiKey,
213
+ opts.signal,
214
+ timeoutMs,
215
+ );
216
+ models = parseModelsResponse(json);
217
+ opts.onDebug?.({
218
+ kind: "catalog_models_loaded",
219
+ details: { apiRoot, count: models.length },
220
+ });
221
+ return applyLocalModelSettings(
222
+ models,
223
+ apiRoot,
224
+ opts.modelSettingsPath,
225
+ opts.onDebug,
226
+ );
227
+ }
228
+
229
+ async function getJson(
230
+ url: string,
231
+ apiKey: string,
232
+ parent: AbortSignal | undefined,
233
+ timeoutMs: number,
234
+ ): Promise<unknown> {
235
+ const signal = withTimeout(parent, timeoutMs);
236
+ const res = await fetch(url, {
237
+ headers: { Authorization: `Bearer ${apiKey}` },
238
+ signal,
239
+ }).catch((err) => {
240
+ if (err instanceof Error && err.name === "AbortError") {
241
+ throw new Error(`GET ${url} timed out after ${timeoutMs}ms`);
242
+ }
243
+ throw err;
244
+ });
245
+ if (!res.ok) {
246
+ const body = await res.text().catch(() => "");
247
+ throw new Error(
248
+ `GET ${url} -> ${res.status} ${res.statusText}${body ? `: ${body}` : ""}`,
249
+ );
250
+ }
251
+ return res.json();
252
+ }
253
+
254
+ function withTimeout(
255
+ parent: AbortSignal | undefined,
256
+ timeoutMs: number,
257
+ ): AbortSignal {
258
+ const ctl = new AbortController();
259
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
260
+ if (parent) {
261
+ if (parent.aborted) ctl.abort();
262
+ else parent.addEventListener("abort", () => ctl.abort(), { once: true });
263
+ }
264
+ ctl.signal.addEventListener("abort", () => clearTimeout(timer), {
265
+ once: true,
266
+ });
267
+ return ctl.signal;
268
+ }
269
+
270
+ export function applyLocalModelSettings(
271
+ models: OmlxModel[],
272
+ apiRoot: string,
273
+ modelSettingsPath = process.env.OMLX_MODEL_SETTINGS_PATH,
274
+ onDebug?: (event: CatalogDebugEvent) => void,
275
+ ): OmlxModel[] {
276
+ const path = resolveLocalModelSettingsPath(modelSettingsPath);
277
+ onDebug?.({
278
+ kind: "catalog_local_settings_considered",
279
+ details: {
280
+ apiRoot,
281
+ path,
282
+ explicitPath: !!modelSettingsPath,
283
+ exists: path ? existsSync(path) : false,
284
+ },
285
+ });
286
+ if (!path || !existsSync(path)) return models;
287
+
288
+ let settings: Record<string, unknown>;
289
+ try {
290
+ settings = JSON.parse(readFileSync(path, "utf8")) as Record<
291
+ string,
292
+ unknown
293
+ >;
294
+ } catch {
295
+ onDebug?.({
296
+ kind: "catalog_local_settings_read_failed",
297
+ details: { path },
298
+ });
299
+ return models;
300
+ }
301
+
302
+ const byModel = settings.models;
303
+ if (!byModel || typeof byModel !== "object" || Array.isArray(byModel)) {
304
+ onDebug?.({
305
+ kind: "catalog_local_settings_invalid",
306
+ details: { path, reason: "models object missing" },
307
+ });
308
+ return models;
309
+ }
310
+
311
+ return models.map((model) => {
312
+ const entry = (byModel as Record<string, unknown>)[model.id];
313
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
314
+ if (model.id === "qwen3.6-8b-documenter") {
315
+ onDebug?.({
316
+ kind: "catalog_local_model_settings_missing",
317
+ details: { path, modelId: model.id },
318
+ });
319
+ }
320
+ return model;
321
+ }
322
+ const next = applyModelSettingsEntry(
323
+ model,
324
+ entry as Record<string, unknown>,
325
+ );
326
+ if (
327
+ next.thinkingDefault !== model.thinkingDefault ||
328
+ next.contextWindow !== model.contextWindow ||
329
+ next.maxTokens !== model.maxTokens ||
330
+ next.displayName !== model.displayName ||
331
+ next.description !== model.description ||
332
+ next.modelAlias !== model.modelAlias ||
333
+ next.taskBudgetTokens !== model.taskBudgetTokens ||
334
+ next.maxToolResultTokens !== model.maxToolResultTokens ||
335
+ next.thinkingBudgetTokens !== model.thinkingBudgetTokens ||
336
+ next.thinkingBudgetEnabled !== model.thinkingBudgetEnabled ||
337
+ next.preserveThinking !== model.preserveThinking ||
338
+ JSON.stringify(next.chatTemplateKwargs) !==
339
+ JSON.stringify(model.chatTemplateKwargs) ||
340
+ JSON.stringify(next.forcedCtKwargs) !==
341
+ JSON.stringify(model.forcedCtKwargs) ||
342
+ next.isDefault !== model.isDefault ||
343
+ next.isPinned !== model.isPinned ||
344
+ next.trustRemoteCode !== model.trustRemoteCode ||
345
+ next.ttlSeconds !== model.ttlSeconds ||
346
+ next.indexCacheFreq !== model.indexCacheFreq ||
347
+ next.reasoningParser !== model.reasoningParser ||
348
+ next.activeProfileName !== model.activeProfileName ||
349
+ next.modelType !== model.modelType ||
350
+ JSON.stringify(next.settingsSummary) !==
351
+ JSON.stringify(model.settingsSummary)
352
+ ) {
353
+ onDebug?.({
354
+ kind: "catalog_local_model_settings_applied",
355
+ details: {
356
+ path,
357
+ modelId: model.id,
358
+ before: model,
359
+ after: next,
360
+ entrySummary: summarizeModelSettingsEntry(
361
+ entry as Record<string, unknown>,
362
+ ),
363
+ },
364
+ });
365
+ }
366
+ return next;
367
+ });
368
+ }
369
+
370
+ function applyModelSettingsEntry(
371
+ model: OmlxModel,
372
+ entry: Record<string, unknown>,
373
+ ): OmlxModel {
374
+ const next: OmlxModel = { ...model };
375
+ const chatTemplateKwargs = asRecord(entry.chat_template_kwargs);
376
+
377
+ if (typeof entry.display_name === "string" && entry.display_name.trim())
378
+ next.displayName = entry.display_name;
379
+ if (typeof entry.description === "string" && entry.description.trim())
380
+ next.description = entry.description;
381
+ if (typeof entry.model_alias === "string" && entry.model_alias.trim())
382
+ next.modelAlias = entry.model_alias;
383
+ if (typeof entry.enable_thinking === "boolean") {
384
+ next.thinkingDefault = entry.enable_thinking;
385
+ }
386
+ if (chatTemplateKwargs) {
387
+ next.chatTemplateKwargs = chatTemplateKwargs;
388
+ const enableThinking = chatTemplateKwargs.enable_thinking;
389
+ if (
390
+ typeof enableThinking === "boolean" &&
391
+ typeof entry.enable_thinking !== "boolean"
392
+ ) {
393
+ next.thinkingDefault = enableThinking;
394
+ }
395
+ }
396
+ if (typeof entry.max_context_window === "number")
397
+ next.contextWindow = entry.max_context_window;
398
+ if (typeof entry.max_tokens === "number") next.maxTokens = entry.max_tokens;
399
+ if (typeof entry.task_budget_tokens === "number")
400
+ next.taskBudgetTokens = entry.task_budget_tokens;
401
+ if (typeof entry.max_tool_result_tokens === "number")
402
+ next.maxToolResultTokens = entry.max_tool_result_tokens;
403
+ if (typeof entry.thinking_budget_tokens === "number")
404
+ next.thinkingBudgetTokens = entry.thinking_budget_tokens;
405
+ if (typeof entry.thinking_budget_enabled === "boolean")
406
+ next.thinkingBudgetEnabled = entry.thinking_budget_enabled;
407
+ // preserve_thinking: top branch handles OmlxModelsStatusResponse (server path).
408
+ // Local model_settings.json always places this inside chat_template_kwargs,
409
+ // so the else-if branch is the active path for local files.
410
+ if (typeof entry.preserve_thinking === "boolean") {
411
+ next.preserveThinking = entry.preserve_thinking;
412
+ } else if (typeof chatTemplateKwargs?.preserve_thinking === "boolean") {
413
+ next.preserveThinking = chatTemplateKwargs.preserve_thinking;
414
+ }
415
+ if (Array.isArray(entry.forced_ct_kwargs)) {
416
+ next.forcedCtKwargs = entry.forced_ct_kwargs.filter(
417
+ (item): item is string => typeof item === "string",
418
+ );
419
+ }
420
+ if (typeof entry.is_default === "boolean") next.isDefault = entry.is_default;
421
+ if (typeof entry.is_pinned === "boolean") next.isPinned = entry.is_pinned;
422
+ if (typeof entry.trust_remote_code === "boolean")
423
+ next.trustRemoteCode = entry.trust_remote_code;
424
+ if (typeof entry.ttl_seconds === "number")
425
+ next.ttlSeconds = entry.ttl_seconds;
426
+ if (typeof entry.index_cache_freq === "number")
427
+ next.indexCacheFreq = entry.index_cache_freq;
428
+ if (
429
+ typeof entry.reasoning_parser === "string" &&
430
+ entry.reasoning_parser.trim()
431
+ )
432
+ next.reasoningParser = entry.reasoning_parser;
433
+ if (
434
+ typeof entry.active_profile_name === "string" &&
435
+ entry.active_profile_name.trim()
436
+ )
437
+ next.activeProfileName = entry.active_profile_name;
438
+ if (typeof entry.model_type_override === "string")
439
+ next.modelType = entry.model_type_override.toLowerCase();
440
+ next.settingsSummary = summarizeModelSettingsEntry(entry);
441
+ return next;
442
+ }
443
+
444
+ export function resolveLocalModelSettingsPath(
445
+ modelSettingsPath: string | undefined,
446
+ ): string | undefined {
447
+ if (modelSettingsPath) return modelSettingsPath;
448
+ return join(homedir(), ".omlx", "model_settings.json");
449
+ }
450
+
451
+ function summarizeModelSettingsEntry(
452
+ entry: Record<string, unknown>,
453
+ ): Record<string, unknown> {
454
+ const chatTemplateKwargs = asRecord(entry.chat_template_kwargs);
455
+ return (
456
+ compactObject({
457
+ identity: compactObject({
458
+ displayName: entry.display_name,
459
+ description: entry.description,
460
+ modelAlias: entry.model_alias,
461
+ modelTypeOverride: entry.model_type_override,
462
+ }),
463
+ thinking: compactObject({
464
+ enabled: entry.enable_thinking ?? chatTemplateKwargs?.enable_thinking,
465
+ budgetEnabled: entry.thinking_budget_enabled,
466
+ budgetTokens: entry.thinking_budget_tokens,
467
+ preserve:
468
+ entry.preserve_thinking ?? chatTemplateKwargs?.preserve_thinking,
469
+ reasoningEffort: chatTemplateKwargs?.reasoning_effort,
470
+ parser: entry.reasoning_parser,
471
+ forcedCtKwargs: entry.forced_ct_kwargs,
472
+ }),
473
+ chatTemplate: compactObject({
474
+ kwargs: chatTemplateKwargs,
475
+ forcedKeys: entry.forced_ct_kwargs,
476
+ }),
477
+ limits: compactObject({
478
+ contextWindow: entry.max_context_window,
479
+ maxTokens: entry.max_tokens,
480
+ maxToolResultTokens: entry.max_tool_result_tokens,
481
+ }),
482
+ sampling: compactObject({
483
+ temperature: entry.temperature,
484
+ topP: entry.top_p,
485
+ topK: entry.top_k,
486
+ minP: entry.min_p,
487
+ repetitionPenalty: entry.repetition_penalty,
488
+ presencePenalty: entry.presence_penalty,
489
+ forceSampling: entry.force_sampling,
490
+ }),
491
+ dflash: compactObject({
492
+ enabled: entry.dflash_enabled,
493
+ draftModel: entry.dflash_draft_model,
494
+ draftQuantBits: entry.dflash_draft_quant_bits,
495
+ }),
496
+ specprefill: compactObject({
497
+ enabled: entry.specprefill_enabled,
498
+ draftModel: entry.specprefill_draft_model,
499
+ keepPct: entry.specprefill_keep_pct,
500
+ threshold: entry.specprefill_threshold,
501
+ }),
502
+ turboquant: compactObject({
503
+ enabled: entry.turboquant_kv_enabled,
504
+ bits: entry.turboquant_kv_bits,
505
+ skipLast: entry.turboquant_skip_last,
506
+ }),
507
+ lifecycle: compactObject({
508
+ isDefault: entry.is_default,
509
+ isPinned: entry.is_pinned,
510
+ ttlSeconds: entry.ttl_seconds,
511
+ indexCacheFreq: entry.index_cache_freq,
512
+ }),
513
+ security: compactObject({
514
+ trustRemoteCode: entry.trust_remote_code,
515
+ }),
516
+ profile: compactObject({
517
+ activeProfileName: entry.active_profile_name,
518
+ }),
519
+ bridge: compactObject({
520
+ taskBudgetTokens: entry.task_budget_tokens,
521
+ }),
522
+ }) ?? {}
523
+ );
524
+ }
525
+
526
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
527
+ return value && typeof value === "object" && !Array.isArray(value)
528
+ ? (value as Record<string, unknown>)
529
+ : undefined;
530
+ }
531
+
532
+ function compactObject(
533
+ record: Record<string, unknown>,
534
+ ): Record<string, unknown> | undefined {
535
+ const entries = Object.entries(record).filter(([, value]) => {
536
+ if (value === undefined) return false;
537
+ if (
538
+ value &&
539
+ typeof value === "object" &&
540
+ !Array.isArray(value) &&
541
+ Object.keys(value).length === 0
542
+ )
543
+ return false;
544
+ return true;
545
+ });
546
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
547
+ }
548
+
package/src/config.ts ADDED
@@ -0,0 +1,27 @@
1
+ export interface OmlxConfig {
2
+ apiRoot: string;
3
+ apiKeyEnvVar: string;
4
+ }
5
+
6
+ export class MissingEnvError extends Error {
7
+ constructor(public readonly varName: string) {
8
+ super(`${varName} is not set`);
9
+ this.name = "MissingEnvError";
10
+ }
11
+ }
12
+
13
+ export function normalizeBaseUrl(raw: string): string {
14
+ const trimmed = raw.trim().replace(/\/+$/, "");
15
+ if (!trimmed) throw new Error("OMLX_BASE_URL is empty");
16
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
17
+ }
18
+
19
+ export function loadConfig(env: NodeJS.ProcessEnv = process.env): OmlxConfig {
20
+ const baseUrl = env.OMLX_BASE_URL;
21
+ if (!baseUrl) throw new MissingEnvError("OMLX_BASE_URL");
22
+ if (!env.OMLX_API_KEY) throw new MissingEnvError("OMLX_API_KEY");
23
+ return {
24
+ apiRoot: normalizeBaseUrl(baseUrl),
25
+ apiKeyEnvVar: "OMLX_API_KEY",
26
+ };
27
+ }
@@ -0,0 +1,254 @@
1
+ import {
2
+ type Api,
3
+ type AssistantMessage,
4
+ type AssistantMessageEvent,
5
+ type AssistantMessageEventStream,
6
+ type Context,
7
+ createAssistantMessageEventStream,
8
+ type Model,
9
+ type SimpleStreamOptions,
10
+ streamSimpleOpenAICompletions,
11
+ } from "@mariozechner/pi-ai";
12
+ import type {
13
+ ProviderConfig,
14
+ ProviderModelConfig,
15
+ } from "@mariozechner/pi-coding-agent";
16
+ import type { OmlxModel } from "./catalog.ts";
17
+
18
+ // Pi's documented defaults when the server doesn't report per-model values.
19
+ // Users can override these via modelOverrides in ~/.pi/config.json.
20
+ const DEFAULT_CONTEXT_WINDOW = 128000;
21
+ const DEFAULT_MAX_TOKENS = 16384;
22
+ const DEFAULT_FIRST_DELTA_TIMEOUT_MS = 120_000;
23
+ const FIRST_DELTA_MAX_ATTEMPTS = 2;
24
+ type StreamTimeoutEvent = {
25
+ model: string;
26
+ timeoutMs: number;
27
+ attempt: number;
28
+ maxAttempts: number;
29
+ final: boolean;
30
+ };
31
+
32
+ export function toProviderConfig(
33
+ apiRoot: string,
34
+ apiKeyEnvVar: string,
35
+ models: OmlxModel[],
36
+ onStreamTimeout?: (event: StreamTimeoutEvent) => void,
37
+ ): ProviderConfig {
38
+ return {
39
+ baseUrl: apiRoot,
40
+ apiKey: apiKeyEnvVar,
41
+ api: "openai-completions",
42
+ authHeader: true,
43
+ streamSimple: (model, context, options) =>
44
+ streamOmlxOpenAICompletions(
45
+ model,
46
+ context,
47
+ options,
48
+ resolveFirstDeltaTimeoutMs(),
49
+ onStreamTimeout,
50
+ ),
51
+ models: models.map(toProviderModel),
52
+ };
53
+ }
54
+
55
+ function toProviderModel(m: OmlxModel): ProviderModelConfig {
56
+ const input: ("text" | "image")[] =
57
+ m.modelType === "vlm" ? ["text", "image"] : ["text"];
58
+ const reasoning = m.thinkingDefault === true;
59
+ const compat = {
60
+ supportsDeveloperRole: false,
61
+ supportsReasoningEffort: false,
62
+ supportsLongCacheRetention: true,
63
+ maxTokensField: "max_tokens" as const,
64
+ ...(reasoning ? { thinkingFormat: "qwen-chat-template" as const } : {}),
65
+ };
66
+ return {
67
+ id: m.id,
68
+ name: m.displayName ?? m.id,
69
+ reasoning,
70
+ input,
71
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
72
+ contextWindow: m.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
73
+ maxTokens: m.maxTokens ?? DEFAULT_MAX_TOKENS,
74
+ compat,
75
+ };
76
+ }
77
+
78
+ function streamOmlxOpenAICompletions(
79
+ model: Model<Api>,
80
+ context: Context,
81
+ options: SimpleStreamOptions | undefined,
82
+ firstDeltaTimeoutMs: number,
83
+ onStreamTimeout: ((event: StreamTimeoutEvent) => void) | undefined,
84
+ ): AssistantMessageEventStream {
85
+ const stream = createAssistantMessageEventStream();
86
+ let closed = false;
87
+ let startEvent: AssistantMessageEvent | undefined;
88
+ let startPushed = false;
89
+
90
+ const pushWithStart = (event: AssistantMessageEvent) => {
91
+ if (!startPushed) {
92
+ stream.push(
93
+ startEvent ?? { type: "start", partial: eventPartial(event, model) },
94
+ );
95
+ startPushed = true;
96
+ }
97
+ stream.push(event);
98
+ };
99
+
100
+ (async () => {
101
+ try {
102
+ for (let attempt = 1; attempt <= FIRST_DELTA_MAX_ATTEMPTS; attempt++) {
103
+ const controller = new AbortController();
104
+ const signal = mergeAbortSignals(options?.signal, controller.signal);
105
+ let attemptTimedOut = false;
106
+ let firstMeaningfulEvent = false;
107
+ const timeout = setTimeout(() => {
108
+ if (closed || firstMeaningfulEvent) return;
109
+ attemptTimedOut = true;
110
+ onStreamTimeout?.({
111
+ model: model.id,
112
+ timeoutMs: firstDeltaTimeoutMs,
113
+ attempt,
114
+ maxAttempts: FIRST_DELTA_MAX_ATTEMPTS,
115
+ final: attempt >= FIRST_DELTA_MAX_ATTEMPTS,
116
+ });
117
+ controller.abort();
118
+ }, firstDeltaTimeoutMs);
119
+
120
+ const inner = streamSimpleOpenAICompletions(
121
+ model as Model<"openai-completions">,
122
+ context,
123
+ {
124
+ ...options,
125
+ signal,
126
+ },
127
+ );
128
+ for await (const event of inner) {
129
+ if (closed || attemptTimedOut) break;
130
+ if (event.type === "start") {
131
+ startEvent ??= event;
132
+ continue;
133
+ }
134
+ if (isMeaningfulBodyEvent(event)) {
135
+ firstMeaningfulEvent = true;
136
+ clearTimeout(timeout);
137
+ }
138
+ if (event.type === "done" || event.type === "error") {
139
+ closed = true;
140
+ clearTimeout(timeout);
141
+ }
142
+ pushWithStart(event);
143
+ }
144
+ clearTimeout(timeout);
145
+ if (closed) return;
146
+ if (!attemptTimedOut) {
147
+ closed = true;
148
+ stream.end();
149
+ return;
150
+ }
151
+ if (attempt < FIRST_DELTA_MAX_ATTEMPTS) continue;
152
+ closed = true;
153
+ pushWithStart({
154
+ type: "error",
155
+ reason: "error",
156
+ error: errorAssistantMessage(
157
+ model,
158
+ `OMLX stream timed out: no text, thinking, or tool delta arrived within ${firstDeltaTimeoutMs}ms after response headers on ${FIRST_DELTA_MAX_ATTEMPTS} attempts.`,
159
+ ),
160
+ });
161
+ stream.end();
162
+ return;
163
+ }
164
+ } catch (error) {
165
+ if (closed) return;
166
+ closed = true;
167
+ pushWithStart({
168
+ type: "error",
169
+ reason: options?.signal?.aborted ? "aborted" : "error",
170
+ error: errorAssistantMessage(
171
+ model,
172
+ error instanceof Error ? error.message : String(error),
173
+ options?.signal?.aborted ? "aborted" : "error",
174
+ ),
175
+ });
176
+ stream.end();
177
+ }
178
+ })();
179
+
180
+ return stream;
181
+ }
182
+
183
+ function isMeaningfulBodyEvent(event: AssistantMessageEvent): boolean {
184
+ return [
185
+ "text_start",
186
+ "text_delta",
187
+ "thinking_start",
188
+ "thinking_delta",
189
+ "toolcall_start",
190
+ "toolcall_delta",
191
+ "done",
192
+ "error",
193
+ ].includes(event.type);
194
+ }
195
+
196
+ function mergeAbortSignals(
197
+ parent: AbortSignal | undefined,
198
+ child: AbortSignal,
199
+ ): AbortSignal {
200
+ if (!parent) return child;
201
+ if (parent.aborted) return parent;
202
+ const controller = new AbortController();
203
+ const abort = () => controller.abort();
204
+ parent.addEventListener("abort", abort, { once: true });
205
+ child.addEventListener("abort", abort, { once: true });
206
+ return controller.signal;
207
+ }
208
+
209
+ function eventPartial(
210
+ event: AssistantMessageEvent,
211
+ model: Model<Api>,
212
+ ): AssistantMessage {
213
+ if ("partial" in event) return event.partial;
214
+ if ("message" in event) return event.message;
215
+ if ("error" in event) return event.error;
216
+ return errorAssistantMessage(
217
+ model,
218
+ "OMLX stream started without a start event",
219
+ );
220
+ }
221
+
222
+ function errorAssistantMessage(
223
+ model: Model<Api>,
224
+ errorMessage: string,
225
+ stopReason: "error" | "aborted" = "error",
226
+ ): AssistantMessage {
227
+ return {
228
+ role: "assistant",
229
+ content: [],
230
+ api: model.api,
231
+ provider: model.provider,
232
+ model: model.id,
233
+ usage: {
234
+ input: 0,
235
+ output: 0,
236
+ cacheRead: 0,
237
+ cacheWrite: 0,
238
+ totalTokens: 0,
239
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
240
+ },
241
+ stopReason,
242
+ errorMessage,
243
+ timestamp: Date.now(),
244
+ };
245
+ }
246
+
247
+ function resolveFirstDeltaTimeoutMs(): number {
248
+ const raw = process.env.OMLX_STREAM_FIRST_DELTA_TIMEOUT_MS;
249
+ if (!raw) return DEFAULT_FIRST_DELTA_TIMEOUT_MS;
250
+ const value = Number(raw);
251
+ return Number.isFinite(value) && value > 0
252
+ ? value
253
+ : DEFAULT_FIRST_DELTA_TIMEOUT_MS;
254
+ }
@@ -0,0 +1,59 @@
1
+ export type SmokeStatusModel = {
2
+ id?: string;
3
+ thinking_default?: boolean | null;
4
+ loaded?: boolean;
5
+ engine_type?: string | null;
6
+ model_type?: string | null;
7
+ estimated_size?: number;
8
+ forced_ct_kwargs?: string[];
9
+ };
10
+
11
+ export function selectNonThinkingSmokeModel(
12
+ models: SmokeStatusModel[],
13
+ ): string | undefined {
14
+ const nonThinkingModels = models.filter(
15
+ (model) =>
16
+ model.thinking_default === false || model.thinking_default === null,
17
+ );
18
+ return (
19
+ selectBestSmokeModel(nonThinkingModels.filter(isChatSmokeModel)) ??
20
+ selectFirstSmokeModel(nonThinkingModels)
21
+ );
22
+ }
23
+
24
+ function isChatSmokeModel(model: SmokeStatusModel): boolean {
25
+ return model.engine_type === "batched" || model.model_type === "llm";
26
+ }
27
+
28
+ function selectFirstSmokeModel(models: SmokeStatusModel[]): string | undefined {
29
+ return models.find(
30
+ (model): model is SmokeStatusModel & { id: string } =>
31
+ typeof model.id === "string",
32
+ )?.id;
33
+ }
34
+
35
+ function selectBestSmokeModel(models: SmokeStatusModel[]): string | undefined {
36
+ return models
37
+ .filter(
38
+ (model): model is SmokeStatusModel & { id: string } =>
39
+ typeof model.id === "string",
40
+ )
41
+ .slice()
42
+ .sort((a, b) => {
43
+ const loadedA = a.loaded === true ? 0 : 1;
44
+ const loadedB = b.loaded === true ? 0 : 1;
45
+ if (loadedA !== loadedB) return loadedA - loadedB;
46
+
47
+ const sizeA =
48
+ typeof a.estimated_size === "number"
49
+ ? a.estimated_size
50
+ : Number.POSITIVE_INFINITY;
51
+ const sizeB =
52
+ typeof b.estimated_size === "number"
53
+ ? b.estimated_size
54
+ : Number.POSITIVE_INFINITY;
55
+ if (sizeA !== sizeB) return sizeA - sizeB;
56
+
57
+ return a.id.localeCompare(b.id);
58
+ })[0]?.id;
59
+ }
@@ -0,0 +1,29 @@
1
+ export function applyOmlxThinkingControls(
2
+ payload: unknown,
3
+ level: string,
4
+ modelThinkingDefault?: boolean | null,
5
+ ): unknown {
6
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
7
+ return payload;
8
+
9
+ const current = payload as Record<string, unknown>;
10
+ const enabled = modelThinkingDefault === true && level !== "off";
11
+ const chatTemplateKwargs = current.chat_template_kwargs;
12
+ const existingChatTemplateKwargs =
13
+ chatTemplateKwargs &&
14
+ typeof chatTemplateKwargs === "object" &&
15
+ !Array.isArray(chatTemplateKwargs)
16
+ ? (chatTemplateKwargs as Record<string, unknown>)
17
+ : {};
18
+
19
+ if (enabled) return current;
20
+
21
+ return {
22
+ ...current,
23
+ thinking_budget: 0,
24
+ chat_template_kwargs: {
25
+ ...existingChatTemplateKwargs,
26
+ enable_thinking: false,
27
+ },
28
+ };
29
+ }