@remnic/core 10.0.157 → 10.0.159
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/dist/access-admin-ops-surface.js +10 -10
- package/dist/access-cli.js +10 -10
- package/dist/access-extraction-force-flush-preempt.js +10 -10
- package/dist/access-extraction-force-flush.js +10 -10
- package/dist/access-http-briefing.js +10 -10
- package/dist/access-http-query.js +10 -10
- package/dist/access-http.js +10 -10
- package/dist/access-identity-continuity-surface.js +10 -10
- package/dist/access-lcm-surface.js +10 -10
- package/dist/access-mcp.js +10 -10
- package/dist/access-observe-write-surface.js +10 -10
- package/dist/access-operations-batch.js +10 -10
- package/dist/access-operations.js +10 -10
- package/dist/access-recall-concurrency.js +10 -10
- package/dist/access-recall-response.js +10 -10
- package/dist/access-recall-surface.js +10 -10
- package/dist/access-service.js +10 -10
- package/dist/calibration.js +3 -3
- package/dist/{chunk-RGXNPAMA.js → chunk-3RHD5TF5.js} +38 -30
- package/dist/{chunk-RGXNPAMA.js.map → chunk-3RHD5TF5.js.map} +1 -1
- package/dist/{chunk-SKCMEZBU.js → chunk-52EM4UQU.js} +2 -2
- package/dist/{chunk-QAQL2OQH.js → chunk-5V3IBSVB.js} +2 -2
- package/dist/{chunk-K4TMUEYI.js → chunk-BT5TAOXG.js} +1 -1
- package/dist/{chunk-4IJBNRMZ.js → chunk-DRXFLPSE.js} +12 -2
- package/dist/chunk-DRXFLPSE.js.map +1 -0
- package/dist/{chunk-AGMMHT4P.js → chunk-GT2HWRST.js} +21 -3
- package/dist/chunk-GT2HWRST.js.map +1 -0
- package/dist/{chunk-BDKLKX43.js → chunk-KYZMCH4I.js} +79 -6
- package/dist/{chunk-BDKLKX43.js.map → chunk-KYZMCH4I.js.map} +1 -1
- package/dist/{chunk-RXG3WF7C.js → chunk-TXVTNDQT.js} +2 -2
- package/dist/{chunk-2TUWMP7B.js → chunk-UADAXWUJ.js} +3 -3
- package/dist/{chunk-Z6AP6O32.js → chunk-XC5BRK7J.js} +2 -2
- package/dist/{chunk-XWRSQWQO.js → chunk-YOR5QBEU.js} +60 -59
- package/dist/chunk-YOR5QBEU.js.map +1 -0
- package/dist/cli.js +10 -10
- package/dist/compounding/engine.js +1 -1
- package/dist/explicit-capture.js +10 -10
- package/dist/extraction.js +4 -4
- package/dist/index.js +10 -10
- package/dist/local-llm-helpers.d.ts +22 -8
- package/dist/local-llm-helpers.d.ts.map +1 -1
- package/dist/local-llm-helpers.js +11 -1
- package/dist/local-llm-rate-limit.d.ts +1 -5
- package/dist/local-llm-rate-limit.d.ts.map +1 -1
- package/dist/local-llm-rate-limit.js +3 -1
- package/dist/local-llm.d.ts +2 -4
- package/dist/local-llm.d.ts.map +1 -1
- package/dist/local-llm.js +3 -3
- package/dist/orchestration/backlog-scheduler.js +11 -11
- package/dist/orchestration/buffer-drain-runner.js +11 -11
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/orchestration/recall-internal.d.ts.map +1 -1
- package/dist/orchestrator.js +10 -10
- package/dist/recall-enrichment-promise.d.ts +7 -2
- package/dist/recall-enrichment-promise.d.ts.map +1 -1
- package/dist/recall-enrichment-promise.js +1 -1
- package/dist/recall-navigation.js +10 -10
- package/dist/summarizer.js +4 -4
- package/dist/support-passport/index.js +4 -4
- package/package.json +12 -2
- package/src/local-llm-helpers.ts +116 -14
- package/src/local-llm-rate-limit.test.ts +79 -1
- package/src/local-llm-rate-limit.ts +37 -1
- package/src/local-llm.ts +75 -74
- package/src/orchestration/recall-internal.ts +36 -24
- package/src/recall-enrichment-promise.ts +20 -2
- package/src/recall-qos.test.ts +24 -0
- package/src/recall-timings-request-contract.test.ts +10 -8
- package/dist/chunk-4IJBNRMZ.js.map +0 -1
- package/dist/chunk-AGMMHT4P.js.map +0 -1
- package/dist/chunk-XWRSQWQO.js.map +0 -1
- /package/dist/{chunk-SKCMEZBU.js.map → chunk-52EM4UQU.js.map} +0 -0
- /package/dist/{chunk-QAQL2OQH.js.map → chunk-5V3IBSVB.js.map} +0 -0
- /package/dist/{chunk-K4TMUEYI.js.map → chunk-BT5TAOXG.js.map} +0 -0
- /package/dist/{chunk-RXG3WF7C.js.map → chunk-TXVTNDQT.js.map} +0 -0
- /package/dist/{chunk-2TUWMP7B.js.map → chunk-UADAXWUJ.js.map} +0 -0
- /package/dist/{chunk-Z6AP6O32.js.map → chunk-XC5BRK7J.js.map} +0 -0
|
@@ -71,7 +71,7 @@ import {
|
|
|
71
71
|
} from "./chunk-7G5NTS7F.js";
|
|
72
72
|
import {
|
|
73
73
|
LocalLlmClient
|
|
74
|
-
} from "./chunk-
|
|
74
|
+
} from "./chunk-YOR5QBEU.js";
|
|
75
75
|
import {
|
|
76
76
|
CONSOLIDATION_RESPONSE_SCHEMA,
|
|
77
77
|
CUE_ANCHOR_PROMPT_INSTRUCTION,
|
|
@@ -2449,4 +2449,4 @@ export {
|
|
|
2449
2449
|
shouldEnableLocalExtractionThinking,
|
|
2450
2450
|
ExtractionEngine
|
|
2451
2451
|
};
|
|
2452
|
-
//# sourceMappingURL=chunk-
|
|
2452
|
+
//# sourceMappingURL=chunk-52EM4UQU.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
LocalLlmClient
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YOR5QBEU.js";
|
|
4
4
|
import {
|
|
5
5
|
FallbackLlmClient
|
|
6
6
|
} from "./chunk-MMRTPH3J.js";
|
|
@@ -4497,4 +4497,4 @@ export {
|
|
|
4497
4497
|
parseSupportPassportModelJob,
|
|
4498
4498
|
SupportPassportModelBridge
|
|
4499
4499
|
};
|
|
4500
|
-
//# sourceMappingURL=chunk-
|
|
4500
|
+
//# sourceMappingURL=chunk-5V3IBSVB.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/recall-enrichment-promise.ts
|
|
2
|
-
function createEnrichmentAbortHandle(parentSignal) {
|
|
2
|
+
function createEnrichmentAbortHandle(parentSignal, deadlineMs) {
|
|
3
3
|
const controller = new AbortController();
|
|
4
4
|
const onAbort = () => controller.abort();
|
|
5
5
|
if (parentSignal?.aborted) {
|
|
@@ -7,14 +7,24 @@ function createEnrichmentAbortHandle(parentSignal) {
|
|
|
7
7
|
} else if (parentSignal) {
|
|
8
8
|
parentSignal.addEventListener("abort", onAbort, { once: true });
|
|
9
9
|
}
|
|
10
|
+
let timedOut = false;
|
|
11
|
+
const timer = deadlineMs !== void 0 && Number.isFinite(deadlineMs) && deadlineMs > 0 ? setTimeout(() => {
|
|
12
|
+
timedOut = true;
|
|
13
|
+
controller.abort();
|
|
14
|
+
}, deadlineMs) : void 0;
|
|
15
|
+
timer?.unref?.();
|
|
10
16
|
let disposed = false;
|
|
11
17
|
const dispose = () => {
|
|
12
18
|
if (disposed) return;
|
|
13
19
|
disposed = true;
|
|
20
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
14
21
|
parentSignal?.removeEventListener("abort", onAbort);
|
|
15
22
|
};
|
|
16
23
|
return {
|
|
17
24
|
signal: controller.signal,
|
|
25
|
+
get timedOut() {
|
|
26
|
+
return timedOut;
|
|
27
|
+
},
|
|
18
28
|
cancel: () => {
|
|
19
29
|
controller.abort();
|
|
20
30
|
dispose();
|
|
@@ -42,4 +52,4 @@ export {
|
|
|
42
52
|
createEnrichmentAbortHandle,
|
|
43
53
|
observeEnrichmentPromise
|
|
44
54
|
};
|
|
45
|
-
//# sourceMappingURL=chunk-
|
|
55
|
+
//# sourceMappingURL=chunk-DRXFLPSE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recall-enrichment-promise.ts"],"sourcesContent":["export type DeferredEnrichmentOutcome<T> =\n | { status: \"resolved\"; value: T }\n | { status: \"rejected\"; error: unknown };\n\nexport type ObservedDeferredEnrichmentPromise<T> =\n Promise<DeferredEnrichmentOutcome<T>> & {\n getSettledOutcome: () => DeferredEnrichmentOutcome<T> | undefined;\n cancel: () => void;\n };\n\n/** Cancelable child abort signal owned by one enrichment promise. */\nexport interface EnrichmentAbortHandle {\n signal: AbortSignal;\n /** True only when the handle's own deadline fired — not a parent abort or a manual cancel. */\n readonly timedOut: boolean;\n cancel: () => void;\n dispose: () => void;\n}\n\n/** Child abort controller that follows `parentSignal` and, when `deadlineMs` is\n * finite and positive, fires on its own at that deadline — the metric label the\n * enrichment sections already carried, enforced (#3499). `dispose` detaches the\n * listener and clears the timer. */\nexport function createEnrichmentAbortHandle(parentSignal?: AbortSignal, deadlineMs?: number): EnrichmentAbortHandle {\n const controller = new AbortController();\n const onAbort = () => controller.abort();\n if (parentSignal?.aborted) {\n controller.abort();\n } else if (parentSignal) {\n parentSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n let timedOut = false;\n const timer =\n deadlineMs !== undefined && Number.isFinite(deadlineMs) && deadlineMs > 0\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, deadlineMs)\n : undefined;\n timer?.unref?.();\n let disposed = false;\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n if (timer !== undefined) clearTimeout(timer);\n parentSignal?.removeEventListener(\"abort\", onAbort);\n };\n return {\n signal: controller.signal,\n get timedOut() {\n return timedOut;\n },\n cancel: () => {\n controller.abort();\n dispose();\n },\n dispose,\n };\n}\n\n/** Never-rejecting view of `promise` that also exposes its settled outcome and a cancel hook. */\nexport function observeEnrichmentPromise<T>(\n promise: Promise<T>,\n cancel: () => void = () => {},\n): ObservedDeferredEnrichmentPromise<T> {\n let settledOutcome: DeferredEnrichmentOutcome<T> | undefined;\n const settled = promise\n .then<DeferredEnrichmentOutcome<T>, DeferredEnrichmentOutcome<T>>(\n (value) => ({ status: \"resolved\", value }),\n (error) => ({ status: \"rejected\", error }),\n )\n .then((outcome) => {\n settledOutcome = outcome;\n return outcome;\n });\n return Object.assign(settled, {\n getSettledOutcome: () => settledOutcome,\n cancel,\n });\n}\n"],"mappings":";AAuBO,SAAS,4BAA4B,cAA4B,YAA4C;AAClH,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,UAAU,MAAM,WAAW,MAAM;AACvC,MAAI,cAAc,SAAS;AACzB,eAAW,MAAM;AAAA,EACnB,WAAW,cAAc;AACvB,iBAAa,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,EAChE;AACA,MAAI,WAAW;AACf,QAAM,QACJ,eAAe,UAAa,OAAO,SAAS,UAAU,KAAK,aAAa,IACpE,WAAW,MAAM;AACf,eAAW;AACX,eAAW,MAAM;AAAA,EACnB,GAAG,UAAU,IACb;AACN,SAAO,QAAQ;AACf,MAAI,WAAW;AACf,QAAM,UAAU,MAAM;AACpB,QAAI,SAAU;AACd,eAAW;AACX,QAAI,UAAU,OAAW,cAAa,KAAK;AAC3C,kBAAc,oBAAoB,SAAS,OAAO;AAAA,EACpD;AACA,SAAO;AAAA,IACL,QAAQ,WAAW;AAAA,IACnB,IAAI,WAAW;AACb,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,MAAM;AACZ,iBAAW,MAAM;AACjB,cAAQ;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,yBACd,SACA,SAAqB,MAAM;AAAC,GACU;AACtC,MAAI;AACJ,QAAM,UAAU,QACb;AAAA,IACC,CAAC,WAAW,EAAE,QAAQ,YAAY,MAAM;AAAA,IACxC,CAAC,WAAW,EAAE,QAAQ,YAAY,MAAM;AAAA,EAC1C,EACC,KAAK,CAAC,YAAY;AACjB,qBAAiB;AACjB,WAAO;AAAA,EACT,CAAC;AACH,SAAO,OAAO,OAAO,SAAS;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -27,9 +27,26 @@ function resolveRateLimitSettings(config) {
|
|
|
27
27
|
maxConcurrency: nonNegativeInt(config.localLlmMaxConcurrency, DEFAULT_MAX_CONCURRENCY)
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
|
-
var
|
|
30
|
+
var TERMINAL_PROXY_POOL_CODES = /* @__PURE__ */ new Set([
|
|
31
|
+
"remnic_recall_pool_unavailable",
|
|
32
|
+
"remnic_extraction_pool_unavailable"
|
|
33
|
+
]);
|
|
34
|
+
function bodyHasTerminalPoolCode(bodyText) {
|
|
35
|
+
try {
|
|
36
|
+
const { code } = JSON.parse(bodyText);
|
|
37
|
+
return code !== void 0 && TERMINAL_PROXY_POOL_CODES.has(code);
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
var TERMINAL_PROXY_POOL_TEXT = "pool missing or disabled";
|
|
43
|
+
function isTerminalLocalLlmProxyPoolError(status, bodyText) {
|
|
44
|
+
if (status !== 503) return false;
|
|
45
|
+
return bodyText.toLowerCase().includes(TERMINAL_PROXY_POOL_TEXT) || bodyHasTerminalPoolCode(bodyText);
|
|
46
|
+
}
|
|
31
47
|
function isRateLimitedResponse(status, bodyText) {
|
|
32
|
-
if (
|
|
48
|
+
if (isTerminalLocalLlmProxyPoolError(status, bodyText)) return false;
|
|
49
|
+
if (bodyText.toLowerCase().includes("pool missing or disabled")) return false;
|
|
33
50
|
if (RATE_LIMIT_STATUSES.has(status)) return true;
|
|
34
51
|
return status >= 500 && RATE_LIMIT_BODY_PATTERN.test(bodyText);
|
|
35
52
|
}
|
|
@@ -285,6 +302,7 @@ export {
|
|
|
285
302
|
DEFAULT_RATE_LIMIT_BACKOFF_MAX_MS,
|
|
286
303
|
DEFAULT_MAX_CONCURRENCY,
|
|
287
304
|
resolveRateLimitSettings,
|
|
305
|
+
isTerminalLocalLlmProxyPoolError,
|
|
288
306
|
isRateLimitedResponse,
|
|
289
307
|
parseRetryAfterMs,
|
|
290
308
|
parseTryAgainHintMs,
|
|
@@ -300,4 +318,4 @@ export {
|
|
|
300
318
|
resetLocalLlmRateLimitStateForTests,
|
|
301
319
|
LocalLlmRateLimitSession
|
|
302
320
|
};
|
|
303
|
-
//# sourceMappingURL=chunk-
|
|
321
|
+
//# sourceMappingURL=chunk-GT2HWRST.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/local-llm-rate-limit.ts"],"sourcesContent":["/**\n * Process-wide rate-limit handling for the local LLM client (COS-447).\n *\n * A LiteLLM proxy in front of the local models answers `429 No deployments\n * available` (and `503`/`408`) when every deployment is busy or in cooldown.\n * Before this module the client returned on the first 429 and the caller\n * loop immediately issued the next request, so one daemon could hammer the\n * proxy with thousands of calls per hour while it was saturated.\n *\n * This module provides three pieces that the client composes:\n *\n * - classification of rate-limit responses and of the retry hint\n * (`Retry-After` header as delta-seconds or HTTP-date, falling back to\n * LiteLLM's `Try again in N seconds` body text);\n * - exponential backoff with full jitter;\n * - process-wide state shared by every `LocalLlmClient` instance: a\n * concurrency semaphore for in-flight HTTP attempts and a per-endpoint\n * \"do not call before\" deadline, so one client's 429 slows every client\n * pointed at the same endpoint.\n *\n * State lives on `globalThis` so duplicated module copies in bundled output\n * still share one limiter.\n */\n\nexport const RATE_LIMIT_STATUSES: ReadonlySet<number> = new Set([408, 429, 503]);\n\nconst RATE_LIMIT_BODY_PATTERN = /no deployments available|cooldown_list|all deployments.*cooldown/i;\nconst TRY_AGAIN_PATTERN = /try again in (\\d+(?:\\.\\d+)?) ?(seconds?|secs?|s|milliseconds?|ms|minutes?|mins?)\\b/i;\n\n/** Upper bound on any server-provided wait we will record (sanity clamp). */\nexport const MAX_RECORDED_BACKOFF_MS = 10 * 60_000;\n\nexport const DEFAULT_RATE_LIMIT_RETRY_COUNT = 3;\nexport const DEFAULT_RATE_LIMIT_BACKOFF_BASE_MS = 1_000;\nexport const DEFAULT_RATE_LIMIT_BACKOFF_MAX_MS = 60_000;\nexport const DEFAULT_MAX_CONCURRENCY = 4;\n\nexport interface LocalLlmRateLimitSettings {\n retryCount: number;\n backoffBaseMs: number;\n backoffMaxMs: number;\n /** 0 disables the process-wide concurrency cap. */\n maxConcurrency: number;\n}\n\nfunction nonNegativeInt(value: number | undefined, fallback: number): number {\n if (value === undefined || !Number.isFinite(value) || value < 0) return fallback;\n return Math.floor(value);\n}\n\nexport function resolveRateLimitSettings(config: {\n localLlmRateLimitRetryCount?: number;\n localLlmRateLimitBackoffBaseMs?: number;\n localLlmRateLimitBackoffMaxMs?: number;\n localLlmMaxConcurrency?: number;\n}): LocalLlmRateLimitSettings {\n const backoffBaseMs = Math.max(\n 1,\n nonNegativeInt(config.localLlmRateLimitBackoffBaseMs, DEFAULT_RATE_LIMIT_BACKOFF_BASE_MS)\n );\n const backoffMaxMs = Math.max(\n backoffBaseMs,\n nonNegativeInt(config.localLlmRateLimitBackoffMaxMs, DEFAULT_RATE_LIMIT_BACKOFF_MAX_MS)\n );\n return {\n retryCount: nonNegativeInt(config.localLlmRateLimitRetryCount, DEFAULT_RATE_LIMIT_RETRY_COUNT),\n backoffBaseMs,\n backoffMaxMs,\n maxConcurrency: nonNegativeInt(config.localLlmMaxConcurrency, DEFAULT_MAX_CONCURRENCY),\n };\n}\n\n/**\n * Pool-side refusals carry \"pool missing or disabled\" — a config failure,\n * not endpoint saturation. Recording backoff for one would throttle every\n * operation sharing the endpoint URL (e.g. extraction waits on a missing\n * recall pool).\n */\nconst POOL_MISSING_PATTERN = /pool missing or disabled/i;\n\n/**\n * True for responses that mean \"the endpoint is saturated, slow down\":\n * 408/429/503, or a 5xx whose body carries LiteLLM's cooldown wording.\n * 400s are never rate limits (context-window errors mention fallbacks).\n */\n/** Proxy 503 with a pool-config error code is terminal; do not enter rate-limit retries. */\nconst TERMINAL_PROXY_POOL_CODES: ReadonlySet<string> = new Set([\n \"remnic_recall_pool_unavailable\",\n \"remnic_extraction_pool_unavailable\",\n]);\n\n/** Today's proxy answers {\"error\": \"...\"} with no code field, so the code path\n * parses the body instead of substring-matching JSON — spacing and key order\n * must not decide whether a terminal refusal retries (kilo on #3474). */\nfunction bodyHasTerminalPoolCode(bodyText: string): boolean {\n try {\n // SAFETY: the proxy body is an opaque JSON object and `code` is optional, so a\n // wrong-shape or wrong-type payload reads as undefined and fails the Set lookup.\n const { code } = JSON.parse(bodyText) as { code?: string };\n return code !== undefined && TERMINAL_PROXY_POOL_CODES.has(code);\n } catch {\n return false;\n }\n}\n\n/** The proxy answers pool-config refusals as {\"error\": \"... pool missing or\n * disabled ...\"} with no code field; the text shape is part of the terminal\n * contract, or the generic 5xx retry still fires (wAN review on #3474). */\nconst TERMINAL_PROXY_POOL_TEXT = \"pool missing or disabled\";\n\nexport function isTerminalLocalLlmProxyPoolError(status: number, bodyText: string): boolean {\n if (status !== 503) return false;\n return (\n bodyText.toLowerCase().includes(TERMINAL_PROXY_POOL_TEXT) ||\n bodyHasTerminalPoolCode(bodyText)\n );\n}\n\nexport function isRateLimitedResponse(status: number, bodyText: string): boolean {\n if (isTerminalLocalLlmProxyPoolError(status, bodyText)) return false;\n // Pool-side refusals carry \"pool missing or disabled\" as text: a config\n // failure, not endpoint saturation. Substring check, no regex.\n if (bodyText.toLowerCase().includes(\"pool missing or disabled\")) return false;\n if (RATE_LIMIT_STATUSES.has(status)) return true;\n return status >= 500 && RATE_LIMIT_BODY_PATTERN.test(bodyText);\n}\n\n/**\n * Parse an HTTP `Retry-After` value (RFC 9110: delta-seconds or HTTP-date).\n * Returns milliseconds to wait, or null when absent/invalid.\n */\nexport function parseRetryAfterMs(value: string | null | undefined, nowMs: number = Date.now()): number | null {\n if (value === null || value === undefined) return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.round(Number(trimmed) * 1000));\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return null;\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.max(0, dateMs - nowMs));\n}\n\n/** Parse LiteLLM's `Try again in N seconds` hint from an error body. */\nexport function parseTryAgainHintMs(bodyText: string): number | null {\n const match = bodyText.match(TRY_AGAIN_PATTERN);\n if (!match) return null;\n const amount = Number(match[1]);\n if (!Number.isFinite(amount)) return null;\n const unit = match[2].toLowerCase();\n let ms: number;\n if (unit.startsWith(\"ms\") || unit.startsWith(\"milli\")) ms = amount;\n else if (unit.startsWith(\"min\")) ms = amount * 60_000;\n else ms = amount * 1000;\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.round(ms));\n}\n\n/** Server-provided wait: `Retry-After` header first, then the body hint. */\nexport function serverRetryHintMs(\n retryAfterHeader: string | null | undefined,\n bodyText: string,\n nowMs: number = Date.now()\n): number | null {\n return parseRetryAfterMs(retryAfterHeader, nowMs) ?? parseTryAgainHintMs(bodyText);\n}\n\n/**\n * Exponential backoff with full jitter: uniform in [0, min(max, base * 2^(n-1))].\n * `attempt` is 1-based (the number of consecutive rate-limit responses).\n */\nexport function computeFullJitterBackoffMs(\n attempt: number,\n baseMs: number,\n maxMs: number,\n random: () => number = Math.random\n): number {\n const exponent = Math.max(0, Math.min(30, attempt - 1));\n const ceiling = Math.min(maxMs, baseMs * 2 ** exponent);\n return Math.floor(random() * ceiling);\n}\n\n/**\n * Delay before the next attempt after a rate-limit response. A server hint\n * is a floor (never call earlier than asked); jitter is added on top of the\n * exponential term so synchronized callers spread out.\n */\nexport function computeRateLimitDelayMs(\n attempt: number,\n settings: Pick<LocalLlmRateLimitSettings, \"backoffBaseMs\" | \"backoffMaxMs\">,\n serverHintMs: number | null,\n random: () => number = Math.random\n): number {\n const jittered = computeFullJitterBackoffMs(attempt, settings.backoffBaseMs, settings.backoffMaxMs, random);\n return serverHintMs === null ? jittered : Math.max(serverHintMs, jittered);\n}\n\ntype Waiter = { highPriority: boolean; grant: () => void };\n\n/** Priority semaphore; finite caps above one protect recall capacity and queued background progress. */\nexport class LocalLlmConcurrencyLimiter {\n private active = 0;\n private activeBackground = 0;\n private max: number;\n private readonly waiters: Waiter[] = [];\n\n constructor(max: number) {\n this.max = max;\n }\n\n setMax(max: number): void {\n this.max = max;\n this.pump();\n }\n\n get inFlight(): number {\n return this.active;\n }\n\n get queued(): number {\n return this.waiters.length;\n }\n\n /**\n * Wait for a slot. Resolves to a release function, or null when the\n * signal aborts first. `max <= 0` means unlimited.\n */\n acquire(\n options: { highPriority?: boolean; signal?: AbortSignal; timeoutMs?: number } = {}\n ): Promise<(() => void) | null> {\n const { signal, timeoutMs } = options;\n const highPriority = options.highPriority === true;\n if (signal?.aborted) return Promise.resolve(null);\n if (\n this.canAcquire(highPriority) &&\n (this.waiters.length === 0 || (highPriority && !this.waiters[0].highPriority))\n ) {\n this.active += 1;\n if (!highPriority) this.activeBackground += 1;\n return Promise.resolve(this.releaser(highPriority));\n }\n if (timeoutMs !== undefined && timeoutMs <= 0) return Promise.resolve(null);\n return new Promise((resolve) => {\n let timer: NodeJS.Timeout | undefined;\n const waiter: Waiter = {\n highPriority,\n grant: () => {\n signal?.removeEventListener(\"abort\", onAbort);\n if (timer) clearTimeout(timer);\n resolve(this.releaser(highPriority));\n },\n };\n const onAbort = (): void => {\n const index = this.waiters.indexOf(waiter);\n if (index >= 0) this.waiters.splice(index, 1);\n signal?.removeEventListener(\"abort\", onAbort);\n if (timer) clearTimeout(timer);\n resolve(null);\n };\n if (waiter.highPriority) {\n const firstLow = this.waiters.findIndex((w) => !w.highPriority);\n if (firstLow < 0) this.waiters.push(waiter);\n else this.waiters.splice(firstLow, 0, waiter);\n } else {\n this.waiters.push(waiter);\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (timeoutMs !== undefined) timer = setTimeout(onAbort, timeoutMs);\n });\n }\n\n private canAcquire(highPriority: boolean): boolean {\n const backgroundWaiting = highPriority && this.max > 1 && this.activeBackground === 0 &&\n this.waiters.some((waiter) => !waiter.highPriority);\n return this.max <= 0 || (\n this.active < this.max &&\n (highPriority || this.max === 1 || this.activeBackground < this.max - 1) &&\n (!highPriority || !backgroundWaiting || this.active < this.max - 1)\n );\n }\n\n private releaser(highPriority: boolean): () => void {\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.active -= 1;\n if (!highPriority) this.activeBackground -= 1;\n this.pump();\n };\n }\n\n private pump(): void {\n while (this.waiters.length > 0) {\n // An ineligible critical head must not strand the background permit.\n const criticalAllowed = this.canAcquire(true);\n const backgroundAllowed = this.canAcquire(false);\n const index = this.waiters.findIndex((waiter) => waiter.highPriority ? criticalAllowed : backgroundAllowed);\n if (index < 0) break;\n const next = this.waiters.splice(index, 1)[0];\n this.active += 1;\n if (!next.highPriority) this.activeBackground += 1;\n next.grant();\n }\n }\n}\n\ninterface EndpointBackoffState {\n untilMs: number;\n consecutiveRateLimits: number;\n}\n\ninterface RateLimitGlobalState {\n limiter: LocalLlmConcurrencyLimiter;\n endpoints: Map<string, EndpointBackoffState>;\n}\n\ndeclare global {\n // Shared across duplicated module copies in bundled output.\n var __remnicLocalLlmRateLimitState: RateLimitGlobalState | undefined;\n}\n\nfunction globalState(): RateLimitGlobalState {\n globalThis.__remnicLocalLlmRateLimitState ??= {\n limiter: new LocalLlmConcurrencyLimiter(DEFAULT_MAX_CONCURRENCY),\n endpoints: new Map(),\n };\n return globalThis.__remnicLocalLlmRateLimitState;\n}\n\n/** Process-wide limiter, resized to the caller's configured cap. */\nexport function getLocalLlmConcurrencyLimiter(maxConcurrency: number): LocalLlmConcurrencyLimiter {\n const { limiter } = globalState();\n limiter.setMax(maxConcurrency);\n return limiter;\n}\n\n/** Milliseconds until `endpoint` may be called again (0 when clear). */\nexport function endpointBackoffRemainingMs(endpoint: string, nowMs: number = Date.now()): number {\n const entry = globalState().endpoints.get(endpoint);\n return entry ? Math.max(0, entry.untilMs - nowMs) : 0;\n}\n\n/**\n * Record a rate-limit response for `endpoint`. Returns the consecutive\n * rate-limit count (1-based) to feed the backoff exponent.\n */\nexport function noteEndpointRateLimited(endpoint: string): number {\n const { endpoints } = globalState();\n const entry = endpoints.get(endpoint) ?? { untilMs: 0, consecutiveRateLimits: 0 };\n entry.consecutiveRateLimits += 1;\n endpoints.set(endpoint, entry);\n return entry.consecutiveRateLimits;\n}\n\n/** Push the endpoint's \"do not call before\" deadline out to at least `nowMs + delayMs`. */\nexport function extendEndpointBackoff(endpoint: string, delayMs: number, nowMs: number = Date.now()): void {\n const { endpoints } = globalState();\n const entry = endpoints.get(endpoint) ?? { untilMs: 0, consecutiveRateLimits: 0 };\n const bounded = Math.min(MAX_RECORDED_BACKOFF_MS, Math.max(0, delayMs));\n entry.untilMs = Math.max(entry.untilMs, nowMs + bounded);\n endpoints.set(endpoint, entry);\n}\n\n/**\n * Reset the backoff exponent after a non-rate-limited response. An already\n * recorded deadline is left to expire so concurrent callers that saw the\n * 429 still wait it out.\n */\nexport function noteEndpointRecovered(endpoint: string): void {\n const entry = globalState().endpoints.get(endpoint);\n if (entry) entry.consecutiveRateLimits = 0;\n}\n\n/** Test seam: drop all process-wide state. */\nexport function resetLocalLlmRateLimitStateForTests(): void {\n const state = globalState();\n state.endpoints.clear();\n state.limiter = new LocalLlmConcurrencyLimiter(DEFAULT_MAX_CONCURRENCY);\n}\n\nexport type RateLimitAttemptGate =\n | { kind: \"go\"; release: () => void }\n | { kind: \"aborted\" }\n | { kind: \"skip\"; reason: \"backoff\" | \"queue\"; remainingMs: number };\n\nexport type RateLimitDecision =\n | { kind: \"not-rate-limited\" }\n | { kind: \"retry\"; delayMs: number; hintMs: number | null; consecutive: number; retry: number }\n | { kind: \"give-up\"; delayMs: number; retries: number };\n\n/**\n * Per-request driver for the rate-limit policy. The client calls\n * `beforeAttempt` ahead of every HTTP attempt (waits out the shared endpoint\n * deadline, then takes a concurrency slot) and `onResponse` after every\n * non-ok response.\n */\nexport class LocalLlmRateLimitSession {\n private retries = 0;\n private readonly limiter: LocalLlmConcurrencyLimiter;\n readonly settings: LocalLlmRateLimitSettings;\n\n /**\n * @param waitBudgetMs the caller's per-attempt time budget. Waiting for the\n * endpoint backoff or a concurrency slot never exceeds it, and a backoff\n * longer than it skips the request instead (fail open to the caller).\n */\n constructor(\n private readonly endpoint: string,\n settings: LocalLlmRateLimitSettings,\n private readonly highPriority: boolean,\n private readonly waitBudgetMs: number = settings.backoffMaxMs\n ) {\n this.settings = settings;\n this.limiter = getLocalLlmConcurrencyLimiter(settings.maxConcurrency);\n }\n\n get retryCount(): number {\n return this.retries;\n }\n\n async beforeAttempt(signal?: AbortSignal): Promise<RateLimitAttemptGate> {\n const deadlineMs = Date.now() + Math.max(0, this.waitBudgetMs);\n // Recheck the shared deadline after every async wait: another attempt may\n // have recorded or extended a cooldown while this one slept or queued.\n for (;;) {\n const remainingMs = endpointBackoffRemainingMs(this.endpoint);\n if (remainingMs > 0) {\n if (remainingMs > Math.min(this.settings.backoffMaxMs, deadlineMs - Date.now())) {\n return { kind: \"skip\", reason: \"backoff\", remainingMs };\n }\n if (!(await waitWithSignal(remainingMs, signal))) return { kind: \"aborted\" };\n continue;\n }\n const release = await this.limiter.acquire({\n highPriority: this.highPriority,\n signal,\n timeoutMs: deadlineMs - Date.now(),\n });\n if (!release) return signal?.aborted ? { kind: \"aborted\" } : { kind: \"skip\", reason: \"queue\", remainingMs: 0 };\n if (endpointBackoffRemainingMs(this.endpoint) > 0) {\n release();\n continue;\n }\n return { kind: \"go\", release };\n }\n }\n\n onSuccess(): void {\n noteEndpointRecovered(this.endpoint);\n }\n\n onResponse(status: number, retryAfterHeader: string | null | undefined, bodyText: string): RateLimitDecision {\n if (!isRateLimitedResponse(status, bodyText)) {\n noteEndpointRecovered(this.endpoint);\n return { kind: \"not-rate-limited\" };\n }\n const consecutive = noteEndpointRateLimited(this.endpoint);\n const hintMs = serverRetryHintMs(retryAfterHeader, bodyText);\n const delayMs = computeRateLimitDelayMs(consecutive, this.settings, hintMs);\n extendEndpointBackoff(this.endpoint, delayMs);\n if (this.retries >= this.settings.retryCount || delayMs > Math.min(this.settings.backoffMaxMs, this.waitBudgetMs)) {\n return { kind: \"give-up\", delayMs, retries: this.retries };\n }\n this.retries += 1;\n return { kind: \"retry\", delayMs, hintMs, consecutive, retry: this.retries };\n }\n}\n\nfunction waitWithSignal(ms: number, signal?: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve(false);\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";AAwBO,IAAM,sBAA2C,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAE/E,IAAM,0BAA0B;AAChC,IAAM,oBAAoB;AAGnB,IAAM,0BAA0B,KAAK;AAErC,IAAM,iCAAiC;AACvC,IAAM,qCAAqC;AAC3C,IAAM,oCAAoC;AAC1C,IAAM,0BAA0B;AAUvC,SAAS,eAAe,OAA2B,UAA0B;AAC3E,MAAI,UAAU,UAAa,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,EAAG,QAAO;AACxE,SAAO,KAAK,MAAM,KAAK;AACzB;AAEO,SAAS,yBAAyB,QAKX;AAC5B,QAAM,gBAAgB,KAAK;AAAA,IACzB;AAAA,IACA,eAAe,OAAO,gCAAgC,kCAAkC;AAAA,EAC1F;AACA,QAAM,eAAe,KAAK;AAAA,IACxB;AAAA,IACA,eAAe,OAAO,+BAA+B,iCAAiC;AAAA,EACxF;AACA,SAAO;AAAA,IACL,YAAY,eAAe,OAAO,6BAA6B,8BAA8B;AAAA,IAC7F;AAAA,IACA;AAAA,IACA,gBAAgB,eAAe,OAAO,wBAAwB,uBAAuB;AAAA,EACvF;AACF;AAgBA,IAAM,4BAAiD,oBAAI,IAAI;AAAA,EAC7D;AAAA,EACA;AACF,CAAC;AAKD,SAAS,wBAAwB,UAA2B;AAC1D,MAAI;AAGF,UAAM,EAAE,KAAK,IAAI,KAAK,MAAM,QAAQ;AACpC,WAAO,SAAS,UAAa,0BAA0B,IAAI,IAAI;AAAA,EACjE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAKA,IAAM,2BAA2B;AAE1B,SAAS,iCAAiC,QAAgB,UAA2B;AAC1F,MAAI,WAAW,IAAK,QAAO;AAC3B,SACE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Q,KAAK;AACb;AAAA,IACF;AACA,UAAM,UAAU,MAAY;AAC1B,mBAAa,KAAK;AAClB,cAAQ,KAAK;AAAA,IACf;AACA,UAAM,QAAQ,WAAW,MAAM;AAC7B,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ,IAAI;AAAA,IACd,GAAG,EAAE;AACL,YAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,EAC3D,CAAC;AACH;","names":[]}
|
|
@@ -154,11 +154,79 @@ var SingleFlightProbe = class {
|
|
|
154
154
|
});
|
|
155
155
|
}
|
|
156
156
|
};
|
|
157
|
+
function isHttpHeaderFieldValue(value) {
|
|
158
|
+
if (!value) return false;
|
|
159
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
160
|
+
const code = value.charCodeAt(i);
|
|
161
|
+
if (code < 32 || code === 127 || code > 255) return false;
|
|
162
|
+
}
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
function trimTrailingSlashes(url) {
|
|
166
|
+
let end = url.length;
|
|
167
|
+
while (end > 0 && url.charCodeAt(end - 1) === 47) end -= 1;
|
|
168
|
+
return end === url.length ? url : url.slice(0, end);
|
|
169
|
+
}
|
|
170
|
+
function formatLocalLlmPoolKey(chatUrl, operation) {
|
|
171
|
+
let normalized = chatUrl.replace("localhost", "127.0.0.1");
|
|
172
|
+
normalized = trimTrailingSlashes(normalized);
|
|
173
|
+
if (normalized.endsWith("/v1")) {
|
|
174
|
+
normalized = normalized.slice(0, -3);
|
|
175
|
+
}
|
|
176
|
+
const completions = normalized.endsWith("/chat/completions") ? normalized : `${normalized}/v1/chat/completions`;
|
|
177
|
+
return `${completions}|op=${operation}`;
|
|
178
|
+
}
|
|
157
179
|
function buildLocalLlmRoutingHeaders(operation, priority) {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
180
|
+
const routingEntries = [
|
|
181
|
+
["Content-Type", "application/json"]
|
|
182
|
+
];
|
|
183
|
+
if (operation !== "unspecified" && isHttpHeaderFieldValue(operation)) {
|
|
184
|
+
routingEntries.push(["X-Remnic-Operation", operation]);
|
|
185
|
+
}
|
|
186
|
+
if (priority) {
|
|
187
|
+
routingEntries.push(["X-Remnic-Priority", priority]);
|
|
188
|
+
}
|
|
189
|
+
return Object.fromEntries(routingEntries);
|
|
190
|
+
}
|
|
191
|
+
var LOCAL_LLM_GLOBAL_BACKEND_STATE = "__openclawEngramLocalLlmBackendState";
|
|
192
|
+
var BACKEND_POOL_TOMBSTONE_MS = 15 * 6e4;
|
|
193
|
+
function localLlmBackendPoolMap() {
|
|
194
|
+
const globalAny = globalThis;
|
|
195
|
+
const existing = globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];
|
|
196
|
+
if (existing) return existing;
|
|
197
|
+
const created = /* @__PURE__ */ new Map();
|
|
198
|
+
globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = created;
|
|
199
|
+
return created;
|
|
200
|
+
}
|
|
201
|
+
function getLocalLlmTrippedBackendPoolState(now, chatUrl, operation) {
|
|
202
|
+
const key = formatLocalLlmPoolKey(chatUrl, operation);
|
|
203
|
+
const map = localLlmBackendPoolMap();
|
|
204
|
+
const state = map.get(key) ?? null;
|
|
205
|
+
if (!state) return null;
|
|
206
|
+
if (state.untilMs <= now) {
|
|
207
|
+
state.expiredAtMs ??= state.untilMs;
|
|
208
|
+
if (state.expiredAtMs + BACKEND_POOL_TOMBSTONE_MS <= now) map.delete(key);
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
return state;
|
|
212
|
+
}
|
|
213
|
+
function localLlmBackendPoolExpiredAtMs(now, chatUrl, operation) {
|
|
214
|
+
const key = formatLocalLlmPoolKey(chatUrl, operation);
|
|
215
|
+
const state = localLlmBackendPoolMap().get(key) ?? null;
|
|
216
|
+
if (state && state.untilMs <= now) {
|
|
217
|
+
state.expiredAtMs ??= state.untilMs;
|
|
218
|
+
return state.expiredAtMs;
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
function markLocalLlmBackendPoolUnavailable(reason, durationMs, chatUrl, operation) {
|
|
223
|
+
const normalizedReason = normalizeBackendTripReason(reason);
|
|
224
|
+
const key = formatLocalLlmPoolKey(chatUrl, operation);
|
|
225
|
+
if (durationMs > 0) {
|
|
226
|
+
localLlmBackendPoolMap().set(key, { untilMs: Date.now() + durationMs, reason: normalizedReason });
|
|
227
|
+
} else {
|
|
228
|
+
localLlmBackendPoolMap().delete(key);
|
|
229
|
+
}
|
|
162
230
|
}
|
|
163
231
|
|
|
164
232
|
export {
|
|
@@ -172,6 +240,11 @@ export {
|
|
|
172
240
|
resolveUnavailableVerdict,
|
|
173
241
|
probeFetch,
|
|
174
242
|
SingleFlightProbe,
|
|
175
|
-
|
|
243
|
+
isHttpHeaderFieldValue,
|
|
244
|
+
formatLocalLlmPoolKey,
|
|
245
|
+
buildLocalLlmRoutingHeaders,
|
|
246
|
+
getLocalLlmTrippedBackendPoolState,
|
|
247
|
+
localLlmBackendPoolExpiredAtMs,
|
|
248
|
+
markLocalLlmBackendPoolUnavailable
|
|
176
249
|
};
|
|
177
|
-
//# sourceMappingURL=chunk-
|
|
250
|
+
//# sourceMappingURL=chunk-KYZMCH4I.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/local-llm-helpers.ts"],"sourcesContent":["import type { ResponseFormatJSONSchema } from \"openai/resources/shared\";\nimport type { Agent } from \"undici\";\nimport { log } from \"./logger.js\";\nimport { directProbeDispatcher } from \"./local-llm-transport.js\";\nimport type { LocalLlmRequestPriority } from \"./local-llm.js\";\n\nexport interface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string } | ResponseFormatJSONSchema;\n timeoutMs?: number;\n operation?: string;\n forceDisableThinking?: boolean;\n disableThinking?: boolean;\n priority?: LocalLlmRequestPriority;\n signal?: AbortSignal;\n redactProviderErrors?: boolean;\n /** Per-request model; defaults to config.localLlmModel. */\n model?: string;\n /**\n * Optional out-box for the terminal failure cause (issue #2891): on a\n * failed request the client records the last provider error here so\n * callers can classify it (e.g. HTTP 429 → rate-limited) in memory\n * instead of seeing only null. Never logged.\n */\n failureDiag?: { lastError?: unknown; finishReason?: string };\n}\n\nexport interface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\nexport function isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n}\n\n/** Caller signal combined with a client-wide shutdown signal, so a daemon\n * stop aborts in-flight requests and retry loops at once — even for\n * callers that pass no signal of their own. */\nexport function combineClientAbortSignals(\n caller: AbortSignal | undefined,\n shutdown: AbortSignal | undefined,\n): AbortSignal | undefined {\n if (shutdown === undefined) return caller;\n if (caller === undefined) return shutdown;\n return AbortSignal.any([caller, shutdown]);\n}\n\nexport function waitForRetryBackoff(backoffMs: number, signal?: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n let timer: NodeJS.Timeout | undefined;\n const onAbort = (): void => {\n if (settled) return;\n settled = true;\n if (timer) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(false);\n };\n const onTimer = (): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n };\n timer = setTimeout(onTimer, backoffMs);\n if (signal) {\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n\nexport function normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n}\n\nexport function extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n}\n\nexport function extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n}\n\n/**\n * Flatten a fetch rejection into one line, including the `cause` undici hides\n * the real reason behind (`fetch failed` alone says nothing).\n */\nexport function describeFetchFailure(err: unknown): string {\n const name = err instanceof Error ? err.name : \"\";\n const message = err instanceof Error ? err.message : String(err);\n const cause: unknown = err instanceof Error ? (err as Error & { cause?: unknown }).cause : undefined;\n const causeText = cause instanceof Error\n ? ` (cause: ${cause.name}: ${cause.message}${\n typeof (cause as Error & { code?: unknown }).code === \"string\"\n ? ` [${String((cause as Error & { code?: unknown }).code)}]`\n : \"\"\n })`\n : cause === undefined\n ? \"\"\n : ` (cause: ${String(cause)})`;\n return `${name ? `${name}: ` : \"\"}${message}${causeText}`;\n}\n\n/**\n * What to record when every availability probe failed.\n *\n * A probe that TIMED OUT is not evidence the backend is down: the budget is a\n * fixed 2s and a busy event loop can burn it before the socket is scheduled,\n * so the backend looks dead while it answers other callers in single-digit ms.\n * Caching that verdict took extraction offline for a whole health-check\n * interval at a time (issue #2210), so a timeout leaves availability UNKNOWN —\n * this call fails, the next one re-probes instead of reading a stale false.\n *\n * A backend that ANSWERED and said no is a real verdict and stays cached, or\n * the daemon re-probes a known-bad endpoint on every request.\n */\nexport function resolveUnavailableVerdict(args: {\n baseUrl: string;\n sawAbortedProbe: boolean;\n wasAvailable: boolean | null;\n}): { cacheVerdict: boolean; warning: string | null } {\n if (args.sawAbortedProbe) {\n return {\n cacheVerdict: false,\n warning:\n `local LLM availability probe timed out at ${args.baseUrl} (event loop busy?); treating availability as ` +\n \"unknown and re-probing on the next request rather than marking the backend down\",\n };\n }\n return {\n cacheVerdict: true,\n // Surfaced at warn, not debug: extraction stops silently when this flips,\n // and the daemon emits no debug at all unless configured for it.\n warning: args.wasAvailable !== false ? `local LLM became unavailable at ${args.baseUrl}` : null,\n };\n}\n\nexport interface ProbeFetchResult {\n ok: boolean;\n data: unknown;\n status: number | null;\n /** The probe hit its own budget rather than getting an answer. */\n aborted?: boolean;\n}\n\n/**\n * One health-probe request.\n *\n * Every failure is logged with its cause: a transport error and a 404 both\n * returned `ok: false` with nothing recorded, so an unreachable backend was\n * indistinguishable from a wrong path and an availability failure had no\n * diagnosable reason at all (§22, issue #2210).\n */\nexport async function probeFetch(\n url: string,\n options: { timeoutMs: number; headers: Record<string, string>; signal?: AbortSignal },\n): Promise<ProbeFetchResult> {\n const controller = new AbortController();\n const requestSignal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs);\n try {\n const init: RequestInit & { dispatcher?: Agent } = { signal: requestSignal, headers: options.headers };\n const dispatcher = directProbeDispatcher();\n if (dispatcher) init.dispatcher = dispatcher;\n const response = await fetch(url, init);\n clearTimeout(timeout);\n if (!response.ok) {\n log.debug(`local LLM probe: ${url} returned HTTP ${response.status}`);\n return { ok: false, data: null, status: response.status };\n }\n const contentType = response.headers.get(\"content-type\");\n const data = contentType?.includes(\"application/json\") ? await response.json() : await response.text();\n return { ok: true, data, status: response.status };\n } catch (err) {\n clearTimeout(timeout);\n const aborted = isAbortError(err);\n log.debug(\n `local LLM probe: ${url} ${aborted ? `timed out after ${options.timeoutMs}ms` : \"failed\"}: ${describeFetchFailure(err)}`,\n );\n return { ok: false, data: null, status: null, aborted };\n }\n}\n\ninterface PendingProbe {\n promise: Promise<boolean>;\n controller: AbortController;\n /** Callers still awaiting this sequence; at zero the sequence is aborted. */\n waiters: number;\n}\n\n/**\n * Collapses concurrent probe sequences onto one in-flight run.\n *\n * A timed-out availability probe deliberately caches nothing (issue #2210),\n * which removed the false verdict that used to absorb concurrent callers:\n * every queued request would then run its own full probe sequence, on a host\n * already slow enough to blow the probe budget.\n *\n * Cancellation is refcounted rather than shared: one caller walking away must\n * not abort a sequence the others are still waiting on, so the underlying task\n * is aborted only once every waiter has gone.\n */\nexport class SingleFlightProbe {\n private pending: PendingProbe | null = null;\n\n run(task: (signal: AbortSignal) => Promise<boolean>, signal?: AbortSignal): Promise<boolean> {\n let active = this.pending;\n if (!active) {\n const controller = new AbortController();\n const created: PendingProbe = { promise: Promise.resolve(false), controller, waiters: 0 };\n created.promise = task(controller.signal).finally(() => {\n if (this.pending === created) this.pending = null;\n });\n this.pending = created;\n active = created;\n }\n const entry = active;\n entry.waiters += 1;\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n entry.waiters -= 1;\n if (entry.waiters > 0) return;\n // Detach BEFORE aborting. `pending` would otherwise still point at this\n // doomed entry until the task's own `finally` runs a microtask later, and\n // a caller arriving in that window would join an aborted sequence and\n // read its `false` as a verdict.\n if (this.pending === entry) this.pending = null;\n entry.controller.abort();\n };\n if (!signal) return entry.promise.finally(release);\n return new Promise<boolean>((resolve, reject) => {\n const onAbort = () => {\n release();\n resolve(false);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n entry.promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n resolve(value);\n },\n (err: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n reject(err instanceof Error ? err : new Error(String(err)));\n },\n );\n });\n }\n}\n\n/** Routing headers sent to the LLM proxy; named so the known Content-Type\n * key survives alongside the optional operation/priority markers. */\nexport type LocalLlmRoutingHeaders = Record<string, string> & {\n \"Content-Type\": string;\n \"X-Remnic-Operation\"?: string;\n \"X-Remnic-Priority\"?: string;\n};\n\n/** Routing headers for the LLM proxy: operation marker and priority hint. */\nexport function buildLocalLlmRoutingHeaders(\n operation: string,\n priority: string | undefined,\n): LocalLlmRoutingHeaders {\n const headers: LocalLlmRoutingHeaders = { \"Content-Type\": \"application/json\" };\n if (operation !== \"unspecified\") headers[\"X-Remnic-Operation\"] = operation;\n if (priority) headers[\"X-Remnic-Priority\"] = priority;\n return headers;\n}\n"],"mappings":";;;;;;;;AAgCO,SAAS,aAAa,KAAuB;AAClD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,QAAQ;AACd,SACE,MAAM,SAAS,gBACf,MAAM,YAAY,gCAClB,MAAM,YAAY;AAEtB;AAKO,SAAS,0BACd,QACA,UACyB;AACzB,MAAI,aAAa,OAAW,QAAO;AACnC,MAAI,WAAW,OAAW,QAAO;AACjC,SAAO,YAAY,IAAI,CAAC,QAAQ,QAAQ,CAAC;AAC3C;AAEO,SAAS,oBAAoB,WAAmB,QAAwC;AAC7F,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,UAAU;AACd,QAAI;AACJ,UAAM,UAAU,MAAY;AAC1B,UAAI,QAAS;AACb,gBAAU;AACV,UAAI,MAAO,cAAa,KAAK;AAC7B,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ,KAAK;AAAA,IACf;AACA,UAAM,UAAU,MAAY;AAC1B,UAAI,QAAS;AACb,gBAAU;AACV,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ,IAAI;AAAA,IACd;AACA,YAAQ,WAAW,SAAS,SAAS;AACrC,QAAI,QAAQ;AACV,UAAI,OAAO,QAAS,SAAQ;AAAA,UACvB,QAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,IAC/D;AAAA,EACF,CAAC;AACH;AAEO,SAAS,2BAA2B,QAAwB;AACjE,QAAM,UAAU,OAAO,QAAQ,QAAQ,GAAG,EAAE,QAAQ,cAAc,EAAE,EAAE,KAAK;AAC3E,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,SAAS,MAAM,GAAG,QAAQ,MAAM,GAAG,GAAG,CAAC,QAAQ;AAChE;AAEO,SAAS,mCAAmC,QAA+B;AA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d,UAAM,WAAW;AACjB,QAAI,WAAW;AACf,UAAM,UAAU,MAAM;AACpB,UAAI,SAAU;AACd,iBAAW;AACX,YAAM,WAAW;AACjB,UAAI,MAAM,UAAU,EAAG;AAKvB,UAAI,KAAK,YAAY,MAAO,MAAK,UAAU;AAC3C,YAAM,WAAW,MAAM;AAAA,IACzB;AACA,QAAI,CAAC,OAAQ,QAAO,MAAM,QAAQ,QAAQ,OAAO;AACjD,WAAO,IAAI,QAAiB,CAAC,SAAS,WAAW;AAC/C,YAAM,UAAU,MAAM;AACpB,gBAAQ;AACR,gBAAQ,KAAK;AAAA,MACf;AACA,aAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACxD,YAAM,QAAQ;AAAA,QACZ,CAAC,UAAU;AACT,iBAAO,oBAAoB,SAAS,OAAO;AAC3C,kBAAQ;AACR,kBAAQ,KAAK;AAAA,QACf;AAAA,QACA,CAAC,QAAiB;AAChB,iBAAO,oBAAoB,SAAS,OAAO;AAC3C,kBAAQ;AACR,iBAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;AAAA,QAC5D;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAWO,SAAS,4BACd,WACA,UACwB;AACxB,QAAM,UAAkC,EAAE,gBAAgB,mBAAmB;AAC7E,MAAI,cAAc,cAAe,SAAQ,oBAAoB,IAAI;AACjE,MAAI,SAAU,SAAQ,mBAAmB,IAAI;AAC7C,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/local-llm-helpers.ts"],"sourcesContent":["import type { ResponseFormatJSONSchema } from \"openai/resources/shared\";\nimport type { Agent } from \"undici\";\nimport { log } from \"./logger.js\";\nimport { directProbeDispatcher } from \"./local-llm-transport.js\";\nimport type { LocalLlmRequestPriority } from \"./local-llm.js\";\n\nexport interface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string } | ResponseFormatJSONSchema;\n timeoutMs?: number;\n operation?: string;\n forceDisableThinking?: boolean;\n disableThinking?: boolean;\n priority?: LocalLlmRequestPriority;\n signal?: AbortSignal;\n redactProviderErrors?: boolean;\n /** Per-request model; defaults to config.localLlmModel. */\n model?: string;\n /**\n * Optional out-box for the terminal failure cause (issue #2891): on a\n * failed request the client records the last provider error here so\n * callers can classify it (e.g. HTTP 429 → rate-limited) in memory\n * instead of seeing only null. Never logged.\n */\n failureDiag?: { lastError?: unknown; finishReason?: string };\n}\n\nexport interface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\nexport function isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n}\n\n/** Caller signal combined with a client-wide shutdown signal, so a daemon\n * stop aborts in-flight requests and retry loops at once — even for\n * callers that pass no signal of their own. */\nexport function combineClientAbortSignals(\n caller: AbortSignal | undefined,\n shutdown: AbortSignal | undefined,\n): AbortSignal | undefined {\n if (shutdown === undefined) return caller;\n if (caller === undefined) return shutdown;\n return AbortSignal.any([caller, shutdown]);\n}\n\nexport function waitForRetryBackoff(backoffMs: number, signal?: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n let timer: NodeJS.Timeout | undefined;\n const onAbort = (): void => {\n if (settled) return;\n settled = true;\n if (timer) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(false);\n };\n const onTimer = (): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n };\n timer = setTimeout(onTimer, backoffMs);\n if (signal) {\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n\nexport function normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n}\n\nexport function extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n}\n\nexport function extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n}\n\n/**\n * Flatten a fetch rejection into one line, including the `cause` undici hides\n * the real reason behind (`fetch failed` alone says nothing).\n */\nexport function describeFetchFailure(err: unknown): string {\n const name = err instanceof Error ? err.name : \"\";\n const message = err instanceof Error ? err.message : String(err);\n const cause: unknown = err instanceof Error ? (err as Error & { cause?: unknown }).cause : undefined;\n const causeText = cause instanceof Error\n ? ` (cause: ${cause.name}: ${cause.message}${\n typeof (cause as Error & { code?: unknown }).code === \"string\"\n ? ` [${String((cause as Error & { code?: unknown }).code)}]`\n : \"\"\n })`\n : cause === undefined\n ? \"\"\n : ` (cause: ${String(cause)})`;\n return `${name ? `${name}: ` : \"\"}${message}${causeText}`;\n}\n\n/**\n * What to record when every availability probe failed.\n *\n * A probe that TIMED OUT is not evidence the backend is down: the budget is a\n * fixed 2s and a busy event loop can burn it before the socket is scheduled,\n * so the backend looks dead while it answers other callers in single-digit ms.\n * Caching that verdict took extraction offline for a whole health-check\n * interval at a time (issue #2210), so a timeout leaves availability UNKNOWN —\n * this call fails, the next one re-probes instead of reading a stale false.\n *\n * A backend that ANSWERED and said no is a real verdict and stays cached, or\n * the daemon re-probes a known-bad endpoint on every request.\n */\nexport function resolveUnavailableVerdict(args: {\n baseUrl: string;\n sawAbortedProbe: boolean;\n wasAvailable: boolean | null;\n}): { cacheVerdict: boolean; warning: string | null } {\n if (args.sawAbortedProbe) {\n return {\n cacheVerdict: false,\n warning:\n `local LLM availability probe timed out at ${args.baseUrl} (event loop busy?); treating availability as ` +\n \"unknown and re-probing on the next request rather than marking the backend down\",\n };\n }\n return {\n cacheVerdict: true,\n // Surfaced at warn, not debug: extraction stops silently when this flips,\n // and the daemon emits no debug at all unless configured for it.\n warning: args.wasAvailable !== false ? `local LLM became unavailable at ${args.baseUrl}` : null,\n };\n}\n\nexport interface ProbeFetchResult {\n ok: boolean;\n data: unknown;\n status: number | null;\n /** The probe hit its own budget rather than getting an answer. */\n aborted?: boolean;\n}\n\n/**\n * One health-probe request.\n *\n * Every failure is logged with its cause: a transport error and a 404 both\n * returned `ok: false` with nothing recorded, so an unreachable backend was\n * indistinguishable from a wrong path and an availability failure had no\n * diagnosable reason at all (§22, issue #2210).\n */\nexport async function probeFetch(\n url: string,\n options: { timeoutMs: number; headers: Record<string, string>; signal?: AbortSignal },\n): Promise<ProbeFetchResult> {\n const controller = new AbortController();\n const requestSignal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs);\n try {\n const init: RequestInit & { dispatcher?: Agent } = { signal: requestSignal, headers: options.headers };\n const dispatcher = directProbeDispatcher();\n if (dispatcher) init.dispatcher = dispatcher;\n const response = await fetch(url, init);\n clearTimeout(timeout);\n if (!response.ok) {\n log.debug(`local LLM probe: ${url} returned HTTP ${response.status}`);\n return { ok: false, data: null, status: response.status };\n }\n const contentType = response.headers.get(\"content-type\");\n const data = contentType?.includes(\"application/json\") ? await response.json() : await response.text();\n return { ok: true, data, status: response.status };\n } catch (err) {\n clearTimeout(timeout);\n const aborted = isAbortError(err);\n log.debug(\n `local LLM probe: ${url} ${aborted ? `timed out after ${options.timeoutMs}ms` : \"failed\"}: ${describeFetchFailure(err)}`,\n );\n return { ok: false, data: null, status: null, aborted };\n }\n}\n\ninterface PendingProbe {\n promise: Promise<boolean>;\n controller: AbortController;\n /** Callers still awaiting this sequence; at zero the sequence is aborted. */\n waiters: number;\n}\n\n/**\n * Collapses concurrent probe sequences onto one in-flight run.\n *\n * A timed-out availability probe deliberately caches nothing (issue #2210),\n * which removed the false verdict that used to absorb concurrent callers:\n * every queued request would then run its own full probe sequence, on a host\n * already slow enough to blow the probe budget.\n *\n * Cancellation is refcounted rather than shared: one caller walking away must\n * not abort a sequence the others are still waiting on, so the underlying task\n * is aborted only once every waiter has gone.\n */\nexport class SingleFlightProbe {\n private pending: PendingProbe | null = null;\n\n run(task: (signal: AbortSignal) => Promise<boolean>, signal?: AbortSignal): Promise<boolean> {\n let active = this.pending;\n if (!active) {\n const controller = new AbortController();\n const created: PendingProbe = { promise: Promise.resolve(false), controller, waiters: 0 };\n created.promise = task(controller.signal).finally(() => {\n if (this.pending === created) this.pending = null;\n });\n this.pending = created;\n active = created;\n }\n const entry = active;\n entry.waiters += 1;\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n entry.waiters -= 1;\n if (entry.waiters > 0) return;\n // Detach BEFORE aborting. `pending` would otherwise still point at this\n // doomed entry until the task's own `finally` runs a microtask later, and\n // a caller arriving in that window would join an aborted sequence and\n // read its `false` as a verdict.\n if (this.pending === entry) this.pending = null;\n entry.controller.abort();\n };\n if (!signal) return entry.promise.finally(release);\n return new Promise<boolean>((resolve, reject) => {\n const onAbort = () => {\n release();\n resolve(false);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n entry.promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n resolve(value);\n },\n (err: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n reject(err instanceof Error ? err : new Error(String(err)));\n },\n );\n });\n }\n}\n\n/** True when `value` is safe for `fetch` request headers. Node's `Headers`\n * accepts a ByteString: controls and DEL are out, and so is anything above\n * U+00FF — `é` is sendable, `Ā` is not (Kilo review on #3474). */\nexport function isHttpHeaderFieldValue(value: string): boolean {\n if (!value) return false;\n for (let i = 0; i < value.length; i += 1) {\n const code = value.charCodeAt(i);\n if (code < 0x20 || code === 0x7f || code > 0xff) return false;\n }\n return true;\n}\n\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === 47) end -= 1;\n return end === url.length ? url : url.slice(0, end);\n}\n\n/** Circuit-breaker and rate-limit scope when recall/extraction share one proxy URL. */\nexport function formatLocalLlmPoolKey(chatUrl: string, operation: string): string {\n let normalized = chatUrl.replace(\"localhost\", \"127.0.0.1\");\n normalized = trimTrailingSlashes(normalized);\n if (normalized.endsWith(\"/v1\")) {\n normalized = normalized.slice(0, -3);\n }\n const completions = normalized.endsWith(\"/chat/completions\")\n ? normalized\n : `${normalized}/v1/chat/completions`;\n return `${completions}|op=${operation}`;\n}\n\n/** HTTP headers the jarvis-ml recall proxy reads for pool routing. */\nexport function buildLocalLlmRoutingHeaders(\n operation: string,\n priority: \"recall-critical\" | \"background\" | undefined,\n): Record<string, string> {\n const routingEntries: Array<readonly [string, string]> = [\n [\"Content-Type\", \"application/json\"],\n ];\n if (operation !== \"unspecified\" && isHttpHeaderFieldValue(operation)) {\n routingEntries.push([\"X-Remnic-Operation\", operation]);\n }\n if (priority) {\n routingEntries.push([\"X-Remnic-Priority\", priority]);\n }\n return Object.fromEntries(routingEntries) satisfies Record<string, string>;\n}\n\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\nexport type LocalLlmBackendPoolState = {\n untilMs: number;\n reason: string;\n /** Once the trip lapses this is set instead of deleting the entry: every\n * client must observe the transition once, so a tombstone stays visible for\n * BACKEND_POOL_TOMBSTONE_MS. */\n expiredAtMs?: number;\n};\n\n/** How long a lapsed circuit stays readable so each client can invalidate its\n * cached health verdict once (the health cache is 60s; this leaves margin). */\nconst BACKEND_POOL_TOMBSTONE_MS = 15 * 60_000;\n\nfunction localLlmBackendPoolMap(): Map<string, LocalLlmBackendPoolState> {\n // SAFETY: globalThis carries one optional Map slot keyed for backend pool state.\n const globalAny = globalThis as typeof globalThis & {\n [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendPoolState>;\n };\n const existing = globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];\n if (existing) return existing;\n const created = new Map<string, LocalLlmBackendPoolState>();\n globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = created;\n return created;\n}\n\nexport function getLocalLlmTrippedBackendPoolState(\n now: number,\n chatUrl: string,\n operation: string,\n): LocalLlmBackendPoolState | null {\n const key = formatLocalLlmPoolKey(chatUrl, operation);\n const map = localLlmBackendPoolMap();\n const state = map.get(key) ?? null;\n if (!state) return null;\n if (state.untilMs <= now) {\n state.expiredAtMs ??= state.untilMs;\n if (state.expiredAtMs + BACKEND_POOL_TOMBSTONE_MS <= now) map.delete(key);\n return null;\n }\n return state;\n}\n\n/** The instant this pool's circuit lapsed, or null while it is active or\n * absent. The tombstone stays in the map so every client holding a cached\n * health verdict can observe the transition once — deleting on first read left\n * later clients stale (wAN review on #3474). */\nexport function localLlmBackendPoolExpiredAtMs(now: number, chatUrl: string, operation: string): number | null {\n const key = formatLocalLlmPoolKey(chatUrl, operation);\n const state = localLlmBackendPoolMap().get(key) ?? null;\n if (state && state.untilMs <= now) {\n state.expiredAtMs ??= state.untilMs;\n return state.expiredAtMs;\n }\n return null;\n}\n\nexport function markLocalLlmBackendPoolUnavailable(\n reason: string,\n durationMs: number,\n chatUrl: string,\n operation: string,\n): void {\n const normalizedReason = normalizeBackendTripReason(reason);\n const key = formatLocalLlmPoolKey(chatUrl, operation);\n if (durationMs > 0) {\n localLlmBackendPoolMap().set(key, { untilMs: Date.now() + durationMs, reason: normalizedReason });\n } else {\n localLlmBackendPoolMap().delete(key);\n }\n}\n"],"mappings":";;;;;;;;AAgCO,SAAS,aAAa,KAAuB;AAClD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,QAAQ;AACd,SACE,MAAM,SAAS,gBAC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AG;AAClB,2BAAuB,EAAE,IAAI,KAAK,EAAE,SAAS,KAAK,IAAI,IAAI,YAAY,QAAQ,iBAAiB,CAAC;AAAA,EAClG,OAAO;AACL,2BAAuB,EAAE,OAAO,GAAG;AAAA,EACrC;AACF;","names":[]}
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
} from "./chunk-QNUNAXBE.js";
|
|
12
12
|
import {
|
|
13
13
|
LocalLlmClient
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-YOR5QBEU.js";
|
|
15
15
|
import {
|
|
16
16
|
completeBackgroundGeneration,
|
|
17
17
|
parseBackgroundGenerationJson
|
|
@@ -808,4 +808,4 @@ export {
|
|
|
808
808
|
summarizeHourlyStatus,
|
|
809
809
|
HourlySummarizer
|
|
810
810
|
};
|
|
811
|
-
//# sourceMappingURL=chunk-
|
|
811
|
+
//# sourceMappingURL=chunk-TXVTNDQT.js.map
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
isIsoWeekId,
|
|
22
22
|
msUntilNextIsoWeek,
|
|
23
23
|
previousIsoWeekId
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-BT5TAOXG.js";
|
|
25
25
|
import {
|
|
26
26
|
planNamespaceMaintenance,
|
|
27
27
|
runNamespaceMaintenanceBatchPlan
|
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
} from "./chunk-UR6COSJN.js";
|
|
32
32
|
import {
|
|
33
33
|
LocalLlmClient
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-YOR5QBEU.js";
|
|
35
35
|
import {
|
|
36
36
|
DEFAULT_TIMELINE_CATEGORIES,
|
|
37
37
|
TIMELINE_RESERVED_IDLE,
|
|
@@ -2874,4 +2874,4 @@ export {
|
|
|
2874
2874
|
ActivitySyncScheduler,
|
|
2875
2875
|
MaintenanceScheduler
|
|
2876
2876
|
};
|
|
2877
|
-
//# sourceMappingURL=chunk-
|
|
2877
|
+
//# sourceMappingURL=chunk-UADAXWUJ.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
ExtractionDrain,
|
|
3
3
|
TurnIngestionCoordinator,
|
|
4
4
|
shouldSkipImplicitExtraction
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-3RHD5TF5.js";
|
|
6
6
|
import {
|
|
7
7
|
headerConnector,
|
|
8
8
|
renderExtractionConversation,
|
|
@@ -447,4 +447,4 @@ export {
|
|
|
447
447
|
ClaimBufferStorage,
|
|
448
448
|
BufferDrainRunner
|
|
449
449
|
};
|
|
450
|
-
//# sourceMappingURL=chunk-
|
|
450
|
+
//# sourceMappingURL=chunk-XC5BRK7J.js.map
|