@drsamonline/cli 0.0.0-stage → 0.12.3

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/src/migrate.js ADDED
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Migration from another router.
3
+ *
4
+ * The importer is shape-based, not schema-locked: it looks for the concepts
5
+ * every router has (providers with a base URL, model entries, virtual models /
6
+ * aliases / combos) under the names they are commonly given. Anything it cannot
7
+ * place is reported by key name instead of being dropped quietly.
8
+ *
9
+ * Nothing is written until you have seen the diff and chosen what to import.
10
+ */
11
+
12
+ import { readFileSync } from 'node:fs';
13
+ import { basename } from 'node:path';
14
+ import { ConfigError } from '@drsamonline/core';
15
+
16
+ const PROVIDER_ALIAS_KEYS = ['providers', 'connections', 'upstreams', 'channels', 'endpoints'];
17
+ const MODEL_KEYS = ['models', 'modelMap', 'model_map'];
18
+ const COMBO_KEYS = ['combos', 'aliases', 'routes', 'virtualModels', 'virtual_models', 'groups', 'profiles'];
19
+
20
+ /**
21
+ * @param {string} path
22
+ * @returns {{source: string, file: string, providers: Record<string, any>, models: Record<string, any>, combos: Record<string, any>, warnings: string[], unknownKeys: string[]}}
23
+ */
24
+ export function readMigrationSource(path) {
25
+ let raw;
26
+ try {
27
+ raw = readFileSync(path, 'utf8');
28
+ } catch {
29
+ throw new ConfigError(`Could not open ${path}. Check the path and try again.`);
30
+ }
31
+ let json;
32
+ try {
33
+ json = JSON.parse(raw);
34
+ } catch {
35
+ throw new ConfigError(
36
+ `${basename(path)} is not JSON. YAML configs need converting first (most tools have an "export config" button that writes JSON).`,
37
+ { path },
38
+ );
39
+ }
40
+ if (!json || typeof json !== 'object') {
41
+ throw new ConfigError(`${basename(path)} does not contain a config object.`, { path });
42
+ }
43
+
44
+ const find = (keys) => keys.find((k) => json[k] && typeof json[k] === 'object');
45
+ const providerKey = find(PROVIDER_ALIAS_KEYS);
46
+ const modelKey = find(MODEL_KEYS);
47
+ const comboKey = find(COMBO_KEYS);
48
+
49
+ /** @type {Record<string, any>} */
50
+ const providers = {};
51
+ /** @type {Record<string, any>} */
52
+ const models = {};
53
+ /** @type {Record<string, any>} */
54
+ const combos = {};
55
+ /** @type {string[]} */
56
+ const warnings = [];
57
+
58
+ const source = guessSource(path, json);
59
+
60
+ if (providerKey) {
61
+ const container = json[providerKey];
62
+ const entries = Array.isArray(container)
63
+ ? container.map((p, i) => [p.name ?? p.id ?? `provider-${i}`, p])
64
+ : Object.entries(container);
65
+ for (const [id, p] of entries) {
66
+ const prov = /** @type {any} */ (p);
67
+ const baseUrl = prov.baseUrl ?? prov.base_url ?? prov.baseURL ?? prov.api_base ?? prov.apiBase ?? prov.url ?? null;
68
+ const keyName = prov.apiKeyEnv ?? prov.api_key_env ?? null;
69
+ const literalKey = prov.apiKey ?? prov.api_key ?? prov.key ?? null;
70
+ const type = normaliseType(prov.type ?? prov.kind ?? prov.format ?? guessType(baseUrl));
71
+ providers[id] = {
72
+ type,
73
+ ...(baseUrl ? { baseUrl } : {}),
74
+ ...(keyName ? { apiKeyEnv: keyName } : literalKey ? { apiKeyEnv: `${String(id).toUpperCase().replace(/[^A-Z0-9]/g, '_')}_API_KEY` } : {}),
75
+ ...(prov.timeoutMs ?? prov.timeout ? { timeoutMs: Number(prov.timeoutMs ?? prov.timeout) } : {}),
76
+ };
77
+ if (literalKey) {
78
+ warnings.push(
79
+ `Provider "${id}" had its key written into the old config. I set apiKeyEnv instead — put the key in .env as ${providers[id].apiKeyEnv}.`,
80
+ );
81
+ }
82
+ if (!baseUrl && type !== 'gemini' && type !== 'mock') {
83
+ warnings.push(`Provider "${id}" has no base URL; it will need one before it can be used.`);
84
+ }
85
+ }
86
+ } else {
87
+ warnings.push(`No provider list found (looked for: ${PROVIDER_ALIAS_KEYS.join(', ')}).`);
88
+ }
89
+
90
+ if (modelKey) {
91
+ const container = json[modelKey];
92
+ const entries = Array.isArray(container)
93
+ ? container.map((m, i) => [m.id ?? m.name ?? `model-${i}`, m])
94
+ : Object.entries(container);
95
+ for (const [id, m] of entries) {
96
+ const model = /** @type {any} */ (m);
97
+ const providerRef = model.provider ?? model.providerId ?? model.upstream ?? model.connection ?? null;
98
+ if (!providerRef) {
99
+ warnings.push(`Model "${id}" does not say which provider it belongs to; skipped.`);
100
+ continue;
101
+ }
102
+ models[id] = {
103
+ provider: providerRef,
104
+ model: model.model ?? model.upstreamModel ?? model.upstream_model ?? model.name ?? id,
105
+ ...(model.costPer1kIn ?? model.inputCost != null ? { costPer1kIn: Number(model.costPer1kIn ?? model.inputCost) } : {}),
106
+ ...(model.costPer1kOut ?? model.outputCost != null ? { costPer1kOut: Number(model.costPer1kOut ?? model.outputCost) } : {}),
107
+ ...(model.quality != null ? { quality: Number(model.quality) } : {}),
108
+ ...(model.label ?? model.title ? { label: model.label ?? model.title } : {}),
109
+ };
110
+ }
111
+ }
112
+
113
+ if (comboKey) {
114
+ const container = json[comboKey];
115
+ const entries = Array.isArray(container)
116
+ ? container.map((c, i) => [c.name ?? c.id ?? `combo-${i}`, c])
117
+ : Object.entries(container);
118
+ for (const [id, c] of entries) {
119
+ const combo = /** @type {any} */ (c);
120
+ const rawTargets = combo.targets ?? combo.models ?? combo.routes ?? combo.members ?? combo.chain ?? [];
121
+ const targets = (Array.isArray(rawTargets) ? rawTargets : Object.keys(rawTargets))
122
+ .map((t) => {
123
+ if (typeof t === 'string') return t;
124
+ const name = t.model ?? t.id ?? t.name ?? t.target ?? null;
125
+ if (!name) return null;
126
+ return t.weight != null ? { model: name, weight: Number(t.weight) } : name;
127
+ })
128
+ .filter(Boolean);
129
+ if (!targets.length) {
130
+ warnings.push(`Combo "${id}" has no usable targets; skipped.`);
131
+ continue;
132
+ }
133
+ combos[id] = {
134
+ label: combo.label ?? combo.description ?? id,
135
+ strategy: normaliseStrategy(combo.strategy ?? combo.mode ?? combo.type),
136
+ targets,
137
+ };
138
+ }
139
+ }
140
+
141
+ const known = new Set([
142
+ ...PROVIDER_ALIAS_KEYS, ...MODEL_KEYS, ...COMBO_KEYS,
143
+ 'version', 'name', 'server', 'settings', 'logging', 'defaults',
144
+ // annotations, not configuration
145
+ '$schema', '_comment', '//',
146
+ ]);
147
+ const unknownKeys = Object.keys(json).filter((k) => !known.has(k));
148
+
149
+ return { source, file: path, providers, models, combos, warnings, unknownKeys };
150
+ }
151
+
152
+ /**
153
+ * Compare an import against the live config.
154
+ * @param {any} current
155
+ * @param {ReturnType<typeof readMigrationSource>} imported
156
+ */
157
+ export function diffImport(current, imported) {
158
+ const added = { providers: [], models: [], combos: [] };
159
+ const conflicts = [];
160
+
161
+ for (const id of Object.keys(imported.providers)) {
162
+ if (current.providers[id]) conflicts.push({ kind: 'provider', id, reason: 'already exists in your config' });
163
+ else added.providers.push(id);
164
+ }
165
+ for (const id of Object.keys(imported.models)) {
166
+ if (current.models[id]) conflicts.push({ kind: 'model', id, reason: 'already exists in your config' });
167
+ else added.models.push(id);
168
+ }
169
+ for (const id of Object.keys(imported.combos)) {
170
+ if (current.combos[id]) conflicts.push({ kind: 'combo', id, reason: 'already exists in your config' });
171
+ else added.combos.push(id);
172
+ }
173
+
174
+ // A model whose provider is not coming along cannot work.
175
+ const providerSet = new Set([...Object.keys(current.providers), ...added.providers]);
176
+ const dangling = Object.entries(imported.models)
177
+ .filter(([, m]) => !providerSet.has(/** @type {any} */ (m).provider))
178
+ .map(([id]) => id);
179
+
180
+ const comboSet = new Set([...Object.keys(current.models), ...added.models]);
181
+ const danglingCombos = Object.entries(imported.combos)
182
+ .filter(([, c]) =>
183
+ /** @type {any} */ (c).targets.some((t) => !comboSet.has(typeof t === 'string' ? t : t.model)),
184
+ )
185
+ .map(([id]) => id);
186
+
187
+ return { added, conflicts, dangling, danglingCombos, total: added.providers.length + added.models.length + added.combos.length };
188
+ }
189
+
190
+ /**
191
+ * Merge chosen entries into a raw config object (returns a new object).
192
+ * @param {any} currentRaw
193
+ * @param {ReturnType<typeof readMigrationSource>} imported
194
+ * @param {{providers?: string[], models?: string[], combos?: string[]}} [select]
195
+ */
196
+ export function applyImport(currentRaw, imported, select = {}) {
197
+ const next = structuredClone(currentRaw);
198
+ next.providers = next.providers ?? {};
199
+ next.models = next.models ?? {};
200
+ next.combos = next.combos ?? {};
201
+
202
+ const pickProviders = select.providers ?? Object.keys(imported.providers);
203
+ const pickModels = select.models ?? Object.keys(imported.models);
204
+ const pickCombos = select.combos ?? Object.keys(imported.combos);
205
+
206
+ for (const id of pickProviders) {
207
+ if (!next.providers[id] && imported.providers[id]) next.providers[id] = imported.providers[id];
208
+ }
209
+ for (const id of pickModels) {
210
+ if (!next.models[id] && imported.models[id]) next.models[id] = imported.models[id];
211
+ }
212
+ for (const id of pickCombos) {
213
+ if (!next.combos[id] && imported.combos[id]) next.combos[id] = imported.combos[id];
214
+ }
215
+ return next;
216
+ }
217
+
218
+ /**
219
+ * Post-migration smoke test: one tiny real turn per imported combo.
220
+ * @param {{chat: Function}} router
221
+ * @param {string[]} combos
222
+ */
223
+ export async function smokeTest(router, combos) {
224
+ const results = [];
225
+ for (const combo of combos) {
226
+ const started = Date.now();
227
+ try {
228
+ const res = await router.chat({
229
+ combo,
230
+ body: { messages: [{ role: 'user', content: 'Reply with the single word: ready' }], max_tokens: 16 },
231
+ });
232
+ results.push({
233
+ combo,
234
+ status: res.meta.verified ? 'ok' : 'unverified',
235
+ provider: res.meta.provider,
236
+ modelId: res.meta.modelId,
237
+ ms: Date.now() - started,
238
+ note: res.meta.verified ? null : 'answered by a mock/local provider, so the upstream was not exercised',
239
+ });
240
+ } catch (err) {
241
+ results.push({ combo, status: 'failed', ms: Date.now() - started, note: /** @type {any} */ (err).message });
242
+ }
243
+ }
244
+ return results;
245
+ }
246
+
247
+ function guessSource(path, json) {
248
+ const name = basename(path).toLowerCase();
249
+ const blob = name + ' ' + JSON.stringify(Object.keys(json)).toLowerCase();
250
+ if (/9router/.test(blob)) return '9router';
251
+ if (/omniroute|omni-route/.test(blob)) return 'OmniRoute';
252
+ if (/hubgate|hub-gate/.test(blob)) return 'HubGate';
253
+ if (json.connections) return '9router-style (connections)';
254
+ if (json.channels) return 'OmniRoute-style (channels)';
255
+ if (json.upstreams) return 'HubGate-style (upstreams)';
256
+ return 'unknown router';
257
+ }
258
+
259
+ function normaliseType(t) {
260
+ const v = String(t ?? '').toLowerCase();
261
+ if (/anthropic|claude/.test(v)) return 'anthropic';
262
+ if (/gemini|google|vertex/.test(v)) return 'gemini';
263
+ if (/mock|test/.test(v)) return 'mock';
264
+ return 'openai';
265
+ }
266
+
267
+ function guessType(baseUrl) {
268
+ const u = String(baseUrl ?? '').toLowerCase();
269
+ if (u.includes('anthropic')) return 'anthropic';
270
+ if (u.includes('generativelanguage') || u.includes('googleapis')) return 'gemini';
271
+ return 'openai';
272
+ }
273
+
274
+ function normaliseStrategy(s) {
275
+ const v = String(s ?? 'fallback').toLowerCase();
276
+ if (/weight|split|ab|a-b|ratio/.test(v)) return 'weighted';
277
+ if (/cheap|cost|budget/.test(v)) return 'cheapest';
278
+ if (/latenc|fast/.test(v)) return 'latency';
279
+ return 'fallback';
280
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * First-run onboarding.
3
+ *
4
+ * The one rule this file exists to enforce: onboarding may not report success
5
+ * without a real model round-trip. A green tick here means a request left this
6
+ * machine and an answer came back — not that a config file was written.
7
+ */
8
+
9
+ import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { join, dirname } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { createGateway, loadEnvFile } from '@drsamonline/gateway';
13
+ import { providerHasCredentials, suiHome } from '@drsamonline/core';
14
+ import { detectTools, writeToolConfig } from './tools.js';
15
+
16
+ const HERE = dirname(fileURLToPath(import.meta.url));
17
+ const TEMPLATE = join(HERE, '..', '..', '..', 'config', 'sui.config.json');
18
+
19
+ const PROVIDER_KEYS = [
20
+ { id: 'groq', env: 'GROQ_API_KEY', note: 'has a free tier' },
21
+ { id: 'gemini', env: 'GEMINI_API_KEY', note: 'has a free tier' },
22
+ { id: 'openai', env: 'OPENAI_API_KEY', note: 'paid' },
23
+ { id: 'anthropic', env: 'ANTHROPIC_API_KEY', note: 'paid' },
24
+ { id: 'openrouter', env: 'OPENROUTER_API_KEY', note: 'free models available' },
25
+ ];
26
+
27
+ /**
28
+ * @param {{
29
+ * cwd?: string, env?: NodeJS.ProcessEnv, interactive?: boolean,
30
+ * out?: (line?: string) => void, prompt?: {ask: Function, choose: Function},
31
+ * force?: boolean, demo?: boolean, port?: number, template?: any
32
+ * }} [opts]
33
+ */
34
+ export async function runInit(opts = {}) {
35
+ const cwd = opts.cwd ?? process.cwd();
36
+ const env = opts.env ?? loadEnvFile(join(cwd, '.env'), { ...process.env });
37
+ const out = opts.out ?? ((line = '') => console.log(line));
38
+ const interactive = opts.interactive ?? false;
39
+ const configPath = join(cwd, 'sui.config.json');
40
+
41
+ out('');
42
+ out('sui · first run');
43
+ out('');
44
+
45
+ // 1. what can we reach?
46
+ out('Looking for provider keys…');
47
+ /** @type {Array<{id: string, env: string, note: string, present: boolean}>} */
48
+ const keys = PROVIDER_KEYS.map((p) => ({ ...p, present: Boolean(env[p.env]) }));
49
+ for (const k of keys) {
50
+ out(` ${k.present ? 'found ' : 'missing'} ${k.env.padEnd(22)} ${k.note}`);
51
+ }
52
+
53
+ let template = opts.template ?? null;
54
+ if (!template) {
55
+ try {
56
+ template = JSON.parse(readFileSync(TEMPLATE, 'utf8'));
57
+ } catch {
58
+ template = { providers: {}, models: {}, combos: {}, server: { host: '127.0.0.1', port: opts.port ?? 8787 } };
59
+ }
60
+ }
61
+
62
+ // A keyless provider (Ollama, LM Studio) only counts if it is actually
63
+ // running — otherwise the first run would "succeed" against nothing.
64
+ const usableProviders = [];
65
+ for (const [id, p] of Object.entries(template.providers ?? {})) {
66
+ const prov = /** @type {any} */ (p);
67
+ const keyed = Boolean(prov.apiKeyEnv && env[prov.apiKeyEnv]) || Boolean(prov.apiKey);
68
+ if (keyed) {
69
+ usableProviders.push(id);
70
+ continue;
71
+ }
72
+ if (prov.apiKeyEnv === null || prov.local) {
73
+ if (await isReachable(prov.baseUrl)) usableProviders.push(id);
74
+ else out(` ${id} is configured but not answering at ${prov.baseUrl} — leaving it out`);
75
+ }
76
+ }
77
+
78
+ const demo = opts.demo || usableProviders.length === 0;
79
+ let config = filterConfig(template, usableProviders);
80
+
81
+ if (demo) {
82
+ out('');
83
+ out('No provider keys are set, so I am wiring a demo provider.');
84
+ out('It answers in-process: it proves the gateway, the dashboard and your tools');
85
+ out('all work, but it is not a real model. Add a key and re-run to switch over.');
86
+ config = demoConfig(template, opts.port ?? 8787);
87
+ }
88
+
89
+ if (config.portOverride) {
90
+ config.server.port = config.portOverride;
91
+ delete config.portOverride;
92
+ }
93
+
94
+ // 2. what will this machine call it from?
95
+ out('');
96
+ out('Looking for coding tools…');
97
+ const tools = detectTools({ env });
98
+ const detected = tools.filter((t) => t.detected && t.id !== 'env');
99
+ if (detected.length) {
100
+ for (const t of detected) out(` found ${t.name.padEnd(28)} ${t.setup === 'file' ? 'config file' : 'paste two fields'}`);
101
+ } else {
102
+ out(' none found — that is fine, anything that speaks OpenAI can use the endpoint.');
103
+ }
104
+
105
+ // 3. write config
106
+ const exists = existsSync(configPath);
107
+ if (exists && !opts.force) {
108
+ const backup = `${configPath}.bak-${Date.now()}`;
109
+ copyFileSync(configPath, backup);
110
+ out('');
111
+ out(`Existing config kept as ${backup}.`);
112
+ }
113
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
114
+ out('');
115
+ out(`Config written: ${configPath}`);
116
+
117
+ const comboNames = Object.keys(config.combos ?? {});
118
+ out(`Combos: ${comboNames.join(', ')}`);
119
+
120
+ // 4. the part that matters: a real turn
121
+ out('');
122
+ out('Checking the route end to end…');
123
+ const gateway = await createGateway({ configPath, env, ledgerFile: join(suiHome(env), 'ledger.jsonl') });
124
+
125
+ const combo = comboNames.includes('chat-default') ? 'chat-default' : comboNames[0];
126
+ const started = Date.now();
127
+ let roundTrip;
128
+ try {
129
+ const res = await gateway.router.chat({
130
+ combo,
131
+ body: { messages: [{ role: 'user', content: 'Reply with the single word: ready' }], max_tokens: 24 },
132
+ });
133
+ roundTrip = {
134
+ ok: true,
135
+ combo,
136
+ provider: res.meta.provider,
137
+ modelId: res.meta.modelId,
138
+ model: res.meta.model,
139
+ verified: res.meta.verified,
140
+ latencyMs: res.meta.latencyMs,
141
+ text: res.text.trim().slice(0, 120),
142
+ costUsd: res.meta.costUsd,
143
+ };
144
+ out(` answered by ${res.meta.modelId} (${res.meta.provider}) in ${res.meta.latencyMs} ms`);
145
+ out(` reply: "${roundTrip.text}"`);
146
+ if (!res.meta.verified) {
147
+ out(' note: this came from the demo provider, not a real upstream model.');
148
+ }
149
+ } catch (err) {
150
+ roundTrip = { ok: false, combo, error: /** @type {any} */ (err).message, ms: Date.now() - started };
151
+ out(` failed: ${roundTrip.error}`);
152
+ out('');
153
+ out('Nothing was marked ready. Fix the problem above and run `npx sui init` again.');
154
+ return { ok: false, configPath, config, roundTrip, tools };
155
+ }
156
+
157
+ const host = config.server.host === '0.0.0.0' ? '127.0.0.1' : config.server.host;
158
+ const endpoint = `http://${host}:${config.server.port}/v1`;
159
+
160
+ out('');
161
+ out('Endpoint ready');
162
+ out(` ${endpoint}`);
163
+ out(` OPENAI_BASE_URL=${endpoint}`);
164
+ out(` OPENAI_API_KEY=${config.apiKeys?.[0]?.key ?? 'any-non-empty-string'}`);
165
+ out(` dashboard: http://${host}:${config.server.port}/`);
166
+
167
+ // 5. one-click tool setup, offered once
168
+ let toolResult = null;
169
+ if (interactive && detected.length && opts.prompt) {
170
+ const choice = await opts.prompt.choose(
171
+ 'Point a tool at it now?',
172
+ [...detected.map((t) => t.name), 'Not now'],
173
+ );
174
+ const picked = detected.find((t) => t.name === choice);
175
+ if (picked) {
176
+ toolResult = writeToolConfig(picked.id, {
177
+ baseUrl: `http://${host}:${config.server.port}`,
178
+ combo,
179
+ apiKey: config.apiKeys?.[0]?.key ?? 'sui-local',
180
+ env,
181
+ });
182
+ out(` ${toolResult.message}`);
183
+ if (toolResult.snippet) out(indent(toolResult.snippet, ' '));
184
+ }
185
+ } else if (detected.length) {
186
+ out('');
187
+ out('Next: `npx sui tools` to point one of these at the gateway.');
188
+ }
189
+
190
+ return { ok: true, configPath, config, roundTrip, endpoint, tools, toolResult, demo };
191
+ }
192
+
193
+ /**
194
+ * Keep only providers we have credentials for (plus local ones), then drop
195
+ * models and combos that lost their backing.
196
+ */
197
+ export function filterConfig(template, providerIds) {
198
+ const keep = new Set(providerIds);
199
+ const providers = Object.fromEntries(Object.entries(template.providers ?? {}).filter(([id]) => keep.has(id)));
200
+ const models = Object.fromEntries(
201
+ Object.entries(template.models ?? {}).filter(([, m]) => keep.has(/** @type {any} */ (m).provider)),
202
+ );
203
+ const modelIds = new Set(Object.keys(models));
204
+ const combos = {};
205
+ for (const [id, c] of Object.entries(template.combos ?? {})) {
206
+ const combo = /** @type {any} */ (c);
207
+ const targets = combo.targets.filter((t) => modelIds.has(typeof t === 'string' ? t : t.model));
208
+ if (targets.length) combos[id] = { ...combo, targets };
209
+ }
210
+ return {
211
+ ...template,
212
+ providers,
213
+ models,
214
+ combos: Object.keys(combos).length
215
+ ? combos
216
+ : { 'chat-default': { label: 'Everyday chat', strategy: 'fallback', targets: [...modelIds].slice(0, 1) } },
217
+ server: { ...(template.server ?? {}), port: template.server?.port ?? 8787 },
218
+ apiKeys: [],
219
+ };
220
+ }
221
+
222
+ function demoConfig(template, port) {
223
+ return {
224
+ ...template,
225
+ providers: {
226
+ demo: { type: 'mock', mock: { delayMs: 10 } },
227
+ },
228
+ models: {
229
+ 'demo-model': {
230
+ provider: 'demo',
231
+ model: 'demo-model',
232
+ label: 'Built-in demo model (no key needed)',
233
+ costPer1kIn: 0,
234
+ costPer1kOut: 0,
235
+ quality: 1,
236
+ tier: 'demo',
237
+ },
238
+ },
239
+ combos: {
240
+ 'chat-default': { label: 'Everyday chat', strategy: 'fallback', targets: ['demo-model'] },
241
+ },
242
+ server: { ...(template.server ?? {}), port },
243
+ apiKeys: [],
244
+ };
245
+ }
246
+
247
+ /** Is a keyless local endpoint actually up? Short timeout, never fatal. */
248
+ async function isReachable(baseUrl) {
249
+ if (!baseUrl) return false;
250
+ try {
251
+ const res = await fetch(String(baseUrl).replace(/\/+$/, '') + '/models', { signal: AbortSignal.timeout(600) });
252
+ return res.ok;
253
+ } catch {
254
+ return false;
255
+ }
256
+ }
257
+
258
+ function indent(text, pad) {
259
+ return String(text)
260
+ .split('\n')
261
+ .map((l) => pad + l)
262
+ .join('\n');
263
+ }