@remnic/core 9.23.1 → 9.23.2

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 (83) hide show
  1. package/dist/access-admin-ops-surface.js +9 -9
  2. package/dist/access-audit.js +2 -2
  3. package/dist/access-boundary.js +9 -9
  4. package/dist/access-cli.js +32 -31
  5. package/dist/access-cli.js.map +1 -1
  6. package/dist/access-http.js +16 -16
  7. package/dist/access-identity-continuity-surface.js +9 -9
  8. package/dist/access-lcm-surface.js +9 -9
  9. package/dist/access-mcp.js +13 -13
  10. package/dist/access-namespace-preflight.js +9 -9
  11. package/dist/access-observe-write-surface.js +9 -9
  12. package/dist/access-operations-batch.js +10 -10
  13. package/dist/access-operations.d.ts +3 -3
  14. package/dist/access-operations.js +12 -12
  15. package/dist/access-recall-concurrency.js +9 -9
  16. package/dist/access-recall-response.js +9 -9
  17. package/dist/access-recall-surface.js +9 -9
  18. package/dist/access-schema.d.ts +76 -76
  19. package/dist/access-schema.js +3 -3
  20. package/dist/access-service.js +9 -9
  21. package/dist/adapters/index.js +4 -4
  22. package/dist/adapters/registry.js +2 -2
  23. package/dist/{chunk-G2NSSQES.js → chunk-3L5O7SMT.js} +3 -3
  24. package/dist/{chunk-JVGUY2AU.js → chunk-4PQ4KLLK.js} +2 -2
  25. package/dist/{chunk-JBPKEARU.js → chunk-AU7Q3LSC.js} +4 -4
  26. package/dist/{chunk-WS32QRLO.js → chunk-DLKRXYRL.js} +6 -6
  27. package/dist/{chunk-IU3XJAQM.js → chunk-FGBJBYWP.js} +2 -2
  28. package/dist/{chunk-A2RFKL3V.js → chunk-GBAJCDTW.js} +2 -2
  29. package/dist/{chunk-RT4TSR2C.js → chunk-HSSIWAZP.js} +25 -25
  30. package/dist/{chunk-KQAFEZQX.js → chunk-IPLYGWQF.js} +5 -5
  31. package/dist/chunk-JUXOTY6J.js +67 -0
  32. package/dist/chunk-JUXOTY6J.js.map +1 -0
  33. package/dist/{chunk-ROUL7RZU.js → chunk-KXGE7L62.js} +17 -17
  34. package/dist/{chunk-OUW4PAY4.js → chunk-M6LJXJ3J.js} +3 -3
  35. package/dist/{chunk-2PHX3I5C.js → chunk-MAXVH44E.js} +5 -5
  36. package/dist/{chunk-YWJBAHTY.js → chunk-P2OZKKYP.js} +10 -12
  37. package/dist/chunk-P2OZKKYP.js.map +1 -0
  38. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  39. package/dist/{chunk-HBYQAOED.js → chunk-V2XVMCP6.js} +2 -2
  40. package/dist/{chunk-IIXLB5E7.js → chunk-WZVIB5BK.js} +15 -15
  41. package/dist/{chunk-KNRG6ZGJ.js → chunk-XGEFGNL5.js} +1 -1
  42. package/dist/cli.js +21 -21
  43. package/dist/extraction.js +3 -2
  44. package/dist/{first-start-migration-BKNGOFED.js → first-start-migration-LEXL3XYL.js} +4 -4
  45. package/dist/index.d.ts +404 -404
  46. package/dist/index.js +61 -60
  47. package/dist/lcm/engine.js +2 -2
  48. package/dist/lcm/index.js +5 -5
  49. package/dist/local-llm-transport.d.ts +55 -0
  50. package/dist/local-llm-transport.js +9 -0
  51. package/dist/local-llm-transport.js.map +1 -0
  52. package/dist/local-llm.d.ts +1 -0
  53. package/dist/local-llm.js +2 -1
  54. package/dist/operator-toolkit.js +1 -1
  55. package/dist/orchestrator.js +32 -31
  56. package/dist/schemas.d.ts +76 -76
  57. package/dist/shared-context/manager.d.ts +8 -8
  58. package/dist/summarizer.js +3 -2
  59. package/dist/transfer/autodetect.js +1 -1
  60. package/dist/transfer/backup.js +1 -1
  61. package/dist/transfer/capsule-export.js +2 -2
  62. package/dist/transfer/types.d.ts +66 -66
  63. package/package.json +3 -2
  64. package/src/local-llm-headers-timeout.test.ts +271 -0
  65. package/src/local-llm-transport.ts +109 -0
  66. package/src/local-llm.ts +6 -13
  67. package/dist/chunk-YWJBAHTY.js.map +0 -1
  68. /package/dist/{chunk-G2NSSQES.js.map → chunk-3L5O7SMT.js.map} +0 -0
  69. /package/dist/{chunk-JVGUY2AU.js.map → chunk-4PQ4KLLK.js.map} +0 -0
  70. /package/dist/{chunk-JBPKEARU.js.map → chunk-AU7Q3LSC.js.map} +0 -0
  71. /package/dist/{chunk-WS32QRLO.js.map → chunk-DLKRXYRL.js.map} +0 -0
  72. /package/dist/{chunk-IU3XJAQM.js.map → chunk-FGBJBYWP.js.map} +0 -0
  73. /package/dist/{chunk-A2RFKL3V.js.map → chunk-GBAJCDTW.js.map} +0 -0
  74. /package/dist/{chunk-RT4TSR2C.js.map → chunk-HSSIWAZP.js.map} +0 -0
  75. /package/dist/{chunk-KQAFEZQX.js.map → chunk-IPLYGWQF.js.map} +0 -0
  76. /package/dist/{chunk-ROUL7RZU.js.map → chunk-KXGE7L62.js.map} +0 -0
  77. /package/dist/{chunk-OUW4PAY4.js.map → chunk-M6LJXJ3J.js.map} +0 -0
  78. /package/dist/{chunk-2PHX3I5C.js.map → chunk-MAXVH44E.js.map} +0 -0
  79. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  80. /package/dist/{chunk-HBYQAOED.js.map → chunk-V2XVMCP6.js.map} +0 -0
  81. /package/dist/{chunk-IIXLB5E7.js.map → chunk-WZVIB5BK.js.map} +0 -0
  82. /package/dist/{chunk-KNRG6ZGJ.js.map → chunk-XGEFGNL5.js.map} +0 -0
  83. /package/dist/{first-start-migration-BKNGOFED.js.map → first-start-migration-LEXL3XYL.js.map} +0 -0
@@ -0,0 +1,271 @@
1
+ import assert from "node:assert/strict";
2
+ import http from "node:http";
3
+ import type { AddressInfo } from "node:net";
4
+ import test from "node:test";
5
+
6
+ import {
7
+ Agent,
8
+ ProxyAgent,
9
+ fetch as undiciFetch,
10
+ getGlobalDispatcher,
11
+ setGlobalDispatcher,
12
+ } from "undici";
13
+
14
+ import { LocalLlmClient } from "./local-llm.js";
15
+ import { ChatTransport } from "./local-llm-transport.js";
16
+ import type { PluginConfig } from "./types.js";
17
+
18
+ /**
19
+ * Issue #2148: `localLlmTimeoutMs` above 300s was dead letter.
20
+ *
21
+ * Node's global fetch runs on undici, whose default `headersTimeout` is
22
+ * 300s. A non-streaming completion emits its response headers only after
23
+ * generation finishes, so every completion slower than five minutes died
24
+ * with a bare `fetch failed` no matter how large the configured budget was.
25
+ *
26
+ * The fix hands the chat fetch an undici `Agent` whose header/body
27
+ * inactivity budgets track `localLlmTimeoutMs`. These tests pin the three
28
+ * links in that chain: the dispatcher is passed, the runtime honors a
29
+ * passed dispatcher, and the dispatcher carries the configured budget.
30
+ *
31
+ * These are integration tests over a real socket: the behavior under test
32
+ * IS undici's wall-clock inactivity timer, which fake timers cannot drive.
33
+ * Delays are kept small, and every budget/delay pair leaves ~1s of room
34
+ * because undici's timer wheel is coarse (a sub-second budget can fire up
35
+ * to roughly a second late).
36
+ */
37
+
38
+ function createConfig(overrides: Partial<PluginConfig> = {}): PluginConfig {
39
+ return {
40
+ localLlmEnabled: true,
41
+ localLlmModel: "test-local-model",
42
+ localLlmUrl: "http://127.0.0.1:1234",
43
+ localLlmTimeoutMs: 1_000,
44
+ localLlmRetry5xxCount: 0,
45
+ localLlmRetryBackoffMs: 1,
46
+ localLlmHeaders: {},
47
+ localLlmApiKey: undefined,
48
+ localLlmAuthHeader: false,
49
+ localLlm400TripThreshold: 3,
50
+ localLlm400CooldownMs: 60_000,
51
+ debug: false,
52
+ localLlmReasoningEffort: "none",
53
+ slowLogEnabled: false,
54
+ slowLogThresholdMs: 1_000,
55
+ ...overrides,
56
+ } as unknown as PluginConfig;
57
+ }
58
+
59
+ function primeClient(client: LocalLlmClient): void {
60
+ // Pin the health probe so chatCompletion() reaches the fetch under test.
61
+ const internals = client as unknown as {
62
+ isAvailable: boolean;
63
+ lastHealthCheck: number;
64
+ detectedType: string | null;
65
+ };
66
+ internals.isAvailable = true;
67
+ internals.lastHealthCheck = Date.now();
68
+ internals.detectedType = "generic";
69
+ }
70
+
71
+ /** Test seam: the pool is private, but its budget is what we assert on. */
72
+ function dispatcherOf(client: LocalLlmClient): Agent {
73
+ const seam = client as unknown as {
74
+ chatTransport: ChatTransport;
75
+ config: PluginConfig;
76
+ };
77
+ const agent = seam.chatTransport.dispatcherFor(seam.config.localLlmTimeoutMs);
78
+ assert.ok(agent, "expected a widened pool under the default global dispatcher");
79
+ return agent;
80
+ }
81
+
82
+ function undiciErrorCode(err: unknown): string | undefined {
83
+ if (!err || typeof err !== "object" || !("cause" in err)) return undefined;
84
+ const cause = err.cause;
85
+ if (!cause || typeof cause !== "object" || !("code" in cause)) return undefined;
86
+ return typeof cause.code === "string" ? cause.code : undefined;
87
+ }
88
+
89
+ function dispatcherOfInit(init: unknown): unknown {
90
+ if (!init || typeof init !== "object" || !("dispatcher" in init)) return undefined;
91
+ return init.dispatcher;
92
+ }
93
+
94
+ /** Server that withholds response headers for `delayMs`, then answers. */
95
+ async function startSlowHeaderServer(delayMs: number): Promise<{
96
+ url: string;
97
+ close: () => Promise<void>;
98
+ }> {
99
+ const pending = new Set<NodeJS.Timeout>();
100
+ const server = http.createServer((_req, res) => {
101
+ const timer = setTimeout(() => {
102
+ pending.delete(timer);
103
+ res.writeHead(200, { "content-type": "application/json" });
104
+ res.end(
105
+ JSON.stringify({
106
+ choices: [{ message: { content: "slow but complete" } }],
107
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
108
+ }),
109
+ );
110
+ }, delayMs);
111
+ pending.add(timer);
112
+ });
113
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
114
+ const { port } = server.address() as AddressInfo;
115
+ return {
116
+ url: `http://127.0.0.1:${port}/v1`,
117
+ close: async () => {
118
+ for (const timer of pending) clearTimeout(timer);
119
+ pending.clear();
120
+ await new Promise<void>((resolve) => server.close(() => resolve()));
121
+ },
122
+ };
123
+ }
124
+
125
+ test("chat completion passes an undici dispatcher to fetch", async () => {
126
+ const original = globalThis.fetch;
127
+ let seenDispatcher: unknown;
128
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
129
+ seenDispatcher = dispatcherOfInit(init);
130
+ return new Response(
131
+ JSON.stringify({ choices: [{ message: { content: "ok" } }] }),
132
+ { status: 200, headers: { "content-type": "application/json" } },
133
+ );
134
+ }) as typeof fetch;
135
+
136
+ try {
137
+ const client = new LocalLlmClient(createConfig());
138
+ primeClient(client);
139
+ const result = await client.chatCompletion([
140
+ { role: "user", content: "hello" },
141
+ ]);
142
+ assert.equal(result?.content, "ok");
143
+ assert.ok(
144
+ seenDispatcher instanceof Agent,
145
+ "chat fetch must carry an undici Agent so headersTimeout tracks localLlmTimeoutMs",
146
+ );
147
+ } finally {
148
+ globalThis.fetch = original;
149
+ }
150
+ });
151
+
152
+ test("runtime honors a per-request dispatcher (regression canary for #2148)", async () => {
153
+ // The fix assumes fetch applies `init.dispatcher`. If a future runtime
154
+ // silently ignores it, the 300s cap returns with no other signal — so
155
+ // assert the mechanism itself rather than trusting it.
156
+ const server = await startSlowHeaderServer(2_500);
157
+ const tight = new Agent({ headersTimeout: 250, bodyTimeout: 250 });
158
+ try {
159
+ await assert.rejects(
160
+ () =>
161
+ fetch(`${server.url}/chat/completions`, {
162
+ dispatcher: tight,
163
+ } as RequestInit & { dispatcher: Agent }),
164
+ (err: unknown) => {
165
+ const code = undiciErrorCode(err);
166
+ assert.equal(
167
+ code,
168
+ "UND_ERR_HEADERS_TIMEOUT",
169
+ `expected the passed dispatcher's headersTimeout to fire, got ${String(code)}`,
170
+ );
171
+ return true;
172
+ },
173
+ );
174
+ } finally {
175
+ await tight.close();
176
+ await server.close();
177
+ }
178
+ });
179
+
180
+ test("client dispatcher carries the configured budget, not undici's default", async () => {
181
+ // One server, two budgets: the only variable is localLlmTimeoutMs.
182
+ const server = await startSlowHeaderServer(2_500);
183
+ const pools: Agent[] = [];
184
+ try {
185
+ const impatient = new LocalLlmClient(createConfig({ localLlmTimeoutMs: 200 }));
186
+ const impatientPool = dispatcherOf(impatient);
187
+ pools.push(impatientPool);
188
+ await assert.rejects(
189
+ () =>
190
+ undiciFetch(`${server.url}/chat/completions`, {
191
+ dispatcher: impatientPool,
192
+ }),
193
+ (err: unknown) => undiciErrorCode(err) === "UND_ERR_HEADERS_TIMEOUT",
194
+ "a 200ms budget must cap the header wait well before the 2.5s response",
195
+ );
196
+
197
+ const patient = new LocalLlmClient(createConfig({ localLlmTimeoutMs: 30_000 }));
198
+ const patientPool = dispatcherOf(patient);
199
+ pools.push(patientPool);
200
+ const res = await undiciFetch(`${server.url}/chat/completions`, {
201
+ dispatcher: patientPool,
202
+ });
203
+ assert.equal(res.status, 200);
204
+ await res.body?.cancel();
205
+ } finally {
206
+ // Client-owned pools keep keep-alive sockets open past the request.
207
+ for (const pool of pools) await pool.close();
208
+ await server.close();
209
+ }
210
+ });
211
+
212
+ test("dispatcher is cached per client and rebuilt when the budget changes", async () => {
213
+ const client = new LocalLlmClient(createConfig({ localLlmTimeoutMs: 5_000 }));
214
+
215
+ const first = dispatcherOf(client);
216
+ assert.equal(dispatcherOf(client), first, "same budget must reuse one pool");
217
+
218
+ const mutable = client as unknown as { config: PluginConfig };
219
+ mutable.config = createConfig({ localLlmTimeoutMs: 9_000 });
220
+ const rebuilt = dispatcherOf(client);
221
+ assert.notEqual(rebuilt, first, "a changed budget must rebuild the pool");
222
+
223
+ await first.close();
224
+ await rebuilt.close();
225
+ });
226
+
227
+ test("a completion whose headers lag the request still succeeds", async () => {
228
+ // Scaled-down proxy for the production shape: generation (and therefore
229
+ // the response head) outlasts undici's default cap. Survivable only
230
+ // because the pool now tracks the configured budget.
231
+ const server = await startSlowHeaderServer(700);
232
+ const client = new LocalLlmClient(
233
+ createConfig({ localLlmUrl: server.url, localLlmTimeoutMs: 30_000 }),
234
+ );
235
+ try {
236
+ primeClient(client);
237
+ const result = await client.chatCompletion([
238
+ { role: "user", content: "extract facts" },
239
+ ]);
240
+ assert.equal(result?.content, "slow but complete");
241
+ } finally {
242
+ await dispatcherOf(client).close();
243
+ await server.close();
244
+ }
245
+ });
246
+
247
+ test("a process-wide custom dispatcher is left in place", async () => {
248
+ // A deployment may reach the local endpoint only through a ProxyAgent (or
249
+ // another custom connect/TLS/DNS transport) installed with
250
+ // setGlobalDispatcher. Swapping in our own pool would bypass it and break
251
+ // the request outright, so the widened pool must stand down.
252
+ const original = getGlobalDispatcher();
253
+ const proxy = new ProxyAgent("http://127.0.0.1:9");
254
+ try {
255
+ setGlobalDispatcher(proxy);
256
+ const transport = new ChatTransport();
257
+ assert.equal(
258
+ transport.dispatcherFor(900_000),
259
+ undefined,
260
+ "must not displace a non-Agent global dispatcher",
261
+ );
262
+ } finally {
263
+ setGlobalDispatcher(original);
264
+ await proxy.close();
265
+ }
266
+
267
+ // ...and the widened pool returns once the default transport is back.
268
+ const restored = new ChatTransport().dispatcherFor(900_000);
269
+ assert.ok(restored);
270
+ await restored.close();
271
+ });
@@ -0,0 +1,109 @@
1
+ import { Agent, getGlobalDispatcher } from "undici";
2
+
3
+ import { log } from "./logger.js";
4
+
5
+ /**
6
+ * Wire transport for local LLM chat completions.
7
+ *
8
+ * Split out of `local-llm.ts` so the client module keeps prompt and
9
+ * response semantics while connection budgets live in one place.
10
+ */
11
+
12
+ export interface ChatCompletionRequest {
13
+ url: string;
14
+ headers: Record<string, string>;
15
+ body: string;
16
+ signal: AbortSignal;
17
+ /**
18
+ * Ceiling for this endpoint, i.e. `localLlmTimeoutMs`. Sizes the
19
+ * connection's inactivity budgets. Per-request budgets below the ceiling
20
+ * stay enforced by `signal`.
21
+ */
22
+ budgetMs: number;
23
+ }
24
+
25
+ /**
26
+ * Is this undici's stock pooling `Agent` — the transport we may widen?
27
+ *
28
+ * `instanceof` alone is not enough: Node's global fetch is backed by its
29
+ * OWN bundled copy of undici, so the dispatcher parked on the well-known
30
+ * global symbol is an `Agent` from a different copy than the one we import,
31
+ * and cross-copy `instanceof` is false. Fall back to the constructor name,
32
+ * which is stable across copies and still distinguishes `ProxyAgent` and
33
+ * `MockAgent` from the stock pool.
34
+ */
35
+ function isPlainPoolingAgent(dispatcher: unknown): boolean {
36
+ if (dispatcher instanceof Agent) return true;
37
+ if (!dispatcher || typeof dispatcher !== "object") return false;
38
+ const ctor = (dispatcher as { constructor?: unknown }).constructor;
39
+ if (!ctor || typeof ctor !== "function") return false;
40
+ return ctor.name === "Agent";
41
+ }
42
+
43
+ /**
44
+ * Connection pool whose header/body inactivity budgets track the configured
45
+ * request budget.
46
+ *
47
+ * Node's global fetch runs on undici, which applies a default
48
+ * `headersTimeout` and `bodyTimeout` of 300s. A non-streaming completion
49
+ * sends its response headers only once generation finishes, so any
50
+ * completion slower than 300s died with a bare `fetch failed` no matter how
51
+ * high `localLlmTimeoutMs` was set — the configured budget was dead letter
52
+ * past five minutes (issue #2148).
53
+ *
54
+ * One pool per client is enough: it is keyed on the ceiling and rebuilt when
55
+ * that changes.
56
+ */
57
+ export class ChatTransport {
58
+ private agent: Agent | null = null;
59
+ private agentBudgetMs: number | null = null;
60
+ private warnedAboutCustomDispatcher = false;
61
+
62
+ /**
63
+ * The widened pool, or `undefined` when the process installed its own
64
+ * transport that we must not displace.
65
+ *
66
+ * A deployment can route the local endpoint through a process-wide
67
+ * dispatcher — a `ProxyAgent` for an HTTP proxy, or a custom
68
+ * connect/TLS/DNS dispatcher. Swapping in our own pool would bypass the
69
+ * proxy entirely and break the request, so those are left alone. A
70
+ * `MockAgent` is excluded by the same check, so test transports keep
71
+ * working. The trade-off is explicit: on those setups the 300s cap stands,
72
+ * because only the dispatcher's owner knows how to rebuild it.
73
+ */
74
+ dispatcherFor(budgetMs: number): Agent | undefined {
75
+ if (!isPlainPoolingAgent(getGlobalDispatcher())) {
76
+ if (!this.warnedAboutCustomDispatcher) {
77
+ this.warnedAboutCustomDispatcher = true;
78
+ log.debug(
79
+ "local LLM: a custom global dispatcher is installed; leaving it in place. " +
80
+ "localLlmTimeoutMs above that dispatcher's headersTimeout will not take effect.",
81
+ );
82
+ }
83
+ return undefined;
84
+ }
85
+ const normalized = Number.isFinite(budgetMs) ? Math.max(0, budgetMs) : 0;
86
+ if (this.agent && this.agentBudgetMs === normalized) return this.agent;
87
+ void this.agent?.close().catch(() => {
88
+ /* pool teardown is best-effort */
89
+ });
90
+ this.agent = new Agent({
91
+ headersTimeout: normalized,
92
+ bodyTimeout: normalized,
93
+ });
94
+ this.agentBudgetMs = normalized;
95
+ return this.agent;
96
+ }
97
+
98
+ async post(request: ChatCompletionRequest): Promise<Response> {
99
+ const init: RequestInit & { dispatcher?: Agent } = {
100
+ method: "POST",
101
+ headers: request.headers,
102
+ body: request.body,
103
+ signal: request.signal,
104
+ };
105
+ const dispatcher = this.dispatcherFor(request.budgetMs);
106
+ if (dispatcher) init.dispatcher = dispatcher;
107
+ return await fetch(request.url, init);
108
+ }
109
+ }
package/src/local-llm.ts CHANGED
@@ -7,6 +7,7 @@ import { launchProcessSync } from "./runtime/child-process.js";
7
7
  import { mergeEnv, readEnvVar } from "./runtime/env.js";
8
8
  import { resolveLocalLlmCapabilities } from "./capabilities.js";
9
9
  import { resolvePipelineProcessingCapabilities } from "./capabilities.js";
10
+ import { ChatTransport } from "./local-llm-transport.js";
10
11
 
11
12
  /** Trim trailing slash characters without backtracking regex. */
12
13
  function trimTrailingSlashes(s: string): string {
@@ -263,6 +264,7 @@ export class LocalLlmClient {
263
264
  private queueDrainScheduled: boolean = false;
264
265
  private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute
265
266
  private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds
267
+ private readonly chatTransport = new ChatTransport();
266
268
 
267
269
  constructor(config: PluginConfig, modelRegistry?: ModelRegistry) {
268
270
  this.config = config;
@@ -1029,16 +1031,6 @@ export class LocalLlmClient {
1029
1031
  // Avoid logging request bodies by default (can contain sensitive user content).
1030
1032
  log.debug(`local LLM: request body length=${requestBodyJson.length}`);
1031
1033
 
1032
- // Write request body to file for debugging
1033
- if (this.config.debug) {
1034
- try {
1035
- const { writeFileSync } = await import("node:fs");
1036
- writeFileSync("/tmp/engram-last-request.json", requestBodyJson);
1037
- } catch {
1038
- /* ignore */
1039
- }
1040
- }
1041
-
1042
1034
  const effectiveTimeoutMs =
1043
1035
  typeof options.timeoutMs === "number"
1044
1036
  ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)
@@ -1050,13 +1042,14 @@ export class LocalLlmClient {
1050
1042
  const attemptAbort = new AbortController();
1051
1043
  const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);
1052
1044
  try {
1053
- response = await fetch(chatUrl, {
1054
- method: "POST",
1045
+ response = await this.chatTransport.post({
1046
+ url: chatUrl,
1055
1047
  headers: this.buildRequestHeaders({
1056
1048
  "Content-Type": "application/json",
1057
1049
  }),
1058
- body: JSON.stringify(requestBody),
1050
+ body: requestBodyJson,
1059
1051
  signal: attemptAbort.signal,
1052
+ budgetMs: this.config.localLlmTimeoutMs,
1060
1053
  });
1061
1054
  } catch (err) {
1062
1055
  if (!this.isAbortError(err)) throw err;
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport { launchProcessSync } from \"./runtime/child-process.js\";\nimport { mergeEnv, readEnvVar } from \"./runtime/env.js\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\n\n/** Trim trailing slash characters without backtracking regex. */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s[end - 1] === \"/\") end--;\n return s.substring(0, end);\n}\n\nfunction stripTrailingV1Path(s: string): string {\n return s.endsWith(\"/v1\") ? s.slice(0, -3) : s;\n}\n\nfunction explicitPortFromUrl(s: string): number | null {\n try {\n const parsed = new URL(s);\n if (!parsed.port) return null;\n const port = Number(parsed.port);\n return Number.isInteger(port) ? port : null;\n } catch {\n return null;\n }\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isLlamaCppPropsResponse(value: unknown): boolean {\n return (\n isObjectRecord(value) &&\n isObjectRecord(value.default_generation_settings) &&\n typeof value.total_slots === \"number\" &&\n (\n typeof value.model_path === \"string\" ||\n typeof value.chat_template === \"string\" ||\n typeof value.build_info === \"string\"\n )\n );\n}\n\nfunction isLlamaCppModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n if (entry.owned_by === \"llamacpp\") return true;\n if (typeof entry.id === \"string\" && entry.id.endsWith(\".gguf\")) return true;\n const meta = entry.meta;\n return (\n isObjectRecord(meta) &&\n (\"n_ctx_train\" in meta || \"n_params\" in meta || \"vocab_type\" in meta)\n );\n });\n}\n\nfunction isLmStudioApiV1ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.models)) {\n return false;\n }\n return value.models.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.key === \"string\" &&\n typeof entry.display_name === \"string\" &&\n (\n typeof entry.format === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n Array.isArray(entry.loaded_instances)\n )\n );\n });\n}\n\nfunction isLmStudioApiV0ModelsResponse(value: unknown): boolean {\n if (!isObjectRecord(value) || !Array.isArray(value.data)) {\n return false;\n }\n return value.data.some((entry) => {\n if (!isObjectRecord(entry)) return false;\n return (\n typeof entry.id === \"string\" &&\n typeof entry.publisher === \"string\" &&\n (\n typeof entry.compatibility_type === \"string\" ||\n typeof entry.max_context_length === \"number\" ||\n typeof entry.state === \"string\"\n )\n );\n });\n}\n\nfunction isLmStudioNativeModelsResponse(value: unknown): boolean {\n return isLmStudioApiV1ModelsResponse(value) || isLmStudioApiV0ModelsResponse(value);\n}\n\n/**\n * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)\n *\n * Based on openclaw-tactician's provider detection patterns for consistency.\n * Provides privacy-preserving, cost-effective LLM operations with\n * graceful fallback to cloud providers when local LLM is unavailable.\n */\nexport type LocalLlmType = \"lmstudio\" | \"ollama\" | \"mlx\" | \"vllm\" | \"llamacpp\" | \"generic\";\n\n/**\n * Backends known to honor `chat_template_kwargs: { enable_thinking: false }`\n * on OpenAI-compatible `/v1/chat/completions`. LM Studio, vLLM, and\n * llama.cpp forward this field to the jinja chat template, where thinking-capable\n * models (Qwen 3.5, Gemma 4, DeepSeek) suppress reasoning tokens.\n *\n * Strict OpenAI-compatible backends (standard OpenAI, Azure OpenAI, some\n * proxies) reject unknown request fields with 400 — which trips the\n * `localLlm400*` cooldown path. `LocalLlmClient` therefore only injects\n * the kwarg when the detected backend is in this set; unknown / `generic`\n * / `ollama` / `mlx` fail open (no injection, no 400 risk). Issue #548.\n */\nconst THINKING_COMPATIBLE_BACKENDS: ReadonlySet<LocalLlmType> = new Set([\n \"lmstudio\",\n \"vllm\",\n \"llamacpp\",\n]);\n\nconst THINKING_SUPPRESSED_OPERATIONS: ReadonlySet<string> = new Set([\n \"extraction\",\n \"extraction-judge\",\n \"extraction-faithfulness\",\n \"contradiction-judge\",\n \"contradiction_verification\",\n \"link_suggestion\",\n \"memory_summarization\",\n \"proactive_extraction\",\n \"lcm-summarize\",\n \"day_summary\",\n \"hourly_summary\",\n \"hourly_summary_extended\",\n]);\n\ninterface LocalServerConfig {\n type: LocalLlmType;\n defaultPort: number;\n healthEndpoint: string;\n modelsEndpoint: string;\n detectFn: (response: unknown) => boolean;\n}\n\nconst LOCAL_SERVERS: LocalServerConfig[] = [\n {\n type: \"ollama\",\n defaultPort: 11434,\n healthEndpoint: \"/\",\n modelsEndpoint: \"/api/tags\",\n detectFn: (resp) => typeof resp === \"string\" && resp.includes(\"Ollama\"),\n },\n {\n type: \"llamacpp\",\n defaultPort: 8080,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && resp.status === \"ok\",\n },\n {\n type: \"mlx\",\n defaultPort: 8080,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && Array.isArray(resp.data),\n },\n {\n type: \"lmstudio\",\n defaultPort: 1234,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => isObjectRecord(resp) && Array.isArray(resp.data),\n },\n {\n type: \"vllm\",\n defaultPort: 8000,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => resp === \"\" || (isObjectRecord(resp) && !(\"status\" in resp)),\n },\n];\n\nfunction orderedLocalServers(configuredBaseUrl: string): LocalServerConfig[] {\n const configuredPort = explicitPortFromUrl(configuredBaseUrl);\n if (configuredPort === null) return LOCAL_SERVERS;\n const matching = LOCAL_SERVERS.filter(\n (serverConfig) => serverConfig.defaultPort === configuredPort,\n );\n if (matching.length === 0) return LOCAL_SERVERS;\n const matchingTypes = new Set(matching.map((serverConfig) => serverConfig.type));\n return [\n ...matching,\n ...LOCAL_SERVERS.filter((serverConfig) => !matchingTypes.has(serverConfig.type)),\n ];\n}\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\ninterface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string };\n timeoutMs?: number;\n operation?: string;\n forceDisableThinking?: boolean;\n disableThinking?: boolean;\n priority?: LocalLlmRequestPriority;\n}\n\ninterface LocalLlmQueuedRequest {\n messages: Array<{ role: string; content: string }>;\n options: LocalLlmChatCompletionOptions;\n priority: LocalLlmRequestPriority;\n enqueuedAtMs: number;\n resolve: (value: LocalLlmChatCompletionResult | null) => void;\n}\n\ninterface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\n\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\ntype LocalLlmBackendState = {\n untilMs: number;\n reason: string;\n};\nexport class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private detectedType: LocalLlmType | null = null;\n private cachedModelInfo: LocalModelInfo | null = null;\n private cachedLmsContext: number | null = null;\n private lastLmsCheck: number = 0;\n private consecutive400s: number = 0;\n private cooldownUntilMs: number = 0;\n private modelRegistry?: ModelRegistry;\n private _disableThinking: boolean = false;\n private readonly requestQueues: Record<LocalLlmRequestPriority, LocalLlmQueuedRequest[]> = {\n \"recall-critical\": [],\n background: [],\n };\n private readonly queueProcessing = new Set<LocalLlmRequestPriority>();\n private queueDrainScheduled: boolean = false;\n private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute\n private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n }\n\n /**\n * Request thinking/reasoning suppression on the next chat completion.\n *\n * When `true`, the client will inject\n * `chat_template_kwargs: { enable_thinking: false }` into the request\n * body — **but only when the detected backend is known to support it**\n * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict\n * OpenAI-compat backends reject unknown fields with 400; on those the\n * client fails open (thinking runs normally). This is the safe\n * default for Remnic extraction-style operations: measurable latency\n * win on thinking-capable backends, zero risk on others. Consolidation\n * operations keep thinking enabled unless explicitly added to\n * `THINKING_SUPPRESSED_OPERATIONS`. Issues #548 and #979.\n */\n set disableThinking(value: boolean) {\n this._disableThinking = value;\n }\n\n private resolveHomeDir(): string {\n return this.config.localLlmHomeDir || readEnvVar(\"HOME\") || os.homedir();\n }\n\n private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {\n const headers: Record<string, string> = {\n ...base,\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return headers;\n }\n\n private 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 /**\n * Set the ModelRegistry for caching detected capabilities\n */\n setModelRegistry(registry: ModelRegistry): void {\n this.modelRegistry = registry;\n }\n\n /**\n * Get the detected server type (null if not detected)\n */\n getDetectedType(): LocalLlmType | null {\n return this.detectedType;\n }\n\n private getBackendKey(): string {\n return trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n ).replace(/\\/v1$/, \"\");\n }\n\n private getGlobalBackendState(): Map<string, LocalLlmBackendState> {\n const globalAny = globalThis as typeof globalThis & {\n [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendState>;\n };\n if (!globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE]) {\n globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = new Map();\n }\n return globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];\n }\n\n private getTrippedBackendState(now: number): LocalLlmBackendState | null {\n const state = this.getGlobalBackendState().get(this.getBackendKey()) ?? null;\n if (!state) return null;\n if (state.untilMs <= now) {\n this.getGlobalBackendState().delete(this.getBackendKey());\n this.lastHealthCheck = 0;\n return null;\n }\n return state;\n }\n\n private markBackendUnavailable(reason: string, durationMs: number): void {\n const normalizedReason = this.normalizeBackendTripReason(reason);\n if (durationMs > 0) {\n const untilMs = Date.now() + durationMs;\n this.getGlobalBackendState().set(this.getBackendKey(), { untilMs, reason: normalizedReason });\n } else {\n this.getGlobalBackendState().delete(this.getBackendKey());\n }\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.warn(\n `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizedReason}`,\n );\n }\n\n private 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\n private extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = this.extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return this.extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n }\n\n private 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\n /**\n * Fetch with timeout for health checks\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n ): Promise<{ ok: boolean; data: unknown; status: number | null }> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n });\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { ok: false, data: null, status: response.status };\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return { ok: true, data: await response.json(), status: response.status };\n } else {\n return { ok: true, data: await response.text(), status: response.status };\n }\n } catch (err) {\n clearTimeout(timeout);\n return { ok: false, data: null, status: null };\n }\n }\n\n private async probeLmStudioNativeModels(\n probeBaseUrl: string,\n ): Promise<{ matched: boolean; unauthorized: boolean }> {\n let unauthorized = false;\n for (const endpoint of [\"/api/v1/models\", \"/api/v0/models\"]) {\n const probe = await this.fetchWithTimeout(`${probeBaseUrl}${endpoint}`);\n if (probe.ok && isLmStudioNativeModelsResponse(probe.data)) {\n return { matched: true, unauthorized };\n }\n if (probe.status === 401 || probe.status === 403) {\n unauthorized = true;\n }\n }\n return { matched: false, unauthorized };\n }\n\n /**\n * Check if local LLM is available\n * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)\n */\n async checkAvailability(): Promise<boolean> {\n // Cache health check results for 1 minute\n const now = Date.now();\n const trippedState = this.getTrippedBackendState(now);\n if (trippedState) {\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.info(\n `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason})`,\n );\n return false;\n }\n if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {\n return this.isAvailable;\n }\n\n // Normalize URL - replace localhost with 127.0.0.1, remove trailing slashes.\n // Probe server-native endpoints from the server root even when users configure\n // the OpenAI-compatible `/v1` base URL for chat completions.\n const configuredBaseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const probeBaseUrl = stripTrailingV1Path(configuredBaseUrl);\n let sawUnauthorizedProbe = false;\n\n // Try to detect which server type is running\n for (const serverConfig of orderedLocalServers(configuredBaseUrl)) {\n const healthUrl = `${probeBaseUrl}${serverConfig.healthEndpoint}`;\n log.debug(`checking ${serverConfig.type} at ${healthUrl}`);\n\n const result = await this.fetchWithTimeout(healthUrl);\n if (result.ok && serverConfig.detectFn(result.data)) {\n if (serverConfig.type === \"mlx\") {\n const lmStudioProbe = await this.probeLmStudioNativeModels(probeBaseUrl);\n if (lmStudioProbe.unauthorized) {\n sawUnauthorizedProbe = true;\n }\n if (lmStudioProbe.matched) {\n this.isAvailable = true;\n this.detectedType = \"lmstudio\";\n this.lastHealthCheck = now;\n log.info(`detected lmstudio at ${configuredBaseUrl}`);\n return true;\n }\n }\n if (serverConfig.type === \"llamacpp\") {\n let sawLlamaCppSignal = false;\n const propsProbe = await this.fetchWithTimeout(`${probeBaseUrl}/props`);\n if (propsProbe.ok && isLlamaCppPropsResponse(propsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (propsProbe.status === 401 || propsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n }\n\n const modelsUrl = `${probeBaseUrl}${serverConfig.modelsEndpoint}`;\n const modelsProbe = await this.fetchWithTimeout(modelsUrl);\n if (modelsProbe.ok && isLlamaCppModelsResponse(modelsProbe.data)) {\n sawLlamaCppSignal = true;\n }\n if (modelsProbe.status === 401 || modelsProbe.status === 403) {\n sawUnauthorizedProbe = true;\n continue;\n }\n\n const authConfigured =\n Boolean(this.config.localLlmApiKey) &&\n this.config.localLlmAuthHeader !== false;\n if (!sawLlamaCppSignal || (authConfigured && !modelsProbe.ok)) {\n continue;\n }\n }\n this.isAvailable = true;\n this.detectedType = serverConfig.type;\n this.lastHealthCheck = now;\n log.info(`detected ${serverConfig.type} at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n }\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${probeBaseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl);\n if (result.ok) {\n this.isAvailable = true;\n this.detectedType = \"generic\";\n this.lastHealthCheck = now;\n log.info(`detected generic OpenAI-compatible server at ${configuredBaseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n } catch {\n // Fall through to unavailable\n }\n\n this.isAvailable = false;\n this.detectedType = null;\n this.lastHealthCheck = now;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${configuredBaseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.debug(\"local LLM not available at\", configuredBaseUrl);\n return false;\n }\n\n /**\n * Try to get context window from LM Studio settings.json as fallback.\n * This reads the defaultContextLength setting which is what LM Studio uses\n * when loading models without explicit context configuration.\n */\n private getContextFromLmStudioSettings(): number | null {\n try {\n const homeDir = this.resolveHomeDir();\n const settingsPath = `${homeDir}/.cache/lm-studio/settings.json`;\n\n if (!fs.existsSync(settingsPath)) {\n log.debug(`LM Studio settings: file not found at ${settingsPath}`);\n return null;\n }\n\n const content = fs.readFileSync(settingsPath, \"utf-8\");\n const settings = JSON.parse(content) as {\n defaultContextLength?: {\n type?: string;\n value?: number;\n };\n };\n\n if (settings.defaultContextLength?.value) {\n const contextWindow = settings.defaultContextLength.value;\n log.debug(`LM Studio settings: found default context length: ${contextWindow}`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LM Studio settings: failed to read - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Try to get context window from LMS CLI (LM Studio specific).\n * Uses --json flag for reliable parsing.\n * Returns null if LMS CLI is not available or model not found.\n */\n private getContextFromLmsCli(modelId: string): number | null {\n try {\n // Check if lms CLI exists in common locations.\n // HOME may be absent in launchd environments, so prefer the resolved helper.\n const homeDir = this.resolveHomeDir();\n const lmsPaths = [\n this.config.localLmsCliPath || \"\",\n `${homeDir}/.cache/lm-studio/bin/lms`,\n \"/usr/local/bin/lms\",\n \"/opt/homebrew/bin/lms\",\n ];\n\n const lmsPath = lmsPaths.find((p) => p.length > 0 && fs.existsSync(p));\n if (!lmsPath) {\n log.debug(`LMS CLI: not found in standard locations (checked: ${lmsPaths.join(\", \")})`);\n return null;\n }\n\n // Run lms ps --json to get loaded models with context\n // Use spawnSync with shell and explicit PATH to ensure lms can find its dependencies\n log.debug(`LMS CLI: running: ${lmsPath} ps --json`);\n const existingPath = readEnvVar(\"PATH\") || \"\";\n const result = launchProcessSync(lmsPath, [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false, // Don't use shell for JSON output - more reliable\n env: mergeEnv({\n PATH: `${this.config.localLmsBinDir || `${homeDir}/.cache/lm-studio/bin`}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${existingPath}`,\n HOME: homeDir,\n }),\n });\n\n if (result.error) {\n log.debug(`LMS CLI: spawn error - ${result.error.message}`);\n return null;\n }\n\n if (result.stderr && result.stderr.trim()) {\n log.debug(`LMS CLI: stderr - ${result.stderr.slice(0, 200)}`);\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n log.debug(\"LMS CLI: empty output - LM Studio may not be running or no models loaded\");\n return null;\n }\n\n // Parse JSON output\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch (parseErr) {\n log.debug(`LMS CLI: JSON parse error - ${parseErr}`);\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n log.debug(\"LMS CLI: no models loaded\");\n return null;\n }\n\n // Find the model matching our configured model ID\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model) {\n log.debug(`LMS CLI: model \"${modelId}\" not found in loaded models: ${models.map(m => m.identifier).join(\", \")}`);\n return null;\n }\n\n // Use contextLength (actual configured) or fall back to maxContextLength (model max)\n const contextWindow = model.contextLength || model.maxContextLength;\n\n if (contextWindow) {\n log.info(`LMS CLI detected context window: ${contextWindow} for ${modelId} (max: ${model.maxContextLength})`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n // LMS CLI not available or failed\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LMS CLI: failed - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Get full model info from LMS CLI including context length and max context length.\n * Returns null if LMS CLI is unavailable or model not found.\n */\n private getLmsModelInfo(modelId: string): { contextLength: number; maxContextLength: number; identifier: string } | null {\n try {\n const result = launchProcessSync(\"lms\", [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false,\n });\n\n if (result.error) {\n return null;\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n return null;\n }\n\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch {\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n return null;\n }\n\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model || !model.contextLength) {\n return null;\n }\n\n return {\n contextLength: model.contextLength,\n maxContextLength: model.maxContextLength || model.contextLength,\n identifier: model.identifier || modelId,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Get context window for the configured model, using cache if available.\n * This method caches the result to avoid repeated LMS CLI calls.\n * Order: ModelRegistry (persistent) -> memory cache -> LMS CLI -> settings.json\n */\n getCachedContextWindow(modelId: string): number | null {\n const now = Date.now();\n\n // 1. Check ModelRegistry for persisted context window\n if (this.modelRegistry) {\n const caps = this.modelRegistry.getCapabilities(modelId);\n if (caps.source === \"lmstudio\" && caps.contextWindow) {\n log.debug(`ModelRegistry: using persisted LM Studio context: ${caps.contextWindow}`);\n // Also update memory cache\n this.cachedLmsContext = caps.contextWindow;\n this.lastLmsCheck = now;\n return caps.contextWindow;\n }\n }\n\n // 2. Return in-memory cached value if still valid\n if (this.cachedLmsContext && now - this.lastLmsCheck < LocalLlmClient.LMS_CACHE_INTERVAL_MS) {\n log.debug(`LMS CLI: returning in-memory cached context: ${this.cachedLmsContext}`);\n return this.cachedLmsContext;\n }\n\n // 3. Try LMS CLI (authoritative source)\n const lmsInfo = this.getLmsModelInfo(modelId);\n if (lmsInfo?.contextLength) {\n this.cachedLmsContext = lmsInfo.contextLength;\n this.lastLmsCheck = now;\n // Calculate appropriate output tokens based on context size\n // Use 12.5% of context window, capped at 16K (generous but safe)\n const calculatedOutputTokens = Math.min(Math.floor(lmsInfo.contextLength / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096); // Minimum 4K\n // Persist to ModelRegistry with detected capabilities\n if (this.modelRegistry) {\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: lmsInfo.maxContextLength || lmsInfo.contextLength,\n contextWindow: lmsInfo.contextLength,\n supportsExtendedContext: (lmsInfo.maxContextLength || lmsInfo.contextLength) > 65536,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n log.info(`LMS CLI: Stored capabilities for ${modelId}: ${lmsInfo.contextLength} context, ${outputTokens} output tokens`);\n }\n return lmsInfo.contextLength;\n }\n\n // Legacy: Try LMS CLI context only (fallback)\n const legacyContext = this.getContextFromLmsCli(modelId);\n if (legacyContext) {\n this.cachedLmsContext = legacyContext;\n this.lastLmsCheck = now;\n // Persist to ModelRegistry with calculated output tokens\n if (this.modelRegistry) {\n const calculatedOutputTokens = Math.min(Math.floor(legacyContext / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096);\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: legacyContext,\n contextWindow: legacyContext,\n supportsExtendedContext: false,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n }\n return legacyContext;\n }\n\n // 4. Fall back to LM Studio settings.json\n const settingsContext = this.getContextFromLmStudioSettings();\n if (settingsContext) {\n log.info(`LM Studio settings: using default context: ${settingsContext}`);\n this.cachedLmsContext = settingsContext;\n this.lastLmsCheck = now;\n return settingsContext;\n }\n\n return null;\n }\n\n /**\n * Clear the LMS context cache. Call this when the model changes.\n */\n clearContextCache(): void {\n this.cachedLmsContext = null;\n this.lastLmsCheck = 0;\n log.debug(\"LMS CLI: context cache cleared\");\n }\n\n private remainingCooldownMs(now: number = Date.now()): number {\n return Math.max(0, this.cooldownUntilMs - now);\n }\n\n private scheduleQueueDrain(): void {\n if (this.queueDrainScheduled) return;\n this.queueDrainScheduled = true;\n\n queueMicrotask(() => {\n this.queueDrainScheduled = false;\n this.startAvailableQueuedRequests();\n });\n }\n\n /** True when a background-priority request occupies or awaits this client's local lane (issue #2011). */\n isBackgroundLaneContended(): boolean {\n return this.queueProcessing.has(\"background\") || this.requestQueues.background.length > 0;\n }\n\n private dequeueQueuedRequest(priority: LocalLlmRequestPriority): LocalLlmQueuedRequest | null {\n const next = this.requestQueues[priority].shift();\n return next ?? null;\n }\n\n private failOpenQueuedRequestsForCooldown(): number {\n let dropped = 0;\n for (const priority of [\"recall-critical\", \"background\"] as const) {\n while (this.requestQueues[priority].length > 0) {\n const queued = this.requestQueues[priority].shift();\n queued?.resolve(null);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n private startAvailableQueuedRequests(): void {\n if (!this.queueProcessing.has(\"recall-critical\")) {\n const nextCritical = this.dequeueQueuedRequest(\"recall-critical\");\n if (nextCritical) {\n this.queueProcessing.add(\"recall-critical\");\n void this.runQueuedRequest(nextCritical);\n }\n }\n\n if (!this.queueProcessing.has(\"background\")) {\n const nextBackground = this.dequeueQueuedRequest(\"background\");\n if (nextBackground) {\n this.queueProcessing.add(\"background\");\n void this.runQueuedRequest(nextBackground);\n }\n }\n }\n\n private async runQueuedRequest(next: LocalLlmQueuedRequest): Promise<void> {\n try {\n const remainingCooldownMs = this.remainingCooldownMs();\n if (remainingCooldownMs > 0) {\n const additionalDropped = this.failOpenQueuedRequestsForCooldown();\n log.warn(\n `local LLM: cooldown active (${remainingCooldownMs}ms remaining), dropping ${additionalDropped + 1} queued request(s) fail-open`,\n );\n next.resolve(null);\n return;\n }\n\n let result: LocalLlmChatCompletionResult | null = null;\n try {\n result = await this.runChatCompletionRequest(next.messages, next.options, {\n priority: next.priority,\n enqueuedAtMs: next.enqueuedAtMs,\n });\n } catch (err) {\n log.warn(`local LLM queue drain failed open: ${err instanceof Error ? err.message : String(err)}`);\n }\n next.resolve(result);\n } finally {\n this.queueProcessing.delete(next.priority);\n if (this.requestQueues[\"recall-critical\"].length > 0 || this.requestQueues.background.length > 0) {\n this.scheduleQueueDrain();\n }\n }\n }\n\n private async runChatCompletionRequest(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions,\n queueMeta?: { priority: LocalLlmRequestPriority; enqueuedAtMs: number },\n ): Promise<LocalLlmChatCompletionResult | null> {\n log.debug(\n `local LLM chatCompletion: localLlmEnabled=${resolveLocalLlmCapabilities(this.config).localLlm}, model=${this.config.localLlmModel}`,\n );\n\n const operation = options.operation ?? \"unspecified\";\n const startedAtMs = Date.now();\n if (queueMeta) {\n log.debug(\n `local LLM queue start: priority=${queueMeta.priority} waitMs=${startedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n\n try {\n const isAvailable = await this.checkAvailability();\n if (!isAvailable) {\n log.debug(\n `local LLM: checkAvailability returned false for ${this.config.localLlmUrl}`,\n );\n return null;\n }\n\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const requestBody: Record<string, unknown> = {\n model: this.config.localLlmModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n };\n\n // Skip response_format for local LLMs - they don't support json_object type\n // The prompts already instruct the model to output JSON\n // Only send if it's json_schema type which some local LLMs support\n if (options.responseFormat?.type === \"json_schema\") {\n requestBody.response_format = options.responseFormat;\n }\n\n // Suppress thinking/reasoning for operations that benefit from terse,\n // structured output. Thinking-capable models (Qwen 3.5, Gemma 4,\n // DeepSeek) default to thinking-on via their chat template; sending\n // `chat_template_kwargs: { enable_thinking: false }` tells the template\n // to skip reasoning tokens. Consolidation operations on the main client\n // intentionally keep thinking enabled so entity resolution and\n // deduplication can use the model's reasoning path. Fast-tier callers can\n // still force suppression per request to preserve their low-latency\n // contract.\n //\n // Gate the injection on detected backend support (issue #548,\n // Codex P1 on PR #550): `chat_template_kwargs` is an LM Studio /\n // vLLM / llama.cpp extension, not part of standard OpenAI chat\n // completions. Strict OpenAI-compatible backends reject\n // unknown fields with 400, which trips the 400-cooldown path and\n // can effectively disable local extraction. Fail open when the\n // backend hasn't been positively identified as thinking-capable.\n const shouldSuppressThinking =\n options.forceDisableThinking === true ||\n ((options.disableThinking ?? this._disableThinking) &&\n THINKING_SUPPRESSED_OPERATIONS.has(operation));\n if (\n shouldSuppressThinking &&\n this.detectedType !== null &&\n THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)\n ) {\n requestBody.chat_template_kwargs = { enable_thinking: false };\n } else if (shouldSuppressThinking && this.detectedType === \"ollama\") {\n // Ollama's /v1 endpoint silently drops `chat_template_kwargs` AND\n // `enable_thinking` — the ONLY field it maps to think-off is\n // `reasoning_effort` (\"none\" → ThinkValue{false} in openai.go;\n // verified against Ollama 0.32.0 source and live probes,\n // issue #1996). Without this, thinking-capable models (Gemma 4,\n // Qwen 3.5+) burn 1,700-2,000 reasoning tokens per extraction on\n // Ollama, exceed the client timeout, and retry forever. The effort\n // is configurable via `localLlmReasoningEffort` (default \"none\");\n // an empty value disables injection (pre-#1996 behavior).\n const effort = this.config.localLlmReasoningEffort;\n if (effort) {\n requestBody.reasoning_effort = effort;\n }\n }\n\n // Normalize URL (use 127.0.0.1 instead of localhost)\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const chatUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/chat/completions`\n : `${baseUrl}/v1/chat/completions`;\n\n const requestBodyJson = JSON.stringify(requestBody);\n log.debug(\n `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,\n );\n // Avoid logging request bodies by default (can contain sensitive user content).\n log.debug(`local LLM: request body length=${requestBodyJson.length}`);\n\n // Write request body to file for debugging\n if (this.config.debug) {\n try {\n const { writeFileSync } = await import(\"node:fs\");\n writeFileSync(\"/tmp/engram-last-request.json\", requestBodyJson);\n } catch {\n /* ignore */\n }\n }\n\n const effectiveTimeoutMs =\n typeof options.timeoutMs === \"number\"\n ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)\n : this.config.localLlmTimeoutMs;\n const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);\n let response: Response | null = null;\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const attemptAbort = new AbortController();\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n try {\n response = await fetch(chatUrl, {\n method: \"POST\",\n headers: this.buildRequestHeaders({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify(requestBody),\n signal: attemptAbort.signal,\n });\n } catch (err) {\n if (!this.isAbortError(err)) throw err;\n lastAbortError = err instanceof Error ? err : new Error(String(err));\n if (attempt < maxAttempts) {\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request aborted: op=${operation} attempt=${attempt}/${maxAttempts} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel}; retrying after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n break;\n } finally {\n clearTimeout(attemptTimeout);\n }\n\n if (response.ok) break;\n if (response.status >= 500 && attempt < maxAttempts) {\n try {\n const errorText = await response.clone().text();\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n } catch (e) {\n log.debug(`local LLM failed to inspect retryable error body: ${e}`);\n }\n }\n if (response.status < 500 || attempt >= maxAttempts) break;\n\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request got ${response.status}; retrying (attempt ${attempt + 1}/${maxAttempts}) after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\n );\n\n if (!response) {\n if (lastAbortError) {\n log.warn(\n `local LLM request aborted after ${maxAttempts} attempt(s): op=${operation} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel} promptChars=${promptChars} durationMs=${Date.now() - startedAtMs}`,\n );\n } else {\n log.warn(\n `local LLM request failed: no response object (op=${operation} model=${this.config.localLlmModel} durationMs=${Date.now() - startedAtMs})`,\n );\n }\n return null;\n }\n\n if (!response.ok) {\n let reason = \"\";\n let errorText = \"\";\n try {\n errorText = await response.text();\n // Try to extract a stable error message without logging content.\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n // Keep a short preview in debug only.\n log.debug(`local LLM error body: ${errorText.slice(0, 500)}`);\n }\n } catch (e) {\n log.debug(`local LLM failed to read error body: ${e}`);\n }\n log.warn(\n `local LLM request failed: ${response.status} ${response.statusText}${reason} ` +\n `(op=${operation}, model=${this.config.localLlmModel}, url=${chatUrl}, promptChars=${promptChars}, maxTokens=${requestBody.max_tokens as number})`,\n );\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReason(reason) ??\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n if (response.status === 400) {\n this.consecutive400s += 1;\n if (this.consecutive400s >= this.config.localLlm400TripThreshold) {\n this.cooldownUntilMs = Date.now() + this.config.localLlm400CooldownMs;\n log.warn(\n `local LLM: entering cooldown for ${this.config.localLlm400CooldownMs}ms ` +\n `after ${this.consecutive400s} consecutive 400 responses`,\n );\n this.consecutive400s = 0;\n }\n } else {\n this.consecutive400s = 0;\n }\n return null;\n }\n this.consecutive400s = 0;\n\n const data = (await response.json()) as {\n choices?: Array<{\n message?: { content?: string; reasoning_content?: string };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n log.debug(\n `local LLM response: choices=${data.choices?.length}, usage=${JSON.stringify(data.usage)}`,\n );\n\n // Thinking models (e.g. Qwen 3.5) may put their response in\n // `reasoning_content` and leave `content` empty. Fall back to\n // reasoning_content so engram still gets a usable result.\n const msg = data.choices?.[0]?.message;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content. choices=${JSON.stringify(data.choices)?.slice(0, 200)}`);\n return null;\n }\n\n // Estimate tokens if not provided by local LLM\n const usage = data.usage\n ? {\n promptTokens: data.usage.prompt_tokens ?? 0,\n completionTokens: data.usage.completion_tokens ?? 0,\n totalTokens: data.usage.total_tokens ?? 0,\n }\n : this.estimateTokens(messages, content);\n\n const durationMs = Date.now() - startedAtMs;\n if (resolvePipelineProcessingCapabilities(this.config).slowLog && durationMs >= this.config.slowLogThresholdMs) {\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const op = options.operation ? ` op=${options.operation}` : \"\";\n log.warn(\n `SLOW local LLM:${op} durationMs=${durationMs} model=${this.config.localLlmModel} url=${chatUrl} promptChars=${promptChars} outputTokens=${usage.completionTokens} totalTokens=${usage.totalTokens}`,\n );\n }\n\n log.debug(\"local LLM: request succeeded, tokens:\", usage.totalTokens);\n return { content, usage };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const durationMs = Date.now() - startedAtMs;\n if (this.isAbortError(err)) {\n log.warn(\n `local LLM request aborted: op=${operation} timeoutMs=${options.timeoutMs ?? this.config.localLlmTimeoutMs} model=${this.config.localLlmModel} durationMs=${durationMs} error=${errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = this.extractNonRecoverableBackendReason(errMsg);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n }\n return null;\n } finally {\n if (queueMeta) {\n const finishedAtMs = Date.now();\n const waitMs = startedAtMs - queueMeta.enqueuedAtMs;\n log.debug(\n `local LLM queue finish: priority=${queueMeta.priority} waitMs=${waitMs} runMs=${finishedAtMs - startedAtMs} totalMs=${finishedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n }\n }\n\n /**\n * Query the local LLM server for loaded model information.\n * Returns null if unavailable or if the model is not found.\n */\n async getLoadedModelInfo(): Promise<LocalModelInfo | null> {\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n\n // Handle URL construction - localLlmUrl may already include /v1\n const modelsUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/models`\n : `${baseUrl}/v1/models`;\n log.debug(`Fetching model info from ${modelsUrl}`);\n\n try {\n const result = await this.fetchWithTimeout(modelsUrl, 3000);\n if (!result.ok) {\n if (result.status === 401 || result.status === 403) {\n log.warn(\n `Local LLM: unauthorized while fetching models from ${modelsUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.warn(`Local LLM: Failed to fetch models from ${modelsUrl} - server returned error`);\n return null;\n }\n if (!result.data) {\n log.warn(`Local LLM: No data returned from ${modelsUrl}`);\n return null;\n }\n\n const data = result.data as {\n data?: Array<{\n id?: string;\n object?: string;\n owned_by?: string;\n // LM Studio specific fields\n max_context_length?: number;\n max_tokens?: number;\n // Ollama specific\n name?: string;\n details?: {\n parameter_size?: string;\n family?: string;\n };\n }>;\n };\n\n if (!Array.isArray(data.data) || data.data.length === 0) {\n log.warn(\"Local LLM returned no models\");\n return null;\n }\n\n // Verbose model listings are noisy on every gateway restart. Keep it debug-only.\n const modelIds = data.data.map((m) => m.id).filter(Boolean);\n log.debug(\n `Local LLM: Found ${modelIds.length} model(s). First 10: ${modelIds.slice(0, 10).join(\", \")}`,\n );\n\n // Find the model matching our configured model ID\n const configuredModel = this.config.localLlmModel;\n let model = data.data.find((m) => m.id === configuredModel);\n\n // If not found by exact match, try partial match (handle suffixes like @4bit)\n if (!model) {\n model = data.data.find((m) =>\n configuredModel.includes(m.id || \"\") ||\n (m.id || \"\").includes(configuredModel.replace(/@\\d+bit$/, \"\"))\n );\n }\n\n // If still not found, use the first loaded model and warn\n if (!model) {\n model = data.data[0];\n const availablePreview = data.data\n .map((m) => m.id)\n .filter(Boolean)\n .slice(0, 10)\n .join(\", \");\n log.warn(\n `Configured model \"${configuredModel}\" not found in local LLM. ` +\n `Using \"${model.id}\" instead. Available (first 10): ${availablePreview}`\n );\n }\n\n // Extract context window - try multiple field names\n let contextWindow = model.max_context_length || model.max_tokens;\n\n // If API doesn't report context window, try LMS CLI (LM Studio specific)\n if (!contextWindow) {\n log.info(\"Local LLM: API did not report context window, trying LMS CLI...\");\n const lmsContext = this.getCachedContextWindow(model.id || \"\");\n if (lmsContext) {\n contextWindow = lmsContext;\n }\n }\n\n this.cachedModelInfo = {\n id: model.id || \"unknown\",\n contextWindow: contextWindow,\n maxTokens: model.max_tokens,\n };\n\n log.info(\n `Local LLM model detected: ${this.cachedModelInfo.id}, ` +\n `context window: ${contextWindow?.toLocaleString() || \"unknown (may use default)\"}`\n );\n\n return this.cachedModelInfo;\n } catch (err) {\n log.warn(`Failed to fetch model info: ${err}`);\n return null;\n }\n }\n\n /**\n * Check if the configured model is available and get its actual context window.\n * Warns if there's a mismatch between expected and actual context.\n */\n async validateModelConfig(expectedContextWindow?: number): Promise<{\n available: boolean;\n actualContextWindow?: number;\n warnings: string[];\n }> {\n const warnings: string[] = [];\n\n const modelInfo = await this.getLoadedModelInfo();\n if (!modelInfo) {\n return { available: false, warnings: [\"Could not query local LLM for model info\"] };\n }\n\n // If we have expected context and the server reports one, check for mismatch\n if (expectedContextWindow && modelInfo.contextWindow) {\n if (modelInfo.contextWindow < expectedContextWindow) {\n warnings.push(\n `Context window mismatch: Model ${modelInfo.id} supports ${modelInfo.contextWindow.toLocaleString()} tokens, ` +\n `but engram is configured for ${expectedContextWindow.toLocaleString()}. ` +\n `Set localLlmMaxContext: ${modelInfo.contextWindow} in config to avoid errors.`\n );\n }\n }\n\n // Warn if server doesn't report context window (common with some local LLM setups)\n if (!modelInfo.contextWindow) {\n warnings.push(\n `Local LLM server did not report context window for ${modelInfo.id}. ` +\n `If you get \"context length exceeded\" errors, set localLlmMaxContext in config.`\n );\n }\n\n return {\n available: true,\n actualContextWindow: modelInfo.contextWindow,\n warnings,\n };\n }\n\n /**\n * Make a chat completion request to local LLM\n */\n async chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions = {},\n ): Promise<LocalLlmChatCompletionResult | null> {\n if (!resolveLocalLlmCapabilities(this.config).localLlm) {\n log.debug(\"local LLM: disabled, returning null\");\n return null;\n }\n\n const remainingMs = this.remainingCooldownMs();\n if (remainingMs > 0) {\n log.debug(`local LLM: cooldown active (${remainingMs}ms remaining), skipping request`);\n return null;\n }\n if (options.priority) {\n const priority = options.priority;\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n this.requestQueues[priority].push({\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve,\n });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n\n /**\n * Estimate tokens when local LLM doesn't return usage stats\n * Rough estimate: 1 token ≈ 4 characters\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n const promptTokens = Math.ceil(promptChars / 4);\n const completionTokens = Math.ceil(response.length / 4);\n\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n }\n\n /**\n * Try local LLM first, fallback to cloud provider if configured\n */\n async withFallback<T>(\n localOperation: () => Promise<T | null>,\n fallbackOperation: () => Promise<T>,\n operationName: string\n ): Promise<T> {\n // Try local LLM first if enabled\n if (resolveLocalLlmCapabilities(this.config).localLlm) {\n const localResult = await localOperation();\n if (localResult !== null) {\n log.debug(`${operationName}: used local LLM`);\n return localResult;\n }\n\n // Local failed or unavailable\n if (this.config.localLlmFallback) {\n log.info(`${operationName}: local LLM unavailable, falling back to cloud`);\n } else {\n throw new Error(`${operationName}: local LLM unavail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