@remnic/core 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/abort-error.d.ts +32 -0
  2. package/dist/abort-error.js +11 -0
  3. package/dist/access-cli.js +41 -40
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +3 -2
  6. package/dist/access-http.js +11 -11
  7. package/dist/access-mcp.d.ts +3 -2
  8. package/dist/access-mcp.js +7 -7
  9. package/dist/access-schema.d.ts +16 -16
  10. package/dist/access-service-HmO1Trrx.d.ts +732 -0
  11. package/dist/access-service.d.ts +11 -658
  12. package/dist/access-service.js +9 -9
  13. package/dist/bootstrap.d.ts +1 -1
  14. package/dist/briefing.js +6 -6
  15. package/dist/calibration.js +3 -3
  16. package/dist/causal-consolidation.js +10 -10
  17. package/dist/{chunk-PMB3WGDL.js → chunk-37UIFYWO.js} +64 -3
  18. package/dist/chunk-37UIFYWO.js.map +1 -0
  19. package/dist/{chunk-X4WESCKA.js → chunk-3QHL5ABG.js} +5 -5
  20. package/dist/{chunk-2VFW5K5U.js → chunk-3SV6CQHO.js} +10 -8
  21. package/dist/chunk-3SV6CQHO.js.map +1 -0
  22. package/dist/{chunk-U2IQTSBY.js → chunk-3WHVNEN7.js} +1 -1
  23. package/dist/chunk-3WHVNEN7.js.map +1 -0
  24. package/dist/{chunk-QKAH5B6E.js → chunk-44ICJRF3.js} +97 -9
  25. package/dist/chunk-44ICJRF3.js.map +1 -0
  26. package/dist/{chunk-S4LX5EBI.js → chunk-47UU5PU2.js} +48 -9
  27. package/dist/chunk-47UU5PU2.js.map +1 -0
  28. package/dist/{chunk-ECKDIK5F.js → chunk-4LACOVZX.js} +2 -2
  29. package/dist/{chunk-AYPYCLR7.js → chunk-6LX5ORAS.js} +2 -2
  30. package/dist/{chunk-GJQPH5G3.js → chunk-6UJ47TVX.js} +2 -2
  31. package/dist/{chunk-KWP7T3DP.js → chunk-7ECD5ATE.js} +2 -2
  32. package/dist/{chunk-74JR4N5J.js → chunk-7WQ6SLIE.js} +2 -2
  33. package/dist/{chunk-7PA4OZEU.js → chunk-BLKTA7MM.js} +6 -14
  34. package/dist/chunk-BLKTA7MM.js.map +1 -0
  35. package/dist/{chunk-XMGSSBFX.js → chunk-DEPL3635.js} +172 -100
  36. package/dist/chunk-DEPL3635.js.map +1 -0
  37. package/dist/{chunk-JROGC36Y.js → chunk-DHHP2Z4X.js} +2 -2
  38. package/dist/{chunk-BKQJBXXX.js → chunk-GGD5W7TB.js} +2 -2
  39. package/dist/chunk-GGD5W7TB.js.map +1 -0
  40. package/dist/{chunk-POMSFKTB.js → chunk-GV6NLQ4X.js} +14 -14
  41. package/dist/{chunk-AAI7JARD.js → chunk-HMDCOMYU.js} +8 -11
  42. package/dist/chunk-HMDCOMYU.js.map +1 -0
  43. package/dist/{chunk-POBPGDWI.js → chunk-ITRLGI2T.js} +2 -2
  44. package/dist/{chunk-MYQWXITD.js → chunk-JIU55F3X.js} +2 -2
  45. package/dist/{chunk-UPMD5XND.js → chunk-JL2PU6AI.js} +16 -5
  46. package/dist/chunk-JL2PU6AI.js.map +1 -0
  47. package/dist/{chunk-OJFGVJS6.js → chunk-MBJHSA7F.js} +65 -9
  48. package/dist/chunk-MBJHSA7F.js.map +1 -0
  49. package/dist/{chunk-V7XCAHIB.js → chunk-MVTHXUBX.js} +46 -23
  50. package/dist/chunk-MVTHXUBX.js.map +1 -0
  51. package/dist/{chunk-BTY5RRRF.js → chunk-N42IWANG.js} +5 -5
  52. package/dist/{chunk-NSB3WSYS.js → chunk-NQEVYWX6.js} +74 -3
  53. package/dist/chunk-NQEVYWX6.js.map +1 -0
  54. package/dist/chunk-OIT5QGG4.js +80 -0
  55. package/dist/chunk-OIT5QGG4.js.map +1 -0
  56. package/dist/chunk-PVGDJXVK.js +21 -0
  57. package/dist/chunk-PVGDJXVK.js.map +1 -0
  58. package/dist/{chunk-RCICHSHL.js → chunk-SYUK3VLY.js} +2 -2
  59. package/dist/{chunk-YFYL2SIJ.js → chunk-WBSAYXVI.js} +127 -39
  60. package/dist/chunk-WBSAYXVI.js.map +1 -0
  61. package/dist/{chunk-KEG4GNGI.js → chunk-XZ2TIKGC.js} +38 -8
  62. package/dist/chunk-XZ2TIKGC.js.map +1 -0
  63. package/dist/chunk-Y4FHOFJ2.js +140 -0
  64. package/dist/chunk-Y4FHOFJ2.js.map +1 -0
  65. package/dist/chunk-YNB73F22.js +137 -0
  66. package/dist/chunk-YNB73F22.js.map +1 -0
  67. package/dist/{chunk-HITJFT7E.js → chunk-ZVBB3T7V.js} +10 -5
  68. package/dist/chunk-ZVBB3T7V.js.map +1 -0
  69. package/dist/{cli-DwIBnp2g.d.ts → cli-BneVIEvh.d.ts} +2 -2
  70. package/dist/cli.d.ts +4 -3
  71. package/dist/cli.js +25 -24
  72. package/dist/config.js +1 -1
  73. package/dist/contradiction-review-WIUBAR52.js +21 -0
  74. package/dist/contradiction-review-WIUBAR52.js.map +1 -0
  75. package/dist/contradiction-scan-GR33PONM.js +376 -0
  76. package/dist/contradiction-scan-GR33PONM.js.map +1 -0
  77. package/dist/direct-answer-wiring.d.ts +77 -0
  78. package/dist/direct-answer-wiring.js +75 -0
  79. package/dist/direct-answer-wiring.js.map +1 -0
  80. package/dist/direct-answer.d.ts +106 -0
  81. package/dist/direct-answer.js +10 -0
  82. package/dist/direct-answer.js.map +1 -0
  83. package/dist/{engine-X7X3AAG3.js → engine-5TIQBYZR.js} +7 -7
  84. package/dist/engine-5TIQBYZR.js.map +1 -0
  85. package/dist/entity-retrieval.js +6 -6
  86. package/dist/explicit-capture.d.ts +1 -1
  87. package/dist/extraction.js +6 -6
  88. package/dist/fallback-llm.d.ts +11 -2
  89. package/dist/fallback-llm.js +3 -3
  90. package/dist/harmonic-retrieval.js +2 -1
  91. package/dist/index.d.ts +10 -124
  92. package/dist/index.js +74 -137
  93. package/dist/index.js.map +1 -1
  94. package/dist/intent.js +1 -1
  95. package/dist/local-llm.d.ts +10 -3
  96. package/dist/local-llm.js +1 -1
  97. package/dist/operator-toolkit.js +12 -11
  98. package/dist/{orchestrator-B9kwlCep.d.ts → orchestrator-DRYA6_lW.d.ts} +21 -2
  99. package/dist/orchestrator.d.ts +1 -1
  100. package/dist/orchestrator.js +36 -35
  101. package/dist/qmd.js +2 -1
  102. package/dist/recall-state.d.ts +28 -1
  103. package/dist/recall-state.js +1 -1
  104. package/dist/resolution-QBTDHTG7.js +100 -0
  105. package/dist/resolution-QBTDHTG7.js.map +1 -0
  106. package/dist/resolve-provider-secret.d.ts +24 -1
  107. package/dist/resolve-provider-secret.js +3 -1
  108. package/dist/resume-bundles.js +3 -3
  109. package/dist/schemas.d.ts +14 -14
  110. package/dist/semantic-consolidation.js +6 -6
  111. package/dist/semantic-rule-promotion.js +6 -6
  112. package/dist/semantic-rule-verifier.js +6 -6
  113. package/dist/storage.js +5 -5
  114. package/dist/summarizer.js +5 -5
  115. package/dist/types-DJhqDJUV.d.ts +50 -0
  116. package/dist/types.d.ts +34 -2
  117. package/dist/types.js +1 -1
  118. package/dist/verified-recall.js +6 -6
  119. package/package.json +1 -1
  120. package/dist/chunk-2VFW5K5U.js.map +0 -1
  121. package/dist/chunk-7PA4OZEU.js.map +0 -1
  122. package/dist/chunk-AAI7JARD.js.map +0 -1
  123. package/dist/chunk-BKQJBXXX.js.map +0 -1
  124. package/dist/chunk-HITJFT7E.js.map +0 -1
  125. package/dist/chunk-KEG4GNGI.js.map +0 -1
  126. package/dist/chunk-NSB3WSYS.js.map +0 -1
  127. package/dist/chunk-OJFGVJS6.js.map +0 -1
  128. package/dist/chunk-PMB3WGDL.js.map +0 -1
  129. package/dist/chunk-QKAH5B6E.js.map +0 -1
  130. package/dist/chunk-S4LX5EBI.js.map +0 -1
  131. package/dist/chunk-U2IQTSBY.js.map +0 -1
  132. package/dist/chunk-UPMD5XND.js.map +0 -1
  133. package/dist/chunk-V7XCAHIB.js.map +0 -1
  134. package/dist/chunk-XMGSSBFX.js.map +0 -1
  135. package/dist/chunk-YFYL2SIJ.js.map +0 -1
  136. /package/dist/{engine-X7X3AAG3.js.map → abort-error.js.map} +0 -0
  137. /package/dist/{chunk-X4WESCKA.js.map → chunk-3QHL5ABG.js.map} +0 -0
  138. /package/dist/{chunk-ECKDIK5F.js.map → chunk-4LACOVZX.js.map} +0 -0
  139. /package/dist/{chunk-AYPYCLR7.js.map → chunk-6LX5ORAS.js.map} +0 -0
  140. /package/dist/{chunk-GJQPH5G3.js.map → chunk-6UJ47TVX.js.map} +0 -0
  141. /package/dist/{chunk-KWP7T3DP.js.map → chunk-7ECD5ATE.js.map} +0 -0
  142. /package/dist/{chunk-74JR4N5J.js.map → chunk-7WQ6SLIE.js.map} +0 -0
  143. /package/dist/{chunk-JROGC36Y.js.map → chunk-DHHP2Z4X.js.map} +0 -0
  144. /package/dist/{chunk-POMSFKTB.js.map → chunk-GV6NLQ4X.js.map} +0 -0
  145. /package/dist/{chunk-POBPGDWI.js.map → chunk-ITRLGI2T.js.map} +0 -0
  146. /package/dist/{chunk-MYQWXITD.js.map → chunk-JIU55F3X.js.map} +0 -0
  147. /package/dist/{chunk-BTY5RRRF.js.map → chunk-N42IWANG.js.map} +0 -0
  148. /package/dist/{chunk-RCICHSHL.js.map → chunk-SYUK3VLY.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-POMSFKTB.js";
3
+ } from "./chunk-GV6NLQ4X.js";
4
4
  import {
5
5
  parseContinuityImprovementLoops,
6
6
  parseContinuityIncident
@@ -1860,4 +1860,4 @@ export {
1860
1860
  defaultTierMigrationCycleBudget,
1861
1861
  CompoundingEngine
1862
1862
  };
1863
- //# sourceMappingURL=chunk-JROGC36Y.js.map
1863
+ //# sourceMappingURL=chunk-DHHP2Z4X.js.map
@@ -20,7 +20,7 @@ var ENTITY_PATTERNS = [
20
20
  { re: /\b(model|llm|qmd|embedding|retrieval|memory)\b/i, entityType: "ai" },
21
21
  { re: /\b(doc|readme|docs|changelog)\b/i, entityType: "docs" }
22
22
  ];
23
- var TASK_INITIATION_RE = /\b(ship(?:ping|ped)?|deploy(?:ing|ed)?|release|publish|open(?:ing)?\s+(?:a\s+)?(?:pr|pull\s+request)|merge(?:ing)?\s+(?:the\s+)?(?:pr|pull\s+request)|run\s+(?:the\s+)?tests?|start(?:ing)?\s+(?:work|on|the)|kick\s+off|implement(?:ing|ed)?|let's\s+|going\s+to\s+(?:ship|deploy|release|open|run|merge)|need\s+to\s+(?:ship|deploy|run|open|merge|test)|fix(?:ing|ed)?\s+(?:the\s+)?(?:bug|build)|patch(?:ing|ed)?|build(?:ing)?\s+(?:and\s+)?(?:ship|deploy))\b/i;
23
+ var TASK_INITIATION_RE = /\b(ship(?:ping|ped)?|deploy(?:ing|ed)?|release|publish|open(?:ing)?\s+(?:a\s+)?(?:pr|pull\s+request)|merge(?:ing)?\s+(?:the\s+)?(?:pr|pull\s+request)|run\s+(?:the\s+)?tests?|start(?:ing)?\s+(?:work|on|the)|kick\s+off|implement(?:ing|ed)?|let's\s+(?:ship|deploy|release|publish|open|run|merge|implement|fix|patch|build|start|do|get|put|wire|hook|land|roll)\b|going\s+to\s+(?:ship|deploy|release|open|run|merge)|need\s+to\s+(?:ship|deploy|run|open|merge|test)|fix(?:ing|ed)?\s+(?:(?:the|a)\s+)?(?:\w+\s+){0,4}(?:bug|build)\b|patch(?:ing|ed)?|build(?:ing)?\s+(?:and\s+)?(?:ship|deploy))\b/i;
24
24
  function normalizeTextInput(input) {
25
25
  return typeof input === "string" ? input : "";
26
26
  }
@@ -102,4 +102,4 @@ export {
102
102
  planRecallMode,
103
103
  hasBroadGraphIntent
104
104
  };
105
- //# sourceMappingURL=chunk-BKQJBXXX.js.map
105
+ //# sourceMappingURL=chunk-GGD5W7TB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/intent.ts"],"sourcesContent":["import type { MemoryIntent, RecallPlanMode } from \"./types.js\";\n\nconst GOAL_PATTERNS: Array<{ re: RegExp; goal: string }> = [\n { re: /\\b(debug(?:s|ged|ging)?|fix(?:es|ed|ing)?|error(?:s)?|incident(?:s)?|outage(?:s)?|failure(?:s)?)\\b/i, goal: \"stabilize\" },\n { re: /\\b(deploy(?:s|ed|ing)?|release(?:s|d|ing)?|ship(?:s|ped|ping)?|publish(?:es|ed|ing)?)\\b/i, goal: \"release\" },\n { re: /\\b(plan(?:s|ned|ning)?|roadmap(?:s)?|strateg(?:y|ies)|design(?:s|ed|ing)?)\\b/i, goal: \"plan\" },\n { re: /\\b(review(?:s|ed|ing)?|audit(?:s|ed|ing)?|security|hardening)\\b/i, goal: \"review\" },\n { re: /\\b(sales|deal|customer|client|prospect)\\b/i, goal: \"close_deal\" },\n];\n\nconst ACTION_PATTERNS: Array<{ re: RegExp; action: string }> = [\n { re: /\\b(review(?:s|ed|ing)?|audit(?:s|ed|ing)?|inspect(?:s|ed|ing)?|check(?:s|ed|ing)?)\\b/i, action: \"review\" },\n { re: /\\b(plan(?:s|ned|ning)?|design(?:s|ed|ing)?|brainstorm(?:s|ed|ing)?|spec(?:s)?)\\b/i, action: \"plan\" },\n { re: /\\b(implement(?:s|ed|ing)?|build(?:s|ing)?|built|code(?:s|d|ing)?|patch(?:es|ed|ing)?|fix(?:es|ed|ing)?)\\b/i, action: \"execute\" },\n { re: /\\b(summariz(?:e|es|ed|ing)|recap(?:s|ped|ping)?|what happened|timeline)\\b/i, action: \"summarize\" },\n { re: /\\b(decid(?:e|es|ed|ing)|decision(?:s)?|cho(?:ose|oses|osing)|chose|chosen)\\b/i, action: \"decide\" },\n];\n\nconst ENTITY_PATTERNS: Array<{ re: RegExp; entityType: string }> = [\n { re: /\\b(pr|pull request|branch|repo|github|ci|workflow)\\b/i, entityType: \"repo\" },\n { re: /\\b(discord|slack|channel|gateway|agent)\\b/i, entityType: \"ops\" },\n { re: /\\b(customer|client|deal|lead|account)\\b/i, entityType: \"client\" },\n { re: /\\b(model|llm|qmd|embedding|retrieval|memory)\\b/i, entityType: \"ai\" },\n { re: /\\b(doc|readme|docs|changelog)\\b/i, entityType: \"docs\" },\n];\n\n/** User/agent is starting a hands-on task (issue #519 procedure recall gate). */\nconst TASK_INITIATION_RE =\n /\\b(ship(?:ping|ped)?|deploy(?:ing|ed)?|release|publish|open(?:ing)?\\s+(?:a\\s+)?(?:pr|pull\\s+request)|merge(?:ing)?\\s+(?:the\\s+)?(?:pr|pull\\s+request)|run\\s+(?:the\\s+)?tests?|start(?:ing)?\\s+(?:work|on|the)|kick\\s+off|implement(?:ing|ed)?|let's\\s+(?:ship|deploy|release|publish|open|run|merge|implement|fix|patch|build|start|do|get|put|wire|hook|land|roll)\\b|going\\s+to\\s+(?:ship|deploy|release|open|run|merge)|need\\s+to\\s+(?:ship|deploy|run|open|merge|test)|fix(?:ing|ed)?\\s+(?:(?:the|a)\\s+)?(?:\\w+\\s+){0,4}(?:bug|build)\\b|patch(?:ing|ed)?|build(?:ing)?\\s+(?:and\\s+)?(?:ship|deploy))\\b/i;\n\nfunction normalizeTextInput(input: unknown): string {\n return typeof input === \"string\" ? input : \"\";\n}\n\nexport function inferIntentFromText(text: string): MemoryIntent {\n const safeText = normalizeTextInput(text);\n const goal = GOAL_PATTERNS.find((p) => p.re.test(safeText))?.goal ?? \"unknown\";\n const actionType = ACTION_PATTERNS.find((p) => p.re.test(safeText))?.action ?? \"unknown\";\n const entityTypes = Array.from(\n new Set(ENTITY_PATTERNS.filter((p) => p.re.test(safeText)).map((p) => p.entityType)),\n );\n const taskInitiation = TASK_INITIATION_RE.test(safeText);\n\n return {\n goal,\n actionType,\n entityTypes,\n taskInitiation,\n };\n}\n\nexport function isTaskInitiationIntent(intent: MemoryIntent): boolean {\n return intent.taskInitiation === true;\n}\n\nexport function intentCompatibilityScore(queryIntent: MemoryIntent, memoryIntent: MemoryIntent): number {\n const queryHasSignal =\n queryIntent.goal !== \"unknown\" ||\n queryIntent.actionType !== \"unknown\" ||\n queryIntent.entityTypes.length > 0;\n const memoryHasSignal =\n memoryIntent.goal !== \"unknown\" ||\n memoryIntent.actionType !== \"unknown\" ||\n memoryIntent.entityTypes.length > 0;\n if (!queryHasSignal || !memoryHasSignal) return 0;\n\n let score = 0;\n if (\n queryIntent.goal !== \"unknown\" &&\n memoryIntent.goal !== \"unknown\" &&\n queryIntent.goal === memoryIntent.goal\n ) {\n score += 0.5;\n }\n if (\n queryIntent.actionType !== \"unknown\" &&\n memoryIntent.actionType !== \"unknown\" &&\n queryIntent.actionType === memoryIntent.actionType\n ) {\n score += 0.3;\n }\n\n const overlap = queryIntent.entityTypes.filter((et) => memoryIntent.entityTypes.includes(et)).length;\n if (overlap > 0) {\n const denom = Math.max(queryIntent.entityTypes.length, memoryIntent.entityTypes.length, 1);\n score += 0.2 * (overlap / denom);\n }\n\n return Math.max(0, Math.min(1, score));\n}\n\nexport function planRecallMode(prompt: string): RecallPlanMode {\n const p = normalizeTextInput(prompt).trim();\n let ackCandidate = p;\n while (ackCandidate.length > 0) {\n const ch = ackCandidate.charCodeAt(ackCandidate.length - 1);\n const isDigit = ch >= 48 && ch <= 57;\n const isUpper = ch >= 65 && ch <= 90;\n const isLower = ch >= 97 && ch <= 122;\n // Strip any trailing non-alphanumeric noise (punctuation/emojis/symbols).\n if (isDigit || isUpper || isLower) break;\n ackCandidate = ackCandidate.slice(0, -1);\n }\n ackCandidate = ackCandidate.trim();\n if (p.length === 0) return \"no_recall\";\n\n if (/\\b(timeline|sequence|history|what happened|chain of events|root cause)\\b/i.test(p)) {\n return \"graph_mode\";\n }\n\n // Reserve no_recall for low-information acknowledgements; avoid broad regressions.\n if (\n p.length <= 18 &&\n /^(ok|okay|kk|thanks|thx|got it|sounds good|yep|yes|nope|no|done|cool|works)$/i.test(ackCandidate)\n ) {\n return \"no_recall\";\n }\n\n // Full recall for prompts that are explicitly memory-seeking or analytical questions.\n if (\n /\\b(previous|earlier|remember|last time|did we|what did we decide|context|summarize|summary|recap|key points|decision)\\b/i.test(p) ||\n /\\?$/.test(p) ||\n /^(what|why|how|when|where|who|which)\\b/i.test(p.toLowerCase())\n ) {\n return \"full\";\n }\n\n // Minimal for short, non-question operational directives to keep latency/tokens down.\n if (\n p.length <= 100 &&\n /^(check|reload|restart|run|verify|show|status|sync|update|open|close|set|enable|disable|fix|patch)\\b/i.test(p)\n ) {\n return \"minimal\";\n }\n\n return \"full\";\n}\n\nexport function hasBroadGraphIntent(prompt: string): boolean {\n const p = normalizeTextInput(prompt).trim().toLowerCase();\n if (!p) return false;\n return /\\b(what changed|how did we get here|why did this happen|what led to|cause chain|dependency chain|regression chain|failure chain)\\b/i.test(\n p,\n );\n}\n"],"mappings":";AAEA,IAAM,gBAAqD;AAAA,EACzD,EAAE,IAAI,uGAAuG,MAAM,YAAY;AAAA,EAC/H,EAAE,IAAI,4FAA4F,MAAM,UAAU;AAAA,EAClH,EAAE,IAAI,iFAAiF,MAAM,OAAO;AAAA,EACpG,EAAE,IAAI,oEAAoE,MAAM,SAAS;AAAA,EACzF,EAAE,IAAI,8CAA8C,MAAM,aAAa;AACzE;AAEA,IAAM,kBAAyD;AAAA,EAC7D,EAAE,IAAI,yFAAyF,QAAQ,SAAS;AAAA,EAChH,EAAE,IAAI,qFAAqF,QAAQ,OAAO;AAAA,EAC1G,EAAE,IAAI,8GAA8G,QAAQ,UAAU;AAAA,EACtI,EAAE,IAAI,8EAA8E,QAAQ,YAAY;AAAA,EACxG,EAAE,IAAI,iFAAiF,QAAQ,SAAS;AAC1G;AAEA,IAAM,kBAA6D;AAAA,EACjE,EAAE,IAAI,yDAAyD,YAAY,OAAO;AAAA,EAClF,EAAE,IAAI,8CAA8C,YAAY,MAAM;AAAA,EACtE,EAAE,IAAI,4CAA4C,YAAY,SAAS;AAAA,EACvE,EAAE,IAAI,mDAAmD,YAAY,KAAK;AAAA,EAC1E,EAAE,IAAI,oCAAoC,YAAY,OAAO;AAC/D;AAGA,IAAM,qBACJ;AAEF,SAAS,mBAAmB,OAAwB;AAClD,SAAO,OAAO,UAAU,W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import {
10
10
  import {
11
11
  createVersion
12
12
  } from "./chunk-6ZH4TU6I.js";
13
+ import {
14
+ normalizeProjectionPreview,
15
+ normalizeProjectionTags
16
+ } from "./chunk-SCU65EZI.js";
17
+ import {
18
+ readProjectedGovernanceRecord,
19
+ readProjectedMemoryBrowse,
20
+ readProjectedMemoryState,
21
+ readProjectedMemoryTimeline
22
+ } from "./chunk-BOUYNNYD.js";
13
23
  import {
14
24
  getCachedEntities,
15
25
  setCachedEntities
@@ -21,15 +31,8 @@ import {
21
31
  toMemoryPathRel
22
32
  } from "./chunk-TP4FZJIZ.js";
23
33
  import {
24
- normalizeProjectionPreview,
25
- normalizeProjectionTags
26
- } from "./chunk-SCU65EZI.js";
27
- import {
28
- readProjectedGovernanceRecord,
29
- readProjectedMemoryBrowse,
30
- readProjectedMemoryState,
31
- readProjectedMemoryTimeline
32
- } from "./chunk-BOUYNNYD.js";
34
+ rotateMarkdownFileToArchive
35
+ } from "./chunk-DM2T26WE.js";
33
36
  import {
34
37
  closeContinuityIncidentRecord,
35
38
  createContinuityIncidentRecord,
@@ -39,9 +42,6 @@ import {
39
42
  serializeContinuityIncident,
40
43
  upsertContinuityLoopInMarkdown
41
44
  } from "./chunk-QSVPYQPG.js";
42
- import {
43
- rotateMarkdownFileToArchive
44
- } from "./chunk-DM2T26WE.js";
45
45
  import {
46
46
  sanitizeMemoryContent
47
47
  } from "./chunk-M62O4P4T.js";
@@ -4317,4 +4317,4 @@ export {
4317
4317
  serializeEntityFile,
4318
4318
  StorageManager
4319
4319
  };
4320
- //# sourceMappingURL=chunk-POMSFKTB.js.map
4320
+ //# sourceMappingURL=chunk-GV6NLQ4X.js.map
@@ -2,6 +2,9 @@ import {
2
2
  resolveCueAnchorStoreDir,
3
3
  validateCueAnchor
4
4
  } from "./chunk-C6QPK5GG.js";
5
+ import {
6
+ throwIfAborted
7
+ } from "./chunk-PVGDJXVK.js";
5
8
  import {
6
9
  resolveAbstractionNodeStoreDir,
7
10
  validateAbstractionNode
@@ -96,13 +99,13 @@ async function readCueAnchors(options) {
96
99
  return anchors;
97
100
  }
98
101
  async function searchHarmonicRetrieval(options) {
99
- throwIfAborted(options.abortSignal);
102
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
100
103
  const queryTokens = new Set(normalizeRecallTokens(options.query, ["what", "which"]));
101
104
  if (queryTokens.size === 0 || options.maxResults <= 0) return [];
102
105
  const nodes = await readAbstractionNodes(options);
103
106
  const candidates = /* @__PURE__ */ new Map();
104
107
  for (const node of nodes) {
105
- throwIfAborted(options.abortSignal);
108
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
106
109
  const { score, matchedFields } = scoreNode(node, queryTokens);
107
110
  if (score <= 0) continue;
108
111
  candidates.set(node.nodeId, {
@@ -114,11 +117,11 @@ async function searchHarmonicRetrieval(options) {
114
117
  });
115
118
  }
116
119
  if (options.anchorsEnabled) {
117
- throwIfAborted(options.abortSignal);
120
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
118
121
  const anchors = await readCueAnchors(options);
119
122
  const nodeIndex = new Map(nodes.map((node) => [node.nodeId, node]));
120
123
  for (const anchor of anchors) {
121
- throwIfAborted(options.abortSignal);
124
+ throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
122
125
  const { score, matchedFields } = scoreAnchor(anchor, queryTokens);
123
126
  if (score <= 0) continue;
124
127
  for (const nodeRef of anchor.nodeRefs) {
@@ -160,14 +163,8 @@ async function searchHarmonicRetrieval(options) {
160
163
  (left, right) => right.score - left.score || right.anchorScore - left.anchorScore || right.node.recordedAt.localeCompare(left.node.recordedAt)
161
164
  ).slice(0, options.maxResults);
162
165
  }
163
- function throwIfAborted(signal) {
164
- if (!signal?.aborted) return;
165
- const err = new Error("harmonic retrieval aborted");
166
- Object.defineProperty(err, "name", { value: "AbortError" });
167
- throw err;
168
- }
169
166
 
170
167
  export {
171
168
  searchHarmonicRetrieval
172
169
  };
173
- //# sourceMappingURL=chunk-AAI7JARD.js.map
170
+ //# sourceMappingURL=chunk-HMDCOMYU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harmonic-retrieval.ts"],"sourcesContent":["import path from \"node:path\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { throwIfAborted } from \"./abort-error.js\";\nimport {\n resolveAbstractionNodeStoreDir,\n validateAbstractionNode,\n type AbstractionNode,\n} from \"./abstraction-nodes.js\";\nimport {\n resolveCueAnchorStoreDir,\n validateCueAnchor,\n type CueAnchor,\n type CueAnchorType,\n} from \"./cue-anchors.js\";\nimport { countRecallTokenOverlap, normalizeRecallTokens } from \"./recall-tokenization.js\";\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 scoreNode(node: AbstractionNode, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const titleMatches = countRecallTokenOverlap(queryTokens, node.title);\n if (titleMatches > 0) {\n score += titleMatches * 3;\n matchedFields.push(\"title\");\n }\n\n const summaryMatches = countRecallTokenOverlap(queryTokens, node.summary);\n if (summaryMatches > 0) {\n score += summaryMatches * 3;\n matchedFields.push(\"summary\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, node.tags?.join(\" \"));\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"tags\");\n }\n\n const entityMatches = countRecallTokenOverlap(queryTokens, node.entityRefs?.join(\" \"));\n if (entityMatches > 0) {\n score += entityMatches * 2;\n matchedFields.push(\"entityRefs\");\n }\n\n const kindMatches = countRecallTokenOverlap(queryTokens, `${node.kind} ${node.abstractionLevel}`);\n if (kindMatches > 0) {\n score += kindMatches;\n matchedFields.push(\"kind\");\n }\n\n return { score, matchedFields };\n}\n\nfunction scoreAnchor(anchor: CueAnchor, queryTokens: Set<string>): { score: number; matchedFields: string[] } {\n const matchedFields: string[] = [];\n let score = 0;\n\n const valueMatches = countRecallTokenOverlap(queryTokens, anchor.anchorValue);\n const normalizedMatches = countRecallTokenOverlap(queryTokens, anchor.normalizedCue);\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 = countRecallTokenOverlap(queryTokens, anchor.anchorType);\n if (typeMatches > 0) {\n score += typeMatches;\n matchedFields.push(\"anchorType\");\n }\n\n const tagMatches = countRecallTokenOverlap(queryTokens, anchor.tags?.join(\" \"));\n if (tagMatches > 0) {\n score += tagMatches * 2;\n matchedFields.push(\"anchorTags\");\n }\n\n return { score, matchedFields };\n}\n\nasync function readAbstractionNodes(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n}): Promise<AbstractionNode[]> {\n const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);\n const files = await listJsonFiles(path.join(rootDir, \"nodes\"));\n const nodes: AbstractionNode[] = [];\n for (const filePath of files) {\n try {\n nodes.push(validateAbstractionNode(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return nodes;\n}\n\nasync 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 listJsonFiles(rootDir);\n const anchors: CueAnchor[] = [];\n for (const filePath of files) {\n try {\n anchors.push(validateCueAnchor(await readJsonFile(filePath)));\n } catch {\n // fail-open: invalid artifacts stay visible via status tooling instead of recall\n }\n }\n return anchors;\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}): 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 const nodes = await readAbstractionNodes(options);\n const candidates = new Map<string, HarmonicCandidate>();\n\n for (const node of nodes) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const { score, matchedFields } = scoreNode(node, 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 const anchors = await readCueAnchors(options);\n const nodeIndex = new Map(nodes.map((node) => [node.nodeId, node]));\n for (const anchor of anchors) {\n throwIfAborted(options.abortSignal, \"harmonic retrieval aborted\");\n const { score, matchedFields } = scoreAnchor(anchor, queryTokens);\n if (score <= 0) continue;\n for (const nodeRef of anchor.nodeRefs) {\n const node = nodeIndex.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((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":";;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AAuCjB,SAAS,UAAU,MAAuB,aAAsE;AAC9G,QAAM,gBAA0B,CAAC;AACjC,MAAI,QAAQ;AAEZ,QAAM,eAAe,wBAAwB,aAAa,KAAK,KAAK;AACpE,MAAI,eAAe,GAAG;AACpB,aAAS,eAAe;AACxB,kBAAc,KAAK,OAAO;AAAA,EAC5B;AAEA,QAAM,iBAAiB,wBAAwB,aAAa,KAAK,OAAO;AACxE,MAAI,iBAAiB,GAAG;AACtB,aAAS,iBAAiB;AAC1B,kBAAc,KAAK,SAAS;AAAA,EAC9B;AAEA,QAAM,aAAa,wBAAwB,aAAa,KAAK,MAAM,KAAK,GAAG,CAAC;AAC5E,MAAI,aAAa,GAAG;AAClB,aAAS,aAAa;AACtB,kBAAc,KAAK,MAAM;AAAA,EAC3B;AAEA,QAAM,gBAAgB,wBAAwB,aAAa,KAAK,YAAY,KAAK,GAAG,CAAC;AACrF,MAAI,gBAAgB,GAAG;AACrB,aAAS,gBAAgB;AACzB,kBAAc,KAAK,YAAY;AAAA,EACjC;AAEA,QAAM,cAAc,wBAAwB,aAAa,GAAG,KAAK,IAAI,IAAI,KAAK,gBAAgB,EAAE;AAChG,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YXW.js";
4
4
  import {
5
5
  StorageManager
6
- } from "./chunk-POMSFKTB.js";
6
+ } from "./chunk-GV6NLQ4X.js";
7
7
 
8
8
  // src/maintenance/memory-governance.ts
9
9
  import path from "path";
@@ -717,4 +717,4 @@ export {
717
717
  listMemoryGovernanceRuns,
718
718
  readMemoryGovernanceRunArtifact
719
719
  };
720
- //# sourceMappingURL=chunk-POBPGDWI.js.map
720
+ //# sourceMappingURL=chunk-ITRLGI2T.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-DT5TVLJE.js";
5
5
  import {
6
6
  StorageManager
7
- } from "./chunk-POMSFKTB.js";
7
+ } from "./chunk-GV6NLQ4X.js";
8
8
  import {
9
9
  getCachedRuleMemories,
10
10
  setCachedRuleMemories
@@ -110,4 +110,4 @@ async function searchVerifiedSemanticRules(options) {
110
110
  export {
111
111
  searchVerifiedSemanticRules
112
112
  };
113
- //# sourceMappingURL=chunk-MYQWXITD.js.map
113
+ //# sourceMappingURL=chunk-JIU55F3X.js.map
@@ -17,6 +17,10 @@ function trimTrailingSlashes(s) {
17
17
  while (end > 0 && s[end - 1] === "/") end--;
18
18
  return s.substring(0, end);
19
19
  }
20
+ var THINKING_COMPATIBLE_BACKENDS = /* @__PURE__ */ new Set([
21
+ "lmstudio",
22
+ "vllm"
23
+ ]);
20
24
  var LOCAL_SERVERS = [
21
25
  {
22
26
  type: "ollama",
@@ -75,9 +79,16 @@ var LocalLlmClient = class _LocalLlmClient {
75
79
  this.modelRegistry = modelRegistry;
76
80
  }
77
81
  /**
78
- * Disable thinking/reasoning mode for models that support it (e.g. Qwen 3.5).
79
- * When enabled, adds chat_template_kwargs to suppress chain-of-thought,
80
- * reducing latency for fast-tier operations.
82
+ * Request thinking/reasoning suppression on the next chat completion.
83
+ *
84
+ * When `true`, the client will inject
85
+ * `chat_template_kwargs: { enable_thinking: false }` into the request
86
+ * body — **but only when the detected backend is known to support it**
87
+ * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict
88
+ * OpenAI-compat backends reject unknown fields with 400; on those the
89
+ * client fails open (thinking runs normally). This is the safe
90
+ * default for Remnic extraction / consolidation: measurable latency
91
+ * win on thinking-capable backends, zero risk on others. Issue #548.
81
92
  */
82
93
  set disableThinking(value) {
83
94
  this._disableThinking = value;
@@ -575,7 +586,7 @@ var LocalLlmClient = class _LocalLlmClient {
575
586
  if (options.responseFormat?.type === "json_schema") {
576
587
  requestBody.response_format = options.responseFormat;
577
588
  }
578
- if (this._disableThinking) {
589
+ if (this._disableThinking && this.detectedType !== null && THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)) {
579
590
  requestBody.chat_template_kwargs = { enable_thinking: false };
580
591
  }
581
592
  const baseUrl = trimTrailingSlashes(
@@ -922,4 +933,4 @@ var LocalLlmClient = class _LocalLlmClient {
922
933
  export {
923
934
  LocalLlmClient
924
935
  };
925
- //# sourceMappingURL=chunk-UPMD5XND.js.map
936
+ //# sourceMappingURL=chunk-JL2PU6AI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport { existsSync, readFileSync } 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\";\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\n/**\n * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)\n *\n * Based on openclaw-tactician's provider detection patterns for consistency.\n * Provides privacy-preserving, cost-effective LLM operations with\n * graceful fallback to cloud providers when local LLM is unavailable.\n */\nexport type LocalLlmType = \"lmstudio\" | \"ollama\" | \"mlx\" | \"vllm\" | \"generic\";\n\n/**\n * Backends known to honor `chat_template_kwargs: { enable_thinking: false }`\n * on OpenAI-compatible `/v1/chat/completions`. LM Studio and vLLM both\n * 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]);\n\ninterface LocalServerConfig {\n type: LocalLlmType;\n defaultPort: number;\n healthEndpoint: string;\n modelsEndpoint: string;\n detectFn: (response: unknown) => boolean;\n}\n\nconst LOCAL_SERVERS: LocalServerConfig[] = [\n {\n type: \"ollama\",\n defaultPort: 11434,\n healthEndpoint: \"/\",\n modelsEndpoint: \"/api/tags\",\n detectFn: (resp) => typeof resp === \"string\" && resp.includes(\"Ollama\"),\n },\n {\n type: \"mlx\",\n defaultPort: 8080,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) =>\n typeof resp === \"object\" &&\n resp !== null &&\n \"data\" in resp &&\n Array.isArray((resp as { data: unknown[] }).data),\n },\n {\n type: \"lmstudio\",\n defaultPort: 1234,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) =>\n typeof resp === \"object\" &&\n resp !== null &&\n \"data\" in resp &&\n Array.isArray((resp as { data: unknown[] }).data),\n },\n {\n type: \"vllm\",\n defaultPort: 8000,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => resp === \"\" || (typeof resp === \"object\" && resp !== null),\n },\n];\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\ninterface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string };\n timeoutMs?: number;\n operation?: string;\n priority?: LocalLlmRequestPriority;\n}\n\ninterface LocalLlmQueuedRequest {\n messages: Array<{ role: string; content: string }>;\n options: LocalLlmChatCompletionOptions;\n priority: LocalLlmRequestPriority;\n enqueuedAtMs: number;\n resolve: (value: LocalLlmChatCompletionResult | null) => void;\n}\n\ninterface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\n\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\ntype LocalLlmBackendState = {\n untilMs: number;\n reason: string;\n};\nexport class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private detectedType: LocalLlmType | null = null;\n private cachedModelInfo: LocalModelInfo | null = null;\n private cachedLmsContext: number | null = null;\n private lastLmsCheck: number = 0;\n private consecutive400s: number = 0;\n private cooldownUntilMs: number = 0;\n private modelRegistry?: ModelRegistry;\n private _disableThinking: boolean = false;\n private readonly requestQueues: Record<LocalLlmRequestPriority, LocalLlmQueuedRequest[]> = {\n \"recall-critical\": [],\n background: [],\n };\n private readonly queueProcessing = new Set<LocalLlmRequestPriority>();\n private queueDrainScheduled: boolean = false;\n private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute\n private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n }\n\n /**\n * Request thinking/reasoning suppression on the next chat completion.\n *\n * When `true`, the client will inject\n * `chat_template_kwargs: { enable_thinking: false }` into the request\n * body — **but only when the detected backend is known to support it**\n * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict\n * OpenAI-compat backends reject unknown fields with 400; on those the\n * client fails open (thinking runs normally). This is the safe\n * default for Remnic extraction / consolidation: measurable latency\n * win on thinking-capable backends, zero risk on others. Issue #548.\n */\n set disableThinking(value: boolean) {\n this._disableThinking = value;\n }\n\n private resolveHomeDir(): string {\n return this.config.localLlmHomeDir || readEnvVar(\"HOME\") || os.homedir();\n }\n\n private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {\n const headers: Record<string, string> = {\n ...base,\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return headers;\n }\n\n private isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n }\n\n /**\n * Set the ModelRegistry for caching detected capabilities\n */\n setModelRegistry(registry: ModelRegistry): void {\n this.modelRegistry = registry;\n }\n\n /**\n * Get the detected server type (null if not detected)\n */\n getDetectedType(): LocalLlmType | null {\n return this.detectedType;\n }\n\n private getBackendKey(): string {\n return trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n ).replace(/\\/v1$/, \"\");\n }\n\n private getGlobalBackendState(): Map<string, LocalLlmBackendState> {\n const globalAny = globalThis as typeof globalThis & {\n [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendState>;\n };\n if (!globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE]) {\n globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = new Map();\n }\n return globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];\n }\n\n private getTrippedBackendState(now: number): LocalLlmBackendState | null {\n const state = this.getGlobalBackendState().get(this.getBackendKey()) ?? null;\n if (!state) return null;\n if (state.untilMs <= now) {\n this.getGlobalBackendState().delete(this.getBackendKey());\n this.lastHealthCheck = 0;\n return null;\n }\n return state;\n }\n\n private markBackendUnavailable(reason: string, durationMs: number): void {\n const normalizedReason = this.normalizeBackendTripReason(reason);\n if (durationMs > 0) {\n const untilMs = Date.now() + durationMs;\n this.getGlobalBackendState().set(this.getBackendKey(), { untilMs, reason: normalizedReason });\n } else {\n this.getGlobalBackendState().delete(this.getBackendKey());\n }\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.warn(\n `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizedReason}`,\n );\n }\n\n private extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n }\n\n private extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = this.extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return this.extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n }\n\n private normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n }\n\n /**\n * Fetch with timeout for health checks\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n ): Promise<{ ok: boolean; data: unknown; status: number | null }> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n });\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { ok: false, data: null, status: response.status };\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return { ok: true, data: await response.json(), status: response.status };\n } else {\n return { ok: true, data: await response.text(), status: response.status };\n }\n } catch (err) {\n clearTimeout(timeout);\n return { ok: false, data: null, status: null };\n }\n }\n\n /**\n * Check if local LLM is available\n * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)\n */\n async checkAvailability(): Promise<boolean> {\n // Cache health check results for 1 minute\n const now = Date.now();\n const trippedState = this.getTrippedBackendState(now);\n if (trippedState) {\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.info(\n `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason})`,\n );\n return false;\n }\n if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {\n return this.isAvailable;\n }\n\n // Normalize URL - replace localhost with 127.0.0.1, remove trailing slashes\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n let sawUnauthorizedProbe = false;\n\n // Try to detect which server type is running\n for (const serverConfig of LOCAL_SERVERS) {\n const healthUrl = `${baseUrl}${serverConfig.healthEndpoint}`;\n log.debug(`checking ${serverConfig.type} at ${healthUrl}`);\n\n const result = await this.fetchWithTimeout(healthUrl);\n if (result.ok && serverConfig.detectFn(result.data)) {\n this.isAvailable = true;\n this.detectedType = serverConfig.type;\n this.lastHealthCheck = now;\n log.info(`detected ${serverConfig.type} at ${baseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n }\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${baseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl);\n if (result.ok) {\n this.isAvailable = true;\n this.detectedType = \"generic\";\n this.lastHealthCheck = now;\n log.info(`detected generic OpenAI-compatible server at ${baseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n } catch {\n // Fall through to unavailable\n }\n\n this.isAvailable = false;\n this.detectedType = null;\n this.lastHealthCheck = now;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${baseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.debug(\"local LLM not available at\", baseUrl);\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 (!existsSync(settingsPath)) {\n log.debug(`LM Studio settings: file not found at ${settingsPath}`);\n return null;\n }\n\n const content = 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 && 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 private hasQueuedRequests(): boolean {\n return (\n this.requestQueues[\"recall-critical\"].length > 0 ||\n this.requestQueues.background.length > 0\n );\n }\n\n private dequeueQueuedRequest(priority: LocalLlmRequestPriority): LocalLlmQueuedRequest | null {\n const next = this.requestQueues[priority].shift();\n return next ?? null;\n }\n\n private failOpenQueuedRequestsForCooldown(): number {\n let dropped = 0;\n for (const priority of [\"recall-critical\", \"background\"] as const) {\n while (this.requestQueues[priority].length > 0) {\n const queued = this.requestQueues[priority].shift();\n queued?.resolve(null);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n private startAvailableQueuedRequests(): void {\n if (!this.queueProcessing.has(\"recall-critical\")) {\n const nextCritical = this.dequeueQueuedRequest(\"recall-critical\");\n if (nextCritical) {\n this.queueProcessing.add(\"recall-critical\");\n void this.runQueuedRequest(nextCritical);\n }\n }\n\n if (!this.queueProcessing.has(\"background\")) {\n const nextBackground = this.dequeueQueuedRequest(\"background\");\n if (nextBackground) {\n this.queueProcessing.add(\"background\");\n void this.runQueuedRequest(nextBackground);\n }\n }\n }\n\n private async runQueuedRequest(next: LocalLlmQueuedRequest): Promise<void> {\n try {\n const remainingCooldownMs = this.remainingCooldownMs();\n if (remainingCooldownMs > 0) {\n const additionalDropped = this.failOpenQueuedRequestsForCooldown();\n log.warn(\n `local LLM: cooldown active (${remainingCooldownMs}ms remaining), dropping ${additionalDropped + 1} queued request(s) fail-open`,\n );\n next.resolve(null);\n return;\n }\n\n let result: LocalLlmChatCompletionResult | null = null;\n try {\n result = await this.runChatCompletionRequest(next.messages, next.options, {\n priority: next.priority,\n enqueuedAtMs: next.enqueuedAtMs,\n });\n } catch (err) {\n log.warn(`local LLM queue drain failed open: ${err instanceof Error ? err.message : String(err)}`);\n }\n next.resolve(result);\n } finally {\n this.queueProcessing.delete(next.priority);\n if (this.hasQueuedRequests()) {\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=${this.config.localLlmEnabled}, model=${this.config.localLlmModel}`,\n );\n\n const operation = options.operation ?? \"unspecified\";\n const startedAtMs = Date.now();\n if (queueMeta) {\n log.debug(\n `local LLM queue start: priority=${queueMeta.priority} waitMs=${startedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n\n try {\n const isAvailable = await this.checkAvailability();\n if (!isAvailable) {\n log.debug(\n `local LLM: checkAvailability returned false for ${this.config.localLlmUrl}`,\n );\n return null;\n }\n\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const requestBody: Record<string, unknown> = {\n model: this.config.localLlmModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n };\n\n // Skip response_format for local LLMs - they don't support json_object type\n // The prompts already instruct the model to output JSON\n // Only send if it's json_schema type which some local LLMs support\n if (options.responseFormat?.type === \"json_schema\") {\n requestBody.response_format = options.responseFormat;\n }\n\n // Suppress thinking/reasoning for thinking-capable models\n // (Qwen 3.5, Gemma 4, DeepSeek). These models default to\n // thinking-on via their chat template; sending\n // `chat_template_kwargs: { enable_thinking: false }` tells the\n // template to skip reasoning tokens.\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 if (\n this._disableThinking &&\n this.detectedType !== null &&\n THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)\n ) {\n requestBody.chat_template_kwargs = { enable_thinking: false };\n }\n\n // Normalize URL (use 127.0.0.1 instead of localhost)\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const chatUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/chat/completions`\n : `${baseUrl}/v1/chat/completions`;\n\n const requestBodyJson = JSON.stringify(requestBody);\n log.debug(\n `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,\n );\n // Avoid logging request bodies by default (can contain sensitive user content).\n log.debug(`local LLM: request body length=${requestBodyJson.length}`);\n\n // Write request body to file for debugging\n if (this.config.debug) {\n try {\n const { writeFileSync } = await import(\"node:fs\");\n writeFileSync(\"/tmp/engram-last-request.json\", requestBodyJson);\n } catch {\n /* ignore */\n }\n }\n\n const effectiveTimeoutMs =\n typeof options.timeoutMs === \"number\"\n ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)\n : this.config.localLlmTimeoutMs;\n const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);\n let response: Response | null = null;\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const attemptAbort = new AbortController();\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n try {\n response = await fetch(chatUrl, {\n method: \"POST\",\n headers: this.buildRequestHeaders({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify(requestBody),\n signal: attemptAbort.signal,\n });\n } catch (err) {\n if (!this.isAbortError(err)) throw err;\n lastAbortError = err instanceof Error ? err : new Error(String(err));\n if (attempt < maxAttempts) {\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request aborted: op=${operation} attempt=${attempt}/${maxAttempts} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel}; retrying after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n break;\n } finally {\n clearTimeout(attemptTimeout);\n }\n\n if (response.ok) break;\n if (response.status >= 500 && attempt < maxAttempts) {\n try {\n const errorText = await response.clone().text();\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n } catch (e) {\n log.debug(`local LLM failed to inspect retryable error body: ${e}`);\n }\n }\n if (response.status < 500 || attempt >= maxAttempts) break;\n\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request got ${response.status}; retrying (attempt ${attempt + 1}/${maxAttempts}) after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\n );\n\n if (!response) {\n if (lastAbortError) {\n log.warn(\n `local LLM request aborted after ${maxAttempts} attempt(s): op=${operation} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel} promptChars=${promptChars} durationMs=${Date.now() - startedAtMs}`,\n );\n } else {\n log.warn(\n `local LLM request failed: no response object (op=${operation} model=${this.config.localLlmModel} durationMs=${Date.now() - startedAtMs})`,\n );\n }\n return null;\n }\n\n if (!response.ok) {\n let reason = \"\";\n let errorText = \"\";\n try {\n errorText = await response.text();\n // Try to extract a stable error message without logging content.\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n // Keep a short preview in debug only.\n log.debug(`local LLM error body: ${errorText.slice(0, 500)}`);\n }\n } catch (e) {\n log.debug(`local LLM failed to read error body: ${e}`);\n }\n log.warn(\n `local LLM request failed: ${response.status} ${response.statusText}${reason} ` +\n `(op=${operation}, model=${this.config.localLlmModel}, url=${chatUrl}, promptChars=${promptChars}, maxTokens=${requestBody.max_tokens as number})`,\n );\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReason(reason) ??\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n if (response.status === 400) {\n this.consecutive400s += 1;\n if (this.consecutive400s >= this.config.localLlm400TripThreshold) {\n this.cooldownUntilMs = Date.now() + this.config.localLlm400CooldownMs;\n log.warn(\n `local LLM: entering cooldown for ${this.config.localLlm400CooldownMs}ms ` +\n `after ${this.consecutive400s} consecutive 400 responses`,\n );\n this.consecutive400s = 0;\n }\n } else {\n this.consecutive400s = 0;\n }\n return null;\n }\n this.consecutive400s = 0;\n\n const data = (await response.json()) as {\n choices?: Array<{\n message?: { content?: string; reasoning_content?: string };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n log.debug(\n `local LLM response: choices=${data.choices?.length}, usage=${JSON.stringify(data.usage)}`,\n );\n\n // Thinking models (e.g. Qwen 3.5) may put their response in\n // `reasoning_content` and leave `content` empty. Fall back to\n // reasoning_content so engram still gets a usable result.\n const msg = data.choices?.[0]?.message;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content. choices=${JSON.stringify(data.choices)?.slice(0, 200)}`);\n return null;\n }\n\n // Estimate tokens if not provided by local LLM\n const usage = data.usage\n ? {\n promptTokens: data.usage.prompt_tokens ?? 0,\n completionTokens: data.usage.completion_tokens ?? 0,\n totalTokens: data.usage.total_tokens ?? 0,\n }\n : this.estimateTokens(messages, content);\n\n const durationMs = Date.now() - startedAtMs;\n if (this.config.slowLogEnabled && durationMs >= this.config.slowLogThresholdMs) {\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const op = options.operation ? ` op=${options.operation}` : \"\";\n log.warn(\n `SLOW local LLM:${op} durationMs=${durationMs} model=${this.config.localLlmModel} url=${chatUrl} promptChars=${promptChars} outputTokens=${usage.completionTokens} totalTokens=${usage.totalTokens}`,\n );\n }\n\n log.debug(\"local LLM: request succeeded, tokens:\", usage.totalTokens);\n return { content, usage };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const durationMs = Date.now() - startedAtMs;\n if (this.isAbortError(err)) {\n log.warn(\n `local LLM request aborted: op=${operation} timeoutMs=${options.timeoutMs ?? this.config.localLlmTimeoutMs} model=${this.config.localLlmModel} durationMs=${durationMs} error=${errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = this.extractNonRecoverableBackendReason(errMsg);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n }\n return null;\n } finally {\n if (queueMeta) {\n const finishedAtMs = Date.now();\n const waitMs = startedAtMs - queueMeta.enqueuedAtMs;\n log.debug(\n `local LLM queue finish: priority=${queueMeta.priority} waitMs=${waitMs} runMs=${finishedAtMs - startedAtMs} totalMs=${finishedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n }\n }\n\n /**\n * Query the local LLM server for loaded model information.\n * Returns null if unavailable or if the model is not found.\n */\n async getLoadedModelInfo(): Promise<LocalModelInfo | null> {\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n\n // Handle URL construction - localLlmUrl may already include /v1\n const modelsUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/models`\n : `${baseUrl}/v1/models`;\n log.debug(`Fetching model info from ${modelsUrl}`);\n\n try {\n const result = await this.fetchWithTimeout(modelsUrl, 3000);\n if (!result.ok) {\n if (result.status === 401 || result.status === 403) {\n log.warn(\n `Local LLM: unauthorized while fetching models from ${modelsUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.warn(`Local LLM: Failed to fetch models from ${modelsUrl} - server returned error`);\n return null;\n }\n if (!result.data) {\n log.warn(`Local LLM: No data returned from ${modelsUrl}`);\n return null;\n }\n\n const data = result.data as {\n data?: Array<{\n id?: string;\n object?: string;\n owned_by?: string;\n // LM Studio specific fields\n max_context_length?: number;\n max_tokens?: number;\n // Ollama specific\n name?: string;\n details?: {\n parameter_size?: string;\n family?: string;\n };\n }>;\n };\n\n if (!Array.isArray(data.data) || data.data.length === 0) {\n log.warn(\"Local LLM returned no models\");\n return null;\n }\n\n // Verbose model listings are noisy on every gateway restart. Keep it debug-only.\n const modelIds = data.data.map((m) => m.id).filter(Boolean);\n log.debug(\n `Local LLM: Found ${modelIds.length} model(s). First 10: ${modelIds.slice(0, 10).join(\", \")}`,\n );\n\n // Find the model matching our configured model ID\n const configuredModel = this.config.localLlmModel;\n let model = data.data.find((m) => m.id === configuredModel);\n\n // If not found by exact match, try partial match (handle suffixes like @4bit)\n if (!model) {\n model = data.data.find((m) =>\n configuredModel.includes(m.id || \"\") ||\n (m.id || \"\").includes(configuredModel.replace(/@\\d+bit$/, \"\"))\n );\n }\n\n // If still not found, use the first loaded model and warn\n if (!model) {\n model = data.data[0];\n const availablePreview = data.data\n .map((m) => m.id)\n .filter(Boolean)\n .slice(0, 10)\n .join(\", \");\n log.warn(\n `Configured model \"${configuredModel}\" not found in local LLM. ` +\n `Using \"${model.id}\" instead. Available (first 10): ${availablePreview}`\n );\n }\n\n // Extract context window - try multiple field names\n let contextWindow = model.max_context_length || model.max_tokens;\n\n // If API doesn't report context window, try LMS CLI (LM Studio specific)\n if (!contextWindow) {\n log.info(\"Local LLM: API did not report context window, trying LMS CLI...\");\n const lmsContext = this.getCachedContextWindow(model.id || \"\");\n if (lmsContext) {\n contextWindow = lmsContext;\n }\n }\n\n this.cachedModelInfo = {\n id: model.id || \"unknown\",\n contextWindow: contextWindow,\n maxTokens: model.max_tokens,\n };\n\n log.info(\n `Local LLM model detected: ${this.cachedModelInfo.id}, ` +\n `context window: ${contextWindow?.toLocaleString() || \"unknown (may use default)\"}`\n );\n\n return this.cachedModelInfo;\n } catch (err) {\n log.warn(`Failed to fetch model info: ${err}`);\n return null;\n }\n }\n\n /**\n * Check if the configured model is available and get its actual context window.\n * Warns if there's a mismatch between expected and actual context.\n */\n async validateModelConfig(expectedContextWindow?: number): Promise<{\n available: boolean;\n actualContextWindow?: number;\n warnings: string[];\n }> {\n const warnings: string[] = [];\n\n const modelInfo = await this.getLoadedModelInfo();\n if (!modelInfo) {\n return { available: false, warnings: [\"Could not query local LLM for model info\"] };\n }\n\n // If we have expected context and the server reports one, check for mismatch\n if (expectedContextWindow && modelInfo.contextWindow) {\n if (modelInfo.contextWindow < expectedContextWindow) {\n warnings.push(\n `Context window mismatch: Model ${modelInfo.id} supports ${modelInfo.contextWindow.toLocaleString()} tokens, ` +\n `but engram is configured for ${expectedContextWindow.toLocaleString()}. ` +\n `Set localLlmMaxContext: ${modelInfo.contextWindow} in config to avoid errors.`\n );\n }\n }\n\n // Warn if server doesn't report context window (common with some local LLM setups)\n if (!modelInfo.contextWindow) {\n warnings.push(\n `Local LLM server did not report context window for ${modelInfo.id}. ` +\n `If you get \"context length exceeded\" errors, set localLlmMaxContext in config.`\n );\n }\n\n return {\n available: true,\n actualContextWindow: modelInfo.contextWindow,\n warnings,\n };\n }\n\n /**\n * Make a chat completion request to local LLM\n */\n async chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions = {},\n ): Promise<LocalLlmChatCompletionResult | null> {\n if (!this.config.localLlmEnabled) {\n log.debug(\"local LLM: disabled, returning null\");\n return null;\n }\n\n const remainingMs = this.remainingCooldownMs();\n if (remainingMs > 0) {\n log.debug(`local LLM: cooldown active (${remainingMs}ms remaining), skipping request`);\n return null;\n }\n if (options.priority) {\n const priority = options.priority;\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n this.requestQueues[priority].push({\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve,\n });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n\n /**\n * Estimate tokens when local LLM doesn't return usage stats\n * Rough estimate: 1 token ≈ 4 characters\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n const promptTokens = Math.ceil(promptChars / 4);\n const completionTokens = Math.ceil(response.length / 4);\n\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n }\n\n /**\n * Try local LLM first, fallback to cloud provider if configured\n */\n async withFallback<T>(\n localOperation: () => Promise<T | null>,\n fallbackOperation: () => Promise<T>,\n operationName: string\n ): Promise<T> {\n // Try local LLM first if enabled\n if (this.config.localLlmEnabled) {\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"],"mappings":";;;;;;;;;;;;AAEA,SAAS,YAAY,oBAAoB;AACzC,OAAO,QAAQ;AAMf,SAAS,oBAAoB,GAAmB;AAC9C,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,MAAM,CAAC,MAAM,IAAK;AACtC,SAAO,EAAE,UAAU,GAAG,GAAG;AAC3B;AAuBA,IAAM,+BAA0D,oBAAI,IAAI;AAAA,EACtE;AAAA,EACA;AACF,CAAC;AAUD,IAAM,gBAAqC;AAAA,EACzC;AAAA,IACE,MAAM;AAAA,IACN,aAAa;AAAA,IACb,gBAAgB;AAA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MemoryRelativeDir(raw, fallback) {
99
99
  const normalized = trimmed.replace(/\\/g, "/").split("/").filter((segment) => segment.length > 0 && segment !== "." && segment !== "..").join("/");
100
100
  return normalized.length > 0 ? normalized : fallback;
101
101
  }
102
+ function parseContradictionScanConfig(raw) {
103
+ if (!raw || typeof raw !== "object") {
104
+ return {
105
+ enabled: false,
106
+ similarityFloor: 0.82,
107
+ topicOverlapFloor: 0.4,
108
+ maxPairsPerRun: 500,
109
+ cooldownDays: 14,
110
+ autoMergeDuplicates: false
111
+ };
112
+ }
113
+ const src = raw;
114
+ const simFloor = coerceNumber(src.similarityFloor) ?? 0.82;
115
+ const topicFloor = coerceNumber(src.topicOverlapFloor) ?? 0.4;
116
+ const maxPairs = coerceNumber(src.maxPairsPerRun) ?? 500;
117
+ const cooldown = coerceNumber(src.cooldownDays) ?? 14;
118
+ return {
119
+ enabled: coerceBool(src.enabled) === true,
120
+ similarityFloor: Math.min(1, Math.max(0, simFloor)),
121
+ topicOverlapFloor: Math.min(1, Math.max(0, topicFloor)),
122
+ maxPairsPerRun: Math.max(1, maxPairs),
123
+ cooldownDays: Math.max(0, cooldown),
124
+ autoMergeDuplicates: coerceBool(src.autoMergeDuplicates) === true
125
+ };
126
+ }
102
127
  function parseSemanticChunkingConfig(raw) {
103
128
  if (!raw || typeof raw !== "object") return {};
104
129
  const src = raw;
@@ -303,17 +328,26 @@ function parseConfig(raw) {
303
328
  fingerprintDedup: rawCodexCompat.fingerprintDedup !== false
304
329
  };
305
330
  const rawProcedural = cfg.procedural && typeof cfg.procedural === "object" && !Array.isArray(cfg.procedural) ? cfg.procedural : {};
306
- const proceduralMinRaw = typeof rawProcedural.minOccurrences === "number" && Number.isFinite(rawProcedural.minOccurrences) ? Math.floor(rawProcedural.minOccurrences) : 3;
331
+ const proceduralMinCoerced = coerceNumber(rawProcedural.minOccurrences);
332
+ const proceduralMinRaw = proceduralMinCoerced !== void 0 ? Math.floor(proceduralMinCoerced) : 3;
333
+ const successFloorRaw = coerceNumber(rawProcedural.successFloor);
334
+ const successFloor = successFloorRaw !== void 0 && successFloorRaw >= 0 && successFloorRaw <= 1 ? successFloorRaw : 0.7;
335
+ const autoPromoteOccRaw = coerceNumber(rawProcedural.autoPromoteOccurrences);
336
+ const autoPromoteOccurrences = autoPromoteOccRaw !== void 0 && Number.isFinite(autoPromoteOccRaw) ? autoPromoteOccRaw <= 0 ? 0 : Math.min(1e4, Math.max(1, Math.floor(autoPromoteOccRaw))) : 8;
337
+ const lookbackCoerced = coerceNumber(rawProcedural.lookbackDays);
338
+ const lookbackDays = lookbackCoerced !== void 0 && Number.isFinite(lookbackCoerced) ? Math.min(3650, Math.max(1, Math.floor(lookbackCoerced))) : 30;
339
+ const recallMaxCoerced = coerceNumber(rawProcedural.recallMaxProcedures);
340
+ const recallMaxProcedures = recallMaxCoerced !== void 0 && Number.isFinite(recallMaxCoerced) ? Math.min(10, Math.max(1, Math.floor(recallMaxCoerced))) : 3;
307
341
  const procedural = {
308
342
  enabled: coerceBool(rawProcedural.enabled) === true,
309
- /** 0 disables miner emission threshold (no clusters qualify). */
343
+ /** `0` skips all mining (`minOccurrences_zero`); otherwise clusters need at least this many members. */
310
344
  minOccurrences: Math.min(1e3, Math.max(0, proceduralMinRaw)),
311
- successFloor: typeof rawProcedural.successFloor === "number" && Number.isFinite(rawProcedural.successFloor) && rawProcedural.successFloor >= 0 && rawProcedural.successFloor <= 1 ? rawProcedural.successFloor : 0.7,
312
- autoPromoteOccurrences: typeof rawProcedural.autoPromoteOccurrences === "number" && Number.isFinite(rawProcedural.autoPromoteOccurrences) ? rawProcedural.autoPromoteOccurrences <= 0 ? 0 : Math.min(1e4, Math.max(1, Math.floor(rawProcedural.autoPromoteOccurrences))) : 8,
345
+ successFloor,
346
+ autoPromoteOccurrences,
313
347
  autoPromoteEnabled: coerceBool(rawProcedural.autoPromoteEnabled) === true,
314
- lookbackDays: typeof rawProcedural.lookbackDays === "number" && Number.isFinite(rawProcedural.lookbackDays) ? Math.min(3650, Math.max(1, Math.floor(rawProcedural.lookbackDays))) : 30,
348
+ lookbackDays,
315
349
  proceduralMiningCronAutoRegister: coerceBool(rawProcedural.proceduralMiningCronAutoRegister) === true,
316
- recallMaxProcedures: typeof rawProcedural.recallMaxProcedures === "number" && Number.isFinite(rawProcedural.recallMaxProcedures) ? Math.min(10, Math.max(1, Math.floor(rawProcedural.recallMaxProcedures))) : 3
350
+ recallMaxProcedures
317
351
  };
318
352
  const memoryDir = typeof cfg.memoryDir === "string" && cfg.memoryDir.length > 0 ? cfg.memoryDir : DEFAULT_MEMORY_DIR;
319
353
  const rawIdentityInjectionMode = cfg.identityInjectionMode;
@@ -497,13 +531,19 @@ function parseConfig(raw) {
497
531
  contradictionSimilarityThreshold: typeof cfg.contradictionSimilarityThreshold === "number" ? cfg.contradictionSimilarityThreshold : 0.7,
498
532
  contradictionMinConfidence: typeof cfg.contradictionMinConfidence === "number" ? cfg.contradictionMinConfidence : 0.9,
499
533
  contradictionAutoResolve: cfg.contradictionAutoResolve !== false,
534
+ // Contradiction Scan cron (issue #520)
535
+ contradictionScan: parseContradictionScanConfig(cfg.contradictionScan),
500
536
  // Temporal Supersession (issue #375)
501
537
  temporalSupersessionEnabled: cfg.temporalSupersessionEnabled !== false,
502
538
  // On by default
503
539
  temporalSupersessionIncludeInRecall: cfg.temporalSupersessionIncludeInRecall === true,
504
540
  // Off by default
505
- // Direct-answer retrieval tier (issue #518)
506
- recallDirectAnswerEnabled: coerceBool(cfg.recallDirectAnswerEnabled) ?? false,
541
+ // Direct-answer retrieval tier (issue #518). Default on — the
542
+ // tier runs in observation mode: it annotates
543
+ // LastRecallSnapshot.tierExplain but never short-circuits the
544
+ // QMD path. Operators can opt out with
545
+ // recallDirectAnswerEnabled=false.
546
+ recallDirectAnswerEnabled: coerceBool(cfg.recallDirectAnswerEnabled) ?? true,
507
547
  recallDirectAnswerTokenOverlapFloor: (() => {
508
548
  const n = coerceNumber(cfg.recallDirectAnswerTokenOverlapFloor);
509
549
  return n !== void 0 && n >= 0 && n <= 1 ? n : 0.55;
@@ -765,6 +805,22 @@ function parseConfig(raw) {
765
805
  localLlmFastModel: typeof cfg.localLlmFastModel === "string" && cfg.localLlmFastModel.length > 0 ? cfg.localLlmFastModel : "",
766
806
  localLlmFastUrl: typeof cfg.localLlmFastUrl === "string" && cfg.localLlmFastUrl.length > 0 ? cfg.localLlmFastUrl : typeof cfg.localLlmUrl === "string" && cfg.localLlmUrl.length > 0 ? cfg.localLlmUrl : "http://localhost:1234/v1",
767
807
  localLlmFastTimeoutMs: typeof cfg.localLlmFastTimeoutMs === "number" ? cfg.localLlmFastTimeoutMs : 15e3,
808
+ // Thinking-mode suppression on the main local LLM (issue #548).
809
+ // Default true — extraction / consolidation produce structured
810
+ // JSON and gain nothing from chain-of-thought; thinking-capable
811
+ // models burn their token budget on reasoning and blow the
812
+ // default 60s timeout. Operators who need thinking on the main
813
+ // client (e.g. for narrative tasks) can set this to false via
814
+ // config or --config CLI flag. The fast-tier `fastLlm` always
815
+ // disables thinking and is unaffected by this flag.
816
+ //
817
+ // Injection is backend-gated inside LocalLlmClient: the
818
+ // `chat_template_kwargs` field is only sent when the detected
819
+ // backend is in `THINKING_COMPATIBLE_BACKENDS` (LM Studio, vLLM).
820
+ // Strict OpenAI-compatible backends reject unknown request
821
+ // fields with 400, so the client fails open on unknown backends
822
+ // rather than tripping the 400 cooldown (Codex P1 on PR #550).
823
+ localLlmDisableThinking: coerceBool(cfg.localLlmDisableThinking) ?? true,
768
824
  // Gateway config (passed from index.ts for fallback AI)
769
825
  gatewayConfig: cfg.gatewayConfig,
770
826
  // Gateway model source (v9.2) — route LLM calls through gateway agent model chain
@@ -1305,4 +1361,4 @@ export {
1305
1361
  VALID_MEMORY_CATEGORIES,
1306
1362
  parseConfig
1307
1363
  };
1308
- //# sourceMappingURL=chunk-OJFGVJS6.js.map
1364
+ //# sourceMappingURL=chunk-MBJHSA7F.js.map