@drsamonline/prober 0.0.0-stage → 0.12.2
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/package.json +23 -4
- package/src/index.js +484 -0
- package/src/local.js +161 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drsamonline/prober",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.12.2",
|
|
4
|
+
"description": "Canary prober: liveness, readiness and suitability checks that decide what may be routed to.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js",
|
|
10
|
+
"./src/*": "./src/*"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git://github.com/drsamonline/sui.git",
|
|
18
|
+
"directory": "packages/prober"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/drsamonline/sui#readme",
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public",
|
|
23
|
+
"registry": "https://registry.npmjs.org/"
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @drsamonline/prober — the canary prober (B2.3).
|
|
3
|
+
*
|
|
4
|
+
* This is the batch that makes "verified before use" mean something. A catalogue
|
|
5
|
+
* entry is an identity; a probed entry is a route. Nothing here runs on the
|
|
6
|
+
* request path (I1): probes happen on a schedule, results are read from memory.
|
|
7
|
+
*
|
|
8
|
+
* Three levels, because "the endpoint answered" and "the endpoint can do what we
|
|
9
|
+
* need" are different facts:
|
|
10
|
+
*
|
|
11
|
+
* liveness does the API respond at all
|
|
12
|
+
* readiness does a minimal chat completion come back with usable text
|
|
13
|
+
* suitability does it actually stream, honour a JSON request, accept tools —
|
|
14
|
+
* only for the capabilities the entry claims
|
|
15
|
+
*
|
|
16
|
+
* Fixtures are tiny, versioned, synthetic and side-effect free: no customer
|
|
17
|
+
* content, no write tools, nothing that could mutate state upstream.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { poolKey } from '@drsamonline/catalog';
|
|
21
|
+
|
|
22
|
+
/** Bump when a fixture changes, so probe history stays comparable. */
|
|
23
|
+
export const PROBE_FIXTURE_VERSION = '1.0.0';
|
|
24
|
+
|
|
25
|
+
export const FIXTURES = {
|
|
26
|
+
readiness: {
|
|
27
|
+
messages: [{ role: 'user', content: 'Reply with the single word: ready' }],
|
|
28
|
+
max_tokens: 8,
|
|
29
|
+
},
|
|
30
|
+
jsonSchema: {
|
|
31
|
+
messages: [{ role: 'user', content: 'Return JSON with exactly one key "ok", set to true.' }],
|
|
32
|
+
max_tokens: 40,
|
|
33
|
+
response_format: { type: 'json_object' },
|
|
34
|
+
},
|
|
35
|
+
tools: {
|
|
36
|
+
messages: [{ role: 'user', content: 'Call the get_time tool for the city Pune.' }],
|
|
37
|
+
max_tokens: 60,
|
|
38
|
+
tools: [
|
|
39
|
+
{
|
|
40
|
+
type: 'function',
|
|
41
|
+
function: {
|
|
42
|
+
name: 'get_time',
|
|
43
|
+
description: 'Return the current time for a city. Read-only.',
|
|
44
|
+
parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const DEFAULT_TIMEOUT_MS = 8000;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Probe one catalogue entry.
|
|
55
|
+
*
|
|
56
|
+
* @param {any} entry a normalised catalogue entry
|
|
57
|
+
* @param {{fetchImpl?: typeof fetch, timeoutMs?: number, now?: () => number, capabilities?: string[]}} [opts]
|
|
58
|
+
*/
|
|
59
|
+
export async function probeTarget(entry, opts = {}) {
|
|
60
|
+
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
61
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
62
|
+
const now = opts.now ?? Date.now;
|
|
63
|
+
const checkedAt = now();
|
|
64
|
+
|
|
65
|
+
const key = entry.pool_key ?? poolKey(entry);
|
|
66
|
+
const base = entry.base_url ? String(entry.base_url).replace(/\/+$/, '') : null;
|
|
67
|
+
|
|
68
|
+
/** @type {{liveness: any, readiness: any, suitability: Record<string, any>}} */
|
|
69
|
+
const levels = { liveness: null, readiness: null, suitability: {} };
|
|
70
|
+
|
|
71
|
+
if (!base) {
|
|
72
|
+
return {
|
|
73
|
+
pool_key: key,
|
|
74
|
+
provider: entry.provider,
|
|
75
|
+
checkedAt,
|
|
76
|
+
fixtureVersion: PROBE_FIXTURE_VERSION,
|
|
77
|
+
ok: false,
|
|
78
|
+
verified: false,
|
|
79
|
+
latencyMs: 0,
|
|
80
|
+
levels,
|
|
81
|
+
reasons: ['no endpoint to probe (base_url is null — the identity is unresolved)'],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const headers = { 'content-type': 'application/json' };
|
|
86
|
+
if (entry.auth === 'key' && entry.key_env && process.env[entry.key_env]) {
|
|
87
|
+
headers.authorization = `Bearer ${process.env[entry.key_env]}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const started = now();
|
|
91
|
+
const reasons = [];
|
|
92
|
+
|
|
93
|
+
// ---- liveness -----------------------------------------------------------
|
|
94
|
+
// The model list is also how we learn what to *call*. Imported entries carry a
|
|
95
|
+
// model family, not a model name, and probing with the family ("openai-compatible")
|
|
96
|
+
// would fail against a perfectly healthy endpoint.
|
|
97
|
+
/** @type {string[]} */
|
|
98
|
+
let discoveredModels = [];
|
|
99
|
+
levels.liveness = await timed(async () => {
|
|
100
|
+
const res = await fetchImpl(`${base}/models`, { method: 'GET', headers, signal: AbortSignal.timeout(timeoutMs) });
|
|
101
|
+
if (res.ok) {
|
|
102
|
+
const json = await res.json().catch(() => null);
|
|
103
|
+
const rows = Array.isArray(json?.data) ? json.data : Array.isArray(json?.models) ? json.models : [];
|
|
104
|
+
discoveredModels = rows
|
|
105
|
+
.map((row) => (typeof row === 'string' ? row : row?.id ?? row?.name))
|
|
106
|
+
.filter((id) => typeof id === 'string' && id.length > 0)
|
|
107
|
+
// a chat probe wants a chat model, not an embedding or a speech model
|
|
108
|
+
.filter((id) => !/embed|whisper|tts|moderation|rerank|guard|image|video|audio/i.test(id));
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
ok: res.ok,
|
|
112
|
+
status: res.status,
|
|
113
|
+
models: discoveredModels.length,
|
|
114
|
+
note: res.ok ? `answered /models (${discoveredModels.length} model(s))` : `HTTP ${res.status}`,
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// ---- readiness ----------------------------------------------------------
|
|
119
|
+
// If liveness did not even reach the host, readiness cannot tell us anything
|
|
120
|
+
// new: it would only spend another timeout to say the same thing.
|
|
121
|
+
const reachedHost = levels.liveness.status !== undefined || levels.liveness.ok === true;
|
|
122
|
+
let sample = '';
|
|
123
|
+
if (!reachedHost) {
|
|
124
|
+
levels.readiness = { ok: false, note: 'not attempted: endpoint unreachable', ms: 0 };
|
|
125
|
+
reasons.push(`liveness: ${levels.liveness.note}`);
|
|
126
|
+
return {
|
|
127
|
+
pool_key: key,
|
|
128
|
+
provider: entry.provider,
|
|
129
|
+
checkedAt,
|
|
130
|
+
fixtureVersion: PROBE_FIXTURE_VERSION,
|
|
131
|
+
ok: false,
|
|
132
|
+
verified: false,
|
|
133
|
+
latencyMs: now() - started,
|
|
134
|
+
levels,
|
|
135
|
+
reasons,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
levels.readiness = await timed(async () => {
|
|
139
|
+
const res = await fetchImpl(`${base}/chat/completions`, {
|
|
140
|
+
method: 'POST',
|
|
141
|
+
headers,
|
|
142
|
+
body: JSON.stringify({ model: probeModel(entry, discoveredModels), ...FIXTURES.readiness }),
|
|
143
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
144
|
+
});
|
|
145
|
+
if (!res.ok) {
|
|
146
|
+
const body = await res.text().catch(() => '');
|
|
147
|
+
return { ok: false, status: res.status, note: `HTTP ${res.status}: ${firstLine(body)}` };
|
|
148
|
+
}
|
|
149
|
+
const json = await res.json().catch(() => null);
|
|
150
|
+
sample = json?.choices?.[0]?.message?.content ?? '';
|
|
151
|
+
const ok = typeof sample === 'string' && sample.trim().length > 0;
|
|
152
|
+
return { ok, status: res.status, note: ok ? 'returned text' : 'empty completion' };
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
if (!levels.readiness.ok) reasons.push(`readiness: ${levels.readiness.note}`);
|
|
156
|
+
|
|
157
|
+
// ---- suitability --------------------------------------------------------
|
|
158
|
+
const capabilities = opts.capabilities ?? entry.capabilities ?? [];
|
|
159
|
+
if (levels.readiness.ok) {
|
|
160
|
+
if (capabilities.includes('streaming')) {
|
|
161
|
+
levels.suitability.streaming = await probeStreaming({ fetchImpl, base, headers, entry, timeoutMs });
|
|
162
|
+
if (!levels.suitability.streaming.ok) reasons.push(`streaming: ${levels.suitability.streaming.note}`);
|
|
163
|
+
}
|
|
164
|
+
if (capabilities.includes('json_schema')) {
|
|
165
|
+
levels.suitability.json_schema = await probeJson({ fetchImpl, base, headers, entry, timeoutMs });
|
|
166
|
+
if (!levels.suitability.json_schema.ok) reasons.push(`json_schema: ${levels.suitability.json_schema.note}`);
|
|
167
|
+
}
|
|
168
|
+
if (capabilities.includes('tools')) {
|
|
169
|
+
levels.suitability.tools = await probeTools({ fetchImpl, base, headers, entry, timeoutMs });
|
|
170
|
+
if (!levels.suitability.tools.ok) reasons.push(`tools: ${levels.suitability.tools.note}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const ok =
|
|
175
|
+
levels.liveness.ok &&
|
|
176
|
+
levels.readiness.ok &&
|
|
177
|
+
Object.values(levels.suitability).every((s) => s.ok);
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
pool_key: key,
|
|
181
|
+
provider: entry.provider,
|
|
182
|
+
checkedAt,
|
|
183
|
+
fixtureVersion: PROBE_FIXTURE_VERSION,
|
|
184
|
+
ok,
|
|
185
|
+
// "verified" is stricter than "ok": a probe that only proves liveness does
|
|
186
|
+
// not prove the route can carry a conversation.
|
|
187
|
+
verified: ok && levels.readiness.ok,
|
|
188
|
+
latencyMs: now() - started,
|
|
189
|
+
sample: sample.slice(0, 40),
|
|
190
|
+
levels,
|
|
191
|
+
reasons,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Streaming must be a real event sequence, not one blob pretending to be SSE. */
|
|
196
|
+
async function probeStreaming({ fetchImpl, base, headers, entry, timeoutMs }) {
|
|
197
|
+
return timed(async () => {
|
|
198
|
+
const res = await fetchImpl(`${base}/chat/completions`, {
|
|
199
|
+
method: 'POST',
|
|
200
|
+
headers,
|
|
201
|
+
body: JSON.stringify({ model: modelFor(entry), stream: true, ...FIXTURES.readiness }),
|
|
202
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
203
|
+
});
|
|
204
|
+
if (!res.ok) return { ok: false, status: res.status, note: `HTTP ${res.status}` };
|
|
205
|
+
if (!res.body) return { ok: false, status: res.status, note: 'no response body to stream' };
|
|
206
|
+
|
|
207
|
+
let frames = 0;
|
|
208
|
+
let deltas = 0;
|
|
209
|
+
let done = false;
|
|
210
|
+
let buffer = '';
|
|
211
|
+
const reader = res.body.getReader();
|
|
212
|
+
const decoder = new TextDecoder();
|
|
213
|
+
|
|
214
|
+
while (frames < 200) {
|
|
215
|
+
const { done: finished, value } = await reader.read();
|
|
216
|
+
if (finished) break;
|
|
217
|
+
buffer += decoder.decode(value, { stream: true });
|
|
218
|
+
let idx;
|
|
219
|
+
while ((idx = buffer.indexOf('\n\n')) !== -1) {
|
|
220
|
+
const block = buffer.slice(0, idx);
|
|
221
|
+
buffer = buffer.slice(idx + 2);
|
|
222
|
+
for (const line of block.split('\n')) {
|
|
223
|
+
if (!line.startsWith('data:')) continue;
|
|
224
|
+
const data = line.slice(5).trim();
|
|
225
|
+
frames += 1;
|
|
226
|
+
if (data === '[DONE]') {
|
|
227
|
+
done = true;
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const payload = JSON.parse(data);
|
|
232
|
+
if (payload.choices?.[0]?.delta?.content) deltas += 1;
|
|
233
|
+
} catch {
|
|
234
|
+
/* a keepalive frame is not a failure */
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (done) break;
|
|
239
|
+
}
|
|
240
|
+
try {
|
|
241
|
+
await reader.cancel();
|
|
242
|
+
} catch {
|
|
243
|
+
/* already closed */
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const ok = frames > 0 && deltas > 0;
|
|
247
|
+
return {
|
|
248
|
+
ok,
|
|
249
|
+
status: res.status,
|
|
250
|
+
note: ok ? `${frames} frames, ${deltas} content deltas` : `${frames} frames, ${deltas} content deltas — not a real stream`,
|
|
251
|
+
frames,
|
|
252
|
+
deltas,
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** A JSON request has to come back as JSON, not as a promise to be JSON. */
|
|
258
|
+
async function probeJson({ fetchImpl, base, headers, entry, timeoutMs }) {
|
|
259
|
+
return timed(async () => {
|
|
260
|
+
const res = await fetchImpl(`${base}/chat/completions`, {
|
|
261
|
+
method: 'POST',
|
|
262
|
+
headers,
|
|
263
|
+
body: JSON.stringify({ model: modelFor(entry), ...FIXTURES.jsonSchema }),
|
|
264
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
265
|
+
});
|
|
266
|
+
if (!res.ok) return { ok: false, status: res.status, note: `HTTP ${res.status}` };
|
|
267
|
+
const json = await res.json().catch(() => null);
|
|
268
|
+
const content = json?.choices?.[0]?.message?.content ?? '';
|
|
269
|
+
const fenced = String(content).match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
270
|
+
const body = (fenced ? fenced[1] : content).trim();
|
|
271
|
+
try {
|
|
272
|
+
const parsed = JSON.parse(body);
|
|
273
|
+
return { ok: typeof parsed === 'object' && parsed !== null, status: res.status, note: 'returned parseable JSON' };
|
|
274
|
+
} catch {
|
|
275
|
+
return { ok: false, status: res.status, note: 'returned text that is not JSON' };
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Tools: the check is that the request is *accepted* and the response has a valid
|
|
282
|
+
* shape — not that the model chose to call the tool. Refusing to call a tool is a
|
|
283
|
+
* legitimate answer; a 400 is not.
|
|
284
|
+
*/
|
|
285
|
+
async function probeTools({ fetchImpl, base, headers, entry, timeoutMs }) {
|
|
286
|
+
return timed(async () => {
|
|
287
|
+
const res = await fetchImpl(`${base}/chat/completions`, {
|
|
288
|
+
method: 'POST',
|
|
289
|
+
headers,
|
|
290
|
+
body: JSON.stringify({ model: modelFor(entry), ...FIXTURES.tools }),
|
|
291
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
292
|
+
});
|
|
293
|
+
if (!res.ok) return { ok: false, status: res.status, note: `HTTP ${res.status} — tools rejected` };
|
|
294
|
+
const json = await res.json().catch(() => null);
|
|
295
|
+
const message = json?.choices?.[0]?.message;
|
|
296
|
+
const ok = Boolean(message && (Array.isArray(message.tool_calls) || typeof message.content === 'string'));
|
|
297
|
+
return { ok, status: res.status, note: ok ? 'tool schema accepted' : 'response had neither tool_calls nor content' };
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Which model to call for the readiness check.
|
|
303
|
+
*
|
|
304
|
+
* In order: an explicit `probe_model` from the catalogue, then the first model
|
|
305
|
+
* the endpoint itself listed, then a known default for a family we recognise.
|
|
306
|
+
* A family name like "openai-compatible" is never sent as a model — that is a
|
|
307
|
+
* category, and every real endpoint rejects it.
|
|
308
|
+
*/
|
|
309
|
+
function probeModel(entry, discovered = []) {
|
|
310
|
+
if (entry.probe_model) return entry.probe_model;
|
|
311
|
+
if (discovered.length) return discovered[0];
|
|
312
|
+
const family = entry.model_family;
|
|
313
|
+
if (family && !/compatible|mixed|unknown/i.test(family)) return family;
|
|
314
|
+
return 'default';
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function modelFor(entry) {
|
|
318
|
+
return entry.probe_model ?? entry.model_family ?? 'default';
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function timed(fn) {
|
|
322
|
+
const t0 = performance.now();
|
|
323
|
+
try {
|
|
324
|
+
const result = await fn();
|
|
325
|
+
return { ...result, ms: Math.round(performance.now() - t0) };
|
|
326
|
+
} catch (err) {
|
|
327
|
+
const e = /** @type {any} */ (err);
|
|
328
|
+
const timedOut = e?.name === 'TimeoutError' || e?.name === 'AbortError';
|
|
329
|
+
return { ok: false, note: timedOut ? 'timed out' : `unreachable: ${e?.message ?? e}`, ms: Math.round(performance.now() - t0) };
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function firstLine(s) {
|
|
334
|
+
return String(s ?? '').split('\n')[0].slice(0, 120);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* B10.1 — the Weather Map's vocabulary.
|
|
339
|
+
*
|
|
340
|
+
* Three labels, because a person reading a status page needs a word, not a state
|
|
341
|
+
* machine: thriving, resting, down. `unverified` is its own answer — "nobody has
|
|
342
|
+
* checked yet" is not the same as "down", and saying so is the point.
|
|
343
|
+
*
|
|
344
|
+
* @param {string} status
|
|
345
|
+
*/
|
|
346
|
+
export function weatherLabel(status) {
|
|
347
|
+
if (status === 'healthy') return 'thriving';
|
|
348
|
+
if (status === 'degraded') return 'resting';
|
|
349
|
+
if (status === 'disabled') return 'down';
|
|
350
|
+
if (status === 'unverified') return 'unverified';
|
|
351
|
+
return 'down';
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A one-line, plain-language reading of a probe row. */
|
|
355
|
+
export function weatherSentence(row) {
|
|
356
|
+
const name = row.provider;
|
|
357
|
+
if (row.weather === 'unverified') return `${name}: not probed yet, so it is not in the pool.`;
|
|
358
|
+
if (row.weather === 'thriving') {
|
|
359
|
+
return `${name}: thriving — ${row.history?.length ?? 0} probe(s) on record, last one answered in ${row.latencyMs ?? '—'} ms.`;
|
|
360
|
+
}
|
|
361
|
+
const why = (row.reasons ?? [])[0] ?? 'no reason recorded';
|
|
362
|
+
return `${name}: ${row.weather} — ${row.failures} consecutive failure(s). ${why}.`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* The prober: state, thresholds and the schedule.
|
|
367
|
+
*
|
|
368
|
+
* `auto_disable_after_failures` and `auto_re_enable_on_recovery` are the two
|
|
369
|
+
* behaviours that keep a free tier honest: a broken route leaves the pool after
|
|
370
|
+
* three consecutive failures, and comes back the moment a probe succeeds.
|
|
371
|
+
*/
|
|
372
|
+
export class Prober {
|
|
373
|
+
/**
|
|
374
|
+
* @param {{
|
|
375
|
+
* entries: any[], intervalMs?: number, failuresBeforeDisable?: number,
|
|
376
|
+
* fetchImpl?: typeof fetch, timeoutMs?: number, now?: () => number,
|
|
377
|
+
* onResult?: (result: any, state: any) => void
|
|
378
|
+
* }} opts
|
|
379
|
+
*/
|
|
380
|
+
constructor(opts) {
|
|
381
|
+
this.entries = opts.entries ?? [];
|
|
382
|
+
this.intervalMs = opts.intervalMs ?? 3600_000;
|
|
383
|
+
this.failuresBeforeDisable = opts.failuresBeforeDisable ?? 3;
|
|
384
|
+
this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
385
|
+
this.timeoutMs = opts.timeoutMs;
|
|
386
|
+
this.now = opts.now ?? Date.now;
|
|
387
|
+
this.onResult = opts.onResult ?? null;
|
|
388
|
+
|
|
389
|
+
/** @type {Map<string, any>} */
|
|
390
|
+
this.state = new Map();
|
|
391
|
+
for (const entry of this.entries) {
|
|
392
|
+
const key = entry.pool_key ?? poolKey(entry);
|
|
393
|
+
this.state.set(key, {
|
|
394
|
+
pool_key: key,
|
|
395
|
+
provider: entry.provider,
|
|
396
|
+
status: 'unverified',
|
|
397
|
+
failures: 0,
|
|
398
|
+
lastProbeAt: null,
|
|
399
|
+
lastOkAt: null,
|
|
400
|
+
lastResult: null,
|
|
401
|
+
history: [],
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
this.timer = null;
|
|
405
|
+
this.runs = 0;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Probe everything once, in parallel, and fold the results into state. */
|
|
409
|
+
async runOnce() {
|
|
410
|
+
this.runs += 1;
|
|
411
|
+
const results = await Promise.all(
|
|
412
|
+
this.entries.map((entry) => probeTarget(entry, { fetchImpl: this.fetchImpl, timeoutMs: this.timeoutMs, now: this.now })),
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
for (const result of results) {
|
|
416
|
+
const key = result.pool_key;
|
|
417
|
+
const current = this.state.get(key) ?? { pool_key: key, provider: result.provider, failures: 0, history: [] };
|
|
418
|
+
current.lastProbeAt = result.checkedAt;
|
|
419
|
+
current.lastResult = result;
|
|
420
|
+
current.history = [...(current.history ?? []), { at: result.checkedAt, ok: result.ok, latencyMs: result.latencyMs }].slice(-24);
|
|
421
|
+
|
|
422
|
+
if (result.ok) {
|
|
423
|
+
current.failures = 0;
|
|
424
|
+
current.status = 'healthy';
|
|
425
|
+
current.lastOkAt = result.checkedAt;
|
|
426
|
+
} else {
|
|
427
|
+
current.failures += 1;
|
|
428
|
+
current.status = current.failures >= this.failuresBeforeDisable ? 'disabled' : 'degraded';
|
|
429
|
+
}
|
|
430
|
+
this.state.set(key, current);
|
|
431
|
+
this.onResult?.(result, current);
|
|
432
|
+
}
|
|
433
|
+
return results;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** The probe map the catalogue's scoring function expects. */
|
|
437
|
+
probeMap() {
|
|
438
|
+
/** @type {Record<string, any>} */
|
|
439
|
+
const map = {};
|
|
440
|
+
for (const [key, s] of this.state.entries()) {
|
|
441
|
+
map[key] = {
|
|
442
|
+
ok: s.status === 'healthy',
|
|
443
|
+
latencyMs: s.lastResult?.latencyMs ?? null,
|
|
444
|
+
checkedAt: s.lastProbeAt,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
return map;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Snapshot for the dashboard and `sui probe --json`. */
|
|
451
|
+
snapshot() {
|
|
452
|
+
return [...this.state.values()].map((s) => ({
|
|
453
|
+
pool_key: s.pool_key,
|
|
454
|
+
provider: s.provider,
|
|
455
|
+
status: s.status,
|
|
456
|
+
weather: weatherLabel(s.status),
|
|
457
|
+
failures: s.failures,
|
|
458
|
+
lastProbeAt: s.lastProbeAt,
|
|
459
|
+
lastOkAt: s.lastOkAt,
|
|
460
|
+
latencyMs: s.lastResult?.latencyMs ?? null,
|
|
461
|
+
reasons: s.lastResult?.reasons ?? [],
|
|
462
|
+
suitability: s.lastResult?.levels?.suitability ?? {},
|
|
463
|
+
// the last 24 observations, for the trend line (B10.1)
|
|
464
|
+
history: s.history ?? [],
|
|
465
|
+
}));
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Start the schedule. Returns this, so it can be chained or stopped. */
|
|
469
|
+
start() {
|
|
470
|
+
if (this.timer) return this;
|
|
471
|
+
this.runOnce().catch(() => {});
|
|
472
|
+
this.timer = setInterval(() => {
|
|
473
|
+
this.runOnce().catch(() => {});
|
|
474
|
+
}, this.intervalMs);
|
|
475
|
+
this.timer.unref?.();
|
|
476
|
+
return this;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
stop() {
|
|
480
|
+
if (this.timer) clearInterval(this.timer);
|
|
481
|
+
this.timer = null;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
export { discoverLocalRuntimes, toConfigPatch, isLoopback, DEFAULT_PORTS } from './local.js';
|
package/src/local.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @drsamonline/prober/local — B2.6, finding a model server on this machine.
|
|
3
|
+
*
|
|
4
|
+
* People run Ollama, LM Studio, llama.cpp, vLLM or LocalAI and then hand-write a
|
|
5
|
+
* provider block for it. This finds it instead: probe the ports those servers
|
|
6
|
+
* use, ask each one what it serves, and report what is actually there.
|
|
7
|
+
*
|
|
8
|
+
* Safety is the design constraint, not a detail:
|
|
9
|
+
*
|
|
10
|
+
* - **Loopback only.** `127.0.0.1`, `::1` and `localhost` and nothing else. A
|
|
11
|
+
* scan that could reach the network is a port scanner, and shipping one
|
|
12
|
+
* inside a gateway is how a helpful feature becomes a liability.
|
|
13
|
+
* - **No credentials, no writes.** Every request is an unauthenticated GET of a
|
|
14
|
+
* public listing endpoint. Discovery changes nothing on the server.
|
|
15
|
+
* - **Short timeouts.** A closed port must cost milliseconds, not the request
|
|
16
|
+
* budget. Default 300ms, and a scan of the whole port list stays under a
|
|
17
|
+
* second in parallel.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { get } from 'node:http';
|
|
21
|
+
|
|
22
|
+
/** Ports these servers use by default. */
|
|
23
|
+
export const DEFAULT_PORTS = [11434, 1234, 8080, 5000, 8000, 3000, 11435];
|
|
24
|
+
|
|
25
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
|
|
26
|
+
|
|
27
|
+
/** @param {string} host */
|
|
28
|
+
export function isLoopback(host) {
|
|
29
|
+
return LOOPBACK.has(String(host).trim().toLowerCase());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The two shapes worth asking for: Ollama's native API, and the OpenAI-compatible one. */
|
|
33
|
+
const PROBES = [
|
|
34
|
+
{ path: '/api/tags', kind: 'ollama', shape: (json) => (json?.models ?? []).map((m) => m.name).filter(Boolean) },
|
|
35
|
+
{ path: '/v1/models', kind: 'openai-compatible', shape: (json) => (json?.data ?? []).map((m) => m.id).filter(Boolean) },
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* One unauthenticated GET, with a hard socket timeout.
|
|
40
|
+
*
|
|
41
|
+
* `node:http` rather than `fetch`, deliberately: a loopback probe wants a socket
|
|
42
|
+
* with a deadline, and a `fetch` AbortSignal turned out to abort instantly under
|
|
43
|
+
* a proxy environment — a bug that made every probe report "nothing here".
|
|
44
|
+
*
|
|
45
|
+
* @param {string} url
|
|
46
|
+
* @param {number} timeoutMs
|
|
47
|
+
* @returns {Promise<any>}
|
|
48
|
+
*/
|
|
49
|
+
function getJson(url, timeoutMs) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const req = get(url, { headers: { accept: 'application/json' }, timeout: timeoutMs }, (res) => {
|
|
52
|
+
if (res.statusCode !== 200) {
|
|
53
|
+
res.resume();
|
|
54
|
+
reject(new Error(`status ${res.statusCode}`));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let body = '';
|
|
58
|
+
res.setEncoding('utf8');
|
|
59
|
+
res.on('data', (chunk) => {
|
|
60
|
+
body += chunk;
|
|
61
|
+
if (body.length > 1_000_000) req.destroy(new Error('response too large'));
|
|
62
|
+
});
|
|
63
|
+
res.on('end', () => {
|
|
64
|
+
try {
|
|
65
|
+
resolve(JSON.parse(body));
|
|
66
|
+
} catch {
|
|
67
|
+
reject(new Error('not JSON'));
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
72
|
+
req.on('error', reject);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {{host?: string, port: number, timeoutMs?: number}} opts
|
|
78
|
+
*/
|
|
79
|
+
async function probePort(opts) {
|
|
80
|
+
const host = opts.host ?? '127.0.0.1';
|
|
81
|
+
if (!isLoopback(host)) {
|
|
82
|
+
throw new Error(`Refusing to probe "${host}": local discovery is loopback-only.`);
|
|
83
|
+
}
|
|
84
|
+
const timeoutMs = Number(opts.timeoutMs ?? 300);
|
|
85
|
+
const started = Date.now();
|
|
86
|
+
|
|
87
|
+
for (const probe of PROBES) {
|
|
88
|
+
try {
|
|
89
|
+
const json = await getJson(`http://${host}:${opts.port}${probe.path}`, timeoutMs);
|
|
90
|
+
const models = probe.shape(json);
|
|
91
|
+
if (!models.length && probe.kind === 'openai-compatible') continue;
|
|
92
|
+
return {
|
|
93
|
+
kind: probe.kind,
|
|
94
|
+
host,
|
|
95
|
+
port: opts.port,
|
|
96
|
+
baseUrl: `http://${host}:${opts.port}${probe.kind === 'ollama' ? '' : '/v1'}`,
|
|
97
|
+
models,
|
|
98
|
+
latencyMs: Date.now() - started,
|
|
99
|
+
};
|
|
100
|
+
} catch {
|
|
101
|
+
// a closed port, a timeout, or something that is not a model server
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Scan the loopback ports in parallel and return whatever answered.
|
|
109
|
+
*
|
|
110
|
+
* @param {{hosts?: string[], ports?: number[], timeoutMs?: number}} [opts]
|
|
111
|
+
*/
|
|
112
|
+
export async function discoverLocalRuntimes(opts = {}) {
|
|
113
|
+
const hosts = opts.hosts ?? ['127.0.0.1'];
|
|
114
|
+
for (const host of hosts) {
|
|
115
|
+
if (!isLoopback(host)) throw new Error(`Refusing to probe "${host}": local discovery is loopback-only.`);
|
|
116
|
+
}
|
|
117
|
+
const ports = opts.ports ?? DEFAULT_PORTS;
|
|
118
|
+
|
|
119
|
+
const results = await Promise.all(
|
|
120
|
+
hosts.flatMap((host) => ports.map((port) => probePort({ host, port, timeoutMs: opts.timeoutMs }))),
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
return results.filter(Boolean).sort((a, b) => a.port - b.port);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Turn a discovery result into the config fragments Sui needs: one provider, one
|
|
128
|
+
* model per served model, and a combo that routes to them.
|
|
129
|
+
*
|
|
130
|
+
* The ids are derived from the kind and the model name, so running discovery
|
|
131
|
+
* twice produces the same ids and the merge stays a no-op.
|
|
132
|
+
*
|
|
133
|
+
* @param {{kind: string, baseUrl: string, models: string[]}} found
|
|
134
|
+
*/
|
|
135
|
+
export function toConfigPatch(found) {
|
|
136
|
+
const providerId = found.kind === 'ollama' ? 'ollama' : 'local-openai';
|
|
137
|
+
const provider = {
|
|
138
|
+
type: 'openai',
|
|
139
|
+
baseUrl: found.baseUrl,
|
|
140
|
+
apiKeyEnv: null,
|
|
141
|
+
tier: 'free',
|
|
142
|
+
privacy: { retention: 'none', trainsOnData: false },
|
|
143
|
+
label: found.kind === 'ollama' ? 'Ollama (local)' : 'Local OpenAI-compatible server',
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** @type {Record<string, any>} */
|
|
147
|
+
const models = {};
|
|
148
|
+
/** @type {string[]} */
|
|
149
|
+
const targets = [];
|
|
150
|
+
for (const model of found.models) {
|
|
151
|
+
const id = `${providerId}-${String(model).replace(/[^a-zA-Z0-9._-]+/g, '-').toLowerCase()}`;
|
|
152
|
+
models[id] = { provider: providerId, model, costPer1kIn: 0, costPer1kOut: 0, quality: 3, tier: 'free' };
|
|
153
|
+
targets.push(id);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
providers: { [providerId]: provider },
|
|
158
|
+
models,
|
|
159
|
+
combos: targets.length ? { local: { label: 'Local', strategy: 'fallback', targets } } : {},
|
|
160
|
+
};
|
|
161
|
+
}
|
package/README.md
DELETED