dsh-harness-reflex 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -6
- package/client.js +3511 -185
- package/dist/attribution.d.ts +266 -0
- package/dist/attribution.js +238 -0
- package/dist/attribution.js.map +1 -0
- package/dist/bridge.d.ts +311 -13
- package/dist/bridge.js +714 -42
- package/dist/bridge.js.map +1 -1
- package/dist/client-bundle.js +4 -1
- package/dist/client-bundle.js.map +1 -1
- package/dist/command.js +10 -0
- package/dist/command.js.map +1 -1
- package/dist/config.d.ts +530 -22
- package/dist/config.js +808 -27
- package/dist/config.js.map +1 -1
- package/dist/delegation-dispatch.d.ts +132 -0
- package/dist/delegation-dispatch.js +186 -0
- package/dist/delegation-dispatch.js.map +1 -0
- package/dist/delegation-health.d.ts +131 -0
- package/dist/delegation-health.js +97 -0
- package/dist/delegation-health.js.map +1 -0
- package/dist/delegation.d.ts +148 -0
- package/dist/delegation.js +186 -0
- package/dist/delegation.js.map +1 -0
- package/dist/effort-delegation.d.ts +144 -0
- package/dist/effort-delegation.js +280 -0
- package/dist/effort-delegation.js.map +1 -0
- package/dist/effort.d.ts +141 -0
- package/dist/effort.js +251 -9
- package/dist/effort.js.map +1 -1
- package/dist/host-patch.d.ts +156 -0
- package/dist/host-patch.js +534 -0
- package/dist/host-patch.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +99 -7
- package/dist/index.js.map +1 -1
- package/dist/interventions.d.ts +98 -373
- package/dist/interventions.js +442 -1702
- package/dist/interventions.js.map +1 -1
- package/dist/panel-api.d.ts +328 -4
- package/dist/panel-api.js +322 -15
- package/dist/panel-api.js.map +1 -1
- package/dist/panel-mount.d.ts +81 -22
- package/dist/panel-mount.js +228 -7
- package/dist/panel-mount.js.map +1 -1
- package/dist/routing.d.ts +23 -18
- package/dist/routing.js +471 -153
- package/dist/routing.js.map +1 -1
- package/dist/session-audit.d.ts +70 -0
- package/dist/session-audit.js +73 -0
- package/dist/session-audit.js.map +1 -1
- package/dist/systemone-probe.d.ts +114 -0
- package/dist/systemone-probe.js +383 -0
- package/dist/systemone-probe.js.map +1 -0
- package/dist/testing.d.ts +212 -7
- package/dist/testing.js +333 -27
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +109 -3
- package/dist/tools.js +103 -4
- package/dist/tools.js.map +1 -1
- package/dist/unconfigured-backend.d.ts +72 -0
- package/dist/unconfigured-backend.js +94 -0
- package/dist/unconfigured-backend.js.map +1 -0
- package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
- package/dist/vendor/harness-reflex/backend/factory.js +18 -3
- package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
- package/dist/vendor/harness-reflex/backend/jev.js +11 -4
- package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
- package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
- package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
- package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
- package/dist/vendor/harness-reflex/core/closing.js +111 -0
- package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
- package/dist/vendor/harness-reflex/core/evidence.js +209 -0
- package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
- package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
- package/dist/vendor/harness-reflex/core/judge.js +251 -0
- package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
- package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
- package/dist/vendor/harness-reflex/core/policy.js +102 -0
- package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
- package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
- package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
- package/dist/vendor/harness-reflex/core/text.js +66 -0
- package/dist/vendor/harness-reflex/core/text.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
- package/dist/vendor/harness-reflex/ports/audit.js +11 -0
- package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/clock.js +11 -0
- package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
- package/dist/vendor/harness-reflex/ports/decision.js +2 -0
- package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/index.js +2 -0
- package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
- package/dist/vendor/harness-reflex/ports/log.js +12 -0
- package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
- package/dist/vendor/harness-reflex/ports/state.js +13 -0
- package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
- package/package.json +25 -13
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side connection test for one System One profile.
|
|
3
|
+
*
|
|
4
|
+
* The panel's "Test" button needs to know *why* a connection fails — a wrong key
|
|
5
|
+
* and an unreachable host are the same red dot to a user and completely
|
|
6
|
+
* different fixes. Passive health (what {@link ReflexRuntime.systemOneHealth}
|
|
7
|
+
* reports) cannot answer that: it only observes calls the runtime happened to
|
|
8
|
+
* make. This module makes one deliberately small, real request and classifies
|
|
9
|
+
* the outcome.
|
|
10
|
+
*
|
|
11
|
+
* Design rules this module keeps:
|
|
12
|
+
*
|
|
13
|
+
* - **The key never leaves this process.** It is read here from the resolved
|
|
14
|
+
* profile and placed in an `Authorization` header; nothing derived from it —
|
|
15
|
+
* not the header, not the key, not a prefix of it — is returned. Every string
|
|
16
|
+
* that reaches the caller passes through {@link redact}.
|
|
17
|
+
* - **Bounded.** The probe uses the profile's own `timeoutMs`, clamped to
|
|
18
|
+
* {@link PROBE_TIMEOUT_MAX_MS}, and additionally guards with its own timer, so
|
|
19
|
+
* a host whose `fetch` ignores the abort signal still cannot hang the route.
|
|
20
|
+
* An in-flight probe is abortable so a closed panel does not leave one behind.
|
|
21
|
+
* - **Minimal payload.** The probe sends the same one-endpoint `choice` shape
|
|
22
|
+
* the runtime sends, with one question of two criteria — a real decision, so
|
|
23
|
+
* the answer distinguishes "authenticated" from "reachable but misconfigured".
|
|
24
|
+
* It does **not** call a models-list route: the Jev gateways this plugin
|
|
25
|
+
* targets serve `POST /v1/systemone` and have no models route, so a models
|
|
26
|
+
* probe would report "unreachable" for a perfectly working deployment.
|
|
27
|
+
*
|
|
28
|
+
* @module dsh-reflex/systemone-probe
|
|
29
|
+
*/
|
|
30
|
+
import { connectionImplementation, resolveApiKeyWithSource, resolvedKeyOf } from './config.js';
|
|
31
|
+
import { normalizeSystemOneEndpoint } from './vendor/harness-reflex/backend/jev.js';
|
|
32
|
+
/** Model the Jev gateway serves when nothing overrides it (mirrors the vendor backend). */
|
|
33
|
+
const JEV_DEFAULT_MODEL = 'jev-latest';
|
|
34
|
+
/** Jev has no default key: an absent one is simply not sent. */
|
|
35
|
+
const JEV_DEFAULT_API_KEY = '';
|
|
36
|
+
/** Per-request timeout the vendor Jev backend falls back to, in milliseconds. */
|
|
37
|
+
const JEV_DEFAULT_TIMEOUT_MS = 10_000;
|
|
38
|
+
/** Model a local vLLM is asked for when nothing overrides it. */
|
|
39
|
+
const LOGITS_DEFAULT_MODEL = 'Qwen/Qwen2.5-7B-Instruct';
|
|
40
|
+
/** A local vLLM usually checks no credentials, so a placeholder keeps the header well-formed. */
|
|
41
|
+
const LOGITS_DEFAULT_API_KEY = 'dummy';
|
|
42
|
+
/** Longest a probe may take, whatever the profile asks for. */
|
|
43
|
+
export const PROBE_TIMEOUT_MAX_MS = 15_000;
|
|
44
|
+
/** Shortest accepted probe timeout; below this a healthy gateway looks like a timeout. */
|
|
45
|
+
export const PROBE_TIMEOUT_MIN_MS = 250;
|
|
46
|
+
/**
|
|
47
|
+
* Remove every credential-shaped substring from one diagnostic line.
|
|
48
|
+
*
|
|
49
|
+
* Belt and braces: callers are expected never to put a key in a detail string in
|
|
50
|
+
* the first place, and this makes an accidental one invisible rather than
|
|
51
|
+
* broadcast. It also flattens newlines so a gateway's multi-line error page
|
|
52
|
+
* cannot break the panel's single-line rendering.
|
|
53
|
+
*
|
|
54
|
+
* @param text - raw text, possibly from a remote server.
|
|
55
|
+
* @param secrets - values that must not appear (the key, the header value).
|
|
56
|
+
* @returns the sanitized single-line text.
|
|
57
|
+
*/
|
|
58
|
+
export function redact(text, secrets = []) {
|
|
59
|
+
let out = String(text ?? '');
|
|
60
|
+
for (const secret of secrets) {
|
|
61
|
+
if (typeof secret !== 'string' || secret.length === 0)
|
|
62
|
+
continue;
|
|
63
|
+
out = out.split(secret).join('***');
|
|
64
|
+
}
|
|
65
|
+
// Any Bearer token that survived (a server echoing headers, say).
|
|
66
|
+
out = out.replace(/Bearer\s+[^\s"',;}]+/gi, 'Bearer ***');
|
|
67
|
+
// Common key shapes, in case a server echoed a *different* credential.
|
|
68
|
+
out = out.replace(/\b(sk|pk|key)-[A-Za-z0-9._-]{6,}/g, '$1-***');
|
|
69
|
+
out = out.replace(/\s+/g, ' ').trim();
|
|
70
|
+
return out.length > 240 ? `${out.slice(0, 237)}...` : out;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Whether a URL is safe to report: it must carry no inline credentials.
|
|
74
|
+
* @param url - the endpoint.
|
|
75
|
+
* @returns the URL without a userinfo component, or `undefined` when unparseable.
|
|
76
|
+
*/
|
|
77
|
+
function safeUrl(url) {
|
|
78
|
+
try {
|
|
79
|
+
const parsed = new URL(url);
|
|
80
|
+
parsed.username = '';
|
|
81
|
+
parsed.password = '';
|
|
82
|
+
parsed.search = '';
|
|
83
|
+
return parsed.toString();
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Build the request one probe sends for a target.
|
|
91
|
+
*
|
|
92
|
+
* Exported so the endpoint's shape is pinned by a test rather than reimplemented
|
|
93
|
+
* in a stub server's expectations.
|
|
94
|
+
* @param target - the projected profile.
|
|
95
|
+
* @param env - environment the `apiKeyEnv` indirection reads.
|
|
96
|
+
* @returns the request spec, or a `status` describing why none can be built.
|
|
97
|
+
*/
|
|
98
|
+
export function buildProbeRequest(target, env = process.env) {
|
|
99
|
+
// The *runtime's* implementation resolver, not a second opinion (g-067 att-002):
|
|
100
|
+
// `auto` is decided from the environment by the vendored factory the runtime
|
|
101
|
+
// builds, so the probe asks that same precedence instead of assuming Jev. A
|
|
102
|
+
// hard-coded `auto → jev` here is how the test button once reported green on
|
|
103
|
+
// the official URL while the runtime dialled a vLLM endpoint.
|
|
104
|
+
const backend = connectionImplementation(target.backend, env);
|
|
105
|
+
const timeoutMs = clampTimeout(target.timeoutMs);
|
|
106
|
+
if (backend === 'mock') {
|
|
107
|
+
return {
|
|
108
|
+
status: 'misconfigured',
|
|
109
|
+
detail: `this profile resolves to the ${target.backend === 'mock' ? '' : 'auto-selected '}mock backend: there is no remote endpoint to test`
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
// A connection whose selected model cannot be sent is refused here, before the
|
|
113
|
+
// key is read and long before any address is used: the runtime builds no
|
|
114
|
+
// transport for it either, so a probe that sent something would report on a
|
|
115
|
+
// request nobody can make (g-066 att-002).
|
|
116
|
+
if (target.modelUnusable === true) {
|
|
117
|
+
return {
|
|
118
|
+
status: 'model-unusable',
|
|
119
|
+
detail: 'the selected model is not in this profile\'s model list, so nothing runs and there is nothing to test'
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
// The key follows the runtime's chain exactly — {@link resolveApiKeyWithSource}
|
|
123
|
+
// is the one implementation of it, so a "test connection" button can never send
|
|
124
|
+
// a different credential from the one the real request would send. A named
|
|
125
|
+
// variable that is empty (g-059) resolves to no key here too: the probe sends
|
|
126
|
+
// an unauthenticated request, exactly as the real one does, so a locked
|
|
127
|
+
// deployment's test button reports the 401 instead of a false green.
|
|
128
|
+
const key = resolvedKeyOf(resolveApiKeyWithSource(target, env));
|
|
129
|
+
if (backend === 'vllm') {
|
|
130
|
+
const base = (target.baseUrl ?? '').trim().replace(/\/+$/, '');
|
|
131
|
+
if (base.length === 0) {
|
|
132
|
+
return { status: 'misconfigured', detail: 'a vllm profile needs a baseUrl (e.g. http://localhost:8000)' };
|
|
133
|
+
}
|
|
134
|
+
const model = target.model ?? LOGITS_DEFAULT_MODEL;
|
|
135
|
+
const authorization = `Bearer ${key ?? LOGITS_DEFAULT_API_KEY}`;
|
|
136
|
+
return {
|
|
137
|
+
spec: {
|
|
138
|
+
url: `${base}/v1/completions`,
|
|
139
|
+
method: 'POST',
|
|
140
|
+
authorization,
|
|
141
|
+
// One token, no sampling: the cheapest request that still proves the
|
|
142
|
+
// model answers and the key is accepted.
|
|
143
|
+
body: JSON.stringify({ model, prompt: 'ok', max_tokens: 1, temperature: 0, stream: false }),
|
|
144
|
+
timeoutMs
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
const model = target.model ?? JEV_DEFAULT_MODEL;
|
|
149
|
+
const keyText = key === undefined || key.length === 0 ? JEV_DEFAULT_API_KEY : key;
|
|
150
|
+
// `normalizeSystemOneEndpoint` appends the path for us; the only unusable case
|
|
151
|
+
// is a baseUrl the normalizer cannot turn into an absolute URL at all.
|
|
152
|
+
const url = normalizeSystemOneEndpoint(target.baseUrl);
|
|
153
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
154
|
+
return { status: 'misconfigured', detail: `baseUrl must be an absolute http(s) URL (resolved to "${url}")` };
|
|
155
|
+
}
|
|
156
|
+
const body = JSON.stringify({
|
|
157
|
+
model,
|
|
158
|
+
state: { probe: true },
|
|
159
|
+
questions: {
|
|
160
|
+
probe: {
|
|
161
|
+
type: 'choice',
|
|
162
|
+
instructions: 'Answer whether this connection works. Either criterion is acceptable.',
|
|
163
|
+
criteria: { yes: 'The connection works.', no: 'The connection does not work.' }
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
return {
|
|
168
|
+
spec: {
|
|
169
|
+
url,
|
|
170
|
+
method: 'POST',
|
|
171
|
+
...(keyText.length > 0 ? { authorization: `Bearer ${keyText}` } : {}),
|
|
172
|
+
body,
|
|
173
|
+
timeoutMs
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Clamp one profile's timeout onto the probe's accepted range.
|
|
179
|
+
* @param timeoutMs - authored per-request timeout.
|
|
180
|
+
* @returns a bounded timeout.
|
|
181
|
+
*/
|
|
182
|
+
export function clampTimeout(timeoutMs) {
|
|
183
|
+
if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs))
|
|
184
|
+
return JEV_DEFAULT_TIMEOUT_MS;
|
|
185
|
+
return Math.min(PROBE_TIMEOUT_MAX_MS, Math.max(PROBE_TIMEOUT_MIN_MS, Math.floor(timeoutMs)));
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Map a rejection from `fetch` onto a probe status.
|
|
189
|
+
* @param error - the thrown value.
|
|
190
|
+
* @param elapsedMs - time spent before the failure.
|
|
191
|
+
* @param secrets - values that must not appear in the detail.
|
|
192
|
+
* @param timedOut - whether our own timer fired first.
|
|
193
|
+
* @returns the classified result.
|
|
194
|
+
*/
|
|
195
|
+
function failureResult(error, elapsedMs, secrets, timedOut) {
|
|
196
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
197
|
+
if (timedOut || /abort/i.test(message)) {
|
|
198
|
+
return { ok: false, status: 'timeout', latencyMs: elapsedMs, detail: redact('the request did not complete within the probe timeout', secrets) };
|
|
199
|
+
}
|
|
200
|
+
// A Node `fetch` reports DNS/refused/TLS failures as TypeError('fetch failed')
|
|
201
|
+
// and hides the real cause on `error.cause`.
|
|
202
|
+
const cause = error?.cause;
|
|
203
|
+
const code = cause?.code ?? '';
|
|
204
|
+
const detail = redact([message, cause?.message ?? ''].filter((part) => part.length > 0).join(': ') || 'the request failed', secrets);
|
|
205
|
+
return {
|
|
206
|
+
ok: false,
|
|
207
|
+
status: 'unreachable',
|
|
208
|
+
latencyMs: elapsedMs,
|
|
209
|
+
detail: code.length > 0 ? redact(`${code}: ${detail}`, secrets) : detail
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Classify one HTTP response.
|
|
214
|
+
* @param response - the gateway's response.
|
|
215
|
+
* @param latencyMs - round-trip time to headers.
|
|
216
|
+
* @param secrets - values that must not appear in the detail.
|
|
217
|
+
* @returns the classified result.
|
|
218
|
+
*/
|
|
219
|
+
async function classifyResponse(response, latencyMs, secrets, backend) {
|
|
220
|
+
const status = response.status;
|
|
221
|
+
if (status === 401 || status === 403) {
|
|
222
|
+
// The body of an auth failure is the gateway's own explanation and is the
|
|
223
|
+
// single most useful line a user can read — but it may echo the key back, so
|
|
224
|
+
// it is redacted like everything else.
|
|
225
|
+
const text = await readBodyText(response);
|
|
226
|
+
return {
|
|
227
|
+
ok: false,
|
|
228
|
+
status: 'auth-failed',
|
|
229
|
+
latencyMs,
|
|
230
|
+
httpStatus: status,
|
|
231
|
+
detail: redact(text.length > 0 ? text : `the gateway rejected the API key (HTTP ${String(status)})`, secrets)
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
if (status === 408 || status === 504) {
|
|
235
|
+
return { ok: false, status: 'timeout', latencyMs, httpStatus: status, detail: redact(`the gateway timed out (HTTP ${String(status)})`, secrets) };
|
|
236
|
+
}
|
|
237
|
+
if (status === 404) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
status: 'misconfigured',
|
|
241
|
+
latencyMs,
|
|
242
|
+
httpStatus: status,
|
|
243
|
+
detail: redact('the endpoint path does not exist on that host (HTTP 404): check baseUrl', secrets)
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
if (!response.ok) {
|
|
247
|
+
const text = await readBodyText(response);
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
status: 'bad-response',
|
|
251
|
+
latencyMs,
|
|
252
|
+
httpStatus: status,
|
|
253
|
+
detail: redact(text.length > 0 ? `HTTP ${String(status)}: ${text}` : `HTTP ${String(status)} ${response.statusText}`, secrets)
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
// A 2xx is not yet success: the body must be the envelope the backend can use,
|
|
257
|
+
// otherwise the runtime would fail on the very first real decision.
|
|
258
|
+
const text = await readBodyText(response);
|
|
259
|
+
let parsed;
|
|
260
|
+
try {
|
|
261
|
+
parsed = JSON.parse(text);
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return { ok: false, status: 'bad-response', latencyMs, httpStatus: status, detail: redact('the response was not JSON', secrets) };
|
|
265
|
+
}
|
|
266
|
+
// A 2xx must also carry the envelope the *backend type* will parse: the
|
|
267
|
+
// single-endpoint gateways answer `{ answers }`, while an OpenAI-compatible
|
|
268
|
+
// server answers `{ choices }`. Checking the wrong one would report a working
|
|
269
|
+
// vLLM as broken (and a working Jev gateway as broken by the reverse).
|
|
270
|
+
const shaped = parsed !== null &&
|
|
271
|
+
typeof parsed === 'object' &&
|
|
272
|
+
(backend === 'vllm' ? Array.isArray(parsed.choices) : parsed.answers !== undefined && parsed.answers !== null);
|
|
273
|
+
if (!shaped) {
|
|
274
|
+
return {
|
|
275
|
+
ok: false,
|
|
276
|
+
status: 'bad-response',
|
|
277
|
+
latencyMs,
|
|
278
|
+
httpStatus: status,
|
|
279
|
+
detail: redact(backend === 'vllm'
|
|
280
|
+
? 'the response carries no "choices" list (is this really an OpenAI-compatible endpoint?)'
|
|
281
|
+
: 'the response carries no "answers" envelope (is this really a System One endpoint?)', secrets)
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
return { ok: true, status: 'ok', latencyMs, httpStatus: status };
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Read at most a bounded slice of a response body.
|
|
288
|
+
* @param response - the response.
|
|
289
|
+
* @returns its text, truncated.
|
|
290
|
+
*/
|
|
291
|
+
async function readBodyText(response) {
|
|
292
|
+
try {
|
|
293
|
+
const text = await response.text();
|
|
294
|
+
return text.length > 500 ? `${text.slice(0, 500)}…` : text;
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return '';
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The `model` of one built request body.
|
|
302
|
+
* @param body - the JSON the spec sends.
|
|
303
|
+
* @returns the model id, or `undefined` when the body carries none.
|
|
304
|
+
*/
|
|
305
|
+
function modelOfSpec(body) {
|
|
306
|
+
try {
|
|
307
|
+
const parsed = JSON.parse(body);
|
|
308
|
+
const model = parsed?.model;
|
|
309
|
+
return typeof model === 'string' && model.length > 0 ? model : undefined;
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return undefined;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Probe one System One connection.
|
|
317
|
+
*
|
|
318
|
+
* Never throws: every failure is classified, because a test button that reports
|
|
319
|
+
* "the handler threw" is less useful than one that reports "timed out after
|
|
320
|
+
* 8000 ms".
|
|
321
|
+
*
|
|
322
|
+
* @param target - the projected profile to test.
|
|
323
|
+
* @param options - environment, seams, and a cancellation signal.
|
|
324
|
+
* @returns the classified result, with bounded latency and redacted detail.
|
|
325
|
+
*/
|
|
326
|
+
export async function probeSystemOne(target, options = {}) {
|
|
327
|
+
const env = options.env ?? process.env;
|
|
328
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
329
|
+
const now = options.now ?? (() => performance.now());
|
|
330
|
+
const built = buildProbeRequest(target, env);
|
|
331
|
+
if (!('spec' in built))
|
|
332
|
+
return { ok: false, status: built.status, latencyMs: 0, detail: redact(built.detail) };
|
|
333
|
+
const { spec } = built;
|
|
334
|
+
// Everything the detail must never echo.
|
|
335
|
+
const secrets = [target.apiKey, spec.authorization];
|
|
336
|
+
const endpoint = safeUrl(spec.url);
|
|
337
|
+
// The implementation the request was actually built for (g-067 att-002): the
|
|
338
|
+
// success-envelope check below must look for the protocol that spec speaks, and
|
|
339
|
+
// a `mock` target never reaches this point.
|
|
340
|
+
const backend = connectionImplementation(target.backend, env) === 'vllm' ? 'vllm' : 'jev';
|
|
341
|
+
// The model the request *carries*, read back out of the built body rather than
|
|
342
|
+
// recomputed: a second `?? DEFAULT` here could name a model the spec does not
|
|
343
|
+
// send (g-066 att-002).
|
|
344
|
+
const model = modelOfSpec(spec.body) ?? (backend === 'vllm' ? LOGITS_DEFAULT_MODEL : JEV_DEFAULT_MODEL);
|
|
345
|
+
const controller = new AbortController();
|
|
346
|
+
let timedOut = false;
|
|
347
|
+
const timer = setTimeout(() => {
|
|
348
|
+
timedOut = true;
|
|
349
|
+
controller.abort();
|
|
350
|
+
}, spec.timeoutMs);
|
|
351
|
+
const onOuterAbort = () => controller.abort();
|
|
352
|
+
options.signal?.addEventListener('abort', onOuterAbort, { once: true });
|
|
353
|
+
if (options.signal?.aborted === true)
|
|
354
|
+
controller.abort();
|
|
355
|
+
const started = now();
|
|
356
|
+
try {
|
|
357
|
+
const response = await fetchImpl(spec.url, {
|
|
358
|
+
method: spec.method,
|
|
359
|
+
headers: {
|
|
360
|
+
'Content-Type': 'application/json',
|
|
361
|
+
...(spec.authorization === undefined ? {} : { Authorization: spec.authorization })
|
|
362
|
+
},
|
|
363
|
+
body: spec.body,
|
|
364
|
+
signal: controller.signal
|
|
365
|
+
});
|
|
366
|
+
const latencyMs = Math.max(0, Math.round(now() - started));
|
|
367
|
+
const classified = await classifyResponse(response, latencyMs, secrets, backend);
|
|
368
|
+
return {
|
|
369
|
+
...classified,
|
|
370
|
+
model,
|
|
371
|
+
...(endpoint === undefined ? {} : { endpoint })
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
const latencyMs = Math.max(0, Math.round(now() - started));
|
|
376
|
+
return { ...failureResult(error, latencyMs, secrets, timedOut), model, ...(endpoint === undefined ? {} : { endpoint }) };
|
|
377
|
+
}
|
|
378
|
+
finally {
|
|
379
|
+
clearTimeout(timer);
|
|
380
|
+
options.signal?.removeEventListener('abort', onOuterAbort);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
//# sourceMappingURL=systemone-probe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"systemone-probe.js","sourceRoot":"","sources":["../src/systemone-probe.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;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C,OAAO,EAAE,YAAY,CAAC,CAAC;IAC7D,CAAC;AACH,CAAC","sourcesContent":["/**\n * Server-side connection test for one System One profile.\n *\n * The panel's \"Test\" button needs to know *why* a connection fails — a wrong key\n * and an unreachable host are the same red dot to a user and completely\n * different fixes. Passive health (what {@link ReflexRuntime.systemOneHealth}\n * reports) cannot answer that: it only observes calls the runtime happened to\n * make. This module makes one deliberately small, real request and classifies\n * the outcome.\n *\n * Design rules this module keeps:\n *\n * - **The key never leaves this process.** It is read here from the resolved\n * profile and placed in an `Authorization` header; nothing derived from it —\n * not the header, not the key, not a prefix of it — is returned. Every string\n * that reaches the caller passes through {@link redact}.\n * - **Bounded.** The probe uses the profile's own `timeoutMs`, clamped to\n * {@link PROBE_TIMEOUT_MAX_MS}, and additionally guards with its own timer, so\n * a host whose `fetch` ignores the abort signal still cannot hang the route.\n * An in-flight probe is abortable so a closed panel does not leave one behind.\n * - **Minimal payload.** The probe sends the same one-endpoint `choice` shape\n * the runtime sends, with one question of two criteria — a real decision, so\n * the answer distinguishes \"authenticated\" from \"reachable but misconfigured\".\n * It does **not** call a models-list route: the Jev gateways this plugin\n * targets serve `POST /v1/systemone` and have no models route, so a models\n * probe would report \"unreachable\" for a perfectly working deployment.\n *\n * @module dsh-reflex/systemone-probe\n */\nimport { connectionImplementation, resolveApiKeyWithSource, resolvedKeyOf } from './config.js';\nimport { normalizeSystemOneEndpoint } from './vendor/harness-reflex/backend/jev.js';\n\n/** Model the Jev gateway serves when nothing overrides it (mirrors the vendor backend). */\nconst JEV_DEFAULT_MODEL = 'jev-latest';\n/** Jev has no default key: an absent one is simply not sent. */\nconst JEV_DEFAULT_API_KEY = '';\n/** Per-request timeout the vendor Jev backend falls back to, in milliseconds. */\nconst JEV_DEFAULT_TIMEOUT_MS = 10_000;\n/** Model a local vLLM is asked for when nothing overrides it. */\nconst LOGITS_DEFAULT_MODEL = 'Qwen/Qwen2.5-7B-Instruct';\n/** A local vLLM usually checks no credentials, so a placeholder keeps the header well-formed. */\nconst LOGITS_DEFAULT_API_KEY = 'dummy';\n\n/** Longest a probe may take, whatever the profile asks for. */\nexport const PROBE_TIMEOUT_MAX_MS = 15_000;\n\n/** Shortest accepted probe timeout; below this a healthy gateway looks like a timeout. */\nexport const PROBE_TIMEOUT_MIN_MS = 250;\n\n/**\n * The outcome classes a probe distinguishes.\n *\n * Four states, because they map onto four different user actions:\n * `ok` → nothing to do; `auth-failed` → the key is wrong; `unreachable` → the\n * address (or this machine's network) is wrong; `timeout` → the gateway is slow\n * or the limit is too tight; `bad-response` → something speaks HTTP there but\n * not the protocol this plugin expects; `misconfigured` → the plugin cannot even\n * build a request (no URL for the backend type it resolved).\n */\nexport type ProbeStatus =\n | 'ok'\n | 'auth-failed'\n | 'unreachable'\n | 'timeout'\n | 'bad-response'\n | 'misconfigured'\n | 'model-unusable';\n\n/** What one probe answers. */\nexport interface ProbeResult {\n ok: boolean;\n status: ProbeStatus;\n /** Real round-trip time from request start to response headers, or the elapsed time of the failure. */\n latencyMs: number;\n /** HTTP status, when a response arrived. */\n httpStatus?: number;\n /** Redacted, single-line explanation. Never contains the key or the header. */\n detail?: string;\n /** Model the probe asked for. */\n model?: string;\n /** Endpoint that was contacted. Contains no credentials (URLs are checked). */\n endpoint?: string;\n}\n\n/** The connection facts one probe needs: a projected profile, never the whole config. */\nexport interface ProbeTarget {\n /** Profile name, for the detail line only. */\n name: string;\n backend: string;\n baseUrl?: string;\n model?: string;\n apiKeyEnv?: string;\n /** The key to present; read by this module and never returned. */\n apiKey?: string;\n timeoutMs?: number;\n /**\n * This connection's model cannot be sent (g-066 att-002), so there is nothing\n * honest to test: the probe reports it instead of guessing a model. Only ever\n * set, never inferred — a target without it carries the model it means.\n */\n modelUnusable?: boolean;\n}\n\n/** Options of one probe. */\nexport interface ProbeOptions {\n /** Environment the `apiKeyEnv` indirection reads. */\n env?: Record<string, string | undefined>;\n /** `fetch` seam for tests. */\n fetch?: typeof fetch;\n /** Clock seam for tests. */\n now?: () => number;\n /** Signal that cancels the probe (panel closed, route disposed). */\n signal?: AbortSignal;\n}\n\n/** What one endpoint probe sends. */\nexport interface ProbeRequestSpec {\n url: string;\n method: 'POST';\n /** Authorization header value, or `undefined` when no key is configured. */\n authorization?: string;\n body: string;\n timeoutMs: number;\n}\n\n/**\n * Remove every credential-shaped substring from one diagnostic line.\n *\n * Belt and braces: callers are expected never to put a key in a detail string in\n * the first place, and this makes an accidental one invisible rather than\n * broadcast. It also flattens newlines so a gateway's multi-line error page\n * cannot break the panel's single-line rendering.\n *\n * @param text - raw text, possibly from a remote server.\n * @param secrets - values that must not appear (the key, the header value).\n * @returns the sanitized single-line text.\n */\nexport function redact(text: string, secrets: readonly (string | undefined)[] = []): string {\n let out = String(text ?? '');\n for (const secret of secrets) {\n if (typeof secret !== 'string' || secret.length === 0) continue;\n out = out.split(secret).join('***');\n }\n // Any Bearer token that survived (a server echoing headers, say).\n out = out.replace(/Bearer\\s+[^\\s\"',;}]+/gi, 'Bearer ***');\n // Common key shapes, in case a server echoed a *different* credential.\n out = out.replace(/\\b(sk|pk|key)-[A-Za-z0-9._-]{6,}/g, '$1-***');\n out = out.replace(/\\s+/g, ' ').trim();\n return out.length > 240 ? `${out.slice(0, 237)}...` : out;\n}\n\n/**\n * Whether a URL is safe to report: it must carry no inline credentials.\n * @param url - the endpoint.\n * @returns the URL without a userinfo component, or `undefined` when unparseable.\n */\nfunction safeUrl(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n parsed.username = '';\n parsed.password = '';\n parsed.search = '';\n return parsed.toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build the request one probe sends for a target.\n *\n * Exported so the endpoint's shape is pinned by a test rather than reimplemented\n * in a stub server's expectations.\n * @param target - the projected profile.\n * @param env - environment the `apiKeyEnv` indirection reads.\n * @returns the request spec, or a `status` describing why none can be built.\n */\nexport function buildProbeRequest(\n target: ProbeTarget,\n env: Record<string, string | undefined> = process.env\n): { spec: ProbeRequestSpec } | { status: ProbeStatus; detail: string } {\n // The *runtime's* implementation resolver, not a second opinion (g-067 att-002):\n // `auto` is decided from the environment by the vendored factory the runtime\n // builds, so the probe asks that same precedence instead of assuming Jev. A\n // hard-coded `auto → jev` here is how the test button once reported green on\n // the official URL while the runtime dialled a vLLM endpoint.\n const backend = connectionImplementation(target.backend, env);\n const timeoutMs = clampTimeout(target.timeoutMs);\n if (backend === 'mock') {\n return {\n status: 'misconfigured',\n detail: `this profile resolves to the ${target.backend === 'mock' ? '' : 'auto-selected '}mock backend: there is no remote endpoint to test`\n };\n }\n // A connection whose selected model cannot be sent is refused here, before the\n // key is read and long before any address is used: the runtime builds no\n // transport for it either, so a probe that sent something would report on a\n // request nobody can make (g-066 att-002).\n if (target.modelUnusable === true) {\n return {\n status: 'model-unusable',\n detail: 'the selected model is not in this profile\\'s model list, so nothing runs and there is nothing to test'\n };\n }\n // The key follows the runtime's chain exactly — {@link resolveApiKeyWithSource}\n // is the one implementation of it, so a \"test connection\" button can never send\n // a different credential from the one the real request would send. A named\n // variable that is empty (g-059) resolves to no key here too: the probe sends\n // an unauthenticated request, exactly as the real one does, so a locked\n // deployment's test button reports the 401 instead of a false green.\n const key = resolvedKeyOf(resolveApiKeyWithSource(target, env));\n\n if (backend === 'vllm') {\n const base = (target.baseUrl ?? '').trim().replace(/\\/+$/, '');\n if (base.length === 0) {\n return { status: 'misconfigured', detail: 'a vllm profile needs a baseUrl (e.g. http://localhost:8000)' };\n }\n const model = target.model ?? LOGITS_DEFAULT_MODEL;\n const authorization = `Bearer ${key ?? LOGITS_DEFAULT_API_KEY}`;\n return {\n spec: {\n url: `${base}/v1/completions`,\n method: 'POST',\n authorization,\n // One token, no sampling: the cheapest request that still proves the\n // model answers and the key is accepted.\n body: JSON.stringify({ model, prompt: 'ok', max_tokens: 1, temperature: 0, stream: false }),\n timeoutMs\n }\n };\n }\n\n const model = target.model ?? JEV_DEFAULT_MODEL;\n const keyText = key === undefined || key.length === 0 ? JEV_DEFAULT_API_KEY : key;\n // `normalizeSystemOneEndpoint` appends the path for us; the only unusable case\n // is a baseUrl the normalizer cannot turn into an absolute URL at all.\n const url = normalizeSystemOneEndpoint(target.baseUrl);\n if (!/^https?:\\/\\//i.test(url)) {\n return { status: 'misconfigured', detail: `baseUrl must be an absolute http(s) URL (resolved to \"${url}\")` };\n }\n const body = JSON.stringify({\n model,\n state: { probe: true },\n questions: {\n probe: {\n type: 'choice',\n instructions: 'Answer whether this connection works. Either criterion is acceptable.',\n criteria: { yes: 'The connection works.', no: 'The connection does not work.' }\n }\n }\n });\n return {\n spec: {\n url,\n method: 'POST',\n ...(keyText.length > 0 ? { authorization: `Bearer ${keyText}` } : {}),\n body,\n timeoutMs\n }\n };\n}\n\n/**\n * Clamp one profile's timeout onto the probe's accepted range.\n * @param timeoutMs - authored per-request timeout.\n * @returns a bounded timeout.\n */\nexport function clampTimeout(timeoutMs: number | undefined): number {\n if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs)) return JEV_DEFAULT_TIMEOUT_MS;\n return Math.min(PROBE_TIMEOUT_MAX_MS, Math.max(PROBE_TIMEOUT_MIN_MS, Math.floor(timeoutMs)));\n}\n\n/**\n * Map a rejection from `fetch` onto a probe status.\n * @param error - the thrown value.\n * @param elapsedMs - time spent before the failure.\n * @param secrets - values that must not appear in the detail.\n * @param timedOut - whether our own timer fired first.\n * @returns the classified result.\n */\nfunction failureResult(\n error: unknown,\n elapsedMs: number,\n secrets: readonly (string | undefined)[],\n timedOut: boolean\n): ProbeResult {\n const message = error instanceof Error ? error.message : String(error);\n if (timedOut || /abort/i.test(message)) {\n return { ok: false, status: 'timeout', latencyMs: elapsedMs, detail: redact('the request did not complete within the probe timeout', secrets) };\n }\n // A Node `fetch` reports DNS/refused/TLS failures as TypeError('fetch failed')\n // and hides the real cause on `error.cause`.\n const cause = (error as { cause?: { code?: string; message?: string } } | undefined)?.cause;\n const code = cause?.code ?? '';\n const detail = redact(\n [message, cause?.message ?? ''].filter((part) => part.length > 0).join(': ') || 'the request failed',\n secrets\n );\n return {\n ok: false,\n status: 'unreachable',\n latencyMs: elapsedMs,\n detail: code.length > 0 ? redact(`${code}: ${detail}`, secrets) : detail\n };\n}\n\n/**\n * Classify one HTTP response.\n * @param response - the gateway's response.\n * @param latencyMs - round-trip time to headers.\n * @param secrets - values that must not appear in the detail.\n * @returns the classified result.\n */\nasync function classifyResponse(\n response: Response,\n latencyMs: number,\n secrets: readonly (string | undefined)[],\n backend: 'jev' | 'vllm'\n): Promise<ProbeResult> {\n const status = response.status;\n if (status === 401 || status === 403) {\n // The body of an auth failure is the gateway's own explanation and is the\n // single most useful line a user can read — but it may echo the key back, so\n // it is redacted like everything else.\n const text = await readBodyText(response);\n return {\n ok: false,\n status: 'auth-failed',\n latencyMs,\n httpStatus: status,\n detail: redact(text.length > 0 ? text : `the gateway rejected the API key (HTTP ${String(status)})`, secrets)\n };\n }\n if (status === 408 || status === 504) {\n return { ok: false, status: 'timeout', latencyMs, httpStatus: status, detail: redact(`the gateway timed out (HTTP ${String(status)})`, secrets) };\n }\n if (status === 404) {\n return {\n ok: false,\n status: 'misconfigured',\n latencyMs,\n httpStatus: status,\n detail: redact('the endpoint path does not exist on that host (HTTP 404): check baseUrl', secrets)\n };\n }\n if (!response.ok) {\n const text = await readBodyText(response);\n return {\n ok: false,\n status: 'bad-response',\n latencyMs,\n httpStatus: status,\n detail: redact(text.length > 0 ? `HTTP ${String(status)}: ${text}` : `HTTP ${String(status)} ${response.statusText}`, secrets)\n };\n }\n // A 2xx is not yet success: the body must be the envelope the backend can use,\n // otherwise the runtime would fail on the very first real decision.\n const text = await readBodyText(response);\n let parsed: any;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ok: false, status: 'bad-response', latencyMs, httpStatus: status, detail: redact('the response was not JSON', secrets) };\n }\n // A 2xx must also carry the envelope the *backend type* will parse: the\n // single-endpoint gateways answer `{ answers }`, while an OpenAI-compatible\n // server answers `{ choices }`. Checking the wrong one would report a working\n // vLLM as broken (and a working Jev gateway as broken by the reverse).\n const shaped =\n parsed !== null &&\n typeof parsed === 'object' &&\n (backend === 'vllm' ? Array.isArray((parsed as { choices?: unknown }).choices) : (parsed as { answers?: unknown }).answers !== undefined && (parsed as { answers?: unknown }).answers !== null);\n if (!shaped) {\n return {\n ok: false,\n status: 'bad-response',\n latencyMs,\n httpStatus: status,\n detail: redact(\n backend === 'vllm'\n ? 'the response carries no \"choices\" list (is this really an OpenAI-compatible endpoint?)'\n : 'the response carries no \"answers\" envelope (is this really a System One endpoint?)',\n secrets\n )\n };\n }\n return { ok: true, status: 'ok', latencyMs, httpStatus: status };\n}\n\n/**\n * Read at most a bounded slice of a response body.\n * @param response - the response.\n * @returns its text, truncated.\n */\nasync function readBodyText(response: Response): Promise<string> {\n try {\n const text = await response.text();\n return text.length > 500 ? `${text.slice(0, 500)}…` : text;\n } catch {\n return '';\n }\n}\n\n/**\n * The `model` of one built request body.\n * @param body - the JSON the spec sends.\n * @returns the model id, or `undefined` when the body carries none.\n */\nfunction modelOfSpec(body: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(body);\n const model = (parsed as { model?: unknown } | null)?.model;\n return typeof model === 'string' && model.length > 0 ? model : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Probe one System One connection.\n *\n * Never throws: every failure is classified, because a test button that reports\n * \"the handler threw\" is less useful than one that reports \"timed out after\n * 8000 ms\".\n *\n * @param target - the projected profile to test.\n * @param options - environment, seams, and a cancellation signal.\n * @returns the classified result, with bounded latency and redacted detail.\n */\nexport async function probeSystemOne(target: ProbeTarget, options: ProbeOptions = {}): Promise<ProbeResult> {\n const env = options.env ?? process.env;\n const fetchImpl = options.fetch ?? fetch;\n const now = options.now ?? (() => performance.now());\n const built = buildProbeRequest(target, env);\n if (!('spec' in built)) return { ok: false, status: built.status, latencyMs: 0, detail: redact(built.detail) };\n const { spec } = built;\n // Everything the detail must never echo.\n const secrets = [target.apiKey, spec.authorization];\n const endpoint = safeUrl(spec.url);\n // The implementation the request was actually built for (g-067 att-002): the\n // success-envelope check below must look for the protocol that spec speaks, and\n // a `mock` target never reaches this point.\n const backend = connectionImplementation(target.backend, env) === 'vllm' ? 'vllm' : 'jev';\n // The model the request *carries*, read back out of the built body rather than\n // recomputed: a second `?? DEFAULT` here could name a model the spec does not\n // send (g-066 att-002).\n const model = modelOfSpec(spec.body) ?? (backend === 'vllm' ? LOGITS_DEFAULT_MODEL : JEV_DEFAULT_MODEL);\n\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, spec.timeoutMs);\n const onOuterAbort = (): void => controller.abort();\n options.signal?.addEventListener('abort', onOuterAbort, { once: true });\n if (options.signal?.aborted === true) controller.abort();\n\n const started = now();\n try {\n const response = await fetchImpl(spec.url, {\n method: spec.method,\n headers: {\n 'Content-Type': 'application/json',\n ...(spec.authorization === undefined ? {} : { Authorization: spec.authorization })\n },\n body: spec.body,\n signal: controller.signal\n });\n const latencyMs = Math.max(0, Math.round(now() - started));\n const classified = await classifyResponse(response, latencyMs, secrets, backend);\n return {\n ...classified,\n model,\n ...(endpoint === undefined ? {} : { endpoint })\n };\n } catch (error) {\n const latencyMs = Math.max(0, Math.round(now() - started));\n return { ...failureResult(error, latencyMs, secrets, timedOut), model, ...(endpoint === undefined ? {} : { endpoint }) };\n } finally {\n clearTimeout(timer);\n options.signal?.removeEventListener('abort', onOuterAbort);\n }\n}\n"]}
|