@curio-data/mcp-intelli-search 0.15.0-alpha.0 → 0.15.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.
@@ -2,7 +2,7 @@ import {
2
2
  identity,
3
3
  validateCacheDir,
4
4
  validateDomains
5
- } from "./chunk-5I6PWQPA.js";
5
+ } from "./chunk-EHXBTGSE.js";
6
6
 
7
7
  // packages/mcp/src/runtime.ts
8
8
  import { Check } from "typebox/value";
@@ -478,6 +478,7 @@ import { mkdir, writeFile, readFile, rename, rm, stat, readdir } from "node:fs/p
478
478
  import { dirname, join as join2 } from "node:path";
479
479
  import { createHash, randomBytes } from "node:crypto";
480
480
  var MAX_JUDGE_ENTRIES = 20;
481
+ var LLMS_FULL_PREFIX = "llms-full-";
481
482
  var DEFAULT_STALE_MS = 3e4;
482
483
  var DEFAULT_POLL_MS = 50;
483
484
  var DEFAULT_LOCK_TIMEOUT_MS = 1e4;
@@ -564,7 +565,41 @@ function domainSlug(url) {
564
565
  function sourceFilename(index, url) {
565
566
  return `${String(index + 1).padStart(2, "0")}-${domainSlug(url)}.md`;
566
567
  }
567
- async function writeCacheFiles(cachePath, extractions, pages, searchSummary, query) {
568
+ function allocateSourceIdentity(extractions, pages) {
569
+ const extractionFileByUrl = /* @__PURE__ */ new Map();
570
+ const sourceFileByUrl = /* @__PURE__ */ new Map();
571
+ const slotByUrl = /* @__PURE__ */ new Map();
572
+ let nextSlot = 0;
573
+ const slotOf = (url) => {
574
+ let slot = slotByUrl.get(url);
575
+ if (slot === void 0) {
576
+ slot = nextSlot++;
577
+ slotByUrl.set(url, slot);
578
+ }
579
+ return slot;
580
+ };
581
+ const extractionFiles = extractions.map((ext) => {
582
+ const slot = slotOf(ext.url);
583
+ if (ext.status !== "success" || !ext.extraction) return null;
584
+ const filename = sourceFilename(slot, ext.url);
585
+ extractionFileByUrl.set(ext.url, filename);
586
+ return filename;
587
+ });
588
+ const sourceFiles = pages.map((page) => {
589
+ const slot = slotOf(page.url);
590
+ if (page.status !== "success") return null;
591
+ const filename = sourceFilename(slot, page.url);
592
+ sourceFileByUrl.set(page.url, filename);
593
+ return filename;
594
+ });
595
+ return {
596
+ extractionFiles,
597
+ sourceFiles,
598
+ extractionFileFor: (url) => extractionFileByUrl.get(url) ?? null,
599
+ sourceFileFor: (url) => sourceFileByUrl.get(url) ?? null
600
+ };
601
+ }
602
+ async function writeCacheFiles(cachePath, extractions, pages, searchSummary, query, identity2 = allocateSourceIdentity(extractions, pages)) {
568
603
  await mkdir(cachePath, { recursive: true });
569
604
  const staging = await createStagingDir(cachePath);
570
605
  try {
@@ -573,9 +608,11 @@ async function writeCacheFiles(cachePath, extractions, pages, searchSummary, que
573
608
  await mkdir(stagingExtractions, { recursive: true });
574
609
  await mkdir(stagingSources, { recursive: true });
575
610
  await writeFile(join2(staging, "query.txt"), query, "utf-8");
576
- for (const [i, ext] of extractions.entries()) {
611
+ const writtenExtractions = /* @__PURE__ */ new Set();
612
+ for (const ext of extractions) {
577
613
  if (ext.status !== "success" || !ext.extraction) continue;
578
- const filename = sourceFilename(i, ext.url);
614
+ const filename = identity2.extractionFileFor(ext.url);
615
+ if (!filename) continue;
579
616
  const header = `# ${ext.title}
580
617
 
581
618
  > Source: ${ext.url}
@@ -585,10 +622,13 @@ async function writeCacheFiles(cachePath, extractions, pages, searchSummary, que
585
622
 
586
623
  `;
587
624
  await writeFile(join2(stagingExtractions, filename), header + ext.extraction, "utf-8");
625
+ writtenExtractions.add(filename);
588
626
  }
589
- for (const [i, page] of pages.entries()) {
627
+ const writtenSources = /* @__PURE__ */ new Set();
628
+ for (const page of pages) {
590
629
  if (page.status !== "success") continue;
591
- const filename = sourceFilename(i, page.url);
630
+ const filename = identity2.sourceFileFor(page.url);
631
+ if (!filename) continue;
592
632
  const header = `# ${page.title}
593
633
 
594
634
  > Source: ${page.url}
@@ -597,29 +637,98 @@ async function writeCacheFiles(cachePath, extractions, pages, searchSummary, que
597
637
 
598
638
  `;
599
639
  await writeFile(join2(stagingSources, filename), header + page.content, "utf-8");
640
+ writtenSources.add(filename);
600
641
  }
601
- await moveStagedFiles(staging, cachePath);
642
+ await commitStagedArtefacts(staging, cachePath, writtenExtractions, writtenSources);
602
643
  } finally {
603
644
  await rm(staging, { recursive: true, force: true }).catch(() => {
604
645
  });
605
646
  }
606
647
  }
607
- async function moveStagedFiles(staging, target) {
608
- const entries = await readdir(staging, { withFileTypes: true });
609
- for (const entry of entries) {
610
- const src = join2(staging, entry.name);
611
- const dst = join2(target, entry.name);
612
- if (entry.isDirectory()) {
613
- await mkdir(dst, { recursive: true });
614
- await moveStagedFiles(src, dst);
615
- } else {
616
- await rm(dst, { force: true }).catch(() => {
648
+ async function commitStagedArtefacts(staging, cachePath, writtenExtractions, writtenSources) {
649
+ const finalExtractions = join2(cachePath, "extractions");
650
+ const finalSources = join2(cachePath, "sources");
651
+ await mkdir(finalExtractions, { recursive: true });
652
+ await mkdir(finalSources, { recursive: true });
653
+ await rename(join2(staging, "query.txt"), join2(cachePath, "query.txt"));
654
+ for (const name of writtenExtractions) {
655
+ await rename(join2(staging, "extractions", name), join2(finalExtractions, name));
656
+ }
657
+ for (const name of writtenSources) {
658
+ await rename(join2(staging, "sources", name), join2(finalSources, name));
659
+ }
660
+ await pruneDirectory(finalExtractions, writtenExtractions, null);
661
+ await pruneDirectory(finalSources, writtenSources, LLMS_FULL_PREFIX);
662
+ }
663
+ async function rotateCacheArtefacts(cachePath) {
664
+ let entries;
665
+ try {
666
+ entries = await readdir(cachePath);
667
+ } catch (err) {
668
+ if (err?.code === "ENOENT") return null;
669
+ throw err;
670
+ }
671
+ const movable = entries.filter((name) => name !== ".lock" && !name.startsWith(".staging."));
672
+ if (movable.length === 0) return null;
673
+ const moves = [];
674
+ for (const name of movable) {
675
+ if (name !== "sources") {
676
+ moves.push({ from: join2(cachePath, name), to: name });
677
+ continue;
678
+ }
679
+ let sourceEntries;
680
+ try {
681
+ sourceEntries = await readdir(join2(cachePath, "sources"));
682
+ } catch (err) {
683
+ if (err?.code === "ENOTDIR") {
684
+ moves.push({ from: join2(cachePath, name), to: name });
685
+ continue;
686
+ }
687
+ if (err?.code === "ENOENT") continue;
688
+ throw err;
689
+ }
690
+ for (const sourceName of sourceEntries) {
691
+ if (sourceName.startsWith(LLMS_FULL_PREFIX)) continue;
692
+ moves.push({
693
+ from: join2(cachePath, "sources", sourceName),
694
+ to: join2("sources", sourceName)
617
695
  });
618
- await rename(src, dst);
619
696
  }
620
697
  }
698
+ if (moves.length === 0) return null;
699
+ let suffix = 1;
700
+ while (await stat(`${cachePath}.${suffix}`).then(() => true, () => false)) suffix++;
701
+ const archive = `${cachePath}.${suffix}`;
702
+ await mkdir(archive, { recursive: true });
703
+ for (const move of moves) {
704
+ await mkdir(dirname(join2(archive, move.to)), { recursive: true });
705
+ await rename(move.from, join2(archive, move.to));
706
+ }
707
+ return archive;
708
+ }
709
+ async function pruneDirectory(dir, keep, preservePrefix) {
710
+ let entries;
711
+ try {
712
+ entries = await readdir(dir);
713
+ } catch (err) {
714
+ if (err?.code === "ENOENT") return;
715
+ throw err;
716
+ }
717
+ for (const name of entries) {
718
+ if (keep.has(name)) continue;
719
+ if (preservePrefix && name.startsWith(preservePrefix)) continue;
720
+ await rm(join2(dir, name), { force: true });
721
+ }
722
+ }
723
+ async function clearCacheArtefacts(cachePath) {
724
+ await Promise.all([
725
+ rm(join2(cachePath, "report.md"), { force: true }),
726
+ rm(join2(cachePath, "query.txt"), { force: true }),
727
+ rm(join2(cachePath, "extractions"), { recursive: true, force: true })
728
+ ]);
729
+ await pruneDirectory(join2(cachePath, "sources"), /* @__PURE__ */ new Set(), LLMS_FULL_PREFIX);
621
730
  }
622
- async function writeReportFile(cachePath, query, collation, extractions, pages, displayPath = cachePath) {
731
+ async function writeReportFile(cachePath, query, collation, extractions, pages, displayPath = cachePath, identity2 = allocateSourceIdentity(extractions, pages)) {
623
732
  await mkdir(cachePath, { recursive: true });
624
733
  const now = (/* @__PURE__ */ new Date()).toISOString();
625
734
  const succeeded = extractions.filter((e) => e.status === "success");
@@ -643,8 +752,9 @@ async function writeReportFile(cachePath, query, collation, extractions, pages,
643
752
  report += `|---|--------|------|------------|----------|
644
753
  `;
645
754
  for (const [i, ext] of succeeded.entries()) {
646
- const filename = sourceFilename(i, ext.url);
647
- report += `| ${i + 1} | ${ext.url} | ${ext.sourceType} | extractions/${filename} | sources/${filename} |
755
+ const extractionFile = identity2.extractionFileFor(ext.url);
756
+ const sourceFile = identity2.sourceFileFor(ext.url);
757
+ report += `| ${i + 1} | ${ext.url} | ${ext.sourceType} | ${extractionFile ? `extractions/${extractionFile}` : "Not cached"} | ${sourceFile ? `sources/${sourceFile}` : "Not cached"} |
648
758
  `;
649
759
  }
650
760
  if (blocked.length > 0) {
@@ -682,13 +792,28 @@ async function readIndex(cacheDir) {
682
792
  return { searches: [] };
683
793
  }
684
794
  }
795
+ async function removeIndexEntry(cacheDir, slug) {
796
+ const indexPath = join2(cacheDir, ".index.json");
797
+ let index;
798
+ try {
799
+ index = JSON.parse(await readFile(indexPath, "utf-8"));
800
+ } catch {
801
+ return;
802
+ }
803
+ if (!Array.isArray(index.searches) || !index.searches.some((e) => e.slug === slug)) return;
804
+ index.searches = index.searches.filter((e) => e.slug !== slug);
805
+ await atomicWriteFile(indexPath, JSON.stringify(index, null, 2) + "\n");
806
+ }
807
+ function judgeCandidates(index, excludeSlug) {
808
+ return index.searches.filter((e) => e.slug !== excludeSlug).slice(-MAX_JUDGE_ENTRIES);
809
+ }
685
810
  function formatIndexForJudge(index, excludeSlug) {
686
- const entries = index.searches.filter((e) => e.slug !== excludeSlug).slice(-MAX_JUDGE_ENTRIES);
811
+ const entries = judgeCandidates(index, excludeSlug);
687
812
  if (entries.length === 0) return "No previous searches.";
688
813
  return entries.map((e, i) => `${i + 1}. "${e.query}" (slug: ${e.slug}, searched: ${e.timestamp})`).join("\n");
689
814
  }
690
815
  function parseJudgeResponse(response, index, excludeSlug) {
691
- const eligible = index.searches.filter((e) => e.slug !== excludeSlug);
816
+ const candidates = judgeCandidates(index, excludeSlug);
692
817
  const jsonMatch = response.match(/\[[\s\S]*\]/);
693
818
  if (!jsonMatch) return [];
694
819
  let parsed;
@@ -701,7 +826,7 @@ function parseJudgeResponse(response, index, excludeSlug) {
701
826
  const results = [];
702
827
  for (const item of parsed) {
703
828
  if (typeof item.index !== "number" || item.index < 1) continue;
704
- const entry = eligible[item.index - 1];
829
+ const entry = candidates[item.index - 1];
705
830
  if (!entry) continue;
706
831
  results.push({ entry, relevance: item.relevance ?? "" });
707
832
  }
@@ -719,14 +844,13 @@ function formatCacheSuggestions(matches, cacheDir) {
719
844
  };
720
845
  let out = "\n---\n\n## \u{1F4DA} Related cached searches\n\n";
721
846
  out += "The following previous searches may contain relevant supplementary information. ";
722
- out += `Read a report with \`read ${cacheDir}/<slug>/report.md\` if the live results are insufficient.
723
-
724
- `;
725
- out += "| # | Query | Age | Why related |\n";
726
- out += "|---|-------|-----|-------------|\n";
847
+ out += "Read the report listed for a match if the live results are insufficient.\n\n";
848
+ out += "| # | Query | Age | Report | Why related |\n";
849
+ out += "|---|-------|-----|--------|-------------|\n";
727
850
  for (const [i, m] of matches.entries()) {
728
851
  const queryTrunc = m.entry.query.length > 60 ? m.entry.query.slice(0, 57) + "..." : m.entry.query;
729
- out += `| ${i + 1} | \`${queryTrunc}\` | ${age(m.entry.timestamp)} | ${m.relevance} |
852
+ out += `| ${i + 1} | \`${queryTrunc}\` | ${age(m.entry.timestamp)} | `;
853
+ out += `\`${cacheDir}/${m.entry.slug}/report.md\` | ${m.relevance} |
730
854
  `;
731
855
  }
732
856
  out += `
@@ -786,7 +910,16 @@ Focus: ${focusPrompt}
786
910
  }
787
911
  return msg;
788
912
  }
789
- function buildCollationMessage(query, cachePath, searchSummary, succeededExtractions) {
913
+ function buildCollationMessage(query, cachePath, searchSummary, succeededExtractions, identity2) {
914
+ const id = identity2 ?? allocateSourceIdentity(
915
+ succeededExtractions,
916
+ succeededExtractions.map((e) => ({
917
+ url: e.url,
918
+ title: e.title,
919
+ content: "",
920
+ status: "success"
921
+ }))
922
+ );
790
923
  let msg = `Original query: ${query}
791
924
  `;
792
925
  msg += `Cache path: ${cachePath}/
@@ -799,17 +932,22 @@ ${searchSummary}
799
932
  `;
800
933
  }
801
934
  for (const [i, ext] of succeededExtractions.entries()) {
802
- const filename = sourceFilename(i, ext.url);
935
+ const extractionFile = id.extractionFileFor(ext.url);
936
+ const sourceFile = id.sourceFileFor(ext.url);
803
937
  msg += `--- Source ${i + 1}: ${ext.url} ---
804
938
  `;
805
939
  msg += `Title: ${ext.title}
806
940
  `;
807
941
  msg += `Type: ${ext.sourceType}
808
942
  `;
809
- msg += `Extraction file: ${cachePath}/extractions/${filename}
943
+ if (extractionFile) {
944
+ msg += `Extraction file: ${cachePath}/extractions/${extractionFile}
810
945
  `;
811
- msg += `Full page file: ${cachePath}/sources/${filename}
946
+ }
947
+ if (sourceFile) {
948
+ msg += `Full page file: ${cachePath}/sources/${sourceFile}
812
949
  `;
950
+ }
813
951
  msg += `
814
952
  ${ext.extraction}
815
953
 
@@ -947,11 +1085,13 @@ async function collate(params, context) {
947
1085
  content: p.content,
948
1086
  status: "success"
949
1087
  }));
1088
+ const identity2 = allocateSourceIdentity(extractResults, fetchedPages);
950
1089
  const userMessage = buildCollationMessage(
951
1090
  params.query,
952
1091
  cachePath,
953
1092
  params.searchSummary,
954
- extractResults.filter((e) => e.status === "success")
1093
+ extractResults.filter((e) => e.status === "success"),
1094
+ identity2
955
1095
  );
956
1096
  const { text: collation } = await models.complete({
957
1097
  model: collateConfig,
@@ -960,15 +1100,21 @@ async function collate(params, context) {
960
1100
  maxTokens: settings.collationMaxTokens,
961
1101
  signal
962
1102
  });
1103
+ if (!collation.trim())
1104
+ throw new Error("Collation returned no visible text; increase collationMaxTokens or choose a model with a smaller reasoning budget");
963
1105
  await withLock(
964
1106
  cacheLockDir(physicalPath),
965
1107
  async () => {
1108
+ await rotateCacheArtefacts(physicalPath).catch((error) => {
1109
+ context.logger.error(`Cache archive failed: ${errMsg(error)}`);
1110
+ });
966
1111
  await writeCacheFiles(
967
1112
  physicalPath,
968
1113
  extractResults,
969
1114
  fetchedPages,
970
1115
  params.searchSummary ?? "",
971
- params.query
1116
+ params.query,
1117
+ identity2
972
1118
  );
973
1119
  await writeReportFile(
974
1120
  physicalPath,
@@ -976,7 +1122,8 @@ async function collate(params, context) {
976
1122
  collation,
977
1123
  extractResults,
978
1124
  fetchedPages,
979
- cachePath
1125
+ cachePath,
1126
+ identity2
980
1127
  );
981
1128
  await withLock(
982
1129
  indexLockDir(paths.cacheRoot),
@@ -1393,7 +1540,7 @@ async function sweepStaleTempFiles(cachePath) {
1393
1540
  }
1394
1541
 
1395
1542
  // src/core/operations/research.ts
1396
- import { mkdir as mkdir3, writeFile as writeFile4, rm as rm2, readdir as readdir3, readFile as readFile2, mkdtemp } from "node:fs/promises";
1543
+ import { mkdir as mkdir3, writeFile as writeFile4, rm as rm2, readdir as readdir3, readFile as readFile2, mkdtemp, stat as stat2 } from "node:fs/promises";
1397
1544
  import { join as join5 } from "node:path";
1398
1545
 
1399
1546
  // src/core/progress.ts
@@ -1490,6 +1637,7 @@ ${search2.searchResult}`,
1490
1637
  p.onProgress?.(progress("collate", "Synthesising results..."));
1491
1638
  const allExtractions = [...extracted.extractions, ...extracted.blockedExtractions];
1492
1639
  const succeededExtractions = allExtractions.filter((e) => e.status === "success");
1640
+ const identity2 = allocateSourceIdentity(allExtractions, fetched.pages);
1493
1641
  if (succeededExtractions.length === 0) {
1494
1642
  const fetchFailed = extracted.blockedExtractions.length;
1495
1643
  const extractFailed = extracted.extractions.filter((e) => e.status === "failed").length;
@@ -1509,11 +1657,11 @@ ${search2.searchResult}`,
1509
1657
  }
1510
1658
  );
1511
1659
  }
1512
- const collation = await runCollateStage(p, search2.searchResult, succeededExtractions);
1660
+ const collation = await runCollateStage(p, search2.searchResult, succeededExtractions, identity2);
1513
1661
  throwIfAborted(p.signal);
1514
1662
  const llms = await startLlmsFullDownloads(p, fetched.successPages);
1515
1663
  try {
1516
- await writeCacheArtifacts(p, allExtractions, fetched, search2.searchResult, collation, llms);
1664
+ await writeCacheArtifacts(p, allExtractions, fetched, search2.searchResult, collation, llms, identity2);
1517
1665
  } finally {
1518
1666
  llms.abort.abort();
1519
1667
  await Promise.allSettled(llms.futures);
@@ -1687,12 +1835,13 @@ async function runExtractStage(p, successPages, pages) {
1687
1835
  });
1688
1836
  return { extractions, blockedExtractions };
1689
1837
  }
1690
- async function runCollateStage(p, searchResult, succeededExtractions) {
1838
+ async function runCollateStage(p, searchResult, succeededExtractions, identity2) {
1691
1839
  const collationUserMsg = buildCollationMessage(
1692
1840
  p.params.query,
1693
1841
  p.cachePath,
1694
1842
  searchResult,
1695
- succeededExtractions
1843
+ succeededExtractions,
1844
+ identity2
1696
1845
  );
1697
1846
  throwIfAborted(p.signal);
1698
1847
  const { text: collation } = await p.models.complete({
@@ -1705,6 +1854,8 @@ async function runCollateStage(p, searchResult, succeededExtractions) {
1705
1854
  timeoutMs: p.settings.llmTimeoutMs,
1706
1855
  onRetryNotice: (msg) => p.onProgress?.(progress("collate", msg))
1707
1856
  });
1857
+ if (!collation.trim())
1858
+ throw new Error("Collation returned no visible text; increase collationMaxTokens or choose a model with a smaller reasoning budget");
1708
1859
  p.tel?.recordCollate({
1709
1860
  model: `${p.collateConfig.provider}/${p.collateConfig.model}`,
1710
1861
  summaryChars: collation.length
@@ -1749,16 +1900,20 @@ async function startLlmsFullDownloads(p, successPages) {
1749
1900
  }
1750
1901
  return { staging, abort, futures };
1751
1902
  }
1752
- async function writeCacheArtifacts(p, allExtractions, fetched, searchResult, collation, llms) {
1903
+ async function writeCacheArtifacts(p, allExtractions, fetched, searchResult, collation, llms, identity2) {
1753
1904
  await withLock(
1754
1905
  cacheLockDir(p.physicalCachePath),
1755
1906
  async () => {
1907
+ await rotateCacheArtefacts(p.physicalCachePath).catch((error) => {
1908
+ p.logger.error(`Cache archive failed: ${errMsg(error)}`);
1909
+ });
1756
1910
  await writeCacheFiles(
1757
1911
  p.physicalCachePath,
1758
1912
  allExtractions,
1759
1913
  fetched.successPages,
1760
1914
  searchResult,
1761
- p.params.query
1915
+ p.params.query,
1916
+ identity2
1762
1917
  );
1763
1918
  await writeReportFile(
1764
1919
  p.physicalCachePath,
@@ -1766,7 +1921,8 @@ async function writeCacheArtifacts(p, allExtractions, fetched, searchResult, col
1766
1921
  collation,
1767
1922
  allExtractions,
1768
1923
  fetched.pages,
1769
- p.cachePath
1924
+ p.cachePath,
1925
+ identity2
1770
1926
  );
1771
1927
  await writeTelemetrySidecar(p.logger, p.tel, p.physicalCachePath, "completed");
1772
1928
  await withLock(
@@ -1836,7 +1992,34 @@ ${indexText}`;
1836
1992
  }
1837
1993
  async function degradedReturn(p, outcome, message, details) {
1838
1994
  throwIfAborted(p.signal);
1839
- await writeLockedTelemetry(p, outcome);
1995
+ const dirExists = await stat2(p.physicalCachePath).then(() => true).catch(() => false);
1996
+ if (!p.tel && !dirExists) return { text: message, details, outcome };
1997
+ try {
1998
+ await withLock(
1999
+ cacheLockDir(p.physicalCachePath),
2000
+ async () => {
2001
+ const hasReport = await stat2(join5(p.physicalCachePath, "report.md")).then(() => true).catch(() => false);
2002
+ if (!hasReport) {
2003
+ await clearCacheArtefacts(p.physicalCachePath).catch((error) => {
2004
+ p.logger.error(`Cache artefact cleanup failed: ${errMsg(error)}`);
2005
+ });
2006
+ await withLock(
2007
+ indexLockDir(p.paths.cacheRoot),
2008
+ async () => {
2009
+ const slug = p.physicalCachePath.split("/").pop() ?? p.physicalCachePath;
2010
+ await removeIndexEntry(p.paths.cacheRoot, slug);
2011
+ },
2012
+ p.signal
2013
+ );
2014
+ }
2015
+ await writeTelemetrySidecar(p.logger, p.tel, p.physicalCachePath, outcome);
2016
+ },
2017
+ p.signal
2018
+ );
2019
+ } catch (error) {
2020
+ throwIfAborted(p.signal);
2021
+ p.logger.error(`Telemetry write failed: ${errMsg(error)}`);
2022
+ }
1840
2023
  return { text: message, details, outcome };
1841
2024
  }
1842
2025
  async function flushLlmsStaging(staging, targetDir) {
@@ -9,7 +9,7 @@ var identity = Object.freeze({
9
9
 
10
10
  // packages/mcp/src/config.ts
11
11
  import { readFile, realpath, stat } from "node:fs/promises";
12
- import { isAbsolute } from "node:path";
12
+ import { isAbsolute, resolve } from "node:path";
13
13
 
14
14
  // src/core/defaults.ts
15
15
  function tuningDefaults() {
@@ -167,7 +167,66 @@ function freeze(value) {
167
167
  }
168
168
  return value;
169
169
  }
170
+ var ConfigurationError = class extends Error {
171
+ constructor(reason, message) {
172
+ super(message);
173
+ this.reason = reason;
174
+ this.name = "ConfigurationError";
175
+ }
176
+ reason;
177
+ };
178
+ function position(source, offset) {
179
+ const before = source.slice(0, Math.max(0, Math.min(offset, source.length)));
180
+ const lines = before.split("\n");
181
+ return { line: lines.length, column: lines[lines.length - 1].length + 1 };
182
+ }
183
+ function failureOffset(source) {
184
+ try {
185
+ JSON.parse(source);
186
+ return void 0;
187
+ } catch (error) {
188
+ const message = error instanceof Error ? error.message : "";
189
+ if (/Unexpected end/.test(message)) return void 0;
190
+ const offset = /at position (\d+)/.exec(message);
191
+ if (!offset) return -1;
192
+ const at = Number(offset[1]);
193
+ return at < source.length ? at : void 0;
194
+ }
195
+ }
196
+ function syntaxLocation(source) {
197
+ let offset = failureOffset(source);
198
+ if (offset === -1) {
199
+ let low = 1;
200
+ let high = source.length;
201
+ while (low < high) {
202
+ const middle = low + high >> 1;
203
+ if (failureOffset(source.slice(0, middle)) === void 0) low = middle + 1;
204
+ else high = middle;
205
+ }
206
+ offset = low - 1;
207
+ }
208
+ if (offset === void 0)
209
+ return `end of input (line ${position(source, source.trimEnd().length).line}); the file is incomplete`;
210
+ const { line, column } = position(source, offset);
211
+ return `line ${line}, column ${column}`;
212
+ }
213
+ async function resolveWorkspace(workspace) {
214
+ if (!isAbsolute(text(workspace, "workspace")))
215
+ throw new Error("workspace must be an explicit absolute directory");
216
+ let canonical;
217
+ try {
218
+ canonical = await realpath(workspace);
219
+ if (!(await stat(canonical)).isDirectory()) throw new Error();
220
+ } catch {
221
+ throw new Error("workspace must be an existing readable directory");
222
+ }
223
+ return canonical;
224
+ }
170
225
  async function parseConfig(value, workspace) {
226
+ const { apiKeyEnv, settings } = parseDocument(value);
227
+ return freeze({ workspace: await resolveWorkspace(workspace), apiKeyEnv, settings });
228
+ }
229
+ function parseDocument(value) {
171
230
  const root = object(value, "configuration");
172
231
  keys(root, ["providers", "models", "tuning"], "configuration");
173
232
  const providers = object(root.providers, "providers");
@@ -224,31 +283,56 @@ async function parseConfig(value, workspace) {
224
283
  throw new Error(
225
284
  "Search requires an explicitly enabled searchWebSearch tool or a supported Sonar search model"
226
285
  );
227
- if (!isAbsolute(text(workspace, "workspace")))
228
- throw new Error("workspace must be an explicit absolute directory");
229
- let canonical;
286
+ return { apiKeyEnv, settings };
287
+ }
288
+ async function loadConfig(file, workspace) {
289
+ const path = resolve(file).replace(/[\x00-\x1f\x7f]/g, "?");
290
+ let source;
230
291
  try {
231
- canonical = await realpath(workspace);
232
- if (!(await stat(canonical)).isDirectory()) throw new Error();
233
- } catch {
234
- throw new Error("workspace must be an existing readable directory");
292
+ source = await readFile(file, "utf8");
293
+ } catch (error) {
294
+ const code = error.code;
295
+ if (code === "ENOENT" || code === "ENOTDIR")
296
+ throw new ConfigurationError("missing", `Configuration file not found: ${path}`);
297
+ throw new ConfigurationError(
298
+ "unreadable",
299
+ code === "EISDIR" ? `Configuration path is a directory, not a file: ${path}` : code === "EACCES" || code === "EPERM" ? `Configuration file is not readable (permission denied): ${path}` : `Cannot read configuration file: ${path}`
300
+ );
235
301
  }
236
- return freeze({ workspace: canonical, apiKeyEnv, settings });
237
- }
238
- async function loadConfig(path, workspace) {
302
+ if (source.startsWith("\uFEFF")) source = source.slice(1);
303
+ if (!source.trim())
304
+ throw new ConfigurationError("invalid-json", `Configuration file is empty: ${path}`);
239
305
  let value;
240
306
  try {
241
- value = JSON.parse(await readFile(path, "utf8"));
307
+ value = JSON.parse(source);
242
308
  } catch {
243
- throw new Error("Cannot read configuration: provide an explicit readable JSON file");
309
+ throw new ConfigurationError(
310
+ "invalid-json",
311
+ `Configuration file is not valid JSON at ${syntaxLocation(source)}: ${path}`
312
+ );
313
+ }
314
+ let parsed;
315
+ try {
316
+ parsed = parseDocument(value);
317
+ } catch (error) {
318
+ throw new ConfigurationError(
319
+ "invalid",
320
+ `Invalid configuration in ${path}: ${error instanceof Error ? error.message : "unknown defect"}`
321
+ );
244
322
  }
245
- return parseConfig(value, workspace);
323
+ return freeze({
324
+ workspace: await resolveWorkspace(workspace),
325
+ apiKeyEnv: parsed.apiKeyEnv,
326
+ settings: parsed.settings
327
+ });
246
328
  }
247
329
 
248
330
  export {
249
331
  identity,
250
332
  validateCacheDir,
251
333
  validateDomains,
334
+ ConfigurationError,
335
+ resolveWorkspace,
252
336
  parseConfig,
253
337
  loadConfig
254
338
  };
package/dist/cli.js CHANGED
@@ -3,9 +3,11 @@ import {
3
3
  installStdoutGuard
4
4
  } from "./chunk-ZTHYRKI2.js";
5
5
  import {
6
+ ConfigurationError,
6
7
  identity,
7
- loadConfig
8
- } from "./chunk-5I6PWQPA.js";
8
+ loadConfig,
9
+ resolveWorkspace
10
+ } from "./chunk-EHXBTGSE.js";
9
11
 
10
12
  // packages/mcp/src/cli.ts
11
13
  import { parseArgs } from "node:util";
@@ -63,11 +65,24 @@ to standard error; standard output carries protocol messages only.
63
65
  throw new Error(
64
66
  "Explicit --config and --workspace are required (or their INTELLI_SEARCH_* environment equivalents)"
65
67
  );
66
- const config = await loadConfig(args.config, args.workspace);
68
+ const { config: file, workspace } = args;
67
69
  if (args["check-config"]) {
70
+ await loadConfig(file, workspace);
68
71
  process.stdout.write("Configuration is valid.\n");
69
72
  return;
70
73
  }
74
+ await resolveWorkspace(workspace);
75
+ let config;
76
+ try {
77
+ config = await loadConfig(file, workspace);
78
+ } catch (error) {
79
+ if (!(error instanceof ConfigurationError)) throw error;
80
+ process.stderr.write(
81
+ `[mcp-intelli-search] ${error.message}. Serving anyway: each tool call reports this and rereads the file until it loads
82
+ `
83
+ );
84
+ config = () => loadConfig(file, workspace);
85
+ }
71
86
  installStdoutGuard();
72
87
  const { startServer } = await import("./server.js");
73
88
  await startServer(config);