@remnic/core 10.0.187 → 10.0.188

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 (170) hide show
  1. package/dist/access-admin-ops-surface.js +38 -38
  2. package/dist/access-cli.js +38 -38
  3. package/dist/access-extraction-force-flush-preempt.js +38 -38
  4. package/dist/access-extraction-force-flush.js +38 -38
  5. package/dist/access-http-briefing.js +38 -38
  6. package/dist/access-http-query.js +38 -38
  7. package/dist/access-http.js +38 -38
  8. package/dist/access-identity-continuity-surface.js +38 -38
  9. package/dist/access-lcm-surface.js +38 -38
  10. package/dist/access-mcp.js +38 -38
  11. package/dist/access-observe-write-surface.js +38 -38
  12. package/dist/access-operations-batch.js +38 -38
  13. package/dist/access-operations.js +38 -38
  14. package/dist/access-recall-concurrency.js +38 -38
  15. package/dist/access-recall-response.js +38 -38
  16. package/dist/access-recall-surface.js +38 -38
  17. package/dist/access-service.js +38 -38
  18. package/dist/active-recall.js +1 -1
  19. package/dist/briefing.js +2 -2
  20. package/dist/buffer-add-turns-bounded.js +2 -2
  21. package/dist/buffer-admission-idempotency.d.ts.map +1 -1
  22. package/dist/buffer-admission-idempotency.js +1 -1
  23. package/dist/buffer-persistence.d.ts +14 -0
  24. package/dist/buffer-persistence.d.ts.map +1 -1
  25. package/dist/buffer-persistence.js +3 -1
  26. package/dist/buffer.js +4 -4
  27. package/dist/calibration.js +3 -3
  28. package/dist/causal-consolidation.js +3 -3
  29. package/dist/{chunk-2ZS7CB5H.js → chunk-2I3ETW3G.js} +2 -2
  30. package/dist/{chunk-PSUSA5SM.js → chunk-2VNMSEZR.js} +2 -2
  31. package/dist/{chunk-LANV6I63.js → chunk-56BNHKZM.js} +7 -7
  32. package/dist/{chunk-3FEQNKMB.js → chunk-5WDUY2ZZ.js} +2 -2
  33. package/dist/{chunk-BANMPRSC.js → chunk-65DWWJKI.js} +2 -2
  34. package/dist/{chunk-O5ZCDK32.js → chunk-6AMFGXG2.js} +39 -11
  35. package/dist/chunk-6AMFGXG2.js.map +1 -0
  36. package/dist/{chunk-VZBKCRU7.js → chunk-6MDHK6NO.js} +2 -2
  37. package/dist/{chunk-2RAVHJCD.js → chunk-6OHCNTKU.js} +2 -2
  38. package/dist/{chunk-K5RGHUX7.js → chunk-A32EBVCZ.js} +2 -2
  39. package/dist/{chunk-KVM3BS5K.js → chunk-ATPY63F5.js} +2 -2
  40. package/dist/chunk-B256MMS7.js +205 -0
  41. package/dist/chunk-B256MMS7.js.map +1 -0
  42. package/dist/{chunk-MOWLANEJ.js → chunk-C6Y2YHJL.js} +2 -2
  43. package/dist/{chunk-IMT7NTFV.js → chunk-CIAQK2OU.js} +6 -1
  44. package/dist/{chunk-IMT7NTFV.js.map → chunk-CIAQK2OU.js.map} +1 -1
  45. package/dist/{chunk-AJVCM2E3.js → chunk-CYX7JI4O.js} +2 -2
  46. package/dist/{chunk-76KL37ON.js → chunk-D3FP4JQI.js} +2 -2
  47. package/dist/{chunk-TQXKUQFX.js → chunk-FZU62GIV.js} +7 -6
  48. package/dist/chunk-FZU62GIV.js.map +1 -0
  49. package/dist/{chunk-YDGQYG4L.js → chunk-H442UKDV.js} +8 -8
  50. package/dist/{chunk-FXDQO7VX.js → chunk-HL53XYHC.js} +3 -3
  51. package/dist/{chunk-4VFEN3WT.js → chunk-IMSLPQJB.js} +2 -2
  52. package/dist/{chunk-FKLSIQBF.js → chunk-K3JGILZC.js} +3 -3
  53. package/dist/{chunk-JRHOL6B5.js → chunk-K6BS5RB4.js} +2 -2
  54. package/dist/{chunk-HHCLV572.js → chunk-KVTUUU7H.js} +2 -2
  55. package/dist/{chunk-TRFSTCQK.js → chunk-LL6WEMTC.js} +34 -6
  56. package/dist/chunk-LL6WEMTC.js.map +1 -0
  57. package/dist/{chunk-L2DYRQQH.js → chunk-MTKSH7HY.js} +30 -30
  58. package/dist/{chunk-2WITFW6F.js → chunk-NKHRIDYP.js} +2 -2
  59. package/dist/{chunk-KYZMCH4I.js → chunk-NN3LMWKA.js} +12 -4
  60. package/dist/chunk-NN3LMWKA.js.map +1 -0
  61. package/dist/{chunk-CTWWMEGR.js → chunk-PCGBESAN.js} +2 -2
  62. package/dist/{chunk-MDXZIU5X.js → chunk-QGT5KNQT.js} +2 -2
  63. package/dist/{chunk-YJZDRM33.js → chunk-QXHWOUS6.js} +3 -3
  64. package/dist/{chunk-OVJAQWHO.js → chunk-RPOG6HLI.js} +2 -2
  65. package/dist/{chunk-2QQCCUXF.js → chunk-RVODERA5.js} +2 -2
  66. package/dist/{chunk-P5FF44G3.js → chunk-T3XOP7TA.js} +4 -4
  67. package/dist/{chunk-FQE5QN5Q.js → chunk-TAPF7T26.js} +2 -2
  68. package/dist/{chunk-7UTCETGK.js → chunk-TQODBIMW.js} +2 -2
  69. package/dist/{chunk-KZJEKKK6.js → chunk-VQQZJ6KJ.js} +3 -3
  70. package/dist/{chunk-I233SAGS.js → chunk-X3ERYOLO.js} +2 -2
  71. package/dist/{chunk-UCCXPMTP.js → chunk-XQF2KLV5.js} +2 -2
  72. package/dist/{chunk-LPYGM6RE.js → chunk-XWPYK5T4.js} +2 -2
  73. package/dist/{chunk-7EPEZYX3.js → chunk-YVXR7CPS.js} +2 -2
  74. package/dist/cli.js +38 -38
  75. package/dist/coding/export-okf-codegraph.js +1 -1
  76. package/dist/compounding/engine.js +3 -3
  77. package/dist/config.js +1 -1
  78. package/dist/connectors/codex-materialize-runner.js +2 -2
  79. package/dist/connectors/index.js +2 -2
  80. package/dist/convergence-refresh.js +4 -4
  81. package/dist/corpus-watermark.js +4 -4
  82. package/dist/entity-retrieval.js +2 -2
  83. package/dist/explicit-capture.js +38 -38
  84. package/dist/extraction.js +6 -6
  85. package/dist/harmonic-retrieval.js +2 -2
  86. package/dist/index.js +38 -38
  87. package/dist/local-llm-helpers.d.ts.map +1 -1
  88. package/dist/local-llm-helpers.js +2 -2
  89. package/dist/local-llm-transport.d.ts +82 -9
  90. package/dist/local-llm-transport.d.ts.map +1 -1
  91. package/dist/local-llm-transport.js +11 -3
  92. package/dist/local-llm.d.ts.map +1 -1
  93. package/dist/local-llm.js +3 -3
  94. package/dist/location/index.js +3 -3
  95. package/dist/maintenance/memory-governance.js +2 -2
  96. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +2 -2
  97. package/dist/maintenance/rebuild-memory-projection-runner.js +4 -4
  98. package/dist/maintenance/rebuild-memory-projection.js +3 -3
  99. package/dist/namespaces/migrate.js +3 -3
  100. package/dist/namespaces/storage.js +2 -2
  101. package/dist/operator-doctor-corpus.js +5 -5
  102. package/dist/operator-toolkit.js +8 -8
  103. package/dist/orchestration/backlog-scheduler.js +39 -39
  104. package/dist/orchestration/buffer-drain-runner.js +39 -39
  105. package/dist/orchestration/maintenance.js +13 -13
  106. package/dist/orchestrator.js +38 -38
  107. package/dist/recall-navigation.js +38 -38
  108. package/dist/resume-bundles.js +1 -1
  109. package/dist/semantic-consolidation.js +3 -3
  110. package/dist/semantic-rule-promotion.js +2 -2
  111. package/dist/semantic-rule-verifier.js +2 -2
  112. package/dist/source-agent-qualifier.js +2 -2
  113. package/dist/standup/build.js +2 -2
  114. package/dist/storage/entity-canonical-id-migration-runner.d.ts.map +1 -1
  115. package/dist/storage.js +1 -1
  116. package/dist/summarizer.js +4 -4
  117. package/dist/support-passport/index.js +4 -4
  118. package/dist/transfer/export-okf.js +2 -2
  119. package/dist/verified-recall.js +2 -2
  120. package/dist/who-knows-cli.js +3 -3
  121. package/dist/who-knows.js +2 -2
  122. package/package.json +2 -2
  123. package/src/buffer-admission-idempotency.test.ts +115 -0
  124. package/src/buffer-admission-idempotency.ts +67 -11
  125. package/src/buffer-persistence.ts +46 -5
  126. package/src/local-llm-headers-timeout.test.ts +246 -16
  127. package/src/local-llm-helpers.ts +14 -4
  128. package/src/local-llm-transport.ts +253 -16
  129. package/src/local-llm.ts +7 -8
  130. package/src/storage/entity-canonical-id-migration-runner.test.ts +90 -0
  131. package/src/storage/entity-canonical-id-migration-runner.ts +10 -0
  132. package/dist/chunk-5YQXWVCP.js +0 -74
  133. package/dist/chunk-5YQXWVCP.js.map +0 -1
  134. package/dist/chunk-KYZMCH4I.js.map +0 -1
  135. package/dist/chunk-O5ZCDK32.js.map +0 -1
  136. package/dist/chunk-TQXKUQFX.js.map +0 -1
  137. package/dist/chunk-TRFSTCQK.js.map +0 -1
  138. /package/dist/{chunk-2ZS7CB5H.js.map → chunk-2I3ETW3G.js.map} +0 -0
  139. /package/dist/{chunk-PSUSA5SM.js.map → chunk-2VNMSEZR.js.map} +0 -0
  140. /package/dist/{chunk-LANV6I63.js.map → chunk-56BNHKZM.js.map} +0 -0
  141. /package/dist/{chunk-3FEQNKMB.js.map → chunk-5WDUY2ZZ.js.map} +0 -0
  142. /package/dist/{chunk-BANMPRSC.js.map → chunk-65DWWJKI.js.map} +0 -0
  143. /package/dist/{chunk-VZBKCRU7.js.map → chunk-6MDHK6NO.js.map} +0 -0
  144. /package/dist/{chunk-2RAVHJCD.js.map → chunk-6OHCNTKU.js.map} +0 -0
  145. /package/dist/{chunk-K5RGHUX7.js.map → chunk-A32EBVCZ.js.map} +0 -0
  146. /package/dist/{chunk-KVM3BS5K.js.map → chunk-ATPY63F5.js.map} +0 -0
  147. /package/dist/{chunk-MOWLANEJ.js.map → chunk-C6Y2YHJL.js.map} +0 -0
  148. /package/dist/{chunk-AJVCM2E3.js.map → chunk-CYX7JI4O.js.map} +0 -0
  149. /package/dist/{chunk-76KL37ON.js.map → chunk-D3FP4JQI.js.map} +0 -0
  150. /package/dist/{chunk-YDGQYG4L.js.map → chunk-H442UKDV.js.map} +0 -0
  151. /package/dist/{chunk-FXDQO7VX.js.map → chunk-HL53XYHC.js.map} +0 -0
  152. /package/dist/{chunk-4VFEN3WT.js.map → chunk-IMSLPQJB.js.map} +0 -0
  153. /package/dist/{chunk-FKLSIQBF.js.map → chunk-K3JGILZC.js.map} +0 -0
  154. /package/dist/{chunk-JRHOL6B5.js.map → chunk-K6BS5RB4.js.map} +0 -0
  155. /package/dist/{chunk-HHCLV572.js.map → chunk-KVTUUU7H.js.map} +0 -0
  156. /package/dist/{chunk-L2DYRQQH.js.map → chunk-MTKSH7HY.js.map} +0 -0
  157. /package/dist/{chunk-2WITFW6F.js.map → chunk-NKHRIDYP.js.map} +0 -0
  158. /package/dist/{chunk-CTWWMEGR.js.map → chunk-PCGBESAN.js.map} +0 -0
  159. /package/dist/{chunk-MDXZIU5X.js.map → chunk-QGT5KNQT.js.map} +0 -0
  160. /package/dist/{chunk-YJZDRM33.js.map → chunk-QXHWOUS6.js.map} +0 -0
  161. /package/dist/{chunk-OVJAQWHO.js.map → chunk-RPOG6HLI.js.map} +0 -0
  162. /package/dist/{chunk-2QQCCUXF.js.map → chunk-RVODERA5.js.map} +0 -0
  163. /package/dist/{chunk-P5FF44G3.js.map → chunk-T3XOP7TA.js.map} +0 -0
  164. /package/dist/{chunk-FQE5QN5Q.js.map → chunk-TAPF7T26.js.map} +0 -0
  165. /package/dist/{chunk-7UTCETGK.js.map → chunk-TQODBIMW.js.map} +0 -0
  166. /package/dist/{chunk-KZJEKKK6.js.map → chunk-VQQZJ6KJ.js.map} +0 -0
  167. /package/dist/{chunk-I233SAGS.js.map → chunk-X3ERYOLO.js.map} +0 -0
  168. /package/dist/{chunk-UCCXPMTP.js.map → chunk-XQF2KLV5.js.map} +0 -0
  169. /package/dist/{chunk-LPYGM6RE.js.map → chunk-XWPYK5T4.js.map} +0 -0
  170. /package/dist/{chunk-7EPEZYX3.js.map → chunk-YVXR7CPS.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import type { ResponseFormatJSONSchema } from "openai/resources/shared";
2
- import type { Agent } from "undici";
2
+ import { fetch as undiciFetch, type Response as UndiciResponse } from "undici";
3
3
  import { log } from "./logger.js";
4
- import { directProbeDispatcher } from "./local-llm-transport.js";
4
+ import { directProbeDispatcher, isInvalidDispatcherArg, type TransportRequestInit } from "./local-llm-transport.js";
5
5
  import type { LocalLlmRequestPriority } from "./local-llm.js";
6
6
 
7
7
  export interface LocalLlmChatCompletionOptions {
@@ -181,10 +181,20 @@ export async function probeFetch(
181
181
  : controller.signal;
182
182
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
183
183
  try {
184
- const init: RequestInit & { dispatcher?: Agent } = { signal: requestSignal, headers: options.headers };
184
+ const init: TransportRequestInit = { signal: requestSignal, headers: options.headers };
185
185
  const dispatcher = directProbeDispatcher();
186
186
  if (dispatcher) init.dispatcher = dispatcher;
187
- const response = await fetch(url, init);
187
+ let response: Response | UndiciResponse;
188
+ try {
189
+ response = await fetch(url, init);
190
+ } catch (err) {
191
+ // node >= 26 wraps dispatch failures in TypeError("fetch failed"),
192
+ // so UND_ERR_INVALID_ARG can ride `err` or its cause chain; the
193
+ // bundled undici's fetch accepts the same init on every supported
194
+ // Node, so direct-mode probes still run there.
195
+ if (!(err instanceof Error) || !isInvalidDispatcherArg(err)) throw err;
196
+ response = await undiciFetch(url, init);
197
+ }
188
198
  clearTimeout(timeout);
189
199
  if (!response.ok) {
190
200
  log.debug(`local LLM probe: ${url} returned HTTP ${response.status}`);
@@ -1,7 +1,167 @@
1
- import { Agent, getGlobalDispatcher } from "undici";
1
+ import {
2
+ Agent,
3
+ EnvHttpProxyAgent,
4
+ MockAgent,
5
+ fetch as undiciFetch,
6
+ getGlobalDispatcher,
7
+ type Dispatcher,
8
+ type Response as UndiciResponse,
9
+ } from "undici";
2
10
 
3
11
  import { log } from "./logger.js";
4
12
 
13
+ /**
14
+ * Transport floor for the extraction route (issue #2148 root cause):
15
+ * extraction completions routinely run past undici's default 300s header
16
+ * budget, and the generic `localLlmTimeoutMs` ceiling is sized for chat. The
17
+ * extraction operation's dispatcher inactivity budgets are floored at this
18
+ * value; the call's abort budget still follows the ceiling/operator bound and
19
+ * the caller's own cancellation signal still ends the request early.
20
+ */
21
+ export const EXTRACTION_MIN_TRANSPORT_BUDGET_MS = 900_000;
22
+
23
+ /**
24
+ * Route-sized budgets: the generic ceiling is `min(ceiling, operator)`,
25
+ * except the extraction route, whose dispatcher inactivity budgets are
26
+ * floored at EXTRACTION_MIN_TRANSPORT_BUDGET_MS (extraction completions
27
+ * routinely outlast chat-sized budgets; issue #2148 root cause). The abort
28
+ * budget (effectiveTimeoutMs) is not floored.
29
+ */
30
+ export interface RouteBudgets {
31
+ effectiveTimeoutMs: number;
32
+ transportBudgetMs: number;
33
+ }
34
+
35
+ export function routeBudgets(
36
+ operation: string,
37
+ ceilingMs: number,
38
+ operatorMs?: number,
39
+ ): RouteBudgets {
40
+ const routeFloorMs =
41
+ operation === "extraction" ? EXTRACTION_MIN_TRANSPORT_BUDGET_MS : 0;
42
+ const operatorBudgetMs = operatorMs ?? ceilingMs;
43
+ // The operator's budget (the signal's ceiling) bounds the call; the floor
44
+ // widens only the transport's inactivity budgets, so a proxyline host's
45
+ // 300s dispatcher cap cannot dead-letter a longer configured budget.
46
+ const effectiveTimeoutMs = Math.min(ceilingMs, operatorBudgetMs);
47
+ const transportBudgetMs = routeFloorMs
48
+ ? Math.max(ceilingMs, routeFloorMs)
49
+ : ceilingMs;
50
+ return { effectiveTimeoutMs, transportBudgetMs };
51
+ }
52
+
53
+ /** The standard egress-proxy environment variables, undici's lowercase-first
54
+ * read order (the `lower ?? upper` read inside EnvHttpProxyAgent). */
55
+ const HTTP_PROXY_KEYS = ["http_proxy", "HTTP_PROXY"] as const;
56
+ const HTTPS_PROXY_KEYS = ["https_proxy", "HTTPS_PROXY"] as const;
57
+ const NO_PROXY_KEYS = ["no_proxy", "NO_PROXY"] as const;
58
+ const PROXY_ENV_KEYS = [...HTTP_PROXY_KEYS, ...HTTPS_PROXY_KEYS] as const;
59
+
60
+ function envValue(keys: readonly string[]): string | undefined {
61
+ // An empty variable must not hide a later one: HTTPS_PROXY="" means "unset",
62
+ // not "the proxy is the empty string".
63
+ for (const key of keys) {
64
+ const value = process.env[key]?.trim();
65
+ if (value) return value;
66
+ }
67
+ return undefined;
68
+ }
69
+
70
+ /**
71
+ * The egress-proxy environment after resolution: lowercase-first read order
72
+ * with empty values treated as unset. The same resolved values are handed
73
+ * to EnvHttpProxyAgent's overrides, so the gate and the pool can never
74
+ * disagree about which proxy applies (undici's own read skips only unset
75
+ * variables — an empty lowercase value would hide a set uppercase one).
76
+ */
77
+ export interface ResolvedProxyEnv {
78
+ httpProxy?: string;
79
+ httpsProxy?: string;
80
+ noProxy?: string;
81
+ }
82
+
83
+ export function resolveProxyEnv(): ResolvedProxyEnv {
84
+ return {
85
+ httpProxy: envValue(HTTP_PROXY_KEYS),
86
+ httpsProxy: envValue(HTTPS_PROXY_KEYS),
87
+ noProxy: envValue(NO_PROXY_KEYS),
88
+ };
89
+ }
90
+
91
+ function proxyUriFromEnv(): string | undefined {
92
+ const { httpsProxy, httpProxy } = resolveProxyEnv();
93
+ return httpsProxy ?? httpProxy;
94
+ }
95
+
96
+ /** undici's DEFAULT_PORTS for the schemes the local endpoint uses. */
97
+ function defaultPortFor(protocol: string): number {
98
+ return protocol === "http:" ? 80 : protocol === "https:" ? 443 : 0;
99
+ }
100
+
101
+ /**
102
+ * EnvHttpProxyAgent's `#shouldProxy` semantics, mirrored: true when `url`'s
103
+ * host and port are exempt from the proxy environment via NO_PROXY/no_proxy.
104
+ */
105
+ function noProxyBypasses(url: string, noProxy: string | undefined): boolean {
106
+ if (!noProxy) return false;
107
+ if (noProxy === "*") return true;
108
+ let hostname: string;
109
+ let port: number;
110
+ try {
111
+ const parsed = new URL(url);
112
+ hostname = parsed.host.replace(/:\d*$/, "").toLowerCase();
113
+ port = Number.parseInt(parsed.port, 10) || defaultPortFor(parsed.protocol);
114
+ } catch {
115
+ return false;
116
+ }
117
+ for (const entry of noProxy.split(/[,\s]/)) {
118
+ if (!entry) continue;
119
+ const hostPort = entry.match(/^(.+):(\d+)$/);
120
+ const entryHost = (hostPort ? hostPort[1] : entry).toLowerCase();
121
+ const entryPort = hostPort ? Number.parseInt(hostPort[2], 10) : 0;
122
+ if (entryPort && entryPort !== port) continue;
123
+ if (!/^[.*]/.test(entryHost)) {
124
+ if (hostname === entryHost) return true;
125
+ } else if (hostname.endsWith(entryHost.replace(/^\*/, ""))) {
126
+ return true;
127
+ }
128
+ }
129
+ return false;
130
+ }
131
+
132
+ /**
133
+ * The per-request init shape the transport hands fetch: undici's RequestInit
134
+ * (minus the body union this client never uses — chat bodies are strings)
135
+ * plus the dispatcher the #2148 fix passes per request.
136
+ */
137
+ export type TransportRequestInit = Omit<RequestInit, "body" | "dispatcher"> & {
138
+ body?: string;
139
+ dispatcher?: Dispatcher;
140
+ };
141
+
142
+ /**
143
+ * True when `err` or its cause chain (node 26 wraps dispatch failures in
144
+ * TypeError("fetch failed")) carries undici's UND_ERR_INVALID_ARG — the
145
+ * runtime's rejection of a per-request dispatcher.
146
+ */
147
+ export function isInvalidDispatcherArg(err: Error): boolean {
148
+ let current: unknown = err;
149
+ for (let depth = 0; current instanceof Error && depth < 5; depth += 1) {
150
+ // SAFETY: undici codes ride NodeJS.ErrnoException-style `code` and `cause` members.
151
+ const errno = current as NodeJS.ErrnoException;
152
+ if (errno.code === "UND_ERR_INVALID_ARG") return true;
153
+ current = errno.cause;
154
+ }
155
+ return false;
156
+ }
157
+
158
+ /**
159
+ * Either wire response: the runtime's (global fetch) or undici's (the
160
+ * dispatcher-carrying fallback for runtimes that reject per-request
161
+ * dispatchers). Every consumer only reads ok/status/headers/text/json.
162
+ */
163
+ export type ChatWireResponse = Response | UndiciResponse;
164
+
5
165
  /**
6
166
  * Wire transport for local LLM chat completions.
7
167
  *
@@ -70,32 +230,100 @@ export class ChatTransport {
70
230
  private agent: Agent | null = null;
71
231
  private agentBudgetMs: number | null = null;
72
232
  private warnedAboutCustomDispatcher = false;
233
+ /** Chained proxy pool: the proxyline stays in the path with widened budgets. */
234
+ private proxyAgent: EnvHttpProxyAgent | null = null;
235
+ private proxyKey: string | null = null;
73
236
 
74
237
  /**
75
238
  * The widened pool, or `undefined` when the process installed its own
76
239
  * transport that we must not displace.
77
240
  *
78
241
  * A deployment can route the local endpoint through a process-wide
79
- * dispatcher — a `ProxyAgent` for an HTTP proxy, or a custom
80
- * connect/TLS/DNS dispatcher. Swapping in our own pool would bypass the
81
- * proxy entirely and break the request, so those are left alone. A
82
- * `MockAgent` is excluded by the same check, so test transports keep
83
- * working. The trade-off is explicit: on those setups the 300s cap stands,
84
- * because only the dispatcher's owner knows how to rebuild it.
242
+ * dispatcher — an agent runtime's managed proxy ("proxyline") or a custom
243
+ * connect/TLS/DNS transport.
244
+ *
245
+ * - When the standard egress-proxy environment variables name the proxy,
246
+ * the transport chains its own `ProxyAgent` over that URI with the
247
+ * widened budgets: the proxyline stays in the path and the budgets take
248
+ * effect. This is the issue-#2148 root cause fix — the managed proxyline
249
+ * dispatcher kept undici's 300s `headersTimeout`, so extraction
250
+ * completions slower than five minutes died.
251
+ * - A NO_PROXY/no_proxy exemption on the request host routes it direct,
252
+ * but a plain direct pool cannot reproduce a custom dispatcher's
253
+ * DNS/connect/TLS logic — the installed transport stays in place.
254
+ * - With no proxy environment to mirror, the installed dispatcher is left
255
+ * alone and the 300s cap stands — only its owner knows how to rebuild
256
+ * it. The trade-off is logged once.
257
+ * - `REMNIC_LOCAL_LLM_DIRECT=1` declares the local endpoint is reached
258
+ * directly even though a global dispatcher exists; the widened direct
259
+ * pool is used, bypassing the proxy.
260
+ *
261
+ * A `MockAgent` is excluded by the same check, so test transports keep
262
+ * working.
85
263
  */
86
- dispatcherFor(budgetMs: number): Agent | undefined {
87
- // REMNIC_LOCAL_LLM_DIRECT=1: the operator declares the local endpoint is reached directly even though the process installed a global dispatcher for other traffic (an agent runtime's managed proxy). Without it the 300s header cap stands silently on such hosts and every completion slower than five minutes dies with `fetch failed`. Off by default so deployments that must use a proxy keep it.
88
- if (!isPlainPoolingAgent(getGlobalDispatcher()) && process.env.REMNIC_LOCAL_LLM_DIRECT !== "1") {
264
+ dispatcherFor(budgetMs: number, url?: string): Agent | EnvHttpProxyAgent | undefined {
265
+ const normalized = Number.isFinite(budgetMs) ? Math.max(0, budgetMs) : 0;
266
+ const installed = getGlobalDispatcher();
267
+ const custom = !isPlainPoolingAgent(installed);
268
+ // A MockAgent is a test transport: it is left in place like any other
269
+ // dispatcher the transport cannot mirror. The constructor-name check
270
+ // covers a MockAgent from a different undici copy than the one we import
271
+ // (same reason isPlainPoolingAgent checks ctor.name).
272
+ const installedIsMock =
273
+ custom && (installed instanceof MockAgent || installed.constructor.name === "MockAgent");
274
+ if (custom && process.env.REMNIC_LOCAL_LLM_DIRECT !== "1") {
275
+ const proxyEnv = installedIsMock ? undefined : resolveProxyEnv();
276
+ const proxyUri = proxyEnv ? proxyEnv.httpsProxy ?? proxyEnv.httpProxy : undefined;
277
+ if (proxyUri) {
278
+ if (url && noProxyBypasses(url, proxyEnv?.noProxy)) {
279
+ // The environment routes this host direct — but a fresh direct pool
280
+ // cannot reproduce the installed transport's custom DNS/connect
281
+ // logic, so it stays. The 300s trade-off is logged once.
282
+ if (!this.warnedAboutCustomDispatcher) {
283
+ this.warnedAboutCustomDispatcher = true;
284
+ log.debug(
285
+ "local LLM: NO_PROXY exempts the local endpoint from the proxy environment; " +
286
+ "leaving the installed custom dispatcher in place. " +
287
+ "localLlmTimeoutMs above that dispatcher's headersTimeout will not take effect.",
288
+ );
289
+ }
290
+ return undefined;
291
+ }
292
+ // The chained agent's behavior tracks the whole proxy environment, so
293
+ // the cache key must too: a changed HTTP_PROXY or NO_PROXY with a
294
+ // steady HTTPS_PROXY must not hand back the stale pool.
295
+ const key = [
296
+ proxyUri,
297
+ ...PROXY_ENV_KEYS.map((k) => process.env[k] ?? ""),
298
+ ...NO_PROXY_KEYS.map((k) => process.env[k] ?? ""),
299
+ normalized,
300
+ ].join("|");
301
+ if (this.proxyAgent && this.proxyKey === key) return this.proxyAgent;
302
+ void this.proxyAgent?.close().catch(() => {
303
+ /* pool teardown is best-effort */
304
+ });
305
+ // EnvHttpProxyAgent keeps NO_PROXY and per-protocol proxy selection;
306
+ // the resolved values are passed as overrides so its raw env read can
307
+ // never disagree with the gate's resolution (empty-lowercase skew).
308
+ this.proxyAgent = new EnvHttpProxyAgent({
309
+ httpProxy: proxyEnv?.httpProxy,
310
+ httpsProxy: proxyEnv?.httpsProxy,
311
+ noProxy: proxyEnv?.noProxy,
312
+ headersTimeout: normalized,
313
+ bodyTimeout: normalized,
314
+ });
315
+ this.proxyKey = key;
316
+ return this.proxyAgent;
317
+ }
89
318
  if (!this.warnedAboutCustomDispatcher) {
90
319
  this.warnedAboutCustomDispatcher = true;
91
320
  log.debug(
92
- "local LLM: a custom global dispatcher is installed; leaving it in place. " +
321
+ "local LLM: a custom global dispatcher is installed and no proxy environment names it; leaving it in place. " +
93
322
  "localLlmTimeoutMs above that dispatcher's headersTimeout will not take effect.",
94
323
  );
95
324
  }
96
325
  return undefined;
97
326
  }
98
- const normalized = Number.isFinite(budgetMs) ? Math.max(0, budgetMs) : 0;
99
327
  if (this.agent && this.agentBudgetMs === normalized) return this.agent;
100
328
  void this.agent?.close().catch(() => {
101
329
  /* pool teardown is best-effort */
@@ -108,15 +336,24 @@ export class ChatTransport {
108
336
  return this.agent;
109
337
  }
110
338
 
111
- async post(request: ChatCompletionRequest): Promise<Response> {
112
- const init: RequestInit & { dispatcher?: Agent } = {
339
+ async post(request: ChatCompletionRequest): Promise<Response | UndiciResponse> {
340
+ const init: TransportRequestInit = {
113
341
  method: "POST",
114
342
  headers: request.headers,
115
343
  body: request.body,
116
344
  signal: request.signal,
117
345
  };
118
- const dispatcher = this.dispatcherFor(request.budgetMs);
346
+ const dispatcher = this.dispatcherFor(request.budgetMs, request.url);
119
347
  if (dispatcher) init.dispatcher = dispatcher;
120
- return await fetch(request.url, init);
348
+ try {
349
+ return await fetch(request.url, init);
350
+ } catch (err) {
351
+ // node >= 26 wraps dispatch failures in TypeError("fetch failed"),
352
+ // so UND_ERR_INVALID_ARG can ride `err` or its cause chain; the
353
+ // bundled undici's fetch accepts the same init on every supported
354
+ // Node, so the widened budget still rides.
355
+ if (!(err instanceof Error) || !isInvalidDispatcherArg(err)) throw err;
356
+ return await undiciFetch(request.url, init);
357
+ }
121
358
  }
122
359
  }
package/src/local-llm.ts CHANGED
@@ -8,7 +8,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
10
  import { resolveLocalLlmCapabilities, resolvePipelineProcessingCapabilities } from "./capabilities.js";
11
- import { ChatTransport } from "./local-llm-transport.js";
11
+ import { ChatTransport, routeBudgets, type ChatWireResponse } from "./local-llm-transport.js";
12
12
  import { LocalLlmRateLimitSession, resolveRateLimitSettings, isTerminalLocalLlmProxyPoolError } from "./local-llm-rate-limit.js";
13
13
  import {
14
14
  extractNonRecoverableBackendReason,
@@ -952,10 +952,9 @@ export class LocalLlmClient {
952
952
  // Avoid logging request bodies by default (can contain sensitive user content).
953
953
  log.debug(`local LLM: request body length=${requestBodyJson.length}`);
954
954
 
955
- const effectiveTimeoutMs =
956
- typeof options.timeoutMs === "number"
957
- ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)
958
- : this.config.localLlmTimeoutMs;
955
+ // Extraction floors its dispatcher inactivity budgets at fifteen minutes
956
+ // (issue #2148 root cause); the sizing lives with the transport budgets.
957
+ const { effectiveTimeoutMs, transportBudgetMs } = routeBudgets(operation, this.config.localLlmTimeoutMs, options.timeoutMs);
959
958
  const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);
960
959
  // COS-447: rate-limit responses (429/503/408, LiteLLM cooldown) get
961
960
  // their own retry budget with exponential full-jitter backoff, and a
@@ -969,7 +968,7 @@ export class LocalLlmClient {
969
968
  effectiveTimeoutMs,
970
969
  );
971
970
  let lastRateLimitDelayMs: number | null = null;
972
- let response: Response | null = null, responseBody = "";
971
+ let response: ChatWireResponse | null = null, responseBody = "";
973
972
  let lastAbortError: Error | null = null;
974
973
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
975
974
  response = null;
@@ -998,12 +997,12 @@ export class LocalLlmClient {
998
997
  }
999
998
  const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);
1000
999
  const routingHeaders = buildLocalLlmRoutingHeaders(operation, options.priority);
1001
- const postAttempt = (bodyJson: string): Promise<Response> => this.chatTransport.post({
1000
+ const postAttempt = (bodyJson: string): Promise<ChatWireResponse> => this.chatTransport.post({
1002
1001
  url: chatUrl,
1003
1002
  headers: this.buildRequestHeaders(routingHeaders),
1004
1003
  body: bodyJson,
1005
1004
  signal: attemptAbort.signal,
1006
- budgetMs: this.config.localLlmTimeoutMs,
1005
+ budgetMs: transportBudgetMs,
1007
1006
  });
1008
1007
  try {
1009
1008
  response = await postAttempt(requestBodyJson);
@@ -0,0 +1,90 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+
7
+ import { EntityCanonicalIdMigrationRunner } from "./entity-canonical-id-migration-runner.js";
8
+
9
+ /**
10
+ * A runner wired to a scripted fingerprint queue and a migrate spy. Reads
11
+ * consume the queue in order; when it runs dry every read returns the settled
12
+ * value (the store converged after the migration's own writes). `settle(fp)`
13
+ * simulates the migration's writes landing: subsequent reads report `fp`.
14
+ */
15
+ async function makeRunner(
16
+ reads: string[],
17
+ onRun?: (settle: (fp: string) => void) => void,
18
+ ): Promise<{
19
+ runner: EntityCanonicalIdMigrationRunner;
20
+ calls: () => number;
21
+ entitiesDir: string;
22
+ }> {
23
+ const entitiesDir = await mkdtemp(path.join(os.tmpdir(), "remnic-runner-entities-"));
24
+ let calls = 0;
25
+ let settled: string | null = null;
26
+ let last = "moving";
27
+ const queue = [...reads];
28
+ const runner = new EntityCanonicalIdMigrationRunner(
29
+ () => true,
30
+ async () => {
31
+ calls += 1;
32
+ onRun?.((fp) => {
33
+ settled = fp;
34
+ });
35
+ },
36
+ async () => {
37
+ const value = queue.shift() ?? settled ?? last;
38
+ last = value;
39
+ return value;
40
+ },
41
+ );
42
+ return { runner, calls: () => calls, entitiesDir };
43
+ }
44
+
45
+ /** First run completes and records the fingerprint it stabilized on; a stable unchanged fingerprint never re-runs. */
46
+ test("first run completes; stable unchanged fingerprint never re-runs", async () => {
47
+ // Run 1: start s0; the migration's writes settle the store on s0, so the
48
+ // post-run reads agree with the start (the void-return storage contract).
49
+ const { runner, calls, entitiesDir } = await makeRunner(["s0"], (settle) => settle("s0"));
50
+ await runner.begin(false, entitiesDir);
51
+ await runner.finishBegin(false);
52
+ await runner.drain();
53
+ assert.equal(calls(), 1);
54
+ await runner.triggerAfterUnlock();
55
+ await runner.drain();
56
+ assert.equal(calls(), 1);
57
+ });
58
+
59
+ /** Issue #3713: under sustained writes the fingerprint keeps moving between reads. Re-running the full migrate on every trigger re-contends the migration lock and starves drains — the runner must DEFER (skip the run) while the fingerprint is unstable; the reconcile marker survives and a later settled trigger reconciles. */
60
+ test("an unstable fingerprint after completion defers the re-run until it settles", async () => {
61
+ // Read script, consumed in order:
62
+ // run 1: start s0; writes settle the store on s0 -> complete
63
+ // trigger 2 (sustained writes): start u1, stability u2 -> moving: defer
64
+ // trigger 3 (still moving): start u3, stability u4 -> defer again
65
+ // trigger 4 (settled): start s9, stability s9 -> reconcile run fires once,
66
+ // and the migration's writes settle the store on s9.
67
+ let runs = 0;
68
+ const reads: string[] = [
69
+ "s0", "s0", "s0", // run 1: start s0, post-run s0 s0 (stable -> complete, fp s0)
70
+ "u1", "u2", // trigger 2: start u1, stability u2 -> moving: defer
71
+ "u3", "u4", // trigger 3: still moving -> defer again
72
+ "s9", "s9", // trigger 4: settled -> reconcile run fires once, fp moves to s9
73
+ ];
74
+ const { runner, calls, entitiesDir } = await makeRunner(reads, () => {
75
+ runs += 1;
76
+ });
77
+ await runner.begin(false, entitiesDir);
78
+ await runner.finishBegin(false);
79
+ await runner.drain();
80
+ await runner.triggerAfterUnlock();
81
+ await runner.drain();
82
+ assert.equal(calls(), 1, "sustained writes: an unstable fingerprint must defer the re-run");
83
+ await runner.triggerAfterUnlock();
84
+ await runner.drain();
85
+ assert.equal(calls(), 1, "still moving: defer again");
86
+ await runner.triggerAfterUnlock();
87
+ await runner.drain();
88
+ assert.equal(calls(), 2, "once the fingerprint settles, the reconcile run fires exactly once");
89
+ assert.equal(runs, 2);
90
+ });
@@ -71,6 +71,16 @@ export class EntityCanonicalIdMigrationRunner {
71
71
  private async runOrReuse(): Promise<void> {
72
72
  let fingerprintAtStart = await this.readFingerprint();
73
73
  if (this.migrationComplete && fingerprintAtStart === this.completedFingerprint) return;
74
+ if (this.migrationComplete) {
75
+ // Issue #3713: under sustained writes the fingerprint keeps moving, and
76
+ // re-running the full migrate on every trigger re-contends the
77
+ // migration lock and starves drains. Defer while it is unstable: the
78
+ // reconcile marker survives, and a later trigger that reads a settled
79
+ // fingerprint serves the reconciliation.
80
+ const stabilityRead = await this.readFingerprint();
81
+ if (stabilityRead !== fingerprintAtStart) return;
82
+ fingerprintAtStart = stabilityRead;
83
+ }
74
84
 
75
85
  for (let attempt = 0; attempt < 3; attempt += 1) {
76
86
  const completionFingerprint = await this.runMigration();
@@ -1,74 +0,0 @@
1
- import {
2
- log
3
- } from "./chunk-3WCASNQZ.js";
4
-
5
- // src/local-llm-transport.ts
6
- import { Agent, getGlobalDispatcher } from "undici";
7
- function isPlainPoolingAgent(dispatcher) {
8
- if (dispatcher instanceof Agent) return true;
9
- if (!dispatcher || typeof dispatcher !== "object") return false;
10
- const ctor = dispatcher.constructor;
11
- if (!ctor || typeof ctor !== "function") return false;
12
- return ctor.name === "Agent";
13
- }
14
- var directProbeAgent = null;
15
- function directProbeDispatcher() {
16
- if (process.env.REMNIC_LOCAL_LLM_DIRECT !== "1") return void 0;
17
- directProbeAgent ??= new Agent();
18
- return directProbeAgent;
19
- }
20
- var ChatTransport = class {
21
- agent = null;
22
- agentBudgetMs = null;
23
- warnedAboutCustomDispatcher = false;
24
- /**
25
- * The widened pool, or `undefined` when the process installed its own
26
- * transport that we must not displace.
27
- *
28
- * A deployment can route the local endpoint through a process-wide
29
- * dispatcher — a `ProxyAgent` for an HTTP proxy, or a custom
30
- * connect/TLS/DNS dispatcher. Swapping in our own pool would bypass the
31
- * proxy entirely and break the request, so those are left alone. A
32
- * `MockAgent` is excluded by the same check, so test transports keep
33
- * working. The trade-off is explicit: on those setups the 300s cap stands,
34
- * because only the dispatcher's owner knows how to rebuild it.
35
- */
36
- dispatcherFor(budgetMs) {
37
- if (!isPlainPoolingAgent(getGlobalDispatcher()) && process.env.REMNIC_LOCAL_LLM_DIRECT !== "1") {
38
- if (!this.warnedAboutCustomDispatcher) {
39
- this.warnedAboutCustomDispatcher = true;
40
- log.debug(
41
- "local LLM: a custom global dispatcher is installed; leaving it in place. localLlmTimeoutMs above that dispatcher's headersTimeout will not take effect."
42
- );
43
- }
44
- return void 0;
45
- }
46
- const normalized = Number.isFinite(budgetMs) ? Math.max(0, budgetMs) : 0;
47
- if (this.agent && this.agentBudgetMs === normalized) return this.agent;
48
- void this.agent?.close().catch(() => {
49
- });
50
- this.agent = new Agent({
51
- headersTimeout: normalized,
52
- bodyTimeout: normalized
53
- });
54
- this.agentBudgetMs = normalized;
55
- return this.agent;
56
- }
57
- async post(request) {
58
- const init = {
59
- method: "POST",
60
- headers: request.headers,
61
- body: request.body,
62
- signal: request.signal
63
- };
64
- const dispatcher = this.dispatcherFor(request.budgetMs);
65
- if (dispatcher) init.dispatcher = dispatcher;
66
- return await fetch(request.url, init);
67
- }
68
- };
69
-
70
- export {
71
- directProbeDispatcher,
72
- ChatTransport
73
- };
74
- //# sourceMappingURL=chunk-5YQXWVCP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/local-llm-transport.ts"],"sourcesContent":["import { Agent, getGlobalDispatcher } from \"undici\";\n\nimport { log } from \"./logger.js\";\n\n/**\n * Wire transport for local LLM chat completions.\n *\n * Split out of `local-llm.ts` so the client module keeps prompt and\n * response semantics while connection budgets live in one place.\n */\n\nexport interface ChatCompletionRequest {\n url: string;\n headers: Record<string, string>;\n body: string;\n signal: AbortSignal;\n /**\n * Ceiling for this endpoint, i.e. `localLlmTimeoutMs`. Sizes the\n * connection's inactivity budgets. Per-request budgets below the ceiling\n * stay enforced by `signal`.\n */\n budgetMs: number;\n}\n\n/**\n * Is this undici's stock pooling `Agent` — the transport we may widen?\n *\n * `instanceof` alone is not enough: Node's global fetch is backed by its\n * OWN bundled copy of undici, so the dispatcher parked on the well-known\n * global symbol is an `Agent` from a different copy than the one we import,\n * and cross-copy `instanceof` is false. Fall back to the constructor name,\n * which is stable across copies and still distinguishes `ProxyAgent` and\n * `MockAgent` from the stock pool.\n */\nfunction isPlainPoolingAgent(dispatcher: unknown): boolean {\n if (dispatcher instanceof Agent) return true;\n if (!dispatcher || typeof dispatcher !== \"object\") return false;\n const ctor = (dispatcher as { constructor?: unknown }).constructor;\n if (!ctor || typeof ctor !== \"function\") return false;\n return ctor.name === \"Agent\";\n}\n\n/**\n * REMNIC_LOCAL_LLM_DIRECT=1 declares that the local endpoint is reached\n * directly. Availability probes use this shared plain pool in that mode so they\n * take the same route as chat requests; `undefined` keeps the global dispatcher.\n */\nlet directProbeAgent: Agent | null = null;\nexport function directProbeDispatcher(): Agent | undefined {\n if (process.env.REMNIC_LOCAL_LLM_DIRECT !== \"1\") return undefined;\n directProbeAgent ??= new Agent();\n return directProbeAgent;\n}\n\n/**\n * Connection pool whose header/body inactivity budgets track the configured\n * request budget.\n *\n * Node's global fetch runs on undici, which applies a default\n * `headersTimeout` and `bodyTimeout` of 300s. A non-streaming completion\n * sends its response headers only once generation finishes, so any\n * completion slower than 300s died with a bare `fetch failed` no matter how\n * high `localLlmTimeoutMs` was set — the configured budget was dead letter\n * past five minutes (issue #2148).\n *\n * One pool per client is enough: it is keyed on the ceiling and rebuilt when\n * that changes.\n */\nexport class ChatTransport {\n private agent: Agent | null = null;\n private agentBudgetMs: number | null = null;\n private warnedAboutCustomDispatcher = false;\n\n /**\n * The widened pool, or `undefined` when the process installed its own\n * transport that we must not displace.\n *\n * A deployment can route the local endpoint through a process-wide\n * dispatcher — a `ProxyAgent` for an HTTP proxy, or a custom\n * connect/TLS/DNS dispatcher. Swapping in our own pool would bypass the\n * proxy entirely and break the request, so those are left alone. A\n * `MockAgent` is excluded by the same check, so test transports keep\n * working. The trade-off is explicit: on those setups the 300s cap stands,\n * because only the dispatcher's owner knows how to rebuild it.\n */\n dispatcherFor(budgetMs: number): Agent | undefined {\n // REMNIC_LOCAL_LLM_DIRECT=1: the operator declares the local endpoint is reached directly even though the process installed a global dispatcher for other traffic (an agent runtime's managed proxy). Without it the 300s header cap stands silently on such hosts and every completion slower than five minutes dies with `fetch failed`. Off by default so deployments that must use a proxy keep it.\n if (!isPlainPoolingAgent(getGlobalDispatcher()) && process.env.REMNIC_LOCAL_LLM_DIRECT !== \"1\") {\n if (!this.warnedAboutCustomDispatcher) {\n this.warnedAboutCustomDispatcher = true;\n log.debug(\n \"local LLM: a custom global dispatcher is installed; leaving it in place. \" +\n \"localLlmTimeoutMs above that dispatcher's headersTimeout will not take effect.\",\n );\n }\n return undefined;\n }\n const normalized = Number.isFinite(budgetMs) ? Math.max(0, budgetMs) : 0;\n if (this.agent && this.agentBudgetMs === normalized) return this.agent;\n void this.agent?.close().catch(() => {\n /* pool teardown is best-effort */\n });\n this.agent = new Agent({\n headersTimeout: normalized,\n bodyTimeout: normalized,\n });\n this.agentBudgetMs = normalized;\n return this.agent;\n }\n\n async post(request: ChatCompletionRequest): Promise<Response> {\n const init: RequestInit & { dispatcher?: Agent } = {\n method: \"POST\",\n headers: request.headers,\n body: request.body,\n signal: request.signal,\n };\n const dispatcher = this.dispatcherFor(request.budgetMs);\n if (dispatcher) init.dispatcher = dispatcher;\n return await fetch(request.url, init);\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,OAAO,2BAA2B;AAkC3C,SAAS,oBAAoB,YAA8B;AACzD,MAAI,sBAAsB,MAAO,QAAO;AACxC,MAAI,CAAC,cAAc,OAAO,eAAe,SAAU,QAAO;AAC1D,QAA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","names":[]}
@@ -1 +0,0 @@
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,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,MA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AsB,SAAS,SAAS;AACpD,QAAM,QAAQ,uBAAuB,EAAE,IAAI,GAAG,KAAK;AACnD,MAAI,SAAS,MAAM,WAAW,KAAK;AACjC,UAAM,gBAAgB,MAAM;AAC5B,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAEO,SAAS,mCACd,QACA,YACA,SACA,WACM;AACN,QAAM,mBAAmB,2BAA2B,MAAM;AAC1D,QAAM,MAAM,sBAAsB,SAAS,SAAS;AACpD,MAAI,aAAa,GAAG;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":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/buffer-admission-idempotency.ts"],"sourcesContent":["/** Fields on {@link BufferState} used by observe-buffer idempotency (#3368). */\nexport interface BufferAdmissionIdempotencyState {\n admissionIdempotency?: Record<string, number>;\n admissionIdempotencyOrder?: string[];\n}\n\n/**\n * FIFO bound on recorded observe-buffer admission keys per session buffer.\n * 4096 retains the most recent keys per session — roughly two\n * hours at typical capture load. A replay of more than 4096 keys for one\n * session still evicts its oldest keys, so a complete 5000-entry outbox\n * replay for a single hot session is not guaranteed; the previous\n * 512-entry ring only covered about fifteen minutes, so any drain outage\n * longer than that made duplicate captures likely once replay caught up.\n */\nexport const BUFFER_ADMISSION_IDEMPOTENCY_CAP = 4096;\n\n/** Client observe idempotency keys are namespaced by durable capture scope. */\nexport function scopeObserveBufferAdmissionIdempotencyKey(input: {\n sessionKey: string;\n writeNamespace: string;\n principal?: string;\n clientKey: string;\n}): string {\n const principal = input.principal?.trim() ?? \"\";\n const client = input.clientKey.trim();\n return `obs\\u001f${input.writeNamespace}\\u001f${principal}\\u001f${input.sessionKey}\\u001e${client}`;\n}\n\nexport function ensureAdmissionIdempotencyMap(state: BufferAdmissionIdempotencyState): Record<string, number> {\n const existing = state.admissionIdempotency;\n if (existing && Object.getPrototypeOf(existing) === null) return existing;\n // SAFETY: prototype-free map contract for observe idempotency keys (#3368).\n const map = Object.create(null) as Record<string, number>;\n if (existing) {\n for (const key of Object.keys(existing)) {\n if (Object.hasOwn(existing, key)) map[key] = existing[key]!;\n }\n }\n state.admissionIdempotency = map;\n return map;\n}\n\nexport function ensureAdmissionIdempotencyOrder(state: BufferAdmissionIdempotencyState): string[] {\n if (!state.admissionIdempotencyOrder) {\n state.admissionIdempotencyOrder = [];\n }\n const order = state.admissionIdempotencyOrder;\n const map = state.admissionIdempotency;\n if (map) {\n for (const key of Object.keys(map)) {\n if (Object.hasOwn(map, key) && !order.includes(key)) order.push(key);\n }\n }\n return order;\n}\n\nexport function hasBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdempotencyState, key: string): boolean {\n const trimmed = key.trim();\n if (!trimmed) return false;\n const map = state.admissionIdempotency;\n return map !== undefined && Object.hasOwn(map, trimmed);\n}\n\nexport function recordBufferedAdmissionIdempotencyKey(state: BufferAdmissionIdempotencyState, key: string, turnCount: number): void {\n const trimmed = key.trim();\n if (!trimmed || turnCount <= 0) return;\n const map = ensureAdmissionIdempotencyMap(state);\n const order = ensureAdmissionIdempotencyOrder(state);\n map[trimmed] = turnCount;\n if (!order.includes(trimmed)) order.push(trimmed);\n while (order.length > BUFFER_ADMISSION_IDEMPOTENCY_CAP) {\n const evicted = order.shift();\n if (evicted !== undefined) delete map[evicted];\n }\n}\n"],"mappings":";AAeO,IAAM,mCAAmC;AAGzC,SAAS,0CAA0C,OAK/C;AACT,QAAM,YAAY,MAAM,WAAW,KAAK,KAAK;AAC7C,QAAM,SAAS,MAAM,UAAU,KAAK;AACpC,SAAO,OAAY,MAAM,cAAc,IAAS,SAAS,IAAS,MAAM,UAAU,IAAS,MAAM;AACnG;AAEO,SAAS,8BAA8B,OAAgE;AAC5G,QAAM,WAAW,MAAM;AACvB,MAAI,YAAY,OAAO,eAAe,QAAQ,MAAM,KAAM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