UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

591 lines (590 loc) • 30.5 kB
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * Low-level OpenAI-compatible chat completions client and capability probing. * * Keeps transport-layer concerns (HTTP request, response parsing, capability * probing, and availability checks) separate from higher-level workflows. */ import { fetchWithTimeout, readBodyWithByteCap } from "../core/common.js"; import { openAiBaseUrl, openAiOperationUrl } from "../core/endpoint-url.js"; import { formatExtraParamsIssue, validateExtraParams } from "../core/extra-params.js"; import { effectiveRequestFields } from "../core/llm-inference.js"; import { redactErrorBody, redactSensitiveText, redactUrlCredentials } from "../core/redaction.js"; import { warn, warnVerbose } from "../core/warn.js"; import { emitLlmUsage, extractUsageTokens, } from "./usage-telemetry.js"; /** Maximum length of an upstream response excerpt included in thrown errors. */ const ERROR_BODY_MAX_LEN = 200; /** Stable OpenAI-compatible response-schema name used for every structured call. */ const JSON_SCHEMA_RESPONSE_NAME = "akm_response"; /** * Re-exported from src/core/redaction.ts, where it lives so every HTTP * transport can apply the same hardening — the embeddings client needs it too. */ export { redactErrorBody } from "../core/redaction.js"; /** * Detect a response body that is an HTML document rather than the expected * JSON. LM Studio (and similar local providers) can serve their web UI on * partial-load / startup failures, producing an HTML page where the OpenAI * API contract promises JSON. */ function isHtmlResponse(body) { const lower = body.trimStart().toLowerCase(); return lower.startsWith("<!doctype html") || lower.startsWith("<html"); } /** * Produce a short plain-text excerpt of an HTML body for inclusion in error * messages: strip tags, collapse whitespace, and truncate. */ function htmlExcerpt(body) { const text = body .replace(/<[^>]*>/g, " ") .replace(/\s+/g, " ") .trim(); return text.length > ERROR_BODY_MAX_LEN ? `${text.slice(0, ERROR_BODY_MAX_LEN)}…` : text; } export class LlmCallError extends Error { code; statusCode; namesResponseFormat; constructor(message, code, statusCode, /** A 5xx whose body names the response format; set from the whole body, since the message keeps only its first 200 characters. */ namesResponseFormat = false) { super(message); this.code = code; this.statusCode = statusCode; this.namesResponseFormat = namesResponseFormat; this.name = "LlmCallError"; } } // ── Single bounded retry for transient failures ───────────────────────────── /** Lower bound of the jittered retry backoff (inclusive), in milliseconds. */ const RETRY_BACKOFF_MIN_MS = 200; /** Upper bound of the jittered retry backoff (exclusive-ish), in milliseconds. */ const RETRY_BACKOFF_MAX_MS = 800; /** * Fraction of the effective timeout budget that, once consumed by the first * attempt, causes the retry to be skipped — there is not enough budget left * for a meaningful second attempt. */ const RETRY_BUDGET_FRACTION = 0.9; /** * Sleep for `ms` milliseconds. Extracted as a named helper so tests can stub * the backoff via the internal `sleep` option on {@link chatCompletion} and * avoid real delays. */ export function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function waitForRetry(ms, wait, signal) { if (!signal) return wait(ms); if (signal.aborted) throw new LlmCallError("LLM request aborted", "aborted"); await new Promise((resolve, reject) => { const onAbort = () => reject(new LlmCallError("LLM request aborted", "aborted")); signal.addEventListener("abort", onAbort, { once: true }); wait(ms) .then(resolve, reject) .finally(() => signal.removeEventListener("abort", onAbort)); }); } /** Compute a uniform jittered backoff in the [200, 800)ms range. */ function retryBackoffMs() { return RETRY_BACKOFF_MIN_MS + Math.random() * (RETRY_BACKOFF_MAX_MS - RETRY_BACKOFF_MIN_MS); } /** * Detect whether an error message indicates a context size exceeded condition. * Covers common patterns from OpenAI-compatible APIs (LM Studio, Ollama, etc). * * Requires BOTH a context keyword AND token-count/overflow evidence so that * model prose merely mentioning "context size" / "context length" (e.g. gemma * narrating about a document) does not get misclassified as a provider * context-limit error (#496). * * Canonical home: `structured-call.ts`'s failure classifier and the retry * classifier (`isRetryable`) here share one definition — retrying a context * overflow cannot shrink the input, so it must never be retried. */ export function isContextSizeError(message) { const lower = message.toLowerCase(); const contextKw = /context (size|length|window)|prompt too long|exceeds.*context/.test(lower); if (!contextKw) { return false; } const evidence = /\b\d+\s*(token|tokens|tk)\b/.test(lower) || /max(imum)?\s+(context|token|input)/.test(lower) || /exceeded|over.*limit|too.*long/.test(lower); return evidence; } /** * Codes describing a failure to reach or get a usable response from the * provider transport itself, as opposed to a malformed-but-received response * (`parse_error`) or a request-shape rejection (`rate_limited`). Used by * {@link isRetryable}, which additionally requires evidence the failure is * transient. Not exported. */ function isTransportFailure(err) { return err.code === "provider_error" || err.code === "network_error" || err.code === "provider_html_error"; } /** * Decide whether a first-attempt {@link LlmCallError} is eligible for a single * retry. Retryable: HTTP 5xx (`provider_error` with statusCode >= 500) and * `network_error` whose message looks like a transient connection drop. * NOT retryable: 4xx, `rate_limited` (429), `timeout`, `parse_error`, * `provider_html_error`, and context-overflow-classified errors. * * The connection-drop heuristic covers the substrings emitted across runtimes * for a mid-flight socket close: * - `ECONNRESET` / `EPIPE` — Node/libuv socket reset codes * - `fetch failed` — undici's generic wrapper message * - `socket connection was closed` — Bun's message for a dropped connection * (e.g. "The socket connection was closed unexpectedly.") * - `terminated` / `other side closed` — undici's phrasings for the same * * These all describe a transient transport failure where a second attempt can * legitimately succeed, which is exactly the case a single bounded retry is * meant to absorb. Before this list was widened, Bun's "socket connection was * closed unexpectedly" fell through unretried and surfaced as a recurring * failure in the improve/reflect and capability-probe flows. */ function isRetryable(err) { if (isContextSizeError(err.message)) return false; if (!isTransportFailure(err)) return false; if (err.code === "provider_error") { return typeof err.statusCode === "number" && err.statusCode >= 500; } if (err.code === "network_error") { const lower = err.message.toLowerCase(); return (lower.includes("econnreset") || lower.includes("epipe") || lower.includes("fetch failed") || lower.includes("socket connection was closed") || lower.includes("terminated") || lower.includes("other side closed")); } return false; } // ── Test seam ──────────────────────────────────────────────────────────────── // Swap-and-restore override. Inert in production; only tests call the setter. let chatCompletionOverride; /** TEST-ONLY. Swap the implementation of `chatCompletion`; pass undefined to restore. */ export function _setChatCompletionForTests(fake) { chatCompletionOverride = fake; } export async function chatCompletion(config, messages, options) { if (chatCompletionOverride) return chatCompletionOverride(config, messages, options); return chatCompletionReal(config, messages, options); } /** * One call's time budget: the first attempt is given all of it and a retry * only what is left, so a call and its retries never outlast its timeout. */ function timeBudget(totalMs) { if (totalMs === null) return () => null; let deadlineAt; return () => { const now = Date.now(); deadlineAt ??= now + totalMs; return Math.max(0, deadlineAt - now); }; } async function chatCompletionReal(config, messages, options) { const effectiveTimeoutMs = options && Object.hasOwn(options, "timeoutMs") ? (options.timeoutMs ?? null) : Object.hasOwn(config, "timeoutMs") ? (config.timeoutMs ?? null) : null; const started = Date.now(); const budget = timeBudget(effectiveTimeoutMs); try { return await chatCompletionAttempt(config, messages, options, budget); } catch (err) { if (!(err instanceof LlmCallError) || !isRetryable(err)) throw err; // Timeout-budget guard: if the first attempt already burned most of the // budget, a second attempt cannot complete — skip the retry. if (effectiveTimeoutMs !== null && Date.now() - started >= effectiveTimeoutMs * RETRY_BUDGET_FRACTION) { throw err; } // Signal the caller so it can bump `retryAttempts` (NOT `failureCount`). options?.onRetryAttempt?.(); // Log the first failure at debug (verbose-only) level; the retry outcome is // authoritative. warnVerbose(`[akm] LLM transient failure (${err.code}); retrying once: ${err.message}`); const wait = retryBackoffMs(); await waitForRetry(wait, options?.sleep ?? sleep, options?.signal); // The retry spends what is left of the original budget. return await chatCompletionAttempt(config, messages, options, budget); } } // ── Structured-output attempt-then-fallback ───────────────────────────────── /** * Connections that have already demonstrated (via a real 4xx response, not a * probe) that they reject `response_format: json_schema`. In-memory only, * per process, never persisted — the replacement for the old * `capabilities.structuredOutput` config cache that `akm setup` wrote once * and nothing ever invalidated on a later `akm config set`. Populated the * first time a real call proves it, forgotten on the next process start, so * a config/endpoint change can never leave a stale verdict in place. */ const jsonSchemaUnsupportedConnections = new Set(); /** * The same, for the two thinking-control fields (`chat_template_kwargs` and * `enable_thinking`): a strict hosted API answers 400 `Unknown parameter`. */ const thinkingControlRejectedConnections = new Set(); /** * And for OpenAI's reasoning models: they answer 400 to any `temperature` but * the default, and to `max_tokens`, naming `max_completion_tokens` instead. */ const temperatureRejectedConnections = new Set(); const maxCompletionTokensConnections = new Set(); function connectionKey(config) { return `${config.endpoint}|${config.model}`; } /** TEST-ONLY. Clear the in-memory endpoint-support trackers between tests. */ export function _resetEndpointSupportTrackersForTests() { jsonSchemaUnsupportedConnections.clear(); thinkingControlRejectedConnections.clear(); temperatureRejectedConnections.clear(); maxCompletionTokensConnections.clear(); } /** * Whether this connection has already been proven, this process, not to * support `response_format: json_schema`. Callers choosing a prompt-framing * strategy up front (e.g. `improve/reflect.ts`'s `outputMode`) can consult * this instead of a persisted config flag — it reflects only what a real * call this run actually observed. */ export function isJsonSchemaKnownUnsupported(config) { return jsonSchemaUnsupportedConnections.has(connectionKey(config)); } /** Whether a real call this process showed this connection rejects the thinking-control fields (#1045). */ export function isThinkingControlKnownRejected(config) { return thinkingControlRejectedConnections.has(connectionKey(config)); } /** * Whether `err` is a provider's 4xx (a rate limit is not one) that may be a * verdict on the shape of this request rather than on the request's own content. */ function isRejectedRequest(err) { return (err instanceof LlmCallError && err.code === "provider_error" && typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500 && err.statusCode !== 429); } /** A strict API names the field it does not know: `Unknown parameter: 'chat_template_kwargs'.` */ const THINKING_FIELD_NAMED = /chat_template_kwargs|enable_thinking/; /** `Unsupported value: 'temperature' does not support 0 with this model. Only the default (1) value is supported.` */ const TEMPERATURE_NAMED = /'temperature'/; /** `Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.` */ const MAX_TOKENS_REPLACED = /max_completion_tokens/; /** A gateway that cannot honour the schema may answer 5xx: `502 {"error":{"code":"format_ignored"}}` (#1150). */ const RESPONSE_FORMAT_NAMED = /format_ignored|response_format|json_schema/; /** * A single chat-completion attempt: one HTTP request/response cycle, with an * inline fallback-once when a schema was requested and the provider 4xx's * (never retried by the transient-failure policy below, by design — 4xx is * a same-request-will-always-fail signal EXCEPT for this one specific, * request-shape-dependent case). Only what a real call this process made has * shown (`isJsonSchemaKnownUnsupported`) skips the first attempt. * * The thinking-control fields get the same treatment (#1045): a 4xx that * names `chat_template_kwargs` or `enable_thinking` is answered by one retry * without them, which may in turn fall back without the schema. A 4xx that * names `temperature`, or asks for `max_completion_tokens`, is answered the * same way: the connection stops sending `temperature`, or sends the token cap * as `max_completion_tokens`, for the rest of the process. */ async function chatCompletionAttempt(config, messages, options, budget, includeThinking = sendsThinkingFields(config, options) && !isThinkingControlKnownRejected(config)) { const wantsSchema = Boolean(options?.responseSchema) && !isJsonSchemaKnownUnsupported(config); // The schema attempt's error record is held, not emitted: when the retry without the schema // recovers the call, that call is ONE success, not a failure plus a success. Every other exit // flushes the held record, so a failed call is still recorded once. const held = wantsSchema ? {} : undefined; const flushHeld = () => { if (held?.record) emitLlmUsage(held.record); }; try { return await chatCompletionAttemptOnce(config, messages, options, budget(), wantsSchema, includeThinking, held); } catch (err) { // A 5xx that names the response format is answered like the 4xx rejection below (#1150). if (wantsSchema && err instanceof LlmCallError && err.namesResponseFormat) { return retryWithoutSchema(config, messages, options, budget, includeThinking, err); } if (!isRejectedRequest(err)) { flushHeld(); throw err; } const key = connectionKey(config); if (TEMPERATURE_NAMED.test(err.message) && !temperatureRejectedConnections.has(key)) { flushHeld(); warnVerbose(`[akm] LLM rejected temperature (${err.statusCode}); retrying once without it: ${err.message}`); temperatureRejectedConnections.add(key); return chatCompletionAttempt(config, messages, options, budget, includeThinking); } if (MAX_TOKENS_REPLACED.test(err.message) && !maxCompletionTokensConnections.has(key)) { flushHeld(); warnVerbose(`[akm] LLM rejected max_tokens (${err.statusCode}); retrying once with max_completion_tokens: ${err.message}`); maxCompletionTokensConnections.add(key); return chatCompletionAttempt(config, messages, options, budget, includeThinking); } if (includeThinking && THINKING_FIELD_NAMED.test(err.message)) { flushHeld(); warnVerbose(`[akm] LLM rejected chat_template_kwargs/enable_thinking (${err.statusCode}); retrying once without them: ${err.message}`); const fallback = await chatCompletionAttempt(config, messages, options, budget, false); thinkingControlRejectedConnections.add(connectionKey(config)); return fallback; } if (!wantsSchema) throw err; return retryWithoutSchema(config, messages, options, budget, includeThinking, err); } } async function retryWithoutSchema(config, messages, options, budget, includeThinking, err) { warnVerbose(`[akm] LLM rejected response_format:json_schema (${err.statusCode}); retrying once without it: ${err.message}`); const fallback = await chatCompletionAttemptOnce(config, messages, options, budget(), false, includeThinking); jsonSchemaUnsupportedConnections.add(connectionKey(config)); return fallback; } /** Whether this request carries the two thinking-control fields, from a setting or as written. */ function sendsThinkingFields(config, options) { return ((options?.enableThinking ?? config.inference?.enableThinking) !== undefined || config.request?.chat_template_kwargs !== undefined || config.request?.enable_thinking !== undefined); } /** * The fields of one request: akm's default temperature, the connection's request * fields as written, and the portable settings (the call's own over the * connection's) translated, nearest last. A field the endpoint has rejected on an * earlier call is left out, and the token cap goes by the name it asked for. */ function requestFields(config, options, includeThinking) { const settings = { ...config.inference, ...(options?.temperature !== undefined ? { temperature: options.temperature } : {}), ...(options?.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}), ...(options?.enableThinking !== undefined ? { enableThinking: options.enableThinking } : {}), }; const fields = effectiveRequestFields({ temperature: 0.3, ...config.request }, settings); const key = connectionKey(config); if (temperatureRejectedConnections.has(key)) delete fields.temperature; if (!includeThinking) { delete fields.chat_template_kwargs; delete fields.enable_thinking; } if (maxCompletionTokensConnections.has(key) && fields.max_tokens !== undefined) { fields.max_completion_tokens = fields.max_tokens; delete fields.max_tokens; } return fields; } async function chatCompletionAttemptOnce(config, messages, options, timeoutMs, includeSchema, includeThinking, held) { if (config.inference?.extraParams !== undefined) { const issue = validateExtraParams(config.inference.extraParams)[0]; if (issue) throw new Error(formatExtraParamsIssue("LLM extraParams", issue)); } const headers = { "Content-Type": "application/json" }; const resolvedKey = config.apiKey; if (resolvedKey) { headers.Authorization = `Bearer ${resolvedKey}`; } const responseFormat = includeSchema && options?.responseSchema ? { response_format: { type: "json_schema", json_schema: { name: JSON_SCHEMA_RESPONSE_NAME, schema: options.responseSchema, strict: true }, }, } : {}; const fields = requestFields(config, options, includeThinking); const requestBody = JSON.stringify({ ...fields, model: config.model, messages, ...responseFormat }); const endpointUrl = openAiOperationUrl(config.endpoint, "chat/completions"); // What a message says about the endpoint: never a username or password the URL carries. const shownEndpoint = redactUrlCredentials(config.endpoint); // Wall-clock start for per-attempt usage telemetry (#576). Captured here so the // emitted duration covers the full request/response/parse cycle of a single // attempt, not the retry-wrapping `chatCompletion`. const requestStartedAt = Date.now(); const requestDeadlineAt = timeoutMs === null ? null : requestStartedAt + timeoutMs; const remainingAttemptMs = () => requestDeadlineAt === null ? undefined : Math.max(0, requestDeadlineAt - Date.now()); let terminalFields = { model: config.model, modelSource: "configured", }; try { let response; try { response = await fetchWithTimeout(endpointUrl, { method: "POST", headers, body: requestBody, }, timeoutMs, options?.signal); } catch (err) { // fetchWithTimeout throws a plain Error with a message containing // "timed out" for AbortController-driven timeouts, or "aborted" for // caller-driven cancellations. Map both to typed LlmCallError. const msg = err instanceof Error ? err.message : String(err); if (options?.signal?.aborted || msg.includes("Request aborted")) { throw new LlmCallError("LLM request aborted", "aborted"); } if (err instanceof DOMException && err.name === "AbortError") { throw new LlmCallError(`Request timed out${timeoutMs === null ? "" : ` after ${timeoutMs}ms`}`, "timeout"); } if (msg.includes("timed out")) { throw new LlmCallError(`Request timed out${timeoutMs === null ? "" : ` after ${timeoutMs}ms`}`, "timeout"); } throw new LlmCallError(`Network error: ${msg}`, "network_error"); } if (!response.ok) { const rawBody = await readBodyWithByteCap(response, undefined, { ...(requestDeadlineAt === null ? {} : { bodyTimeoutMs: remainingAttemptMs() }), signal: options?.signal, }).catch((err) => { if (options?.signal?.aborted) throw new LlmCallError("LLM response read aborted", "aborted"); if (err instanceof Error && err.name === "BodyReadTimeoutError") { throw new LlmCallError("LLM response body read timed out", "timeout"); } return ""; }); const safeBody = redactSensitiveText(redactErrorBody(rawBody), resolvedKey ? [resolvedKey] : []); const status = response.status; if (status === 429) { throw new LlmCallError(`LLM request rate limited (429) ${shownEndpoint}: ${safeBody}`, "rate_limited", status); } if (status >= 500 && isHtmlResponse(rawBody)) { throw new LlmCallError(`LLM provider returned HTML instead of JSON (${status}) ${shownEndpoint}: ${redactSensitiveText(htmlExcerpt(rawBody), resolvedKey ? [resolvedKey] : [])}`, "provider_html_error", status); } if (status >= 500) { throw new LlmCallError(`LLM provider error (${status}) ${shownEndpoint}: ${safeBody}`, "provider_error", status, RESPONSE_FORMAT_NAMED.test(rawBody)); } throw new LlmCallError(`LLM request failed (${status}) ${shownEndpoint}: ${safeBody}`, "provider_error", status); } // A 2xx response is still an error if the body is HTML where JSON was // expected (e.g. a provider serving its web UI). Read the raw body first so // we can categorize an HTML page distinctly from a malformed-JSON parse_error. let rawOkBody; try { rawOkBody = await readBodyWithByteCap(response, undefined, { ...(requestDeadlineAt === null ? {} : { bodyTimeoutMs: remainingAttemptMs() }), signal: options?.signal, }); } catch (err) { if (options?.signal?.aborted) throw new LlmCallError("LLM response read aborted", "aborted"); if (err instanceof Error && err.name === "BodyReadTimeoutError") { throw new LlmCallError("LLM response body read timed out", "timeout"); } throw err; } if (isHtmlResponse(rawOkBody)) { throw new LlmCallError(`LLM provider returned HTML instead of JSON (${response.status}) ${shownEndpoint}: ${redactSensitiveText(htmlExcerpt(rawOkBody), resolvedKey ? [resolvedKey] : [])}`, "provider_html_error", response.status); } let json; try { json = JSON.parse(rawOkBody); } catch { throw new LlmCallError(`LLM response was not valid JSON ${shownEndpoint}: ${redactSensitiveText(redactErrorBody(rawOkBody), resolvedKey ? [resolvedKey] : [])}`, "parse_error", response.status); } // A 2xx can still carry a provider failure. OpenRouter answers a provider // that fails after the headers with a body holding only `error`. if (json.error !== undefined && json.error !== null && !json.choices?.length) { throw new LlmCallError(`LLM provider error (${response.status}) ${shownEndpoint}: ${redactSensitiveText(redactErrorBody(rawOkBody), resolvedKey ? [resolvedKey] : [])}`, "provider_error", response.status); } const responseModel = typeof json.model === "string" && json.model.trim().length > 0 ? json.model : undefined; terminalFields = { model: responseModel ?? config.model, modelSource: responseModel === undefined ? "configured" : "response", finishReason: typeof json.choices?.[0]?.finish_reason === "string" ? json.choices[0].finish_reason : undefined, ...extractUsageTokens(json.usage), }; if (fields.enable_thinking === false && (terminalFields.reasoningTokens ?? 0) > 0) { warn(`[akm] LLM returned ${terminalFields.reasoningTokens} reasoning tokens despite thinking being off; ` + 'the provider may not honor that control. Configure reasoningEffort: "none" when the provider supports it.'); } const content = (json.choices?.[0]?.message?.content ?? "").trim(); const reasoning = (json.choices?.[0]?.message?.reasoning_content ?? "").trim(); // A reply cut at the output limit, or with no content, is not an answer; the model's reasoning is never one. const from = `from ${terminalFields.model} at ${shownEndpoint}`; if (terminalFields.finishReason === "length") throw new LlmCallError(`reply cut at the output limit (finish_reason "length") ${from}`, "parse_error", response.status); if (!content) throw new LlmCallError(`reply had no content${reasoning ? " (the model returned reasoning_content only)" : ""} ${from}`, "parse_error", response.status); const result = redactSensitiveText(content, resolvedKey ? [resolvedKey] : []); emitLlmUsage({ ...terminalFields, outcome: "success", durationMs: Date.now() - requestStartedAt, }); return result; } catch (err) { const errorRecord = { ...terminalFields, outcome: "error", durationMs: Date.now() - requestStartedAt, errorCode: err instanceof LlmCallError ? err.code : "unknown_error", }; if (held) held.record = errorRecord; else emitLlmUsage(errorRecord); throw err; } } // ── Availability check ────────────────────────────────────────────────────── // ── Reachability probe ────────────────────────────────────────────────────── /** * Reachability probe for `akm health` (#914): one GET against the * OpenAI-compatible `/models` route, bounded by `timeoutMs`. Any HTTP * response counts as reachable — the question is whether the endpoint * answers, not whether the route exists or the credential is right — so a * cold local server is never asked to load a model just to be checked. */ export async function probeLlmEndpoint(config, timeoutMs = 3_000) { try { await fetch(openAiOperationUrl(config.endpoint, "models"), { signal: AbortSignal.timeout(timeoutMs) }); return { reachable: true }; } catch (err) { // Node's fetch says only "fetch failed" and keeps the cause (ECONNREFUSED, ENOTFOUND) underneath; name it too. const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : undefined; const message = err instanceof Error ? err.message : String(err); return { reachable: false, error: cause && !message.includes(cause) ? `${message} (${cause})` : message }; } } /** * Endpoint-keyed probe memoization (#957): a caller that probes several * connections in one pass (`akm health`'s connections-and-harnesses check) * shares one in-flight probe per distinct endpoint (trailing slashes * normalized) instead of firing a duplicate probe when two connections point * at the same server. `cache` must be scoped to one * invocation and never shared across calls — a stale "reachable" surviving * past the run that produced it is the failure mode this exists to avoid. */ export function probeEndpointOnce(connection, cache, probe) { const key = openAiBaseUrl(connection.endpoint); let pending = cache.get(key); if (!pending) { pending = probe(connection); cache.set(key, pending); } return pending; }