@remnic/core 10.0.150 → 10.0.152
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-admin-ops-surface.js +10 -10
- package/dist/access-cli.js +10 -10
- package/dist/access-extraction-force-flush-preempt.js +10 -10
- package/dist/access-extraction-force-flush.js +10 -10
- package/dist/access-http-briefing.js +10 -10
- package/dist/access-http-query.js +10 -10
- package/dist/access-http.js +10 -10
- package/dist/access-identity-continuity-surface.js +10 -10
- package/dist/access-lcm-surface.js +10 -10
- package/dist/access-mcp.js +10 -10
- package/dist/access-observe-write-surface.js +10 -10
- package/dist/access-operations-batch.js +10 -10
- package/dist/access-operations.js +10 -10
- package/dist/access-recall-concurrency.js +10 -10
- package/dist/access-recall-response.js +10 -10
- package/dist/access-recall-surface.js +10 -10
- package/dist/access-service.js +10 -10
- package/dist/calibration.js +3 -3
- package/dist/{chunk-2NGTY22Z.js → chunk-5JZ5CYTR.js} +6 -4
- package/dist/chunk-5JZ5CYTR.js.map +1 -0
- package/dist/{chunk-XYW5HHFS.js → chunk-5Y3UVK6S.js} +59 -22
- package/dist/chunk-5Y3UVK6S.js.map +1 -0
- package/dist/{chunk-QEDLJDHP.js → chunk-AGMMHT4P.js} +3 -1
- package/dist/chunk-AGMMHT4P.js.map +1 -0
- package/dist/{chunk-LD7I5AZW.js → chunk-B57CAZPI.js} +2 -2
- package/dist/{chunk-WUQH7BDU.js → chunk-BDKLKX43.js} +9 -2
- package/dist/{chunk-WUQH7BDU.js.map → chunk-BDKLKX43.js.map} +1 -1
- package/dist/{chunk-65B3XGQR.js → chunk-C4AAKTP5.js} +2 -2
- package/dist/{chunk-3JZZ6WTA.js → chunk-E2JONYZR.js} +8 -8
- package/dist/{chunk-7P72BY4F.js → chunk-R4O4JDTS.js} +2 -2
- package/dist/{chunk-CAFF45W4.js → chunk-RAOM5WU2.js} +1 -1
- package/dist/{chunk-3YZYD5XJ.js → chunk-SBG5RR6X.js} +3 -3
- package/dist/{chunk-OFFT2B5R.js → chunk-WE6MSFYM.js} +2 -2
- package/dist/cli.js +10 -10
- package/dist/compounding/engine.js +1 -1
- package/dist/explicit-capture.js +10 -10
- package/dist/extraction.js +4 -4
- package/dist/harmonic-retrieval.d.ts +3 -0
- package/dist/harmonic-retrieval.d.ts.map +1 -1
- package/dist/harmonic-retrieval.js +3 -1
- package/dist/index.js +10 -10
- package/dist/local-llm-helpers.d.ts +9 -0
- package/dist/local-llm-helpers.d.ts.map +1 -1
- package/dist/local-llm-helpers.js +3 -1
- package/dist/local-llm-rate-limit.d.ts.map +1 -1
- package/dist/local-llm-rate-limit.js +1 -1
- package/dist/local-llm.d.ts.map +1 -1
- package/dist/local-llm.js +3 -3
- package/dist/orchestration/backlog-scheduler.js +11 -11
- package/dist/orchestration/buffer-drain-runner.js +11 -11
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/orchestrator.js +10 -10
- package/dist/recall-navigation.js +10 -10
- package/dist/summarizer.js +4 -4
- package/dist/support-passport/index.js +4 -4
- package/package.json +2 -2
- package/src/harmonic-retrieval-index.test.ts +183 -1
- package/src/harmonic-retrieval.ts +96 -25
- package/src/local-llm-helpers.ts +19 -0
- package/src/local-llm-rate-limit.test.ts +7 -0
- package/src/local-llm-rate-limit.ts +9 -0
- package/src/local-llm.ts +5 -6
- package/dist/chunk-2NGTY22Z.js.map +0 -1
- package/dist/chunk-QEDLJDHP.js.map +0 -1
- package/dist/chunk-XYW5HHFS.js.map +0 -1
- /package/dist/{chunk-LD7I5AZW.js.map → chunk-B57CAZPI.js.map} +0 -0
- /package/dist/{chunk-65B3XGQR.js.map → chunk-C4AAKTP5.js.map} +0 -0
- /package/dist/{chunk-3JZZ6WTA.js.map → chunk-E2JONYZR.js.map} +0 -0
- /package/dist/{chunk-7P72BY4F.js.map → chunk-R4O4JDTS.js.map} +0 -0
- /package/dist/{chunk-CAFF45W4.js.map → chunk-RAOM5WU2.js.map} +0 -0
- /package/dist/{chunk-3YZYD5XJ.js.map → chunk-SBG5RR6X.js.map} +0 -0
- /package/dist/{chunk-OFFT2B5R.js.map → chunk-WE6MSFYM.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport { isUnsupportedJsonSchemaError } from \"./fallback-llm-codex-subscription.js\";\nimport { estimateTokenCount } from \"./token-estimate.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\";\nimport { ChatTransport } from \"./local-llm-transport.js\";\nimport { LocalLlmRateLimitSession, resolveRateLimitSettings } from \"./local-llm-rate-limit.js\";\nimport {\n extractNonRecoverableBackendReason,\n extractNonRecoverableBackendReasonFromErrorText,\n isAbortError,\n probeFetch,\n resolveUnavailableVerdict,\n type ProbeFetchResult,\n normalizeBackendTripReason,\n waitForRetryBackoff,\n combineClientAbortSignals,\n SingleFlightProbe,\n type LocalLlmChatCompletionOptions,\n type LocalLlmChatCompletionResult,\n buildLocalLlmRoutingHeaders,\n} from \"./local-llm-helpers.js\";\nimport { NativeSchemaGate, type LocalLlmChatRequestBody } from \"./local-llm-native-schema.js\";\nimport {\n isObjectRecord,\n orderedLocalServers,\n type LocalLlmType,\n} from \"./local-llm-servers.js\";\n\nexport type { LocalLlmType } from \"./local-llm-servers.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 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 * 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 \"correction-classify\",\n]);\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\n// LocalLlmChatCompletionOptions and LocalLlmChatCompletionResult live in\n// local-llm-helpers.ts so this file stays under its size ceiling (#1995).\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\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\ntype LocalLlmBackendState = {\n untilMs: number;\n reason: string;\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 class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private readonly availabilityProbe = new SingleFlightProbe();\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 readonly nativeSchemaGate = new NativeSchemaGate(() => this.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 private readonly chatTransport = new ChatTransport();\n /** Orchestrator-owned stop signal: aborts every in-flight and queued\n * request (and their retry backoffs) the moment teardown begins. */\n private readonly shutdownSignal: AbortSignal | undefined;\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry, shutdownSignal?: AbortSignal) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n this.shutdownSignal = shutdownSignal;\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\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 = 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\n /**\n * Fetch with timeout for health checks. Body lives in the sibling helper so\n * this file stays under its size ceiling (issue #1995).\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ): Promise<ProbeFetchResult> {\n return await probeFetch(url, {\n timeoutMs,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n signal,\n });\n }\n\n private async probeLmStudioNativeModels(\n probeBaseUrl: string,\n signal?: AbortSignal,\n ): Promise<{ matched: boolean; unauthorized: boolean }> {\n let unauthorized = false;\n for (const endpoint of [\"/api/v1/models\", \"/api/v0/models\"]) {\n if (signal?.aborted) return { matched: false, unauthorized };\n const probe = await this.fetchWithTimeout(`${probeBaseUrl}${endpoint}`, 2000, undefined, signal);\n if (signal?.aborted) return { matched: false, unauthorized };\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(signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted) return false;\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 return await this.availabilityProbe.run((probeSignal) => this.probeAvailability(probeSignal), signal);\n }\n\n private async probeAvailability(signal?: AbortSignal): Promise<boolean> {\n const now = Date.now();\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 // A probe that TIMED OUT says the event loop was busy, not that the backend\n // is down (issue #2210). Tracked separately so a loaded daemon cannot cache\n // itself into a blackout.\n let sawAbortedProbe = false;\n // Several server shapes share a probe URL (LiteLLM and Ollama both use\n // `/`); fetch each URL once per pass.\n const probed = new Map<string, ProbeFetchResult>();\n const probeOnce = async (url: string): Promise<ProbeFetchResult> => {\n const cached = probed.get(url);\n if (cached) return cached;\n const result = await this.fetchWithTimeout(url, 2000, undefined, signal);\n probed.set(url, result);\n return result;\n };\n\n // Try to detect which server type is running\n if (signal?.aborted) return false;\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 probeOnce(healthUrl);\n if (result.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\n if (result.ok && serverConfig.detectFn(result.data)) {\n if (serverConfig.type === \"mlx\") {\n const lmStudioProbe = await this.probeLmStudioNativeModels(probeBaseUrl, signal);\n if (signal?.aborted) return false;\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`, 2000, undefined, signal);\n if (propsProbe.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\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, 2000, undefined, signal);\n if (modelsProbe.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\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 = Boolean(this.config.localLlmApiKey) && 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 if (signal?.aborted) return false;\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${probeBaseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl, 2000, undefined, signal);\n if (result.aborted) sawAbortedProbe = true;\n if (signal?.aborted) return false;\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 const wasAvailable = this.isAvailable;\n this.detectedType = null;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${configuredBaseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n const verdict = resolveUnavailableVerdict({\n baseUrl: configuredBaseUrl,\n sawAbortedProbe,\n wasAvailable,\n });\n this.isAvailable = verdict.cacheVerdict ? false : null;\n this.lastHealthCheck = verdict.cacheVerdict ? now : 0;\n if (verdict.warning) log.warn(verdict.warning);\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 if (combineClientAbortSignals(next.options.signal, this.shutdownSignal)?.aborted) {\n next.resolve(null);\n return;\n }\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: ${next.options.redactProviderErrors ? \"provider error details redacted\" : 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 signal = combineClientAbortSignals(options.signal, this.shutdownSignal);\n if (signal?.aborted) return null;\n const isAvailable = await this.checkAvailability(signal);\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 requestModel = options.model ?? this.config.localLlmModel;\n const requestBody: LocalLlmChatRequestBody = {\n model: requestModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n stream: false,\n };\n this.nativeSchemaGate.attach(requestBody, options, requestModel);\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 let 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 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 // COS-447: rate-limit responses (429/503/408, LiteLLM cooldown) get\n // their own retry budget with exponential full-jitter backoff, and a\n // process-wide semaphore caps concurrent HTTP attempts across clients.\n // Waits are bounded by the request timeout so a short caller budget\n // (e.g. rerankTimeoutMs) is never stretched by a long cooldown.\n const rateLimit = new LocalLlmRateLimitSession(chatUrl, resolveRateLimitSettings(this.config),\n (queueMeta?.priority ?? options.priority) === \"recall-critical\", effectiveTimeoutMs);\n let lastRateLimitDelayMs: number | null = null;\n let response: Response | null = null, responseBody = \"\";\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n response = null;\n responseBody = \"\";\n // Wait out the shared endpoint backoff, then take a concurrency slot.\n const gate = await rateLimit.beforeAttempt(signal);\n if (gate.kind === \"skip\") {\n log.warn(gate.reason === \"queue\"\n ? `local LLM concurrency queue exceeded the ${effectiveTimeoutMs}ms request budget; skipping request (op=${operation})`\n : `local LLM rate-limit backoff active (${gate.remainingMs}ms remaining); skipping request (op=${operation})`);\n if (options.failureDiag)\n options.failureDiag.lastError = Object.assign(new Error(\"local LLM rate limited\"), { status: 429 });\n return null;\n }\n if (gate.kind === \"aborted\") return null;\n const attemptAbort = new AbortController();\n const onCallerAbort = (): void => {\n attemptAbort.abort(signal?.reason);\n };\n if (signal) {\n if (signal.aborted) {\n onCallerAbort();\n } else {\n signal.addEventListener(\"abort\", onCallerAbort, { once: true });\n }\n }\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n const routingHeaders = buildLocalLlmRoutingHeaders(operation, options.priority);\n const postAttempt = (bodyJson: string): Promise<Response> => this.chatTransport.post({\n url: chatUrl,\n headers: this.buildRequestHeaders(routingHeaders),\n body: bodyJson,\n signal: attemptAbort.signal,\n budgetMs: this.config.localLlmTimeoutMs,\n });\n try {\n response = await postAttempt(requestBodyJson);\n responseBody = await response.text();\n if (\n response.status === 400 &&\n requestBody.response_format &&\n isUnsupportedJsonSchemaError(`400 ${responseBody}`)\n ) {\n this.nativeSchemaGate.rememberRejection(requestModel);\n // Match gateway degradation without extending this attempt's deadline.\n delete requestBody.response_format;\n requestBodyJson = JSON.stringify(requestBody);\n log.debug(\"local LLM rejected native JSON schema; retrying without it\");\n response = null;\n response = await postAttempt(requestBodyJson);\n responseBody = await response.text();\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n if (signal?.aborted) {\n response = null;\n lastAbortError = error;\n break;\n }\n if (response && !response.ok) {\n log.debug(`local LLM failed to read ${response.status} response body: ${options.redactProviderErrors ? \"details redacted\" : error.message}`);\n } else {\n response = null;\n if (!isAbortError(err)) throw err;\n lastAbortError = error;\n if (attempt >= maxAttempts) break;\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 if (!(await waitForRetryBackoff(backoffMs, signal))) return null;\n continue;\n }\n } finally {\n clearTimeout(attemptTimeout);\n signal?.removeEventListener(\"abort\", onCallerAbort);\n gate.release();\n }\n\n if (response.ok) {\n rateLimit.onSuccess();\n break;\n }\n if (response.status >= 500 && attempt < maxAttempts) {\n const nonRecoverableReason = extractNonRecoverableBackendReasonFromErrorText(responseBody);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n }\n const decision = rateLimit.onResponse(response.status, response.headers?.get(\"retry-after\"), responseBody);\n lastRateLimitDelayMs = decision.kind === \"not-rate-limited\" ? null : decision.delayMs;\n if (decision.kind === \"give-up\") break;\n if (decision.kind === \"retry\") {\n log.warn(`local LLM rate limited: ${response.status}; backing off ${decision.delayMs}ms before retry ${decision.retry}/${rateLimit.settings.retryCount} (op=${operation}, serverHintMs=${decision.hintMs ?? \"none\"}, consecutive=${decision.consecutive})`);\n attempt -= 1; // own retry budget; the loop top waits out the backoff\n continue;\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 if (!(await waitForRetryBackoff(backoffMs, signal))) return null;\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\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}${queueMeta ? ` waitMs=${startedAtMs - queueMeta.enqueuedAtMs}` : \"\"}`,\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 if (lastRateLimitDelayMs !== null)\n log.warn(`local LLM rate-limit retries exhausted: op=${operation} retries=${rateLimit.retryCount} nextBackoffMs=${lastRateLimitDelayMs}`);\n let reason = \"\";\n try {\n const parsed = JSON.parse(responseBody) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n if (!options.redactProviderErrors) log.debug(`local LLM error body: ${responseBody.slice(0, 500)}`);\n }\n log.warn(\n `local LLM request failed: ${response.status}${options.redactProviderErrors ? \"\" : ` ${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 extractNonRecoverableBackendReason(reason) ??\n extractNonRecoverableBackendReasonFromErrorText(responseBody);\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 if (options.failureDiag)\n options.failureDiag.lastError = Object.assign(new Error(\"local LLM http failure\"), {\n status: response.status,\n });\n return null;\n }\n this.consecutive400s = 0;\n this.nativeSchemaGate.recordSuccess(requestBody, requestModel);\n\n // SAFETY: OpenAI-compatible wire format; every field is optional and read defensively below.\n const data = JSON.parse(responseBody) as {\n choices?: Array<{ message?: { content?: string; reasoning_content?: string }; finish_reason?: string }>;\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 if (options.failureDiag) options.failureDiag.finishReason = data.choices?.[0]?.finish_reason;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content.${options.redactProviderErrors ? \"\" : ` 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 (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=${options.redactProviderErrors ? \"provider error details redacted\" : errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${options.redactProviderErrors ? \"provider error details redacted\" : errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = 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 const signal = combineClientAbortSignals(options.signal, this.shutdownSignal);\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n let settled = false;\n let onAbort: (() => void) | undefined;\n const finish = (value: LocalLlmChatCompletionResult | null): void => {\n if (settled) return;\n settled = true;\n if (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n resolve(value);\n };\n const queued: LocalLlmQueuedRequest = {\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve: finish,\n };\n onAbort = () => {\n const queue = this.requestQueues[priority];\n const index = queue.indexOf(queued);\n if (index >= 0) queue.splice(index, 1);\n finish(null);\n };\n this.requestQueues[priority].push(queued);\n if (signal?.aborted) onAbort();\n else if (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n /**\n * Estimate tokens when local LLM does not return usage stats.\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptTokens = messages.reduce((sum, message) => sum + estimateTokenCount(message.content), 0);\n const completionTokens = estimateTokenCount(response);\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 unavailable and fallback disabled`);\n }\n }\n\n // Use fallback (cloud provider)\n return fallbackOperation();\n }\n}\n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A,iBACpB,OAAQ,QAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AACzE,aAAK,mBAAmB;AAAA,MAC1B,CAAC;AAAA,IACH;AAEA,WAAO,MAAM,KAAK,yBAAyB,UAAU,OAAO;AAAA,EAC9D;AAAA;AAAA;AAAA;AAAA,EAIQ,eACN,UACA,UACyE;AACzE,UAAM,eAAe,SAAS,OAAO,CAAC,KAAK,YAAY,MAAM,mBAAmB,QAAQ,OAAO,GAAG,CAAC;AACnG,UAAM,mBAAmB,mBAAmB,QAAQ;AAEpD,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,aAAa,eAAe;AAAA,IAC9B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aACJ,gBACA,mBACA,eACY;AAEZ,QAAI,4BAA4B,KAAK,MAAM,EAAE,UAAU;AACrD,YAAM,cAAc,MAAM,eAAe;AACzC,UAAI,gBAAgB,MAAM;AACxB,YAAI,MAAM,GAAG,aAAa,kBAAkB;AAC5C,eAAO;AAAA,MACT;AAGA,UAAI,KAAK,OAAO,kBAAkB;AAChC,YAAI,KAAK,GAAG,aAAa,gDAAgD;AAAA,MAC3E,OAAO;AACL,cAAM,IAAI,MAAM,GAAG,aAAa,+CAA+C;AAAA,MACjF;AAAA,IACF;AAGA,WAAO,kBAAkB;AAAA,EAC3B;AACF;","names":["backoffMs","promptChars"]}
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
isValidityExpiredNow
|
|
20
20
|
} from "./chunk-6CIAGZ6X.js";
|
|
21
21
|
import {
|
|
22
|
-
|
|
22
|
+
normalizeRecallTokenSet,
|
|
23
23
|
normalizeRecallTokens
|
|
24
24
|
} from "./chunk-YCVB7X56.js";
|
|
25
25
|
import {
|
|
@@ -236,53 +236,88 @@ function anchorMatchesProjectedNode(anchor, nodeRef, node, allowLegacyAttributio
|
|
|
236
236
|
const anchorSourceMemoryIds = anchor.sourceMemoryIdsByNodeRef[nodeRef] ?? [];
|
|
237
237
|
return anchorSourceMemoryIds.some((sourceMemoryId) => activeSourceMemoryIds.includes(sourceMemoryId));
|
|
238
238
|
}
|
|
239
|
-
function
|
|
239
|
+
function tokenOverlap(queryTokens, fieldTokens) {
|
|
240
|
+
let matches = 0;
|
|
241
|
+
for (const token of queryTokens) {
|
|
242
|
+
if (fieldTokens.has(token)) matches += 1;
|
|
243
|
+
}
|
|
244
|
+
return matches;
|
|
245
|
+
}
|
|
246
|
+
var harmonicSearchIndexStats = { builds: 0 };
|
|
247
|
+
var harmonicSearchIndexes = /* @__PURE__ */ new WeakMap();
|
|
248
|
+
function getHarmonicSearchIndex(graph) {
|
|
249
|
+
const cached = harmonicSearchIndexes.get(graph);
|
|
250
|
+
if (cached) return cached;
|
|
251
|
+
harmonicSearchIndexStats.builds += 1;
|
|
252
|
+
const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));
|
|
253
|
+
const nodeTokens = graph.nodes.map((node) => ({
|
|
254
|
+
title: normalizeRecallTokenSet(node.title ?? ""),
|
|
255
|
+
summary: normalizeRecallTokenSet(node.summary ?? ""),
|
|
256
|
+
tags: normalizeRecallTokenSet(node.tags?.join(" ") ?? ""),
|
|
257
|
+
entities: normalizeRecallTokenSet(node.entityRefs?.join(" ") ?? ""),
|
|
258
|
+
kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`)
|
|
259
|
+
}));
|
|
260
|
+
const anchorTokens = graph.anchors.map((anchor) => {
|
|
261
|
+
const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));
|
|
262
|
+
const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];
|
|
263
|
+
return {
|
|
264
|
+
value: normalizeRecallTokenSet(anchor.anchorValue ?? ""),
|
|
265
|
+
normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? ""),
|
|
266
|
+
type: normalizeRecallTokenSet(anchor.anchorType),
|
|
267
|
+
eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(" "))
|
|
268
|
+
};
|
|
269
|
+
});
|
|
270
|
+
const index = { nodesById, nodeTokens, anchorTokens };
|
|
271
|
+
harmonicSearchIndexes.set(graph, index);
|
|
272
|
+
return index;
|
|
273
|
+
}
|
|
274
|
+
function scoreNode(tokens, queryTokens) {
|
|
240
275
|
const matchedFields = [];
|
|
241
276
|
let score = 0;
|
|
242
|
-
const titleMatches =
|
|
277
|
+
const titleMatches = tokenOverlap(queryTokens, tokens.title);
|
|
243
278
|
if (titleMatches > 0) {
|
|
244
279
|
score += titleMatches * 3;
|
|
245
280
|
matchedFields.push("title");
|
|
246
281
|
}
|
|
247
|
-
const summaryMatches =
|
|
282
|
+
const summaryMatches = tokenOverlap(queryTokens, tokens.summary);
|
|
248
283
|
if (summaryMatches > 0) {
|
|
249
284
|
score += summaryMatches * 3;
|
|
250
285
|
matchedFields.push("summary");
|
|
251
286
|
}
|
|
252
|
-
const tagMatches =
|
|
287
|
+
const tagMatches = tokenOverlap(queryTokens, tokens.tags);
|
|
253
288
|
if (tagMatches > 0) {
|
|
254
289
|
score += tagMatches * 2;
|
|
255
290
|
matchedFields.push("tags");
|
|
256
291
|
}
|
|
257
|
-
const entityMatches =
|
|
292
|
+
const entityMatches = tokenOverlap(queryTokens, tokens.entities);
|
|
258
293
|
if (entityMatches > 0) {
|
|
259
294
|
score += entityMatches * 2;
|
|
260
295
|
matchedFields.push("entityRefs");
|
|
261
296
|
}
|
|
262
|
-
const kindMatches =
|
|
297
|
+
const kindMatches = tokenOverlap(queryTokens, tokens.kind);
|
|
263
298
|
if (kindMatches > 0) {
|
|
264
299
|
score += kindMatches;
|
|
265
300
|
matchedFields.push("kind");
|
|
266
301
|
}
|
|
267
302
|
return { score, matchedFields };
|
|
268
303
|
}
|
|
269
|
-
function scoreAnchor(
|
|
304
|
+
function scoreAnchor(tokens, queryTokens) {
|
|
270
305
|
const matchedFields = [];
|
|
271
306
|
let score = 0;
|
|
272
|
-
const valueMatches =
|
|
273
|
-
const normalizedMatches =
|
|
307
|
+
const valueMatches = tokenOverlap(queryTokens, tokens.value);
|
|
308
|
+
const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);
|
|
274
309
|
const cueMatches = Math.max(valueMatches, normalizedMatches);
|
|
275
310
|
if (cueMatches > 0) {
|
|
276
311
|
score += cueMatches * 4;
|
|
277
312
|
if (valueMatches > 0) matchedFields.push("anchorValue");
|
|
278
313
|
if (normalizedMatches > 0) matchedFields.push("anchor");
|
|
279
314
|
}
|
|
280
|
-
const typeMatches =
|
|
315
|
+
const typeMatches = tokenOverlap(queryTokens, tokens.type);
|
|
281
316
|
if (typeMatches > 0) {
|
|
282
317
|
score += typeMatches;
|
|
283
318
|
matchedFields.push("anchorType");
|
|
284
319
|
}
|
|
285
|
-
const tagMatches =
|
|
320
|
+
const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);
|
|
286
321
|
if (tagMatches > 0) {
|
|
287
322
|
score += tagMatches * 2;
|
|
288
323
|
matchedFields.push("anchorTags");
|
|
@@ -509,15 +544,18 @@ async function searchHarmonicRetrieval(options) {
|
|
|
509
544
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
510
545
|
const queryTokens = new Set(normalizeRecallTokens(options.query, ["what", "which"]));
|
|
511
546
|
if (queryTokens.size === 0 || options.maxResults <= 0) return [];
|
|
512
|
-
const
|
|
547
|
+
const graph = await readProjectedHarmonicGraph({
|
|
513
548
|
...options,
|
|
514
549
|
useCache: options.useGraphCache === true,
|
|
515
550
|
waitBudgetMs: options.waitBudgetMs === void 0 ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs
|
|
516
551
|
});
|
|
552
|
+
const { nodes: eligibleNodes, anchors } = graph;
|
|
553
|
+
const searchIndex = getHarmonicSearchIndex(graph);
|
|
517
554
|
const candidates = /* @__PURE__ */ new Map();
|
|
518
|
-
for (const node of eligibleNodes) {
|
|
555
|
+
for (const [nodeIndexPos, node] of eligibleNodes.entries()) {
|
|
519
556
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
520
|
-
const
|
|
557
|
+
const tokens = searchIndex.nodeTokens[nodeIndexPos];
|
|
558
|
+
const { score, matchedFields } = scoreNode(tokens, queryTokens);
|
|
521
559
|
if (score <= 0) continue;
|
|
522
560
|
candidates.set(node.nodeId, {
|
|
523
561
|
node,
|
|
@@ -529,16 +567,14 @@ async function searchHarmonicRetrieval(options) {
|
|
|
529
567
|
}
|
|
530
568
|
if (options.anchorsEnabled) {
|
|
531
569
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
532
|
-
const
|
|
533
|
-
for (const anchor of anchors) {
|
|
570
|
+
for (const [anchorIndex, anchor] of anchors.entries()) {
|
|
534
571
|
throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
|
|
535
572
|
const eligibleNodeRefs = anchor.nodeRefs;
|
|
536
|
-
const
|
|
537
|
-
const
|
|
538
|
-
const { score, matchedFields } = scoreAnchor(anchor, queryTokens, eligibleAnchorTags);
|
|
573
|
+
const anchorTokens = searchIndex.anchorTokens[anchorIndex];
|
|
574
|
+
const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);
|
|
539
575
|
if (score <= 0) continue;
|
|
540
576
|
for (const nodeRef of eligibleNodeRefs) {
|
|
541
|
-
const node =
|
|
577
|
+
const node = searchIndex.nodesById.get(nodeRef);
|
|
542
578
|
if (!node) continue;
|
|
543
579
|
const existing = candidates.get(nodeRef) ?? {
|
|
544
580
|
node,
|
|
@@ -578,6 +614,7 @@ async function searchHarmonicRetrieval(options) {
|
|
|
578
614
|
}
|
|
579
615
|
|
|
580
616
|
export {
|
|
617
|
+
harmonicSearchIndexStats,
|
|
581
618
|
readAbstractionNodes,
|
|
582
619
|
readCueAnchors,
|
|
583
620
|
harmonicGraphCacheStats,
|
|
@@ -589,4 +626,4 @@ export {
|
|
|
589
626
|
readProjectedHarmonicGraph,
|
|
590
627
|
searchHarmonicRetrieval
|
|
591
628
|
};
|
|
592
|
-
//# sourceMappingURL=chunk-
|
|
629
|
+
//# sourceMappingURL=chunk-5Y3UVK6S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { realpath } from \"node:fs/promises\";\nimport { listJsonFilesStrict, readJsonFile } from \"./json-store.js\";\nimport { raceAbort, throwIfAborted } from \"./abort-error.js\";\nimport { log } from \"./logger.js\";\nimport { readHarmonicGraphStamp } from \"./harmonic-graph-version.js\";\nimport { inferMemoryStatus, toMemoryPathRel } from \"./memory-lifecycle-ledger-utils.js\";\n import {\n HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY,\n resolveAbstractionNodeStoreDir,\n validateAbstractionNode,\n type AbstractionNode,\n } from \"./abstraction-nodes.js\";\nimport { resolveCueAnchorStoreDir, validateCueAnchor, type CueAnchor, type CueAnchorType } from \"./cue-anchors.js\";\nimport { compareDeterministicStrings } from \"./deterministic-order.js\";\nimport { normalizeRecallTokenSet, normalizeRecallTokens } from \"./recall-tokenization.js\";\nimport { stripAttributesSuffix } from \"./structured-attributes.js\";\nimport { isValidityExpiredNow } from \"./temporal-validity.js\";\nimport { assertSafePathSegment, isRecord } from \"./store-contract.js\";\nimport { isSupportPassportPrivateMemory } from \"./support-passport/card-projection.js\";\nimport type { MemoryFile } from \"./types.js\";\nimport { readProjectedMemoryStates } from \"./memory-projection-batch.js\";\nimport { SecureStoreLockedError } from \"./secure-store/secure-fs.js\";\nimport { StorageManager } from \"./storage.js\";\nimport { RECALL_FALLBACK_DIRS } from \"./utils/category-dir.js\";\nimport { readHarmonicSourceMemory, readUnresolvedHarmonicSources } from \"./harmonic-source-lookup.js\";\nimport { mapInBatches } from \"./map-in-batches.js\";\n\n\ntype SourceMemoryMap = Map<string, MemoryFile>;\n\n\n// An index older than this is treated as unusable: the date window needed to\n// cover \"created since the last rebuild\" would stop being cheap.\nconst INDEX_MAX_AGE_MS = 7 * 86_400_000;\nconst DAY_MS = 86_400_000;\n\nfunction utcDaysSince(rebuiltMs: number, nowMs: number): string[] {\n const days: string[] = [];\n for (let day = Math.floor((rebuiltMs - DAY_MS) / DAY_MS) * DAY_MS; day <= nowMs; day += DAY_MS) {\n days.push(new Date(day).toISOString().slice(0, 10));\n }\n return days;\n}\n\n\n// Memories the projection has no row for were written after its last rebuild, so\n// their dated directory is normally one of `days`. Hot and cold tiers are probed\n// by exact path. Only recall-corpus categories are probed: `questions/` is a queue\n// and `artifacts/` is outside the recall surface, so neither can be a source.\nfunction unprojectedCandidatePaths(memoryDir: string, id: string, days: string[]): string[] {\n const paths: string[] = [];\n for (const root of [memoryDir, path.join(memoryDir, \"cold\")]) {\n for (const dir of RECALL_FALLBACK_DIRS) {\n paths.push(path.join(root, dir, `${id}.md`));\n for (const day of days) paths.push(path.join(root, dir, day, `${id}.md`));\n }\n }\n return paths;\n}\n\n/** Resolve indexed sources first, then use the durable unresolved-id path cache. */\nasync function readIndexedSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs: number;\n}): Promise<SourceMemoryMap | null> {\n // The ids go to SQL as bound parameters, so any id the projection holds is safe to look up.\n const batch = readProjectedMemoryStates(options.memoryDir, options.sourceMemoryIds);\n const rebuiltMs = Date.parse(batch?.rebuiltAt ?? \"\");\n if (!batch?.complete || !batch.rebuiltAt || !Number.isFinite(rebuiltMs) || options.nowMs - rebuiltMs > INDEX_MAX_AGE_MS) return null;\n const rootReal = await realpath(options.memoryDir).catch(() => null);\n if (rootReal === null) return null;\n\n const storage = new StorageManager(options.memoryDir);\n const days = utcDaysSince(rebuiltMs, options.nowMs);\n const sourceMemories: SourceMemoryMap = new Map();\n const pending: string[] = [];\n const resolved = await mapInBatches(options.sourceMemoryIds, async (id) => {\n const state = batch.states.get(id);\n // An id is only ever joined into a path when it is a single safe segment.\n let safeId = true;\n try {\n assertSafePathSegment(id, \"sourceMemoryId\");\n } catch {\n safeId = false;\n }\n // state.path was containment-checked by the projection reader.\n const candidates = state\n ? [state.path, path.join(options.memoryDir, \"cold\", state.pathRel)]\n : safeId ? unprojectedCandidatePaths(options.memoryDir, id, days) : [];\n for (const candidate of candidates) {\n const memory = await readHarmonicSourceMemory(storage, rootReal, candidate, options.abortSignal);\n if (memory?.frontmatter.id !== id) continue;\n return { id, memory };\n }\n return { id, memory: undefined };\n });\n for (const { id, memory } of resolved) {\n if (memory) sourceMemories.set(id, memory);\n else pending.push(id);\n }\n if (pending.length === 0) return sourceMemories;\n\n const unresolved = await readUnresolvedHarmonicSources({\n storage, rootReal, rebuiltAt: batch.rebuiltAt, sourceMemoryIds: pending,\n nowMs: options.nowMs, abortSignal: options.abortSignal,\n });\n for (const [id, memory] of unresolved) sourceMemories.set(id, memory);\n return sourceMemories;\n}\n\nasync function readCorpusSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n}): Promise<SourceMemoryMap> {\n const sourceMemories: SourceMemoryMap = new Map();\n try {\n const storage = new StorageManager(options.memoryDir);\n const [hotMemories, coldMemories] = await Promise.all([\n storage.readAllMemories({ abortSignal: options.abortSignal }),\n storage.readAllColdMemories({ abortSignal: options.abortSignal }),\n ]);\n for (const memory of [...hotMemories, ...coldMemories]) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n sourceMemories.set(memory.frontmatter.id, memory);\n }\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n // Source validation fails closed when the authorized memory directory is\n // unreadable. Source-less nodes remain eligible for retrieval.\n sourceMemories.clear();\n }\n return sourceMemories;\n}\n\nasync function readSourceMemories(options: {\n memoryDir: string;\n abortSignal?: AbortSignal;\n sourceMemoryIds: string[];\n nowMs?: number;\n}): Promise<SourceMemoryMap> {\n try {\n const indexed = await readIndexedSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds: options.sourceMemoryIds,\n nowMs: options.nowMs ?? Date.now(),\n });\n if (indexed) return indexed;\n } catch (err) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n if (err instanceof SecureStoreLockedError) return new Map();\n }\n return readCorpusSourceMemories(options);\n}\n\nfunction parseSourceMemoryInsertedAt(node: AbstractionNode): Map<string, string> {\n const insertedAtById = new Map<string, string>();\n const insertedAtRaw = node.metadata?.[HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY];\n if (!insertedAtRaw) return insertedAtById;\n try {\n const parsed = JSON.parse(insertedAtRaw) as unknown;\n if (!isRecord(parsed)) return insertedAtById;\n for (const [memoryId, value] of Object.entries(parsed)) {\n if (typeof value === \"string\") insertedAtById.set(memoryId, value);\n }\n } catch {\n // Malformed insertion metadata leaves ordering on the recordedAt fallback.\n }\n return insertedAtById;\n}\n\n/**\n * Whether a source memory can back a projected node at all. Shared with `earliestInvalidAtMs`, so the cache\n * deadline only follows a source that the projection would use.\n * #2332: a private support-passport record leaves the eligible set the same way a rejected one does — a node\n * title or anchor attribution rebuilt from it would leak governed metadata into the deep-recall frontier (and\n * every other graph reader) before any content check runs.\n */\nfunction isEligibleSourceMemory(memory: MemoryFile, memoryDir: string): boolean {\n return (\n !isSupportPassportPrivateMemory(memory) &&\n inferMemoryStatus(memory.frontmatter, toMemoryPathRel(memoryDir, memory.path)) === \"active\"\n );\n}\n\nfunction projectSourceBackedNode(\n node: AbstractionNode,\n sourceMemories: SourceMemoryMap,\n memoryDir: string,\n temporalExpiredInInjection: boolean,\n nowMs: number\n): AbstractionNode | null {\n const sourceMemoryIds = node.sourceMemoryIds ?? [];\n if (sourceMemoryIds.length === 0) return node;\n\n const activeSourceMemoryIds = sourceMemoryIds.filter((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return (\n memory !== undefined &&\n isEligibleSourceMemory(memory, memoryDir) &&\n (temporalExpiredInInjection || !isValidityExpiredNow(memory.frontmatter, nowMs))\n );\n });\n if (activeSourceMemoryIds.length === 0) return null;\n\n // Newest-first source order keeps the projected title and summary on the most\n // recently inserted facts. Equal or missing timestamps fall back to ascending\n // id order, which matches the stored sourceMemoryIds order.\n const insertedAtById = parseSourceMemoryInsertedAt(node);\n const insertedAtMs = (memoryId: string): number => {\n const parsedMs = Date.parse(insertedAtById.get(memoryId) ?? \"\");\n return Number.isFinite(parsedMs) ? parsedMs : Date.parse(node.recordedAt);\n };\n activeSourceMemoryIds.sort(\n (left, right) =>\n insertedAtMs(right) - insertedAtMs(left) || compareDeterministicStrings(left, right)\n );\n\n const activeMemories = activeSourceMemoryIds.flatMap((memoryId) => {\n const memory = sourceMemories.get(memoryId);\n return memory ? [memory] : [];\n });\n const activeContents = activeMemories.map((memory) =>\n memory.frontmatter.structuredAttributes ? stripAttributesSuffix(memory.content) : memory.content\n );\n let metadata: Record<string, string> | undefined;\n const activeInsertedAt = activeSourceMemoryIds.flatMap((memoryId) => {\n const value = insertedAtById.get(memoryId);\n return typeof value === \"string\" ? [[memoryId, value] as const] : [];\n });\n if (activeInsertedAt.length > 0) {\n metadata = {\n [HARMONIC_SOURCE_MEMORY_INSERTED_AT_KEY]: JSON.stringify(Object.fromEntries(activeInsertedAt)),\n };\n }\n\n return {\n ...node,\n sourceMemoryIds: activeSourceMemoryIds,\n title: activeContents[0]?.slice(0, 80) ?? node.title,\n summary: activeContents.slice(0, 3).join(\"; \").slice(0, 400),\n tags: [...new Set(activeMemories.flatMap((memory) => memory.frontmatter.tags))].sort(compareDeterministicStrings),\n entityRefs: [\n ...new Set(\n activeMemories.flatMap((memory) =>\n typeof memory.frontmatter.entityRef === \"string\" ? [memory.frontmatter.entityRef] : []\n )\n ),\n ].sort(compareDeterministicStrings),\n metadata,\n };\n}\n\nfunction anchorMatchesProjectedNode(\n anchor: CueAnchor,\n nodeRef: string,\n node: AbstractionNode,\n allowLegacyAttribution: boolean\n): boolean {\n const activeSourceMemoryIds = node.sourceMemoryIds ?? [];\n if (activeSourceMemoryIds.length === 0) return true;\n if (!anchor.sourceMemoryIdsByNodeRef) return allowLegacyAttribution;\n const anchorSourceMemoryIds = anchor.sourceMemoryIdsByNodeRef[nodeRef] ?? [];\n return anchorSourceMemoryIds.some((sourceMemoryId) => activeSourceMemoryIds.includes(sourceMemoryId));\n}\n\nexport interface HarmonicMatchedAnchor {\n anchorId: string;\n anchorType: CueAnchorType;\n anchorValue: string;\n}\n\nexport interface HarmonicRetrievalResult {\n node: AbstractionNode;\n score: number;\n nodeScore: number;\n anchorScore: number;\n matchedFields: string[];\n matchedAnchors: HarmonicMatchedAnchor[];\n}\n\ninterface HarmonicCandidate {\n node: AbstractionNode;\n nodeScore: number;\n anchorScore: number;\n matchedFields: Set<string>;\n matchedAnchors: Map<string, HarmonicMatchedAnchor>;\n}\n\nfunction tokenOverlap(queryTokens: Set<string>, fieldTokens: ReadonlySet<string>): number {\n let matches = 0;\n for (const token of queryTokens) {\n if (fieldTokens.has(token)) matches += 1;\n }\n return matches;\n}\n\ninterface HarmonicNodeTokens {\n title: ReadonlySet<string>;\n summary: ReadonlySet<string>;\n tags: ReadonlySet<string>;\n entities: ReadonlySet<string>;\n kind: ReadonlySet<string>;\n}\n\ninterface HarmonicAnchorTokens {\n value: ReadonlySet<string>;\n normalized: ReadonlySet<string>;\n type: ReadonlySet<string>;\n eligibleTags: ReadonlySet<string>;\n}\n\ninterface HarmonicSearchIndex {\n nodesById: Map<string, AbstractionNode>;\n nodeTokens: HarmonicNodeTokens[];\n anchorTokens: HarmonicAnchorTokens[];\n}\n\nexport const harmonicSearchIndexStats = { builds: 0 };\n\n/**\n * Per-graph scoring index, keyed on the frozen graph object itself. Scoring a\n * recall tokenizes every node's title/summary/tags/entities/kind and every\n * anchor's value/cue/type/eligible tags; on a cache hit that repeated the\n * whole normalization for each recall (~0.75 s on a ~2.5k node, ~10k anchor\n * corpus, issue #3450). The sets are identical to what `countRecallTokenOverlap`\n * computed from the raw fields, so scores and matchedFields are unchanged.\n * For an uncached graph the index is built per call — the same work the old\n * code did inline.\n */\nconst harmonicSearchIndexes = new WeakMap<ProjectedHarmonicGraph, HarmonicSearchIndex>();\n\nfunction getHarmonicSearchIndex(graph: ProjectedHarmonicGraph): HarmonicSearchIndex {\n const cached = harmonicSearchIndexes.get(graph);\n if (cached) return cached;\n harmonicSearchIndexStats.builds += 1;\n const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));\n // Node ids are only unique per record day (nodes/<day>/<nodeId>.json), so\n // tokens are indexed by position in graph.nodes.\n const nodeTokens = graph.nodes.map((node) => ({\n title: normalizeRecallTokenSet(node.title ?? \"\"),\n summary: normalizeRecallTokenSet(node.summary ?? \"\"),\n tags: normalizeRecallTokenSet(node.tags?.join(\" \") ?? \"\"),\n entities: normalizeRecallTokenSet(node.entityRefs?.join(\" \") ?? \"\"),\n kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`),\n }));\n // Anchor ids are only unique per anchorType (cue-anchors dedups by\n // type+id), so tokens are indexed by position in graph.anchors.\n const anchorTokens = graph.anchors.map((anchor) => {\n const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));\n const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];\n return {\n value: normalizeRecallTokenSet(anchor.anchorValue ?? \"\"),\n normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? \"\"),\n type: normalizeRecallTokenSet(anchor.anchorType),\n eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(\" \")),\n };\n });\n const index: HarmonicSearchIndex = { nodesById, nodeTokens, anchorTokens };\n harmonicSearchIndexes.set(graph, index);\n return index;\n}\n\nfunction scoreNode(tokens: HarmonicNodeTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = tokenOverlap(queryTokens, tokens.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = tokenOverlap(queryTokens, tokens.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.tags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = tokenOverlap(queryTokens, tokens.entities);\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = tokenOverlap(queryTokens, tokens.kind);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(tokens: HarmonicAnchorTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = tokenOverlap(queryTokens, tokens.value);\n const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);\n const cueMatches = Math.max(valueMatches, normalizedMatches);\n if (cueMatches > 0) {\n score += cueMatches * 4;\n if (valueMatches > 0) matchedFields.push(\"anchorValue\");\n if (normalizedMatches > 0) matchedFields.push(\"anchor\");\n }\n\n const typeMatches = tokenOverlap(queryTokens, tokens.type);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"anchorTags\");\n }\n\n return { score, matchedFields };\n}\n\nexport async function readAbstractionNodes(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<AbstractionNode[]> {\n const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const files = await listJsonFilesStrict(path.join(rootDir, \"nodes\"), { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateAbstractionNode(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((node): node is AbstractionNode => node !== null);\n}\n\nexport async function readCueAnchors(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<CueAnchor[]> {\n const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const rootDir = resolveCueAnchorStoreDir(abstractionRoot);\n const files = await listJsonFilesStrict(rootDir, { allowMissingDirectory: true });\n const parsed = await mapInBatches(files, async (filePath) => {\n try {\n return validateCueAnchor(await readJsonFile(filePath));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n return null;\n }\n });\n return parsed.filter((anchor): anchor is CueAnchor => anchor !== null);\n}\n\nexport interface ProjectedHarmonicGraph {\n nodes: AbstractionNode[];\n anchors: CueAnchor[];\n}\n\n/**\n * Read nodes + anchors and project BOTH against the namespace's current active\n * memories. This is the single projection every graph reader shares: a raw\n * `readAbstractionNodes` / `readCueAnchors` pair still carries the stored title,\n * summary, tags, and anchor attribution of a memory that was later rejected,\n * quarantined, or otherwise moved out of the active set, so a second reader\n * that skipped the projection could leak governed metadata even when the\n * memory itself is excluded from the final results.\n *\n * - A node whose every source memory left the active set is dropped.\n * - A surviving node's title/summary/tags/entityRefs are rebuilt from its\n * active sources only.\n * - An anchor keeps a node reference only while its attribution runs through\n * one of that node's surviving active sources, and is dropped once no\n * reference survives.\n */\ninterface ExpiringHarmonicGraph extends ProjectedHarmonicGraph {\n /** First instant a source memory's `invalid_at` passes: from then on the graph is wrong without any write. */\n validUntilMs: number;\n}\n\nfunction earliestInvalidAtMs(sourceMemories: SourceMemoryMap, memoryDir: string, nowMs: number): number {\n let earliest = Number.POSITIVE_INFINITY;\n for (const memory of sourceMemories.values()) {\n // An ineligible source drops out of the projection whatever its `invalid_at`, so its deadline changes nothing.\n if (!isEligibleSourceMemory(memory, memoryDir)) continue;\n const invalidAtMs = Date.parse(memory.frontmatter.invalid_at?.trim() ?? \"\");\n if (Number.isFinite(invalidAtMs) && invalidAtMs > nowMs && invalidAtMs < earliest) earliest = invalidAtMs;\n }\n return earliest;\n}\n\nasync function buildProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n const { nodes, anchors } = await buildExpiringHarmonicGraph(options);\n return { nodes, anchors };\n}\n\nasync function buildExpiringHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n}): Promise<ExpiringHarmonicGraph> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const buildDelayMs = harmonicGraphBuildTestHooks?.buildDelayMs;\n if (buildDelayMs !== undefined && buildDelayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, buildDelayMs));\n }\n const nodes = await readAbstractionNodes(options);\n const sourceMemoryIds = [...new Set(nodes.flatMap((node) => node.sourceMemoryIds ?? []))];\n const sourceMemories: SourceMemoryMap = sourceMemoryIds.length > 0\n ? await readSourceMemories({\n memoryDir: options.memoryDir,\n abortSignal: options.abortSignal,\n sourceMemoryIds,\n nowMs: options.nowMs,\n })\n : new Map();\n const nowMs = options.nowMs ?? Date.now();\n // With temporalExpiredInInjection the validity filter is off, so no `invalid_at` can age the graph.\n const validUntilMs = options.temporalExpiredInInjection === true\n ? Number.POSITIVE_INFINITY\n : earliestInvalidAtMs(sourceMemories, options.memoryDir, nowMs);\n // A node whose full stored source set survived projection keeps legacy\n // anchor attribution (an anchor written before per-node source ids existed).\n const legacyCompatibleNodeRefs = new Set<string>();\n const projectedNodes = nodes.flatMap((node) => {\n const projected = projectSourceBackedNode(\n node,\n sourceMemories,\n options.memoryDir,\n options.temporalExpiredInInjection === true,\n nowMs\n );\n if (\n projected &&\n (node.sourceMemoryIds?.length ?? 0) > 0 &&\n projected.sourceMemoryIds?.length === node.sourceMemoryIds?.length\n ) {\n legacyCompatibleNodeRefs.add(node.nodeId);\n }\n return projected ? [projected] : [];\n });\n if (!options.anchorsEnabled) return { nodes: projectedNodes, anchors: [], validUntilMs };\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeIndex = new Map(projectedNodes.map((node) => [node.nodeId, node]));\n const anchors = (await readCueAnchors(options)).flatMap((anchor) => {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeRefs = anchor.nodeRefs.filter((nodeRef) => {\n const node = nodeIndex.get(nodeRef);\n return (\n node !== undefined &&\n anchorMatchesProjectedNode(anchor, nodeRef, node, legacyCompatibleNodeRefs.has(nodeRef))\n );\n });\n return nodeRefs.length > 0 ? [{ ...anchor, nodeRefs }] : [];\n });\n return { nodes: projectedNodes, anchors, validUntilMs };\n}\n\nconst GRAPH_CACHE_TTL_MS = 30_000;\n/**\n * Past the TTL a graph whose stamp is unchanged is still served while a refresh runs behind it, so no\n * recall waits for a rebuild just because the TTL lapsed. This is how long past the TTL; after it the graph is rebuilt first.\n */\nconst GRAPH_CACHE_MAX_STALE_MS = 300_000;\nconst GRAPH_CACHE_MAX_ENTRIES = 8;\n\ninterface GraphCacheEntry {\n stamp: string;\n /** When the build finished, so the TTL measures how long the graph has been available. */\n builtAtMs: number;\n validUntilMs: number;\n graph: ProjectedHarmonicGraph;\n}\n\ninterface GraphBuild {\n stamp: string;\n promise: Promise<ProjectedHarmonicGraph>;\n /** Cancels the build's source scan; fired when no caller is waiting for it. */\n controller: AbortController;\n /** Callers currently waiting for this build. */\n waiting: number;\n}\n\nconst graphCache = new Map<string, GraphCacheEntry>();\n/** One build per cache key at a time: every recall that lands on a miss waits for the same build. */\nconst graphBuilds = new Map<string, GraphBuild>();\n/** When a background refresh last failed, per key: stale reads retry at most once per TTL. Capped like the cache. */\nconst refreshFailedAtMs = new Map<string, number>();\n\nfunction rememberRefreshFailure(key: string): void {\n refreshFailedAtMs.delete(key);\n refreshFailedAtMs.set(key, Date.now());\n while (refreshFailedAtMs.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = refreshFailedAtMs.keys().next().value;\n if (oldest === undefined) break;\n refreshFailedAtMs.delete(oldest);\n }\n}\n\n/**\n * A source's `invalid_at` can pass while the build is still reading anchors, which would hand every caller\n * that joined this build a graph that is already expired. Rebuild until the graph is unexpired at completion.\n * Each round drops the sources that expired, so the set of future deadlines shrinks and the loop ends.\n */\nasync function buildUnexpiredHarmonicGraph(options: GraphReadOptions, abortSignal: AbortSignal): Promise<ExpiringHarmonicGraph> {\n for (;;) {\n const built = await buildExpiringHarmonicGraph({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n anchorsEnabled: options.anchorsEnabled,\n temporalExpiredInInjection: options.temporalExpiredInInjection,\n abortSignal,\n });\n if (Date.now() < built.validUntilMs) return built;\n }\n}\n/** Counters for tests and diagnostics. `stale` hits also count as `hits`. */\nexport const harmonicGraphCacheStats = { hits: 0, misses: 0, stale: 0, shared: 0, deadlineExits: 0 };\n\n/** Default per-caller bound on waiting for a shared graph build (see `waitBudgetMs`). */\nexport const HARMONIC_GRAPH_WAIT_BUDGET_MS = 5_000;\n\nconst HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE = \"harmonic graph wait deadline exceeded\";\n\nexport class HarmonicGraphWaitDeadlineError extends Error {\n constructor() {\n super(HARMONIC_GRAPH_WAIT_DEADLINE_MESSAGE);\n this.name = \"HarmonicGraphWaitDeadlineError\";\n }\n}\n\ninterface HarmonicGraphBuildTestHooks {\n /** Extra delay inside every build, for wait-budget tests. */\n buildDelayMs?: number;\n}\nlet harmonicGraphBuildTestHooks: HarmonicGraphBuildTestHooks | null = null;\nexport function setHarmonicGraphBuildTestHooks(hooks: HarmonicGraphBuildTestHooks | null): void {\n harmonicGraphBuildTestHooks = hooks;\n}\n\n/** Freeze records and their nested arrays/objects so a caller cannot corrupt the shared cache. */\nfunction deepFreeze<T extends object>(value: T): T {\n // isFrozen is true for primitives and null, and a frozen value is not revisited, so this ends on cycles too.\n if (Object.isFrozen(value)) return value;\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n return value;\n}\n\nexport function clearHarmonicGraphCache(): void {\n graphCache.clear();\n graphBuilds.clear();\n refreshFailedAtMs.clear();\n}\n\n/**\n * Resolves once every build running now has settled, and after the failure bookkeeping of a background\n * refresh (that handler was attached when the refresh started, so it runs first). For tests: a time-based\n * wait races a slow build.\n */\nexport async function settleHarmonicGraphBuilds(): Promise<void> {\n await Promise.allSettled([...graphBuilds.values()].map((build) => build.promise));\n}\n\ntype GraphReadOptions = Parameters<typeof buildProjectedHarmonicGraph>[0];\n\n/**\n * Start the one build for `key`. The build owns an abort controller instead of using one caller's signal,\n * so a caller that leaves does not cancel it for the others; `joinGraphBuild` cancels it when the last caller leaves.\n */\nfunction startGraphBuild(key: string, stamp: string, options: GraphReadOptions): GraphBuild {\n harmonicGraphCacheStats.misses++;\n const controller = new AbortController();\n const promise: Promise<ProjectedHarmonicGraph> = buildUnexpiredHarmonicGraph(options, controller.signal)\n .then((built) => {\n const graph = { nodes: deepFreeze(built.nodes), anchors: deepFreeze(built.anchors) };\n // A cleared cache or a newer build for this key has replaced this one: do not store a stale graph.\n if (graphBuilds.get(key)?.promise !== promise) return graph;\n refreshFailedAtMs.delete(key);\n graphCache.delete(key);\n graphCache.set(key, { stamp, builtAtMs: Date.now(), validUntilMs: built.validUntilMs, graph });\n while (graphCache.size > GRAPH_CACHE_MAX_ENTRIES) {\n const oldest = graphCache.keys().next().value;\n if (oldest === undefined) break;\n graphCache.delete(oldest);\n }\n return graph;\n })\n .finally(() => {\n if (graphBuilds.get(key)?.promise === promise) graphBuilds.delete(key);\n });\n const build: GraphBuild = { stamp, promise, controller, waiting: 0 };\n graphBuilds.set(key, build);\n return build;\n}\n\n/**\n * Wait for `build` on behalf of one caller. The caller's own signal ends only its own wait. When the last\n * waiting caller has left, the build is cancelled and dropped, so abandoned recalls do not leave full scans running\n * (cancelling a build that already finished does nothing). A caller that leaves on `waitBudgetMs` is the exception:\n * the build keeps running so its completed graph warms the cache for the next caller.\n */\nfunction joinGraphBuild(\n key: string,\n build: GraphBuild,\n signal: AbortSignal | undefined,\n waitBudgetMs?: number,\n): Promise<ProjectedHarmonicGraph> {\n build.waiting++;\n let timedOut = false;\n let timer: NodeJS.Timeout | undefined;\n const waited =\n waitBudgetMs === undefined || waitBudgetMs <= 0\n ? raceAbort(build.promise, signal, \"harmonic retrieval aborted\")\n : Promise.race([\n raceAbort(build.promise, signal, \"harmonic retrieval aborted\"),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new HarmonicGraphWaitDeadlineError());\n }, waitBudgetMs);\n }),\n ]);\n return waited.finally(() => {\n if (timer) clearTimeout(timer);\n build.waiting--;\n // A caller that left on the wait budget does not cancel the build: it keeps\n // running and stores the fresh graph, so the next caller gets a cache hit\n // instead of restarting the scan a write storm keeps invalidating.\n if (timedOut) harmonicGraphCacheStats.deadlineExits++;\n if (build.waiting > 0 || timedOut) return;\n if (graphBuilds.get(key) === build) graphBuilds.delete(key);\n build.controller.abort();\n });\n}\n\n/**\n * `readProjectedHarmonicGraph` with an opt-in in-memory cache. Every recall used\n * to re-read all nodes, anchors and source memories from disk (about 4.7 s on a\n * 2107 node, 9199 anchor, 4105 source graph). With `useCache` a completed graph is\n * reused while the stamp below is unchanged: the memory corpus, memory status and\n * cold-write version sentinels (bumped by every memory write, in any process) and\n * the graph version sentinel (bumped by node and anchor writes). A stamp read is\n * four stats, not a scan of the memories. The TTL bounds the one input a sentinel\n * cannot see, which is wall-clock validity expiry; past it the stale graph is served\n * while one refresh runs (up to GRAPH_CACHE_MAX_STALE_MS). A changed stamp always\n * waits for a fresh build, because a stale graph could carry governed metadata of a\n * memory that left the active set. Concurrent misses share one build. An explicit\n * `nowMs` bypasses the cache so tests stay deterministic. The cached arrays are\n * frozen: callers must not mutate them.\n */\nexport async function readProjectedHarmonicGraph(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n nowMs?: number;\n useCache?: boolean;\n /** Per-caller bound on joining a shared build, in ms. On expiry the caller\n * leaves with a HarmonicGraphWaitDeadlineError while the build keeps running.\n * `0` or unset waits without a bound. Applies only on the cached path. */\n waitBudgetMs?: number;\n}): Promise<ProjectedHarmonicGraph> {\n if (options.useCache !== true || options.nowMs !== undefined) return buildProjectedHarmonicGraph(options);\n // Same cancellation contract as the builder: a cache hit must not mask an aborted signal.\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const nodeStoreDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const key = JSON.stringify([\n options.memoryDir,\n nodeStoreDir,\n options.anchorsEnabled === true,\n options.temporalExpiredInInjection === true,\n ]);\n // The stamp is read BEFORE the build, so a write that lands mid-build leaves the\n // entry stale and the next call rebuilds.\n const stamp = readHarmonicGraphStamp(options.memoryDir, nodeStoreDir);\n const nowMs = Date.now();\n const hit = graphCache.get(key);\n // A source's `invalid_at` passing changes the projection without bumping the stamp, so it ends the entry\n // at the exact instant, however fresh the entry is.\n if (hit && hit.stamp === stamp && nowMs < hit.validUntilMs && nowMs - hit.builtAtMs < GRAPH_CACHE_TTL_MS + GRAPH_CACHE_MAX_STALE_MS) {\n harmonicGraphCacheStats.hits++;\n graphCache.delete(key);\n graphCache.set(key, hit);\n if (nowMs - hit.builtAtMs >= GRAPH_CACHE_TTL_MS) {\n harmonicGraphCacheStats.stale++;\n const failedAtMs = refreshFailedAtMs.get(key);\n const backingOff = failedAtMs !== undefined && nowMs - failedAtMs < GRAPH_CACHE_TTL_MS;\n if (graphBuilds.get(key)?.stamp !== stamp && !backingOff) {\n startGraphBuild(key, stamp, options).promise.catch((err) => {\n rememberRefreshFailure(key);\n log.debug(`harmonic graph refresh failed: ${err}`);\n });\n }\n }\n return hit.graph;\n }\n const running = graphBuilds.get(key);\n if (running?.stamp === stamp) {\n harmonicGraphCacheStats.shared++;\n return joinGraphBuild(key, running, options.abortSignal, options.waitBudgetMs);\n }\n return joinGraphBuild(key, startGraphBuild(key, stamp, options), options.abortSignal, options.waitBudgetMs);\n}\n\nexport async function searchHarmonicRetrieval(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n query: string;\n maxResults: number;\n sessionKey?: string;\n anchorsEnabled: boolean;\n abortSignal?: AbortSignal;\n temporalExpiredInInjection?: boolean;\n /** Share one projected graph between recalls until a write bumps a version sentinel (see readProjectedHarmonicGraph). */\n useGraphCache?: boolean;\n /** Bound on waiting for a shared graph build, in ms. Past it the search\n * rejects with a HarmonicGraphWaitDeadlineError so a recall fails open\n * instead of blocking on a rebuild a write storm keeps invalidating.\n * `0` waits without a bound. Defaults to HARMONIC_GRAPH_WAIT_BUDGET_MS. */\n waitBudgetMs?: number;\n}): Promise<HarmonicRetrievalResult[]> {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const queryTokens = new Set(normalizeRecallTokens(options.query, [\"what\", \"which\"]));\n if (queryTokens.size === 0 || options.maxResults <= 0) return [];\n\n // One projection for every graph reader: nodes and anchors both arrive\n // already narrowed to the namespace's current active memories.\n const graph = await readProjectedHarmonicGraph({\n ...options,\n useCache: options.useGraphCache === true,\n waitBudgetMs:\n options.waitBudgetMs === undefined ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs,\n });\n const { nodes: eligibleNodes, anchors } = graph;\n const searchIndex = getHarmonicSearchIndex(graph);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const [nodeIndexPos, node] of eligibleNodes.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const tokens = searchIndex.nodeTokens[nodeIndexPos];\n const { score, matchedFields } = scoreNode(tokens, queryTokens);\n if (score <= 0) continue;\n candidates.set(node.nodeId, {\n node,\n nodeScore: score,\n anchorScore: 0,\n matchedFields: new Set(matchedFields),\n matchedAnchors: new Map(),\n });\n }\n\n if (options.anchorsEnabled) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n for (const [anchorIndex, anchor] of anchors.entries()) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n // `nodeRefs` are the projection's surviving references already.\n const eligibleNodeRefs = anchor.nodeRefs;\n const anchorTokens = searchIndex.anchorTokens[anchorIndex];\n const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);\n if (score <= 0) continue;\n for (const nodeRef of eligibleNodeRefs) {\n const node = searchIndex.nodesById.get(nodeRef);\n if (!node) continue;\n const existing = candidates.get(nodeRef) ?? {\n node,\n nodeScore: 0,\n anchorScore: 0,\n matchedFields: new Set<string>(),\n matchedAnchors: new Map<string, HarmonicMatchedAnchor>(),\n };\n existing.anchorScore += score;\n existing.matchedFields.add(\"anchor\");\n for (const field of matchedFields) existing.matchedFields.add(field);\n existing.matchedAnchors.set(anchor.anchorId, {\n anchorId: anchor.anchorId,\n anchorType: anchor.anchorType,\n anchorValue: anchor.anchorValue,\n });\n candidates.set(nodeRef, existing);\n }\n }\n }\n\n return [...candidates.values()]\n .map((candidate) => {\n let score = candidate.nodeScore + candidate.anchorScore;\n if (options.sessionKey && candidate.node.sessionKey === options.sessionKey) score += 0.5;\n return {\n node: candidate.node,\n score,\n nodeScore: candidate.nodeScore,\n anchorScore: candidate.anchorScore,\n matchedFields: [...candidate.matchedFields].sort(),\n matchedAnchors: [...candidate.matchedAnchors.values()].sort(\n (left, right) =>\n left.anchorType.localeCompare(right.anchorType) || left.anchorValue.localeCompare(right.anchorValue)\n ),\n };\n })\n .filter((result) => result.nodeScore > 0 || result.anchorScore > 0)\n .sort(\n (left, right) =>\n right.score - left.score ||\n right.anchorScore - left.anchorScore ||\n right.node.recordedAt.localeCompare(left.node.recordedAt)\n )\n .slice(0, options.maxResults);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ClC;AAAA,IACF;AAAA,EACF;AAEA,SAAO,CAAC,GAAG,WAAW,OAAO,CAAC,EAC3B,IAAI,CAAC,cAAc;AAClB,QAAI,QAAQ,UAAU,YAAY,UAAU;AAC5C,QAAI,QAAQ,cAAc,UAAU,KAAK,eAAe,QAAQ,WAAY,UAAS;AACrF,WAAO;AAAA,MACL,MAAM,UAAU;AAAA,MAChB;AAAA,MACA,WAAW,UAAU;AAAA,MACrB,aAAa,UAAU;AAAA,MACvB,eAAe,CAAC,GAAG,UAAU,aAAa,EAAE,KAAK;AAAA,MACjD,gBAAgB,CAAC,GAAG,UAAU,eAAe,OAAO,CAAC,EAAE;AAAA,QACrD,CAAC,MAAM,UACL,KAAK,WAAW,cAAc,MAAM,UAAU,KAAK,KAAK,YAAY,cAAc,MAAM,WAAW;AAAA,MACvG;AAAA,IACF;AAAA,EACF,CAAC,EACA,OAAO,CAAC,WAAW,OAAO,YAAY,KAAK,OAAO,cAAc,CAAC,EACjE;AAAA,IACC,CAAC,MAAM,UACL,MAAM,QAAQ,KAAK,SACnB,MAAM,cAAc,KAAK,eACzB,MAAM,KAAK,WAAW,cAAc,KAAK,KAAK,UAAU;AAAA,EAC5D,EACC,MAAM,GAAG,QAAQ,UAAU;AAChC;","names":[]}
|
|
@@ -27,7 +27,9 @@ function resolveRateLimitSettings(config) {
|
|
|
27
27
|
maxConcurrency: nonNegativeInt(config.localLlmMaxConcurrency, DEFAULT_MAX_CONCURRENCY)
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
|
+
var POOL_MISSING_PATTERN = /pool missing or disabled/i;
|
|
30
31
|
function isRateLimitedResponse(status, bodyText) {
|
|
32
|
+
if (POOL_MISSING_PATTERN.test(bodyText)) return false;
|
|
31
33
|
if (RATE_LIMIT_STATUSES.has(status)) return true;
|
|
32
34
|
return status >= 500 && RATE_LIMIT_BODY_PATTERN.test(bodyText);
|
|
33
35
|
}
|
|
@@ -298,4 +300,4 @@ export {
|
|
|
298
300
|
resetLocalLlmRateLimitStateForTests,
|
|
299
301
|
LocalLlmRateLimitSession
|
|
300
302
|
};
|
|
301
|
-
//# sourceMappingURL=chunk-
|
|
303
|
+
//# sourceMappingURL=chunk-AGMMHT4P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/local-llm-rate-limit.ts"],"sourcesContent":["/**\n * Process-wide rate-limit handling for the local LLM client (COS-447).\n *\n * A LiteLLM proxy in front of the local models answers `429 No deployments\n * available` (and `503`/`408`) when every deployment is busy or in cooldown.\n * Before this module the client returned on the first 429 and the caller\n * loop immediately issued the next request, so one daemon could hammer the\n * proxy with thousands of calls per hour while it was saturated.\n *\n * This module provides three pieces that the client composes:\n *\n * - classification of rate-limit responses and of the retry hint\n * (`Retry-After` header as delta-seconds or HTTP-date, falling back to\n * LiteLLM's `Try again in N seconds` body text);\n * - exponential backoff with full jitter;\n * - process-wide state shared by every `LocalLlmClient` instance: a\n * concurrency semaphore for in-flight HTTP attempts and a per-endpoint\n * \"do not call before\" deadline, so one client's 429 slows every client\n * pointed at the same endpoint.\n *\n * State lives on `globalThis` so duplicated module copies in bundled output\n * still share one limiter.\n */\n\nexport const RATE_LIMIT_STATUSES: ReadonlySet<number> = new Set([408, 429, 503]);\n\nconst RATE_LIMIT_BODY_PATTERN = /no deployments available|cooldown_list|all deployments.*cooldown/i;\nconst TRY_AGAIN_PATTERN = /try again in (\\d+(?:\\.\\d+)?) ?(seconds?|secs?|s|milliseconds?|ms|minutes?|mins?)\\b/i;\n\n/** Upper bound on any server-provided wait we will record (sanity clamp). */\nexport const MAX_RECORDED_BACKOFF_MS = 10 * 60_000;\n\nexport const DEFAULT_RATE_LIMIT_RETRY_COUNT = 3;\nexport const DEFAULT_RATE_LIMIT_BACKOFF_BASE_MS = 1_000;\nexport const DEFAULT_RATE_LIMIT_BACKOFF_MAX_MS = 60_000;\nexport const DEFAULT_MAX_CONCURRENCY = 4;\n\nexport interface LocalLlmRateLimitSettings {\n retryCount: number;\n backoffBaseMs: number;\n backoffMaxMs: number;\n /** 0 disables the process-wide concurrency cap. */\n maxConcurrency: number;\n}\n\nfunction nonNegativeInt(value: number | undefined, fallback: number): number {\n if (value === undefined || !Number.isFinite(value) || value < 0) return fallback;\n return Math.floor(value);\n}\n\nexport function resolveRateLimitSettings(config: {\n localLlmRateLimitRetryCount?: number;\n localLlmRateLimitBackoffBaseMs?: number;\n localLlmRateLimitBackoffMaxMs?: number;\n localLlmMaxConcurrency?: number;\n}): LocalLlmRateLimitSettings {\n const backoffBaseMs = Math.max(\n 1,\n nonNegativeInt(config.localLlmRateLimitBackoffBaseMs, DEFAULT_RATE_LIMIT_BACKOFF_BASE_MS)\n );\n const backoffMaxMs = Math.max(\n backoffBaseMs,\n nonNegativeInt(config.localLlmRateLimitBackoffMaxMs, DEFAULT_RATE_LIMIT_BACKOFF_MAX_MS)\n );\n return {\n retryCount: nonNegativeInt(config.localLlmRateLimitRetryCount, DEFAULT_RATE_LIMIT_RETRY_COUNT),\n backoffBaseMs,\n backoffMaxMs,\n maxConcurrency: nonNegativeInt(config.localLlmMaxConcurrency, DEFAULT_MAX_CONCURRENCY),\n };\n}\n\n/**\n * Pool-side refusals carry \"pool missing or disabled\" — a config failure,\n * not endpoint saturation. Recording backoff for one would throttle every\n * operation sharing the endpoint URL (e.g. extraction waits on a missing\n * recall pool).\n */\nconst POOL_MISSING_PATTERN = /pool missing or disabled/i;\n\n/**\n * True for responses that mean \"the endpoint is saturated, slow down\":\n * 408/429/503, or a 5xx whose body carries LiteLLM's cooldown wording.\n * 400s are never rate limits (context-window errors mention fallbacks).\n */\nexport function isRateLimitedResponse(status: number, bodyText: string): boolean {\n if (POOL_MISSING_PATTERN.test(bodyText)) return false;\n if (RATE_LIMIT_STATUSES.has(status)) return true;\n return status >= 500 && RATE_LIMIT_BODY_PATTERN.test(bodyText);\n}\n\n/**\n * Parse an HTTP `Retry-After` value (RFC 9110: delta-seconds or HTTP-date).\n * Returns milliseconds to wait, or null when absent/invalid.\n */\nexport function parseRetryAfterMs(value: string | null | undefined, nowMs: number = Date.now()): number | null {\n if (value === null || value === undefined) return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.round(Number(trimmed) * 1000));\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return null;\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.max(0, dateMs - nowMs));\n}\n\n/** Parse LiteLLM's `Try again in N seconds` hint from an error body. */\nexport function parseTryAgainHintMs(bodyText: string): number | null {\n const match = bodyText.match(TRY_AGAIN_PATTERN);\n if (!match) return null;\n const amount = Number(match[1]);\n if (!Number.isFinite(amount)) return null;\n const unit = match[2].toLowerCase();\n let ms: number;\n if (unit.startsWith(\"ms\") || unit.startsWith(\"milli\")) ms = amount;\n else if (unit.startsWith(\"min\")) ms = amount * 60_000;\n else ms = amount * 1000;\n return Math.min(MAX_RECORDED_BACKOFF_MS, Math.round(ms));\n}\n\n/** Server-provided wait: `Retry-After` header first, then the body hint. */\nexport function serverRetryHintMs(\n retryAfterHeader: string | null | undefined,\n bodyText: string,\n nowMs: number = Date.now()\n): number | null {\n return parseRetryAfterMs(retryAfterHeader, nowMs) ?? parseTryAgainHintMs(bodyText);\n}\n\n/**\n * Exponential backoff with full jitter: uniform in [0, min(max, base * 2^(n-1))].\n * `attempt` is 1-based (the number of consecutive rate-limit responses).\n */\nexport function computeFullJitterBackoffMs(\n attempt: number,\n baseMs: number,\n maxMs: number,\n random: () => number = Math.random\n): number {\n const exponent = Math.max(0, Math.min(30, attempt - 1));\n const ceiling = Math.min(maxMs, baseMs * 2 ** exponent);\n return Math.floor(random() * ceiling);\n}\n\n/**\n * Delay before the next attempt after a rate-limit response. A server hint\n * is a floor (never call earlier than asked); jitter is added on top of the\n * exponential term so synchronized callers spread out.\n */\nexport function computeRateLimitDelayMs(\n attempt: number,\n settings: Pick<LocalLlmRateLimitSettings, \"backoffBaseMs\" | \"backoffMaxMs\">,\n serverHintMs: number | null,\n random: () => number = Math.random\n): number {\n const jittered = computeFullJitterBackoffMs(attempt, settings.backoffBaseMs, settings.backoffMaxMs, random);\n return serverHintMs === null ? jittered : Math.max(serverHintMs, jittered);\n}\n\ntype Waiter = { highPriority: boolean; grant: () => void };\n\n/** Priority semaphore; finite caps above one protect recall capacity and queued background progress. */\nexport class LocalLlmConcurrencyLimiter {\n private active = 0;\n private activeBackground = 0;\n private max: number;\n private readonly waiters: Waiter[] = [];\n\n constructor(max: number) {\n this.max = max;\n }\n\n setMax(max: number): void {\n this.max = max;\n this.pump();\n }\n\n get inFlight(): number {\n return this.active;\n }\n\n get queued(): number {\n return this.waiters.length;\n }\n\n /**\n * Wait for a slot. Resolves to a release function, or null when the\n * signal aborts first. `max <= 0` means unlimited.\n */\n acquire(\n options: { highPriority?: boolean; signal?: AbortSignal; timeoutMs?: number } = {}\n ): Promise<(() => void) | null> {\n const { signal, timeoutMs } = options;\n const highPriority = options.highPriority === true;\n if (signal?.aborted) return Promise.resolve(null);\n if (\n this.canAcquire(highPriority) &&\n (this.waiters.length === 0 || (highPriority && !this.waiters[0].highPriority))\n ) {\n this.active += 1;\n if (!highPriority) this.activeBackground += 1;\n return Promise.resolve(this.releaser(highPriority));\n }\n if (timeoutMs !== undefined && timeoutMs <= 0) return Promise.resolve(null);\n return new Promise((resolve) => {\n let timer: NodeJS.Timeout | undefined;\n const waiter: Waiter = {\n highPriority,\n grant: () => {\n signal?.removeEventListener(\"abort\", onAbort);\n if (timer) clearTimeout(timer);\n resolve(this.releaser(highPriority));\n },\n };\n const onAbort = (): void => {\n const index = this.waiters.indexOf(waiter);\n if (index >= 0) this.waiters.splice(index, 1);\n signal?.removeEventListener(\"abort\", onAbort);\n if (timer) clearTimeout(timer);\n resolve(null);\n };\n if (waiter.highPriority) {\n const firstLow = this.waiters.findIndex((w) => !w.highPriority);\n if (firstLow < 0) this.waiters.push(waiter);\n else this.waiters.splice(firstLow, 0, waiter);\n } else {\n this.waiters.push(waiter);\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (timeoutMs !== undefined) timer = setTimeout(onAbort, timeoutMs);\n });\n }\n\n private canAcquire(highPriority: boolean): boolean {\n const backgroundWaiting = highPriority && this.max > 1 && this.activeBackground === 0 &&\n this.waiters.some((waiter) => !waiter.highPriority);\n return this.max <= 0 || (\n this.active < this.max &&\n (highPriority || this.max === 1 || this.activeBackground < this.max - 1) &&\n (!highPriority || !backgroundWaiting || this.active < this.max - 1)\n );\n }\n\n private releaser(highPriority: boolean): () => void {\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.active -= 1;\n if (!highPriority) this.activeBackground -= 1;\n this.pump();\n };\n }\n\n private pump(): void {\n while (this.waiters.length > 0) {\n // An ineligible critical head must not strand the background permit.\n const criticalAllowed = this.canAcquire(true);\n const backgroundAllowed = this.canAcquire(false);\n const index = this.waiters.findIndex((waiter) => waiter.highPriority ? criticalAllowed : backgroundAllowed);\n if (index < 0) break;\n const next = this.waiters.splice(index, 1)[0];\n this.active += 1;\n if (!next.highPriority) this.activeBackground += 1;\n next.grant();\n }\n }\n}\n\ninterface EndpointBackoffState {\n untilMs: number;\n consecutiveRateLimits: number;\n}\n\ninterface RateLimitGlobalState {\n limiter: LocalLlmConcurrencyLimiter;\n endpoints: Map<string, EndpointBackoffState>;\n}\n\ndeclare global {\n // Shared across duplicated module copies in bundled output.\n var __remnicLocalLlmRateLimitState: RateLimitGlobalState | undefined;\n}\n\nfunction globalState(): RateLimitGlobalState {\n globalThis.__remnicLocalLlmRateLimitState ??= {\n limiter: new LocalLlmConcurrencyLimiter(DEFAULT_MAX_CONCURRENCY),\n endpoints: new Map(),\n };\n return globalThis.__remnicLocalLlmRateLimitState;\n}\n\n/** Process-wide limiter, resized to the caller's configured cap. */\nexport function getLocalLlmConcurrencyLimiter(maxConcurrency: number): LocalLlmConcurrencyLimiter {\n const { limiter } = globalState();\n limiter.setMax(maxConcurrency);\n return limiter;\n}\n\n/** Milliseconds until `endpoint` may be called again (0 when clear). */\nexport function endpointBackoffRemainingMs(endpoint: string, nowMs: number = Date.now()): number {\n const entry = globalState().endpoints.get(endpoint);\n return entry ? Math.max(0, entry.untilMs - nowMs) : 0;\n}\n\n/**\n * Record a rate-limit response for `endpoint`. Returns the consecutive\n * rate-limit count (1-based) to feed the backoff exponent.\n */\nexport function noteEndpointRateLimited(endpoint: string): number {\n const { endpoints } = globalState();\n const entry = endpoints.get(endpoint) ?? { untilMs: 0, consecutiveRateLimits: 0 };\n entry.consecutiveRateLimits += 1;\n endpoints.set(endpoint, entry);\n return entry.consecutiveRateLimits;\n}\n\n/** Push the endpoint's \"do not call before\" deadline out to at least `nowMs + delayMs`. */\nexport function extendEndpointBackoff(endpoint: string, delayMs: number, nowMs: number = Date.now()): void {\n const { endpoints } = globalState();\n const entry = endpoints.get(endpoint) ?? { untilMs: 0, consecutiveRateLimits: 0 };\n const bounded = Math.min(MAX_RECORDED_BACKOFF_MS, Math.max(0, delayMs));\n entry.untilMs = Math.max(entry.untilMs, nowMs + bounded);\n endpoints.set(endpoint, entry);\n}\n\n/**\n * Reset the backoff exponent after a non-rate-limited response. An already\n * recorded deadline is left to expire so concurrent callers that saw the\n * 429 still wait it out.\n */\nexport function noteEndpointRecovered(endpoint: string): void {\n const entry = globalState().endpoints.get(endpoint);\n if (entry) entry.consecutiveRateLimits = 0;\n}\n\n/** Test seam: drop all process-wide state. */\nexport function resetLocalLlmRateLimitStateForTests(): void {\n const state = globalState();\n state.endpoints.clear();\n state.limiter = new LocalLlmConcurrencyLimiter(DEFAULT_MAX_CONCURRENCY);\n}\n\nexport type RateLimitAttemptGate =\n | { kind: \"go\"; release: () => void }\n | { kind: \"aborted\" }\n | { kind: \"skip\"; reason: \"backoff\" | \"queue\"; remainingMs: number };\n\nexport type RateLimitDecision =\n | { kind: \"not-rate-limited\" }\n | { kind: \"retry\"; delayMs: number; hintMs: number | null; consecutive: number; retry: number }\n | { kind: \"give-up\"; delayMs: number; retries: number };\n\n/**\n * Per-request driver for the rate-limit policy. The client calls\n * `beforeAttempt` ahead of every HTTP attempt (waits out the shared endpoint\n * deadline, then takes a concurrency slot) and `onResponse` after every\n * non-ok response.\n */\nexport class LocalLlmRateLimitSession {\n private retries = 0;\n private readonly limiter: LocalLlmConcurrencyLimiter;\n readonly settings: LocalLlmRateLimitSettings;\n\n /**\n * @param waitBudgetMs the caller's per-attempt time budget. Waiting for the\n * endpoint backoff or a concurrency slot never exceeds it, and a backoff\n * longer than it skips the request instead (fail open to the caller).\n */\n constructor(\n private readonly endpoint: string,\n settings: LocalLlmRateLimitSettings,\n private readonly highPriority: boolean,\n private readonly waitBudgetMs: number = settings.backoffMaxMs\n ) {\n this.settings = settings;\n this.limiter = getLocalLlmConcurrencyLimiter(settings.maxConcurrency);\n }\n\n get retryCount(): number {\n return this.retries;\n }\n\n async beforeAttempt(signal?: AbortSignal): Promise<RateLimitAttemptGate> {\n const deadlineMs = Date.now() + Math.max(0, this.waitBudgetMs);\n // Recheck the shared deadline after every async wait: another attempt may\n // have recorded or extended a cooldown while this one slept or queued.\n for (;;) {\n const remainingMs = endpointBackoffRemainingMs(this.endpoint);\n if (remainingMs > 0) {\n if (remainingMs > Math.min(this.settings.backoffMaxMs, deadlineMs - Date.now())) {\n return { kind: \"skip\", reason: \"backoff\", remainingMs };\n }\n if (!(await waitWithSignal(remainingMs, signal))) return { kind: \"aborted\" };\n continue;\n }\n const release = await this.limiter.acquire({\n highPriority: this.highPriority,\n signal,\n timeoutMs: deadlineMs - Date.now(),\n });\n if (!release) return signal?.aborted ? { kind: \"aborted\" } : { kind: \"skip\", reason: \"queue\", remainingMs: 0 };\n if (endpointBackoffRemainingMs(this.endpoint) > 0) {\n release();\n continue;\n }\n return { kind: \"go\", release };\n }\n }\n\n onSuccess(): void {\n noteEndpointRecovered(this.endpoint);\n }\n\n onResponse(status: number, retryAfterHeader: string | null | undefined, bodyText: string): RateLimitDecision {\n if (!isRateLimitedResponse(status, bodyText)) {\n noteEndpointRecovered(this.endpoint);\n return { kind: \"not-rate-limited\" };\n }\n const consecutive = noteEndpointRateLimited(this.endpoint);\n const hintMs = serverRetryHintMs(retryAfterHeader, bodyText);\n const delayMs = computeRateLimitDelayMs(consecutive, this.settings, hintMs);\n extendEndpointBackoff(this.endpoint, delayMs);\n if (this.retries >= this.settings.retryCount || delayMs > Math.min(this.settings.backoffMaxMs, this.waitBudgetMs)) {\n return { kind: \"give-up\", delayMs, retries: this.retries };\n }\n this.retries += 1;\n return { kind: \"retry\", delayMs, hintMs, consecutive, retry: this.retries };\n }\n}\n\nfunction waitWithSignal(ms: number, signal?: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve(false);\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";AAwBO,IAAM,sBAA2C,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAE/E,IAAM,0BAA0B;AAChC,IAAM,oBAAoB;AAGnB,IAAM,0BAA0B,KAAK;AAErC,IAAM,iCAAiC;AACvC,IAAM,qCAAqC;AAC3C,IAAM,oCAAoC;AAC1C,IAAM,0BAA0B;AAUvC,SAAS,eAAe,OAA2B,UAA0B;AAC3E,MAAI,UAAU,UAAa,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,EAAG,QAAO;AACxE,SAAO,KAAK,MAAM,KAAK;AACzB;AAEO,SAAS,yBAAyB,QAKX;AAC5B,QAAM,gBAAgB,KAAK;AAAA,IACzB;AAAA,IACA,eAAe,OAAO,gCAAgC,kCAAkC;AAAA,EAC1F;AACA,QAAM,eAAe,KAAK;AAAA,IACxB;AAAA,IACA,eAAe,OAAO,+BAA+B,iCAAiC;AAAA,EACxF;AACA,SAAO;AAAA,IACL,Y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QAAQ,SAAS;AACnB,cAAQ,KAAK;AACb;AAAA,IACF;AACA,UAAM,UAAU,MAAY;AAC1B,mBAAa,KAAK;AAClB,cAAQ,KAAK;AAAA,IACf;AACA,UAAM,QAAQ,WAAW,MAAM;AAC7B,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ,IAAI;AAAA,IACd,GAAG,EAAE;AACL,YAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,EAC3D,CAAC;AACH;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
LocalLlmClient
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-5JZ5CYTR.js";
|
|
4
4
|
import {
|
|
5
5
|
FallbackLlmClient
|
|
6
6
|
} from "./chunk-MMRTPH3J.js";
|
|
@@ -4497,4 +4497,4 @@ export {
|
|
|
4497
4497
|
parseSupportPassportModelJob,
|
|
4498
4498
|
SupportPassportModelBridge
|
|
4499
4499
|
};
|
|
4500
|
-
//# sourceMappingURL=chunk-
|
|
4500
|
+
//# sourceMappingURL=chunk-B57CAZPI.js.map
|
|
@@ -154,6 +154,12 @@ var SingleFlightProbe = class {
|
|
|
154
154
|
});
|
|
155
155
|
}
|
|
156
156
|
};
|
|
157
|
+
function buildLocalLlmRoutingHeaders(operation, priority) {
|
|
158
|
+
const headers = { "Content-Type": "application/json" };
|
|
159
|
+
if (operation !== "unspecified") headers["X-Remnic-Operation"] = operation;
|
|
160
|
+
if (priority) headers["X-Remnic-Priority"] = priority;
|
|
161
|
+
return headers;
|
|
162
|
+
}
|
|
157
163
|
|
|
158
164
|
export {
|
|
159
165
|
isAbortError,
|
|
@@ -165,6 +171,7 @@ export {
|
|
|
165
171
|
describeFetchFailure,
|
|
166
172
|
resolveUnavailableVerdict,
|
|
167
173
|
probeFetch,
|
|
168
|
-
SingleFlightProbe
|
|
174
|
+
SingleFlightProbe,
|
|
175
|
+
buildLocalLlmRoutingHeaders
|
|
169
176
|
};
|
|
170
|
-
//# sourceMappingURL=chunk-
|
|
177
|
+
//# sourceMappingURL=chunk-BDKLKX43.js.map
|