@totalreclaw/mcp-server 3.3.0-rc.2 → 3.3.0-rc.4

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.
@@ -0,0 +1,704 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP-server - Extraction LLM Client
4
+ *
5
+ * Ported verbatim from `skill/plugin/llm-client.ts` (mcp-server 3.3.0-rc.3,
6
+ * MCP-first autonomous extraction pivot). The plugin file is the canonical
7
+ * source — keep them in sync. Local divergences:
8
+ * - imports `EXTRACTION_CONFIG` (from `./config.js` here) instead of the
9
+ * plugin's `CONFIG`.
10
+ * - drops the `./embedding.js` re-export at the bottom (mcp-server's
11
+ * embedding module lives at `../subgraph/embedding.js` and is loaded
12
+ * by the existing on-chain pipeline; the extraction LLM doesn't need
13
+ * embeddings).
14
+ *
15
+ * Auto-detects the user's LLM provider from OpenClaw's config and derives a
16
+ * cheap extraction model. Supports OpenAI-compatible APIs and Anthropic's
17
+ * Messages API. No external dependencies — uses native fetch().
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.LLMUpstreamOutageError = exports.DEFAULT_RETRY_BUDGET_MS = exports.CHEAP_MODEL_BY_PROVIDER = exports.ZAI_STANDARD_BASE_URL = exports.ZAI_CODING_BASE_URL = void 0;
21
+ exports.getZaiBaseUrl = getZaiBaseUrl;
22
+ exports.deriveCheapModel = deriveCheapModel;
23
+ exports.initLLMClient = initLLMClient;
24
+ exports.resolveLLMConfig = resolveLLMConfig;
25
+ exports.isZaiBalanceError = isZaiBalanceError;
26
+ exports.zaiFallbackBaseUrl = zaiFallbackBaseUrl;
27
+ exports.chatCompletion = chatCompletion;
28
+ exports.isRetryable = isRetryable;
29
+ const config_js_1 = require("./config.js");
30
+ // ---------------------------------------------------------------------------
31
+ // Provider mappings
32
+ // ---------------------------------------------------------------------------
33
+ /** Maps provider name to CONFIG.llmApiKeys property names to check (in order). */
34
+ const PROVIDER_KEY_NAMES = {
35
+ zai: ['zai'],
36
+ anthropic: ['anthropic'],
37
+ openai: ['openai'],
38
+ gemini: ['gemini'],
39
+ google: ['gemini', 'google'],
40
+ mistral: ['mistral'],
41
+ groq: ['groq'],
42
+ deepseek: ['deepseek'],
43
+ openrouter: ['openrouter'],
44
+ xai: ['xai'],
45
+ together: ['together'],
46
+ cerebras: ['cerebras'],
47
+ };
48
+ /**
49
+ * zai has TWO public endpoints. The CODING endpoint is what GLM Coding Plan
50
+ * subscription keys are provisioned against; the STANDARD (PAYG) endpoint
51
+ * serves pay-as-you-go balances. A coding-plan key that hits the STANDARD
52
+ * endpoint returns HTTP 429 with body `"Insufficient balance or no resource
53
+ * package. Please recharge."` — misleading because the subscription is in
54
+ * good standing. Vice-versa for PAYG keys that accidentally hit CODING.
55
+ *
56
+ * 3.3.1-rc.3: exported so the rc.3 auto-fallback (see `chatCompletion`)
57
+ * can flip between them when the upstream error signature matches.
58
+ */
59
+ exports.ZAI_CODING_BASE_URL = 'https://api.z.ai/api/coding/paas/v4';
60
+ exports.ZAI_STANDARD_BASE_URL = 'https://api.z.ai/api/paas/v4';
61
+ /**
62
+ * Resolve the zai base URL.
63
+ *
64
+ * Precedence:
65
+ * 1. `ZAI_BASE_URL` env var (explicit operator override — read by
66
+ * `CONFIG.zaiBaseUrl` via a getter so tests can mutate the env
67
+ * between calls)
68
+ * 2. Default: coding endpoint (coding-plan-biased; the rc.3 auto-fallback
69
+ * hops to the standard endpoint on an "Insufficient balance" 429).
70
+ *
71
+ * Documented in plugin SKILL.md — Coding-Plan users can leave it unset (or
72
+ * set it explicitly to `https://api.z.ai/api/coding/paas/v4`). PAYG users
73
+ * MUST set it to `https://api.z.ai/api/paas/v4` to avoid the auto-fallback
74
+ * tax on every first call.
75
+ *
76
+ * Scanner-isolation note: the env read lives in `config.ts` (which has no
77
+ * network triggers). This module has network calls, so it cannot touch
78
+ * env vars directly — both rules 1 (env-harvesting) and 2 (potential-
79
+ * exfiltration) in check-scanner.mjs would fire.
80
+ */
81
+ function getZaiBaseUrl() {
82
+ return config_js_1.EXTRACTION_CONFIG.zaiBaseUrl;
83
+ }
84
+ const PROVIDER_BASE_URLS = {
85
+ // zai: resolved lazily at each init/call so `ZAI_BASE_URL` env changes
86
+ // propagate without a module re-import. See `getZaiBaseUrl()`.
87
+ zai: getZaiBaseUrl(),
88
+ anthropic: 'https://api.anthropic.com/v1',
89
+ openai: 'https://api.openai.com/v1',
90
+ gemini: 'https://generativelanguage.googleapis.com/v1beta/openai',
91
+ google: 'https://generativelanguage.googleapis.com/v1beta/openai',
92
+ mistral: 'https://api.mistral.ai/v1',
93
+ groq: 'https://api.groq.com/openai/v1',
94
+ deepseek: 'https://api.deepseek.com/v1',
95
+ openrouter: 'https://openrouter.ai/api/v1',
96
+ xai: 'https://api.x.ai/v1',
97
+ together: 'https://api.together.xyz/v1',
98
+ cerebras: 'https://api.cerebras.ai/v1',
99
+ };
100
+ // ---------------------------------------------------------------------------
101
+ // Cheap model derivation
102
+ // ---------------------------------------------------------------------------
103
+ const CHEAP_INDICATORS = ['flash', 'mini', 'nano', 'haiku', 'small', 'lite', 'fast'];
104
+ /**
105
+ * Regex that tests whether a model id genuinely mentions a "cheap" tier.
106
+ * Uses word-boundary + `-` separators so we do NOT match substrings like
107
+ * "mini" inside "gemini" (real bug caught in 3.3.1 tests — deriveCheapModel
108
+ * was passing gemini-2.5-pro through unchanged because `.includes('mini')`
109
+ * matched the letters inside "gemini"). The canonical cheap-tier naming
110
+ * conventions put the indicator at a hyphen boundary or end of string:
111
+ * gpt-4.1-mini, claude-haiku-4-5, gemini-flash-lite, glm-4.5-flash, o4-mini
112
+ */
113
+ const CHEAP_INDICATOR_RE = new RegExp(`(?:^|[-_/.])(?:${CHEAP_INDICATORS.join('|')})(?:[-_/.]|$)`, 'i');
114
+ /**
115
+ * Default cheap extraction model per provider. Exported so callers that
116
+ * resolve a provider WITHOUT knowing the user's primary model (e.g. the
117
+ * auth-profiles.json path) can still pick a sensible model.
118
+ *
119
+ * 3.3.1 update: haiku is now `claude-haiku-4-5-20251001` (latest cheap
120
+ * Claude as of 2026-04). glm-4.5-flash stays the zai extraction default.
121
+ */
122
+ exports.CHEAP_MODEL_BY_PROVIDER = {
123
+ zai: 'glm-4.5-flash',
124
+ anthropic: 'claude-haiku-4-5-20251001',
125
+ openai: 'gpt-4.1-mini',
126
+ gemini: 'gemini-flash-lite',
127
+ google: 'gemini-flash-lite',
128
+ mistral: 'mistral-small-latest',
129
+ groq: 'llama-3.3-70b-versatile',
130
+ deepseek: 'deepseek-chat',
131
+ openrouter: 'anthropic/claude-haiku-4-5-20251001',
132
+ xai: 'grok-2',
133
+ together: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
134
+ cerebras: 'llama3.3-70b',
135
+ };
136
+ /**
137
+ * Derive a cheap/fast model suitable for fact extraction, given the user's
138
+ * provider and primary (potentially expensive) model.
139
+ */
140
+ function deriveCheapModel(provider, primaryModel) {
141
+ // If already on a cheap model, use it as-is.
142
+ // Word-boundary match to avoid false positives (see CHEAP_INDICATOR_RE).
143
+ if (CHEAP_INDICATOR_RE.test(primaryModel)) {
144
+ return primaryModel;
145
+ }
146
+ // Derive based on provider naming conventions
147
+ const fromTable = exports.CHEAP_MODEL_BY_PROVIDER[provider];
148
+ if (fromTable)
149
+ return fromTable;
150
+ // Fallback: use the primary model (best-effort — caller may still work)
151
+ return primaryModel;
152
+ }
153
+ // ---------------------------------------------------------------------------
154
+ // Module-level state
155
+ // ---------------------------------------------------------------------------
156
+ let _cachedConfig = null;
157
+ let _initialized = false;
158
+ let _logger = null;
159
+ // ---------------------------------------------------------------------------
160
+ // Initialization
161
+ // ---------------------------------------------------------------------------
162
+ /**
163
+ * Build an LLMClientConfig for a known provider + apiKey, picking a
164
+ * cheap default model if none is specified. Returns null if the
165
+ * provider is unknown and no baseUrl is available.
166
+ */
167
+ function buildConfigForProvider(provider, apiKey, opts = {}) {
168
+ // zai's base URL is resolved via `getZaiBaseUrl()` (reads CONFIG) so
169
+ // the `ZAI_BASE_URL` env override takes effect even when this helper is
170
+ // called with no `baseUrlOverride` (i.e. the env-var fallback tier in
171
+ // initLLMClient).
172
+ const defaultForProvider = provider === 'zai' ? getZaiBaseUrl() : PROVIDER_BASE_URLS[provider] ?? '';
173
+ const baseUrl = (opts.baseUrlOverride ?? defaultForProvider).replace(/\/+$/, '');
174
+ if (!baseUrl)
175
+ return null;
176
+ const model = opts.modelOverride ??
177
+ (opts.primaryModelHint ? deriveCheapModel(provider, opts.primaryModelHint) : null) ??
178
+ exports.CHEAP_MODEL_BY_PROVIDER[provider];
179
+ if (!model)
180
+ return null;
181
+ const apiFormat = opts.apiFormatOverride ?? (provider === 'anthropic' ? 'anthropic' : 'openai');
182
+ return { apiKey, baseUrl, model, apiFormat };
183
+ }
184
+ /**
185
+ * Initialize the LLM client by detecting the provider from OpenClaw's config.
186
+ * Called once from the plugin's `register()` function.
187
+ *
188
+ * 3.3.1 resolution cascade (highest priority first):
189
+ * 1. Plugin config `extraction.llm` override block (provider/apiKey/baseUrl/model)
190
+ * 2. `api.config.providers` / `openclawProviders` — SDK-passed
191
+ * 3. `~/.openclaw/agents/*\/agent/auth-profiles.json` (harvested by caller)
192
+ * 4. Env var fallback (`ZAI_API_KEY`, `OPENAI_API_KEY`, ...)
193
+ * 5. No source → disable extraction cleanly (single log at startup, never
194
+ * per-turn).
195
+ *
196
+ * The `TOTALRECLAW_LLM_MODEL` user-facing override was removed in v1 —
197
+ * `deriveCheapModel(provider)` covers the 99% case and a model-level knob
198
+ * was adding config surface for no tangible win.
199
+ */
200
+ function initLLMClient(options) {
201
+ _logger = options.logger ?? null;
202
+ _initialized = true;
203
+ _cachedConfig = null;
204
+ const { primaryModel, pluginConfig, openclawProviders, authProfileKeys } = options;
205
+ // Check if extraction is explicitly disabled
206
+ const extraction = pluginConfig?.extraction;
207
+ if (extraction?.enabled === false) {
208
+ _logger?.info?.('TotalReclaw extraction LLM: disabled via plugin config (extraction.enabled=false).');
209
+ return;
210
+ }
211
+ const modelOverride = typeof extraction?.model === 'string' ? extraction.model : undefined;
212
+ const llmOverrideRaw = extraction?.llm;
213
+ const llmOverride = typeof llmOverrideRaw === 'object' && llmOverrideRaw !== null ? llmOverrideRaw : undefined;
214
+ // Derive provider name from primary-model ("anthropic/claude-sonnet-4-5" etc)
215
+ let providerFromPrimary = '';
216
+ let modelFromPrimary;
217
+ if (primaryModel) {
218
+ const parts = primaryModel.split('/');
219
+ if (parts.length >= 2) {
220
+ providerFromPrimary = parts[0].toLowerCase();
221
+ modelFromPrimary = parts.slice(1).join('/');
222
+ }
223
+ else {
224
+ modelFromPrimary = primaryModel;
225
+ }
226
+ }
227
+ // ---------------------------------------------------------------------
228
+ // Tier 1 — explicit plugin-config override (highest priority)
229
+ // Accepts any subset of { provider, model, apiKey, baseUrl }. A bare
230
+ // `model` override without a provider+apiKey falls through to lower
231
+ // tiers — matches pre-3.3.1 behaviour.
232
+ // ---------------------------------------------------------------------
233
+ if (llmOverride && typeof llmOverride === 'object') {
234
+ const provider = (llmOverride.provider ?? providerFromPrimary).toLowerCase();
235
+ const apiKey = typeof llmOverride.apiKey === 'string' && llmOverride.apiKey.trim()
236
+ ? llmOverride.apiKey.trim()
237
+ : undefined;
238
+ if (provider && apiKey) {
239
+ const cfg = buildConfigForProvider(provider, apiKey, {
240
+ baseUrlOverride: llmOverride.baseUrl,
241
+ modelOverride: llmOverride.model ?? modelOverride,
242
+ primaryModelHint: modelFromPrimary,
243
+ });
244
+ if (cfg) {
245
+ _cachedConfig = cfg;
246
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${provider}/${cfg.model} (plugin config override)`);
247
+ return;
248
+ }
249
+ }
250
+ }
251
+ // ---------------------------------------------------------------------
252
+ // Tier 2 — SDK-passed openclawProviders. Try the primary-model's provider
253
+ // first, then any other provider that has an apiKey.
254
+ // ---------------------------------------------------------------------
255
+ if (openclawProviders) {
256
+ if (providerFromPrimary) {
257
+ const ocProvider = openclawProviders[providerFromPrimary];
258
+ if (ocProvider?.apiKey) {
259
+ const cfg = buildConfigForProvider(providerFromPrimary, ocProvider.apiKey, {
260
+ baseUrlOverride: ocProvider.baseUrl,
261
+ modelOverride,
262
+ primaryModelHint: modelFromPrimary,
263
+ apiFormatOverride: ocProvider.api === 'anthropic-messages' || providerFromPrimary === 'anthropic'
264
+ ? 'anthropic'
265
+ : 'openai',
266
+ });
267
+ if (cfg) {
268
+ _cachedConfig = cfg;
269
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${providerFromPrimary}/${cfg.model} (OpenClaw provider config)`);
270
+ return;
271
+ }
272
+ }
273
+ }
274
+ for (const [providerName, providerConfig] of Object.entries(openclawProviders)) {
275
+ if (!providerConfig?.apiKey)
276
+ continue;
277
+ const provider = providerName.toLowerCase();
278
+ const firstModelId = providerConfig.models?.[0]?.id;
279
+ const cfg = buildConfigForProvider(provider, providerConfig.apiKey, {
280
+ baseUrlOverride: providerConfig.baseUrl,
281
+ modelOverride,
282
+ primaryModelHint: firstModelId,
283
+ apiFormatOverride: providerConfig.api === 'anthropic-messages' || provider === 'anthropic'
284
+ ? 'anthropic'
285
+ : 'openai',
286
+ });
287
+ if (cfg) {
288
+ _cachedConfig = cfg;
289
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${provider}/${cfg.model} (OpenClaw provider config)`);
290
+ return;
291
+ }
292
+ }
293
+ }
294
+ // ---------------------------------------------------------------------
295
+ // Tier 3 — auth-profiles.json keys harvested by llm-profile-reader.
296
+ // 3.3.1: new tier. Prefer the primary-model's provider, then any other.
297
+ // ---------------------------------------------------------------------
298
+ if (authProfileKeys && authProfileKeys.length > 0) {
299
+ if (providerFromPrimary) {
300
+ const hit = authProfileKeys.find((k) => k.provider === providerFromPrimary);
301
+ if (hit) {
302
+ const cfg = buildConfigForProvider(providerFromPrimary, hit.apiKey, {
303
+ modelOverride,
304
+ primaryModelHint: modelFromPrimary,
305
+ });
306
+ if (cfg) {
307
+ _cachedConfig = cfg;
308
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${providerFromPrimary}/${cfg.model} (auth-profiles.json)`);
309
+ return;
310
+ }
311
+ }
312
+ }
313
+ // Try zai / openai / anthropic first (cheapest+most available), then anything else.
314
+ const priority = ['zai', 'openai', 'anthropic', 'gemini', 'groq', 'deepseek', 'mistral', 'openrouter', 'xai', 'together', 'cerebras'];
315
+ const ordered = [
316
+ ...priority.flatMap((p) => authProfileKeys.filter((k) => k.provider === p)),
317
+ ...authProfileKeys.filter((k) => !priority.includes(k.provider)),
318
+ ];
319
+ for (const entry of ordered) {
320
+ const cfg = buildConfigForProvider(entry.provider, entry.apiKey, {
321
+ modelOverride,
322
+ });
323
+ if (cfg) {
324
+ _cachedConfig = cfg;
325
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${entry.provider}/${cfg.model} (auth-profiles.json)`);
326
+ return;
327
+ }
328
+ }
329
+ }
330
+ // ---------------------------------------------------------------------
331
+ // Tier 4 — env var fallback (for dev/test without OpenClaw config)
332
+ // ---------------------------------------------------------------------
333
+ const envFallback = [
334
+ ['zai', 'zai'],
335
+ ['openai', 'openai'],
336
+ ['anthropic', 'anthropic'],
337
+ ['gemini', 'gemini'],
338
+ ['groq', 'groq'],
339
+ ['deepseek', 'deepseek'],
340
+ ['mistral', 'mistral'],
341
+ ['openrouter', 'openrouter'],
342
+ ['xai', 'xai'],
343
+ ];
344
+ // If primary model hints a specific provider, try it first.
345
+ if (providerFromPrimary) {
346
+ const keyNames = PROVIDER_KEY_NAMES[providerFromPrimary];
347
+ if (keyNames) {
348
+ const apiKey = keyNames.map((n) => config_js_1.EXTRACTION_CONFIG.llmApiKeys[n]).find(Boolean);
349
+ if (apiKey) {
350
+ const cfg = buildConfigForProvider(providerFromPrimary, apiKey, {
351
+ modelOverride,
352
+ primaryModelHint: modelFromPrimary,
353
+ });
354
+ if (cfg) {
355
+ _cachedConfig = cfg;
356
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${providerFromPrimary}/${cfg.model} (env var)`);
357
+ return;
358
+ }
359
+ }
360
+ }
361
+ }
362
+ for (const [provider, keyName] of envFallback) {
363
+ const apiKey = config_js_1.EXTRACTION_CONFIG.llmApiKeys[keyName];
364
+ if (!apiKey)
365
+ continue;
366
+ const cfg = buildConfigForProvider(provider, apiKey, { modelOverride });
367
+ if (cfg) {
368
+ _cachedConfig = cfg;
369
+ _logger?.info?.(`TotalReclaw extraction LLM: resolved ${provider}/${cfg.model} (env var)`);
370
+ return;
371
+ }
372
+ }
373
+ // ---------------------------------------------------------------------
374
+ // No source — extraction disabled. Single startup log, INFO-level.
375
+ // NOT a warn: this is the default state for users who have not set up a
376
+ // provider. Warning per turn is what 3.3.0 did and it was misleading.
377
+ // ---------------------------------------------------------------------
378
+ _logger?.info?.('TotalReclaw extraction LLM: not configured — auto-extraction disabled. ' +
379
+ 'To enable, configure a provider in ~/.openclaw/agents/*\/agent/auth-profiles.json ' +
380
+ 'or set an API key env var (ZAI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, ...).');
381
+ }
382
+ // ---------------------------------------------------------------------------
383
+ // Public API
384
+ // ---------------------------------------------------------------------------
385
+ /**
386
+ * Resolve LLM configuration. Returns the cached config set by `initLLMClient()`,
387
+ * or falls back to the legacy env-var detection if `initLLMClient()` was never called.
388
+ */
389
+ function resolveLLMConfig() {
390
+ if (_initialized) {
391
+ return _cachedConfig;
392
+ }
393
+ // Legacy fallback: if initLLMClient() was never called (e.g. running outside
394
+ // the plugin context), try the config-based approach for backwards compat.
395
+ const zaiKey = config_js_1.EXTRACTION_CONFIG.llmApiKeys.zai;
396
+ const openaiKey = config_js_1.EXTRACTION_CONFIG.llmApiKeys.openai;
397
+ const model = zaiKey ? 'glm-4.5-flash' : 'gpt-4.1-mini';
398
+ if (zaiKey) {
399
+ return {
400
+ apiKey: zaiKey,
401
+ baseUrl: getZaiBaseUrl(),
402
+ model,
403
+ apiFormat: 'openai',
404
+ };
405
+ }
406
+ if (openaiKey) {
407
+ return {
408
+ apiKey: openaiKey,
409
+ baseUrl: 'https://api.openai.com/v1',
410
+ model,
411
+ apiFormat: 'openai',
412
+ };
413
+ }
414
+ return null;
415
+ }
416
+ /**
417
+ * Default retry budget in ms. Configurable via
418
+ * `TOTALRECLAW_LLM_RETRY_BUDGET_MS` env var — read by `config.ts`. Callers
419
+ * can override per-call via `retry.budgetMs`. 60_000ms covers ~8 minutes
420
+ * worth of upstream outages with the 2s→32s schedule.
421
+ *
422
+ * Scanner-isolation note: the env read lives in `config.ts` so this file
423
+ * stays clean of env-harvesting triggers.
424
+ */
425
+ exports.DEFAULT_RETRY_BUDGET_MS = config_js_1.EXTRACTION_CONFIG.llmRetryBudgetMs;
426
+ /**
427
+ * Structured error thrown when the extraction LLM upstream is unreachable
428
+ * after the full retry budget is exhausted. The extraction pipeline
429
+ * recognizes this via `err instanceof LLMUpstreamOutageError` and can
430
+ * choose to:
431
+ * - queue the message batch for retry next turn,
432
+ * - surface a one-time notification to the user, or
433
+ * - simply skip this extraction window silently.
434
+ */
435
+ class LLMUpstreamOutageError extends Error {
436
+ attempts;
437
+ lastStatus;
438
+ constructor(message, attempts, lastStatus) {
439
+ super(message);
440
+ this.name = 'LLMUpstreamOutageError';
441
+ this.attempts = attempts;
442
+ this.lastStatus = lastStatus;
443
+ }
444
+ }
445
+ exports.LLMUpstreamOutageError = LLMUpstreamOutageError;
446
+ /**
447
+ * Detect the "Insufficient balance" error shape from zai. Matches both
448
+ * the exact production wording ("Insufficient balance or no resource
449
+ * package. Please recharge.") and the short "no resource package" variant
450
+ * we've seen in some historical responses.
451
+ */
452
+ function isZaiBalanceError(errorMessage) {
453
+ const m = errorMessage.toLowerCase();
454
+ return m.includes('insufficient balance') || m.includes('no resource package');
455
+ }
456
+ /**
457
+ * Identify the "other" zai endpoint when the current one returns a balance
458
+ * error — CODING ↔ STANDARD. Returns `null` when the URL is neither of
459
+ * the two zai endpoints we know about (e.g. a self-hosted proxy), which
460
+ * means the fallback logic stays put.
461
+ */
462
+ function zaiFallbackBaseUrl(currentBaseUrl) {
463
+ const normalized = currentBaseUrl.replace(/\/+$/, '');
464
+ if (normalized === exports.ZAI_CODING_BASE_URL)
465
+ return exports.ZAI_STANDARD_BASE_URL;
466
+ if (normalized === exports.ZAI_STANDARD_BASE_URL)
467
+ return exports.ZAI_CODING_BASE_URL;
468
+ return null;
469
+ }
470
+ /**
471
+ * Call the LLM chat completion endpoint.
472
+ *
473
+ * Supports both OpenAI-compatible format and Anthropic Messages API,
474
+ * determined by `config.apiFormat`.
475
+ *
476
+ * 3.3.1-rc.3 — lifts the retry budget 5 attempts × (2s/4s/8s/16s/32s), total
477
+ * ~62s. Configurable via `TOTALRECLAW_LLM_RETRY_BUDGET_MS`. Adds zai
478
+ * "Insufficient balance" auto-fallback: when a zai 429 carries the balance
479
+ * error body AND we're on one of the two known zai endpoints, we flip to
480
+ * the OTHER endpoint and retry ONCE (accounted for separately from the
481
+ * normal retry loop). On exhaustion, throws `LLMUpstreamOutageError`.
482
+ *
483
+ * Non-retryable errors (4xx other than 429, network refused, JSON parse)
484
+ * fail fast on the first attempt.
485
+ *
486
+ * @returns The assistant's response content, or null on failure.
487
+ */
488
+ async function chatCompletion(config, messages, options) {
489
+ const maxTokens = options?.maxTokens ?? 2048;
490
+ const temperature = options?.temperature ?? 0; // Deterministic output for dedup (same input → same text → same content fingerprint)
491
+ const attempts = Math.max(1, options?.retry?.attempts ?? 5);
492
+ const baseDelayMs = Math.max(100, options?.retry?.baseDelayMs ?? 2000);
493
+ const budgetMs = Math.max(100, options?.retry?.budgetMs ?? exports.DEFAULT_RETRY_BUDGET_MS);
494
+ const timeoutMs = options?.timeoutMs ?? 30_000;
495
+ const logger = options?.logger;
496
+ // We mutate `activeConfig.baseUrl` in the zai fallback branch so the
497
+ // retried call hits the other endpoint. Shallow-clone so the caller's
498
+ // config object stays untouched.
499
+ const activeConfig = { ...config };
500
+ // One-shot flag: we only auto-fallback zai once per chatCompletion call
501
+ // to prevent ping-pong between the two endpoints if both reject.
502
+ let zaiFallbackAttempted = false;
503
+ const callOnce = () => activeConfig.apiFormat === 'anthropic'
504
+ ? chatCompletionAnthropic(activeConfig, messages, maxTokens, temperature, timeoutMs)
505
+ : chatCompletionOpenAI(activeConfig, messages, maxTokens, temperature, timeoutMs);
506
+ let lastErr;
507
+ let cumulativeDelayMs = 0;
508
+ let lastStatus;
509
+ for (let attempt = 1; attempt <= attempts; attempt++) {
510
+ try {
511
+ return await callOnce();
512
+ }
513
+ catch (err) {
514
+ lastErr = err;
515
+ const msg = err instanceof Error ? err.message : String(err);
516
+ lastStatus = parseHttpStatus(msg) ?? lastStatus;
517
+ // ── zai "Insufficient balance" auto-fallback ──
518
+ // Fires BEFORE the normal retry accounting. If the error is a zai
519
+ // balance-shaped 429, flip the baseUrl once and immediately retry —
520
+ // no backoff, no decrement of the attempt count. Keeps the total
521
+ // attempt budget reserved for genuine outages.
522
+ if (!zaiFallbackAttempted && /\b429\b/.test(msg) && isZaiBalanceError(msg)) {
523
+ const fallback = zaiFallbackBaseUrl(activeConfig.baseUrl);
524
+ if (fallback) {
525
+ zaiFallbackAttempted = true;
526
+ const oldUrl = activeConfig.baseUrl;
527
+ activeConfig.baseUrl = fallback;
528
+ logger?.info?.(`chatCompletion: zai endpoint auto-fallback: ${oldUrl} → ${fallback} due to "Insufficient balance" response`);
529
+ // Retry immediately — do NOT decrement attempts counter further;
530
+ // this "extra" attempt is the fallback freebie.
531
+ attempt--;
532
+ continue;
533
+ }
534
+ }
535
+ const retryable = isRetryable(msg);
536
+ const isFinalAttempt = attempt >= attempts;
537
+ if (!retryable || isFinalAttempt) {
538
+ // Fail-fast OR last attempt — rethrow.
539
+ if (attempt > 1 || !retryable) {
540
+ if (retryable) {
541
+ logger?.warn?.(`chatCompletion: giving up after ${attempt} attempts: ${msg.slice(0, 200)}`);
542
+ }
543
+ // Structured outage error when the retryable error budget is
544
+ // fully exhausted — lets downstream recognize vs bail silently.
545
+ if (retryable) {
546
+ throw new LLMUpstreamOutageError(`LLM upstream outage after ${attempt} attempts: ${msg.slice(0, 200)}`, attempt, lastStatus);
547
+ }
548
+ }
549
+ throw err;
550
+ }
551
+ // Compute next delay, but respect the cumulative retry-budget cap.
552
+ const delayMs = baseDelayMs * Math.pow(2, attempt - 1);
553
+ if (cumulativeDelayMs + delayMs > budgetMs) {
554
+ logger?.warn?.(`chatCompletion: retry budget exhausted (${cumulativeDelayMs}ms used + ${delayMs}ms next > ${budgetMs}ms budget); surfacing outage after ${attempt} attempts: ${msg.slice(0, 160)}`);
555
+ throw new LLMUpstreamOutageError(`LLM upstream outage (budget ${budgetMs}ms exhausted after ${attempt} attempts): ${msg.slice(0, 200)}`, attempt, lastStatus);
556
+ }
557
+ cumulativeDelayMs += delayMs;
558
+ // Log only the FIRST retry at INFO to avoid spamming during long
559
+ // outages; subsequent retries are DEBUG (debounced per outage).
560
+ if (attempt === 1) {
561
+ logger?.info?.(`chatCompletion: retrying after transient failure (attempt ${attempt}/${attempts}, wait ${delayMs}ms): ${msg.slice(0, 160)}`);
562
+ }
563
+ else {
564
+ logger?.debug?.(`chatCompletion: retry attempt ${attempt}/${attempts} (wait ${delayMs}ms): ${msg.slice(0, 160)}`);
565
+ }
566
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
567
+ }
568
+ }
569
+ // Defensive — should never reach here since the loop always throws on the
570
+ // final attempt when it fails. Keeps TS happy.
571
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
572
+ }
573
+ /**
574
+ * Parse the HTTP status code from an error message of the form
575
+ * `"LLM API 429: rate limit"` or `"Anthropic API 503: ..."`. Returns
576
+ * `undefined` when the message doesn't follow that shape (e.g. network
577
+ * refused). Used by `LLMUpstreamOutageError.lastStatus` for downstream
578
+ * classification.
579
+ */
580
+ function parseHttpStatus(errorMessage) {
581
+ const m = errorMessage.match(/\b(\d{3})\b/);
582
+ if (!m)
583
+ return undefined;
584
+ const code = parseInt(m[1], 10);
585
+ return code >= 100 && code < 600 ? code : undefined;
586
+ }
587
+ /**
588
+ * Which LLM-call errors are worth retrying. Exported for testability.
589
+ *
590
+ * Retryable:
591
+ * - HTTP 429 (rate limit)
592
+ * - HTTP 503 / 502 / 504 (gateway transients)
593
+ * - AbortError / "aborted due to timeout" / "TimeoutError"
594
+ *
595
+ * NOT retryable:
596
+ * - HTTP 400 / 401 / 403 / 404 (auth / request errors — no point retrying)
597
+ * - JSON parse errors
598
+ * - DNS / connection refused (usually misconfig, not transient)
599
+ */
600
+ function isRetryable(errorMessage) {
601
+ const m = errorMessage.toLowerCase();
602
+ // Rate limit
603
+ if (/\b429\b/.test(errorMessage) || m.includes('rate limit'))
604
+ return true;
605
+ // Transient gateway errors
606
+ if (/\b50(2|3|4)\b/.test(errorMessage))
607
+ return true;
608
+ // Timeouts
609
+ if (m.includes('timeout') ||
610
+ m.includes('aborterror') ||
611
+ m.includes('was aborted') ||
612
+ m.includes('operation was aborted')) {
613
+ return true;
614
+ }
615
+ return false;
616
+ }
617
+ // ---------------------------------------------------------------------------
618
+ // OpenAI-compatible chat completion
619
+ // ---------------------------------------------------------------------------
620
+ async function chatCompletionOpenAI(config, messages, maxTokens, temperature, timeoutMs) {
621
+ const url = `${config.baseUrl}/chat/completions`;
622
+ const body = {
623
+ model: config.model,
624
+ messages,
625
+ temperature,
626
+ max_completion_tokens: maxTokens,
627
+ };
628
+ try {
629
+ const res = await fetch(url, {
630
+ method: 'POST',
631
+ headers: {
632
+ 'Content-Type': 'application/json',
633
+ Authorization: `Bearer ${config.apiKey}`,
634
+ },
635
+ body: JSON.stringify(body),
636
+ signal: AbortSignal.timeout(timeoutMs),
637
+ });
638
+ if (!res.ok) {
639
+ const text = await res.text().catch(() => '');
640
+ throw new Error(`LLM API ${res.status}: ${text.slice(0, 200)}`);
641
+ }
642
+ const json = (await res.json());
643
+ return json.choices?.[0]?.message?.content ?? null;
644
+ }
645
+ catch (err) {
646
+ const msg = err instanceof Error ? err.message : String(err);
647
+ throw new Error(`LLM call failed: ${msg}`);
648
+ }
649
+ }
650
+ // ---------------------------------------------------------------------------
651
+ // Anthropic Messages API chat completion
652
+ // ---------------------------------------------------------------------------
653
+ async function chatCompletionAnthropic(config, messages, maxTokens, temperature, timeoutMs) {
654
+ const url = `${config.baseUrl}/messages`;
655
+ // Anthropic requires system prompt to be a top-level param, not in messages
656
+ let system;
657
+ const apiMessages = [];
658
+ for (const msg of messages) {
659
+ if (msg.role === 'system') {
660
+ system = msg.content;
661
+ }
662
+ else {
663
+ apiMessages.push({ role: msg.role, content: msg.content });
664
+ }
665
+ }
666
+ const body = {
667
+ model: config.model,
668
+ max_tokens: maxTokens,
669
+ temperature,
670
+ messages: apiMessages,
671
+ };
672
+ if (system) {
673
+ body.system = system;
674
+ }
675
+ try {
676
+ const res = await fetch(url, {
677
+ method: 'POST',
678
+ headers: {
679
+ 'Content-Type': 'application/json',
680
+ 'x-api-key': config.apiKey,
681
+ 'anthropic-version': '2023-06-01',
682
+ },
683
+ body: JSON.stringify(body),
684
+ signal: AbortSignal.timeout(timeoutMs),
685
+ });
686
+ if (!res.ok) {
687
+ const text = await res.text().catch(() => '');
688
+ throw new Error(`Anthropic API ${res.status}: ${text.slice(0, 200)}`);
689
+ }
690
+ const json = (await res.json());
691
+ const textBlock = json.content?.find((block) => block.type === 'text');
692
+ return textBlock?.text ?? null;
693
+ }
694
+ catch (err) {
695
+ const msg = err instanceof Error ? err.message : String(err);
696
+ throw new Error(`LLM call failed: ${msg}`);
697
+ }
698
+ }
699
+ // Embeddings are NOT re-exported here — mcp-server has its own embedding
700
+ // pipeline at `../subgraph/embedding.js` (used by the on-chain submit
701
+ // path, not the extraction LLM). The plugin's llm-client.ts re-exports
702
+ // `generateEmbedding` etc. so plugin callers have one import surface for
703
+ // "all LLM things"; mcp-server keeps the two surfaces separate.
704
+ //# sourceMappingURL=llm-client.js.map