@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.
Files changed (77) hide show
  1. package/dist/access-admin-ops-surface.js +10 -10
  2. package/dist/access-cli.js +10 -10
  3. package/dist/access-extraction-force-flush-preempt.js +10 -10
  4. package/dist/access-extraction-force-flush.js +10 -10
  5. package/dist/access-http-briefing.js +10 -10
  6. package/dist/access-http-query.js +10 -10
  7. package/dist/access-http.js +10 -10
  8. package/dist/access-identity-continuity-surface.js +10 -10
  9. package/dist/access-lcm-surface.js +10 -10
  10. package/dist/access-mcp.js +10 -10
  11. package/dist/access-observe-write-surface.js +10 -10
  12. package/dist/access-operations-batch.js +10 -10
  13. package/dist/access-operations.js +10 -10
  14. package/dist/access-recall-concurrency.js +10 -10
  15. package/dist/access-recall-response.js +10 -10
  16. package/dist/access-recall-surface.js +10 -10
  17. package/dist/access-service.js +10 -10
  18. package/dist/calibration.js +3 -3
  19. package/dist/{chunk-RGXNPAMA.js → chunk-3RHD5TF5.js} +38 -30
  20. package/dist/{chunk-RGXNPAMA.js.map → chunk-3RHD5TF5.js.map} +1 -1
  21. package/dist/{chunk-SKCMEZBU.js → chunk-52EM4UQU.js} +2 -2
  22. package/dist/{chunk-QAQL2OQH.js → chunk-5V3IBSVB.js} +2 -2
  23. package/dist/{chunk-K4TMUEYI.js → chunk-BT5TAOXG.js} +1 -1
  24. package/dist/{chunk-4IJBNRMZ.js → chunk-DRXFLPSE.js} +12 -2
  25. package/dist/chunk-DRXFLPSE.js.map +1 -0
  26. package/dist/{chunk-AGMMHT4P.js → chunk-GT2HWRST.js} +21 -3
  27. package/dist/chunk-GT2HWRST.js.map +1 -0
  28. package/dist/{chunk-BDKLKX43.js → chunk-KYZMCH4I.js} +79 -6
  29. package/dist/{chunk-BDKLKX43.js.map → chunk-KYZMCH4I.js.map} +1 -1
  30. package/dist/{chunk-RXG3WF7C.js → chunk-TXVTNDQT.js} +2 -2
  31. package/dist/{chunk-2TUWMP7B.js → chunk-UADAXWUJ.js} +3 -3
  32. package/dist/{chunk-Z6AP6O32.js → chunk-XC5BRK7J.js} +2 -2
  33. package/dist/{chunk-XWRSQWQO.js → chunk-YOR5QBEU.js} +60 -59
  34. package/dist/chunk-YOR5QBEU.js.map +1 -0
  35. package/dist/cli.js +10 -10
  36. package/dist/compounding/engine.js +1 -1
  37. package/dist/explicit-capture.js +10 -10
  38. package/dist/extraction.js +4 -4
  39. package/dist/index.js +10 -10
  40. package/dist/local-llm-helpers.d.ts +22 -8
  41. package/dist/local-llm-helpers.d.ts.map +1 -1
  42. package/dist/local-llm-helpers.js +11 -1
  43. package/dist/local-llm-rate-limit.d.ts +1 -5
  44. package/dist/local-llm-rate-limit.d.ts.map +1 -1
  45. package/dist/local-llm-rate-limit.js +3 -1
  46. package/dist/local-llm.d.ts +2 -4
  47. package/dist/local-llm.d.ts.map +1 -1
  48. package/dist/local-llm.js +3 -3
  49. package/dist/orchestration/backlog-scheduler.js +11 -11
  50. package/dist/orchestration/buffer-drain-runner.js +11 -11
  51. package/dist/orchestration/maintenance.js +5 -5
  52. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  53. package/dist/orchestrator.js +10 -10
  54. package/dist/recall-enrichment-promise.d.ts +7 -2
  55. package/dist/recall-enrichment-promise.d.ts.map +1 -1
  56. package/dist/recall-enrichment-promise.js +1 -1
  57. package/dist/recall-navigation.js +10 -10
  58. package/dist/summarizer.js +4 -4
  59. package/dist/support-passport/index.js +4 -4
  60. package/package.json +12 -2
  61. package/src/local-llm-helpers.ts +116 -14
  62. package/src/local-llm-rate-limit.test.ts +79 -1
  63. package/src/local-llm-rate-limit.ts +37 -1
  64. package/src/local-llm.ts +75 -74
  65. package/src/orchestration/recall-internal.ts +36 -24
  66. package/src/recall-enrichment-promise.ts +20 -2
  67. package/src/recall-qos.test.ts +24 -0
  68. package/src/recall-timings-request-contract.test.ts +10 -8
  69. package/dist/chunk-4IJBNRMZ.js.map +0 -1
  70. package/dist/chunk-AGMMHT4P.js.map +0 -1
  71. package/dist/chunk-XWRSQWQO.js.map +0 -1
  72. /package/dist/{chunk-SKCMEZBU.js.map → chunk-52EM4UQU.js.map} +0 -0
  73. /package/dist/{chunk-QAQL2OQH.js.map → chunk-5V3IBSVB.js.map} +0 -0
  74. /package/dist/{chunk-K4TMUEYI.js.map → chunk-BT5TAOXG.js.map} +0 -0
  75. /package/dist/{chunk-RXG3WF7C.js.map → chunk-TXVTNDQT.js.map} +0 -0
  76. /package/dist/{chunk-2TUWMP7B.js.map → chunk-UADAXWUJ.js.map} +0 -0
  77. /package/dist/{chunk-Z6AP6O32.js.map → chunk-XC5BRK7J.js.map} +0 -0
package/src/local-llm.ts CHANGED
@@ -7,10 +7,9 @@ import os from "node:os";
7
7
  import type { ModelRegistry } from "./model-registry.js";
8
8
  import { launchProcessSync } from "./runtime/child-process.js";
9
9
  import { mergeEnv, readEnvVar } from "./runtime/env.js";
10
- import { resolveLocalLlmCapabilities } from "./capabilities.js";
11
- import { resolvePipelineProcessingCapabilities } from "./capabilities.js";
10
+ import { resolveLocalLlmCapabilities, resolvePipelineProcessingCapabilities } from "./capabilities.js";
12
11
  import { ChatTransport } from "./local-llm-transport.js";
13
- import { LocalLlmRateLimitSession, resolveRateLimitSettings } from "./local-llm-rate-limit.js";
12
+ import { LocalLlmRateLimitSession, resolveRateLimitSettings, isTerminalLocalLlmProxyPoolError } from "./local-llm-rate-limit.js";
14
13
  import {
15
14
  extractNonRecoverableBackendReason,
16
15
  extractNonRecoverableBackendReasonFromErrorText,
@@ -22,9 +21,13 @@ import {
22
21
  waitForRetryBackoff,
23
22
  combineClientAbortSignals,
24
23
  SingleFlightProbe,
24
+ buildLocalLlmRoutingHeaders,
25
+ formatLocalLlmPoolKey,
26
+ localLlmBackendPoolExpiredAtMs,
27
+ getLocalLlmTrippedBackendPoolState,
28
+ markLocalLlmBackendPoolUnavailable,
25
29
  type LocalLlmChatCompletionOptions,
26
30
  type LocalLlmChatCompletionResult,
27
- buildLocalLlmRoutingHeaders,
28
31
  } from "./local-llm-helpers.js";
29
32
  import { NativeSchemaGate, type LocalLlmChatRequestBody } from "./local-llm-native-schema.js";
30
33
  import {
@@ -167,12 +170,6 @@ interface LocalLlmQueuedRequest {
167
170
  resolve: (value: LocalLlmChatCompletionResult | null) => void;
168
171
  }
169
172
 
170
- const LOCAL_LLM_GLOBAL_BACKEND_STATE = "__openclawEngramLocalLlmBackendState";
171
-
172
- type LocalLlmBackendState = {
173
- untilMs: number;
174
- reason: string;
175
- };
176
173
  /**
177
174
  * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)
178
175
  *
@@ -184,6 +181,7 @@ export class LocalLlmClient {
184
181
  private config: PluginConfig;
185
182
  private isAvailable: boolean | null = null;
186
183
  private lastHealthCheck: number = 0;
184
+ private poolExpirySeenMs = new Map<string, number>(); // pool key → lapsed-circuit instant already invalidated
187
185
  private readonly availabilityProbe = new SingleFlightProbe();
188
186
  private detectedType: LocalLlmType | null = null;
189
187
  private cachedModelInfo: LocalModelInfo | null = null;
@@ -236,11 +234,16 @@ export class LocalLlmClient {
236
234
  }
237
235
 
238
236
  private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {
239
- const headers: Record<string, string> = {
240
- ...base,
241
- ...(this.config.localLlmHeaders ?? {}),
242
- };
237
+ const headers = { ...base } satisfies Record<string, string>;
238
+ const configured = this.config.localLlmHeaders ?? {};
239
+ for (const [key, value] of Object.entries(configured)) {
240
+ const existing = Object.keys(headers).find((name) => name.toLowerCase() === key.toLowerCase());
241
+ if (existing !== undefined) delete headers[existing];
242
+ headers[key] = value;
243
+ }
243
244
  if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {
245
+ const existing = Object.keys(headers).find((name) => name.toLowerCase() === "authorization");
246
+ if (existing !== undefined) delete headers[existing];
244
247
  headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;
245
248
  }
246
249
  return headers;
@@ -261,45 +264,17 @@ export class LocalLlmClient {
261
264
  return this.detectedType;
262
265
  }
263
266
 
264
- private getBackendKey(): string {
265
- return trimTrailingSlashes(
266
- this.config.localLlmUrl.replace("localhost", "127.0.0.1"),
267
- ).replace(/\/v1$/, "");
268
- }
269
-
270
- private getGlobalBackendState(): Map<string, LocalLlmBackendState> {
271
- const globalAny = globalThis as typeof globalThis & {
272
- [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendState>;
273
- };
274
- if (!globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE]) {
275
- globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = new Map();
276
- }
277
- return globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];
278
- }
279
-
280
- private getTrippedBackendState(now: number): LocalLlmBackendState | null {
281
- const state = this.getGlobalBackendState().get(this.getBackendKey()) ?? null;
282
- if (!state) return null;
283
- if (state.untilMs <= now) {
284
- this.getGlobalBackendState().delete(this.getBackendKey());
285
- this.lastHealthCheck = 0;
286
- return null;
287
- }
288
- return state;
289
- }
290
-
291
- private markBackendUnavailable(reason: string, durationMs: number): void {
292
- const normalizedReason = normalizeBackendTripReason(reason);
293
- if (durationMs > 0) {
294
- const untilMs = Date.now() + durationMs;
295
- this.getGlobalBackendState().set(this.getBackendKey(), { untilMs, reason: normalizedReason });
296
- } else {
297
- this.getGlobalBackendState().delete(this.getBackendKey());
298
- }
267
+ private markBackendUnavailable(
268
+ reason: string,
269
+ durationMs: number,
270
+ chatUrl: string,
271
+ operation: string,
272
+ ): void {
273
+ markLocalLlmBackendPoolUnavailable(reason, durationMs, chatUrl, operation);
299
274
  this.isAvailable = false;
300
275
  this.lastHealthCheck = 0;
301
276
  log.warn(
302
- `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizedReason}`,
277
+ `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizeBackendTripReason(reason)} op=${operation}`,
303
278
  );
304
279
  }
305
280
 
@@ -344,18 +319,33 @@ export class LocalLlmClient {
344
319
  * Check if local LLM is available
345
320
  * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)
346
321
  */
347
- async checkAvailability(signal?: AbortSignal): Promise<boolean> {
322
+ async checkAvailability(
323
+ signal?: AbortSignal,
324
+ chatUrl?: string,
325
+ operation?: string,
326
+ ): Promise<boolean> {
348
327
  if (signal?.aborted) return false;
349
- // Cache health check results for 1 minute
350
- const now = Date.now();
351
- const trippedState = this.getTrippedBackendState(now);
352
- if (trippedState) {
353
- this.isAvailable = false;
354
- this.lastHealthCheck = 0;
355
- log.info(
356
- `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason})`,
357
- );
358
- return false;
328
+ const now = Date.now(); // cache health check results for 1 minute
329
+ if (chatUrl) {
330
+ // An empty label is a real pool key: a "" caller still sees a recorded circuit (wAN on #3474).
331
+ const poolOperation = operation ?? "unspecified";
332
+ const poolKey = formatLocalLlmPoolKey(chatUrl, poolOperation);
333
+ // A lapsed circuit stays visible as a tombstone; each client clears its cached verdict once.
334
+ const expiredAtMs = localLlmBackendPoolExpiredAtMs(now, chatUrl, poolOperation);
335
+ if (expiredAtMs !== null && expiredAtMs > (this.poolExpirySeenMs.get(poolKey) ?? 0)) {
336
+ this.poolExpirySeenMs.set(poolKey, expiredAtMs);
337
+ this.isAvailable = null;
338
+ this.lastHealthCheck = 0;
339
+ }
340
+ const trippedState = getLocalLlmTrippedBackendPoolState(now, chatUrl, poolOperation);
341
+ if (trippedState) {
342
+ this.isAvailable = false;
343
+ this.lastHealthCheck = 0;
344
+ log.info(
345
+ `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason}) op=${poolOperation}`,
346
+ );
347
+ return false;
348
+ }
359
349
  }
360
350
  if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {
361
351
  return this.isAvailable;
@@ -882,13 +872,20 @@ export class LocalLlmClient {
882
872
  );
883
873
  }
884
874
 
875
+ let chatUrl = "";
885
876
  try {
886
877
  const signal = combineClientAbortSignals(options.signal, this.shutdownSignal);
887
878
  if (signal?.aborted) return null;
888
- const isAvailable = await this.checkAvailability(signal);
879
+ const baseUrl = trimTrailingSlashes(
880
+ this.config.localLlmUrl.replace("localhost", "127.0.0.1"),
881
+ );
882
+ chatUrl = baseUrl.endsWith("/v1")
883
+ ? `${baseUrl}/chat/completions`
884
+ : `${baseUrl}/v1/chat/completions`;
885
+ const isAvailable = await this.checkAvailability(signal, chatUrl, operation);
889
886
  if (!isAvailable) {
890
887
  log.debug(
891
- `local LLM: checkAvailability returned false for ${this.config.localLlmUrl}`,
888
+ `local LLM: checkAvailability returned false for ${this.config.localLlmUrl} op=${operation}`,
892
889
  );
893
890
  return null;
894
891
  }
@@ -948,14 +945,6 @@ export class LocalLlmClient {
948
945
  }
949
946
  }
950
947
 
951
- // Normalize URL (use 127.0.0.1 instead of localhost)
952
- const baseUrl = trimTrailingSlashes(
953
- this.config.localLlmUrl.replace("localhost", "127.0.0.1"),
954
- );
955
- const chatUrl = baseUrl.endsWith("/v1")
956
- ? `${baseUrl}/chat/completions`
957
- : `${baseUrl}/v1/chat/completions`;
958
-
959
948
  let requestBodyJson = JSON.stringify(requestBody);
960
949
  log.debug(
961
950
  `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,
@@ -973,8 +962,12 @@ export class LocalLlmClient {
973
962
  // process-wide semaphore caps concurrent HTTP attempts across clients.
974
963
  // Waits are bounded by the request timeout so a short caller budget
975
964
  // (e.g. rerankTimeoutMs) is never stretched by a long cooldown.
976
- const rateLimit = new LocalLlmRateLimitSession(chatUrl, resolveRateLimitSettings(this.config),
977
- (queueMeta?.priority ?? options.priority) === "recall-critical", effectiveTimeoutMs);
965
+ const rateLimit = new LocalLlmRateLimitSession(
966
+ formatLocalLlmPoolKey(chatUrl, operation),
967
+ resolveRateLimitSettings(this.config),
968
+ (queueMeta?.priority ?? options.priority) === "recall-critical",
969
+ effectiveTimeoutMs,
970
+ );
978
971
  let lastRateLimitDelayMs: number | null = null;
979
972
  let response: Response | null = null, responseBody = "";
980
973
  let lastAbortError: Error | null = null;
@@ -1066,6 +1059,8 @@ export class LocalLlmClient {
1066
1059
  this.markBackendUnavailable(
1067
1060
  nonRecoverableReason,
1068
1061
  this.config.localLlm400CooldownMs,
1062
+ chatUrl,
1063
+ operation,
1069
1064
  );
1070
1065
  this.consecutive400s = 0;
1071
1066
  return null;
@@ -1079,6 +1074,8 @@ export class LocalLlmClient {
1079
1074
  attempt -= 1; // own retry budget; the loop top waits out the backoff
1080
1075
  continue;
1081
1076
  }
1077
+ // A terminal pool-unavailable 503 must not reach the generic 5xx retry.
1078
+ if (isTerminalLocalLlmProxyPoolError(response.status, responseBody)) break;
1082
1079
  if (response.status < 500 || attempt >= maxAttempts) break;
1083
1080
 
1084
1081
  const backoffMs = this.config.localLlmRetryBackoffMs * attempt;
@@ -1124,6 +1121,8 @@ export class LocalLlmClient {
1124
1121
  this.markBackendUnavailable(
1125
1122
  nonRecoverableReason,
1126
1123
  this.config.localLlm400CooldownMs,
1124
+ chatUrl,
1125
+ operation,
1127
1126
  );
1128
1127
  this.consecutive400s = 0;
1129
1128
  return null;
@@ -1207,10 +1206,12 @@ export class LocalLlmClient {
1207
1206
  log.warn(`local LLM request error: op=${operation} error=${options.redactProviderErrors ? "provider error details redacted" : errMsg}`);
1208
1207
  this.isAvailable = false; // Mark as unavailable on non-abort errors
1209
1208
  const nonRecoverableReason = extractNonRecoverableBackendReason(errMsg);
1210
- if (nonRecoverableReason) {
1209
+ if (nonRecoverableReason && chatUrl.length > 0) {
1211
1210
  this.markBackendUnavailable(
1212
1211
  nonRecoverableReason,
1213
1212
  this.config.localLlm400CooldownMs,
1213
+ chatUrl,
1214
+ operation,
1214
1215
  );
1215
1216
  }
1216
1217
  return null;
@@ -56,6 +56,7 @@ import {
56
56
  import {
57
57
  createBoundedCoreSectionRunner,
58
58
  createRecallSectionMetricRecorder,
59
+ resolveRecallCoreSectionDeadlineMs,
59
60
  } from "../recall-qos.js";
60
61
  import { buildRecallQueryPolicy } from "../recall-query-policy.js";
61
62
  import { type GraphRecallExpandedEntry, type LastRecallSnapshot } from "../recall-state.js";
@@ -68,7 +69,7 @@ import {
68
69
  import { foldQueueWaitTiming } from "../recall-timings.js";
69
70
  import { emitRecallTiming } from "../recall-attempt-timing.js";
70
71
  import { createPhase2Timer, type Phase2AwaitStatus } from "../recall-phase2-timing.js";
71
- import { createEnrichmentAbortHandle, observeEnrichmentPromise, type DeferredEnrichmentOutcome, type ObservedDeferredEnrichmentPromise } from "../recall-enrichment-promise.js";
72
+ import { createEnrichmentAbortHandle, observeEnrichmentPromise, type DeferredEnrichmentOutcome, type EnrichmentAbortHandle, type ObservedDeferredEnrichmentPromise } from "../recall-enrichment-promise.js";
72
73
  import { findUnresolvedEntityRefs } from "../reconstruct.js";
73
74
  import { rerankLocalOrNoop, reorderByRankedKeys } from "../rerank.js";
74
75
  import { buildResponseGuidanceRecallSection, shouldRecallResponseGuidance } from "../response-guidance-recall.js";
@@ -180,10 +181,15 @@ export class RecallInternalCoordinator {
180
181
  timings,
181
182
  logger: log,
182
183
  });
184
+ const outerDeadlineAtMs =
185
+ recallOuterTimeoutMs > 0 ? recallStart + recallOuterTimeoutMs : null;
186
+ const enrichmentAbort = () =>
187
+ createEnrichmentAbortHandle(options.abortSignal, resolveRecallCoreSectionDeadlineMs({
188
+ configuredCoreDeadlineMs: enrichmentSectionDeadlineMs,
189
+ remainingOuterMs: outerDeadlineAtMs === null ? null : outerDeadlineAtMs - Date.now() }));
183
190
  const runBoundedCoreSection = createBoundedCoreSectionRunner({
184
191
  configuredDeadlineMs: recallSectionDeadlineMs,
185
- outerDeadlineAtMs:
186
- recallOuterTimeoutMs > 0 ? recallStart + recallOuterTimeoutMs : null,
192
+ outerDeadlineAtMs,
187
193
  parentSignal: options.abortSignal,
188
194
  record: recordRecallSectionMetric,
189
195
  logger: log,
@@ -1446,9 +1452,7 @@ export class RecallInternalCoordinator {
1446
1452
  })();
1447
1453
 
1448
1454
  const harmonicStartedMs = performance.now();
1449
- const harmonicRetrievalAbort = createEnrichmentAbortHandle(
1450
- options.abortSignal,
1451
- );
1455
+ const harmonicRetrievalAbort = enrichmentAbort();
1452
1456
  const harmonicRetrievalPromise = observeEnrichmentPromise(
1453
1457
  (async (): Promise<string | null> => {
1454
1458
  const t0 = Date.now();
@@ -1878,7 +1882,7 @@ export class RecallInternalCoordinator {
1878
1882
  vectorTierAvailable: resolveMemoryLifecycleCapabilities(this.deps.config).embeddingFallback,
1879
1883
  });
1880
1884
  })().catch(() => null);
1881
- const qmdEnrichmentAbort = createEnrichmentAbortHandle(options.abortSignal);
1885
+ const qmdEnrichmentAbort = enrichmentAbort();
1882
1886
  const qmdPromise = observeEnrichmentPromise(
1883
1887
  (async (): Promise<QmdPhaseResult> => {
1884
1888
  const t0 = Date.now();
@@ -2485,9 +2489,7 @@ export class RecallInternalCoordinator {
2485
2489
  return section;
2486
2490
  })();
2487
2491
 
2488
- const nativeKnowledgeAbort = createEnrichmentAbortHandle(
2489
- options.abortSignal,
2490
- );
2492
+ const nativeKnowledgeAbort = enrichmentAbort();
2491
2493
  const nativeKnowledgePromise = observeEnrichmentPromise(
2492
2494
  (async (): Promise<string | null> => {
2493
2495
  const t0 = Date.now();
@@ -2851,18 +2853,11 @@ export class RecallInternalCoordinator {
2851
2853
  name: string,
2852
2854
  promise: ObservedDeferredEnrichmentPromise<T>,
2853
2855
  onStatus?: (status: Phase2AwaitStatus) => void,
2856
+ sectionHandle?: EnrichmentAbortHandle,
2854
2857
  ): Promise<T | null> => {
2855
2858
  const finalizeEnrichmentOutcome = (
2856
2859
  outcome: DeferredEnrichmentOutcome<T>,
2857
2860
  ): T | null => {
2858
- if (outcome.status === "resolved") {
2859
- log.debug(
2860
- `recall phase-1 enrichment [${name}]: resolved at +${Date.now() - phase1Start}ms`,
2861
- );
2862
- onStatus?.("ok");
2863
- return outcome.value;
2864
- }
2865
-
2866
2861
  if (options.abortSignal?.aborted) {
2867
2862
  log.debug(
2868
2863
  `recall phase-1 enrichment [${name}]: skipped after abort at +${Date.now() - phase1Start}ms`,
@@ -2870,6 +2865,26 @@ export class RecallInternalCoordinator {
2870
2865
  onStatus?.("skipped");
2871
2866
  return null;
2872
2867
  }
2868
+ if (sectionHandle?.timedOut) {
2869
+ // cancel() routes a deadline cut through the degradation accounting
2870
+ // the assembly race performs; keep a value the section still
2871
+ // delivered (e.g. a stale-cache fallback served before the cut).
2872
+ promise.cancel();
2873
+ if (outcome.status === "resolved" && outcome.value != null) {
2874
+ onStatus?.("ok");
2875
+ return outcome.value;
2876
+ }
2877
+ log.debug(`recall phase-1 enrichment [${name}]: section deadline fired at +${Date.now() - phase1Start}ms`);
2878
+ onStatus?.("timeout");
2879
+ return null;
2880
+ }
2881
+ if (outcome.status === "resolved") {
2882
+ log.debug(
2883
+ `recall phase-1 enrichment [${name}]: resolved at +${Date.now() - phase1Start}ms`,
2884
+ );
2885
+ onStatus?.("ok");
2886
+ return outcome.value;
2887
+ }
2873
2888
  log.warn(
2874
2889
  `recall phase-1 enrichment [${name}] failed open: ` +
2875
2890
  `${outcome.error instanceof Error ? outcome.error.message : String(outcome.error)}`,
@@ -3388,10 +3403,7 @@ export class RecallInternalCoordinator {
3388
3403
  );
3389
3404
  }
3390
3405
 
3391
- const nativeKnowledgeSection = await awaitEnrichmentSection(
3392
- "nativeKnowledge",
3393
- nativeKnowledgePromise,
3394
- );
3406
+ const nativeKnowledgeSection = await awaitEnrichmentSection("nativeKnowledge", nativeKnowledgePromise, undefined, nativeKnowledgeAbort);
3395
3407
  if (nativeKnowledgeSection) {
3396
3408
  this.deps.appendRecallSection(
3397
3409
  sectionBuckets,
@@ -3640,7 +3652,7 @@ export class RecallInternalCoordinator {
3640
3652
  // 2. QMD results — post-process and format
3641
3653
  const qmdWasSettledBeforeAssemblyWait =
3642
3654
  qmdPromise.getSettledOutcome() !== undefined;
3643
- const qmdResult = await awaitEnrichmentSection("qmd", qmdPromise);
3655
+ const qmdResult = await awaitEnrichmentSection("qmd", qmdPromise, undefined, qmdEnrichmentAbort);
3644
3656
  if (qmdResult) {
3645
3657
  const t0 = Date.now();
3646
3658
  const {
@@ -4740,7 +4752,7 @@ export class RecallInternalCoordinator {
4740
4752
  "Harmonic",
4741
4753
  harmonicStartedMs,
4742
4754
  () => timings.harmonicRetrieval?.startsWith("skip") === true,
4743
- (onStatus) => awaitEnrichmentSection("harmonic", harmonicRetrievalPromise, onStatus),
4755
+ (onStatus) => awaitEnrichmentSection("harmonic", harmonicRetrievalPromise, onStatus, harmonicRetrievalAbort),
4744
4756
  );
4745
4757
  if (harmonicRetrievalSection) {
4746
4758
  this.deps.appendRecallSection(
@@ -11,12 +11,17 @@ export type ObservedDeferredEnrichmentPromise<T> =
11
11
  /** Cancelable child abort signal owned by one enrichment promise. */
12
12
  export interface EnrichmentAbortHandle {
13
13
  signal: AbortSignal;
14
+ /** True only when the handle's own deadline fired — not a parent abort or a manual cancel. */
15
+ readonly timedOut: boolean;
14
16
  cancel: () => void;
15
17
  dispose: () => void;
16
18
  }
17
19
 
18
- /** Child abort controller that follows `parentSignal`; `dispose` detaches the listener. */
19
- export function createEnrichmentAbortHandle(parentSignal?: AbortSignal): EnrichmentAbortHandle {
20
+ /** Child abort controller that follows `parentSignal` and, when `deadlineMs` is
21
+ * finite and positive, fires on its own at that deadline — the metric label the
22
+ * enrichment sections already carried, enforced (#3499). `dispose` detaches the
23
+ * listener and clears the timer. */
24
+ export function createEnrichmentAbortHandle(parentSignal?: AbortSignal, deadlineMs?: number): EnrichmentAbortHandle {
20
25
  const controller = new AbortController();
21
26
  const onAbort = () => controller.abort();
22
27
  if (parentSignal?.aborted) {
@@ -24,14 +29,27 @@ export function createEnrichmentAbortHandle(parentSignal?: AbortSignal): Enrichm
24
29
  } else if (parentSignal) {
25
30
  parentSignal.addEventListener("abort", onAbort, { once: true });
26
31
  }
32
+ let timedOut = false;
33
+ const timer =
34
+ deadlineMs !== undefined && Number.isFinite(deadlineMs) && deadlineMs > 0
35
+ ? setTimeout(() => {
36
+ timedOut = true;
37
+ controller.abort();
38
+ }, deadlineMs)
39
+ : undefined;
40
+ timer?.unref?.();
27
41
  let disposed = false;
28
42
  const dispose = () => {
29
43
  if (disposed) return;
30
44
  disposed = true;
45
+ if (timer !== undefined) clearTimeout(timer);
31
46
  parentSignal?.removeEventListener("abort", onAbort);
32
47
  };
33
48
  return {
34
49
  signal: controller.signal,
50
+ get timedOut() {
51
+ return timedOut;
52
+ },
35
53
  cancel: () => {
36
54
  controller.abort();
37
55
  dispose();
@@ -1,6 +1,7 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { throwIfAborted } from "./abort-error.js";
4
+ import { createEnrichmentAbortHandle } from "./recall-enrichment-promise.js";
4
5
  import {
5
6
  createBoundedCoreSectionRunner,
6
7
  createRecallSectionMetricRecorder,
@@ -372,3 +373,26 @@ test("yieldToEventLoop lets a pending timer run", async () => {
372
373
 
373
374
  assert.equal(timerFired, true);
374
375
  });
376
+
377
+ test("an enrichment abort handle fires its deadline without a parent abort (#3499)", async () => {
378
+ // Enrichment sections (harmonic retrieval, QMD, native knowledge) only followed
379
+ // the parent signal, so their deadlineMs was a metric label — a slow section ran
380
+ // past the client's budget with nothing to cut it. A real timer is the subject.
381
+ const handle = createEnrichmentAbortHandle(undefined, 15);
382
+ const fired = Promise.withResolvers<void>();
383
+ handle.signal.addEventListener("abort", () => fired.resolve());
384
+ // The deadline timer is unref'd so a stale budget never holds the process;
385
+ // this ref'd wait is only the test keeping the loop alive for it to fire.
386
+ await new Promise((resolve) => setTimeout(resolve, 40));
387
+ assert.equal(handle.signal.aborted, true);
388
+ await fired.promise;
389
+ handle.dispose();
390
+ });
391
+
392
+ test("an enrichment abort handle with no deadline still follows the parent signal", async () => {
393
+ const parent = new AbortController();
394
+ const handle = createEnrichmentAbortHandle(parent.signal);
395
+ parent.abort();
396
+ assert.equal(handle.signal.aborted, true);
397
+ handle.dispose();
398
+ });
@@ -13,6 +13,7 @@ import { CompoundingEngine } from "./compounding/engine.js";
13
13
  import { parseConfig } from "./config.js";
14
14
  import { rebuildMemoryProjection } from "./maintenance/rebuild-memory-projection.js";
15
15
  import { Orchestrator } from "./orchestrator.js";
16
+ import { NamespaceReadFanoutCoordinator } from "./orchestration/namespace-read-fanout.js";
16
17
  import {
17
18
  PHASE2_AWAIT_STATUSES,
18
19
  type Phase2AwaitStatus,
@@ -467,19 +468,20 @@ test("recall response body carries no timing-contract fields", async () => {
467
468
 
468
469
  test("a recall the outer timeout cuts short records outcome error, not ok", async () => {
469
470
  const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-timing-outer-timeout-"));
470
- const config = makeConfig(memoryDir, {
471
- qmdEnabled: true,
472
- harmonicRetrievalEnabled: true,
473
- recallOuterTimeoutMs: 50,
474
- });
471
+ const config = makeConfig(memoryDir, { recallOuterTimeoutMs: 50 });
475
472
  const orchestrator = new Orchestrator(config);
476
- const harness = await makeHarmonicHarness(memoryDir);
477
- stubQmd(orchestrator, harness);
473
+ // Enrichment deadlines can now degrade a slow section inside the request
474
+ // budget, so park the corpus read itself: a recall that never gets its
475
+ // memories still owes the outer timeout its cut.
476
+ mock.method(
477
+ NamespaceReadFanoutCoordinator.prototype,
478
+ "readAllMemoriesForNamespaces",
479
+ () => new Promise<MemoryFile[]>(() => {}),
480
+ );
478
481
  const service = new EngramAccessService(orchestrator);
479
482
  // The entry coordinator swallows the timeout and returns a degraded context,
480
483
  // so the surface call resolves; the record must still say it did not complete.
481
484
  await service.recall({ query: "atlas source lookup", sessionKey: "outer:timeout" });
482
- harness.releaseHarmonicRead();
483
485
  const records = getRecallTimings(config);
484
486
  assert.equal(records.length, 1);
485
487
  assert.equal(records[0]?.outcome, "error");
@@ -1 +0,0 @@
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 cancel: () => void;\n dispose: () => void;\n}\n\n/** Child abort controller that follows `parentSignal`; `dispose` detaches the listener. */\nexport function createEnrichmentAbortHandle(parentSignal?: AbortSignal): 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 disposed = false;\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n parentSignal?.removeEventListener(\"abort\", onAbort);\n };\n return {\n signal: controller.signal,\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":";AAkBO,SAAS,4BAA4B,cAAmD;AAC7F,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,UAAU,MAAM;AACpB,QAAI,SAAU;AACd,eAAW;AACX,kBAAc,oBAAoB,SAAS,OAAO;AAAA,EACpD;AACA,SAAO;AAAA,IACL,QAAQ,WAAW;AAAA,IACnB,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":[]}
@@ -1 +0,0 @@
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 */\nexport function isRateLimitedResponse(status: number, bodyText: string): boolean {\n if (POOL_MISSING_PATTERN.test(bodyText)) 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,IAA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