@mcoda/mswarm 0.1.57 → 0.1.61

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 (250) hide show
  1. package/README.md +19 -0
  2. package/dist/codali-executor.d.ts +278 -0
  3. package/dist/codali-executor.d.ts.map +1 -0
  4. package/dist/codali-executor.js +243 -0
  5. package/dist/codali-executor.js.map +1 -0
  6. package/dist/runtime.d.ts +46 -1
  7. package/dist/runtime.d.ts.map +1 -1
  8. package/dist/runtime.js +298 -30
  9. package/dist/runtime.js.map +1 -1
  10. package/dist/server.d.ts.map +1 -1
  11. package/dist/server.js +66 -1
  12. package/dist/server.js.map +1 -1
  13. package/dist/vendor/codali/agents/AgentProtocol.d.ts +287 -0
  14. package/dist/vendor/codali/agents/AgentProtocol.d.ts.map +1 -0
  15. package/dist/vendor/codali/agents/AgentProtocol.js +365 -0
  16. package/dist/vendor/codali/agents/AgentResolver.d.ts +23 -0
  17. package/dist/vendor/codali/agents/AgentResolver.d.ts.map +1 -0
  18. package/dist/vendor/codali/agents/AgentResolver.js +77 -0
  19. package/dist/vendor/codali/agents/PhaseAgentSelector.d.ts +23 -0
  20. package/dist/vendor/codali/agents/PhaseAgentSelector.d.ts.map +1 -0
  21. package/dist/vendor/codali/agents/PhaseAgentSelector.js +287 -0
  22. package/dist/vendor/codali/cli/EvalCommand.d.ts +37 -0
  23. package/dist/vendor/codali/cli/EvalCommand.d.ts.map +1 -0
  24. package/dist/vendor/codali/cli/EvalCommand.js +333 -0
  25. package/dist/vendor/codali/cli/FeedbackCommand.d.ts +22 -0
  26. package/dist/vendor/codali/cli/FeedbackCommand.d.ts.map +1 -0
  27. package/dist/vendor/codali/cli/FeedbackCommand.js +163 -0
  28. package/dist/vendor/codali/cli/RunCommand.d.ts +78 -0
  29. package/dist/vendor/codali/cli/RunCommand.d.ts.map +1 -0
  30. package/dist/vendor/codali/cli/RunCommand.js +2261 -0
  31. package/dist/vendor/codali/cli.d.ts +3 -0
  32. package/dist/vendor/codali/cli.d.ts.map +1 -0
  33. package/dist/vendor/codali/cli.js +109 -0
  34. package/dist/vendor/codali/cognitive/ArchitectPlanner.d.ts +107 -0
  35. package/dist/vendor/codali/cognitive/ArchitectPlanner.d.ts.map +1 -0
  36. package/dist/vendor/codali/cognitive/ArchitectPlanner.js +1726 -0
  37. package/dist/vendor/codali/cognitive/BuilderOutputParser.d.ts +25 -0
  38. package/dist/vendor/codali/cognitive/BuilderOutputParser.d.ts.map +1 -0
  39. package/dist/vendor/codali/cognitive/BuilderOutputParser.js +164 -0
  40. package/dist/vendor/codali/cognitive/BuilderRunner.d.ts +76 -0
  41. package/dist/vendor/codali/cognitive/BuilderRunner.d.ts.map +1 -0
  42. package/dist/vendor/codali/cognitive/BuilderRunner.js +1159 -0
  43. package/dist/vendor/codali/cognitive/ContextAssembler.d.ts +91 -0
  44. package/dist/vendor/codali/cognitive/ContextAssembler.d.ts.map +1 -0
  45. package/dist/vendor/codali/cognitive/ContextAssembler.js +4547 -0
  46. package/dist/vendor/codali/cognitive/ContextBudget.d.ts +19 -0
  47. package/dist/vendor/codali/cognitive/ContextBudget.d.ts.map +1 -0
  48. package/dist/vendor/codali/cognitive/ContextBudget.js +35 -0
  49. package/dist/vendor/codali/cognitive/ContextFileLoader.d.ts +30 -0
  50. package/dist/vendor/codali/cognitive/ContextFileLoader.d.ts.map +1 -0
  51. package/dist/vendor/codali/cognitive/ContextFileLoader.js +307 -0
  52. package/dist/vendor/codali/cognitive/ContextManager.d.ts +47 -0
  53. package/dist/vendor/codali/cognitive/ContextManager.d.ts.map +1 -0
  54. package/dist/vendor/codali/cognitive/ContextManager.js +272 -0
  55. package/dist/vendor/codali/cognitive/ContextRedactor.d.ts +18 -0
  56. package/dist/vendor/codali/cognitive/ContextRedactor.d.ts.map +1 -0
  57. package/dist/vendor/codali/cognitive/ContextRedactor.js +53 -0
  58. package/dist/vendor/codali/cognitive/ContextSelector.d.ts +22 -0
  59. package/dist/vendor/codali/cognitive/ContextSelector.d.ts.map +1 -0
  60. package/dist/vendor/codali/cognitive/ContextSelector.js +431 -0
  61. package/dist/vendor/codali/cognitive/ContextSerializer.d.ts +8 -0
  62. package/dist/vendor/codali/cognitive/ContextSerializer.d.ts.map +1 -0
  63. package/dist/vendor/codali/cognitive/ContextSerializer.js +882 -0
  64. package/dist/vendor/codali/cognitive/ContextStore.d.ts +27 -0
  65. package/dist/vendor/codali/cognitive/ContextStore.d.ts.map +1 -0
  66. package/dist/vendor/codali/cognitive/ContextStore.js +79 -0
  67. package/dist/vendor/codali/cognitive/ContextSummarizer.d.ts +16 -0
  68. package/dist/vendor/codali/cognitive/ContextSummarizer.d.ts.map +1 -0
  69. package/dist/vendor/codali/cognitive/ContextSummarizer.js +45 -0
  70. package/dist/vendor/codali/cognitive/CostEstimator.d.ts +31 -0
  71. package/dist/vendor/codali/cognitive/CostEstimator.d.ts.map +1 -0
  72. package/dist/vendor/codali/cognitive/CostEstimator.js +66 -0
  73. package/dist/vendor/codali/cognitive/CriticEvaluator.d.ts +32 -0
  74. package/dist/vendor/codali/cognitive/CriticEvaluator.d.ts.map +1 -0
  75. package/dist/vendor/codali/cognitive/CriticEvaluator.js +297 -0
  76. package/dist/vendor/codali/cognitive/EvidenceGate.d.ts +9 -0
  77. package/dist/vendor/codali/cognitive/EvidenceGate.d.ts.map +1 -0
  78. package/dist/vendor/codali/cognitive/EvidenceGate.js +75 -0
  79. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.d.ts +12 -0
  80. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.d.ts.map +1 -0
  81. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.js +34 -0
  82. package/dist/vendor/codali/cognitive/GoldenSetStore.d.ts +33 -0
  83. package/dist/vendor/codali/cognitive/GoldenSetStore.d.ts.map +1 -0
  84. package/dist/vendor/codali/cognitive/GoldenSetStore.js +159 -0
  85. package/dist/vendor/codali/cognitive/IntentSignals.d.ts +7 -0
  86. package/dist/vendor/codali/cognitive/IntentSignals.d.ts.map +1 -0
  87. package/dist/vendor/codali/cognitive/IntentSignals.js +285 -0
  88. package/dist/vendor/codali/cognitive/LearningGovernance.d.ts +100 -0
  89. package/dist/vendor/codali/cognitive/LearningGovernance.d.ts.map +1 -0
  90. package/dist/vendor/codali/cognitive/LearningGovernance.js +276 -0
  91. package/dist/vendor/codali/cognitive/MemoryWriteback.d.ts +64 -0
  92. package/dist/vendor/codali/cognitive/MemoryWriteback.d.ts.map +1 -0
  93. package/dist/vendor/codali/cognitive/MemoryWriteback.js +287 -0
  94. package/dist/vendor/codali/cognitive/PatchApplier.d.ts +49 -0
  95. package/dist/vendor/codali/cognitive/PatchApplier.d.ts.map +1 -0
  96. package/dist/vendor/codali/cognitive/PatchApplier.js +199 -0
  97. package/dist/vendor/codali/cognitive/PatchInterpreter.d.ts +35 -0
  98. package/dist/vendor/codali/cognitive/PatchInterpreter.d.ts.map +1 -0
  99. package/dist/vendor/codali/cognitive/PatchInterpreter.js +100 -0
  100. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.d.ts +7 -0
  101. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.d.ts.map +1 -0
  102. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.js +59 -0
  103. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.d.ts +17 -0
  104. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.d.ts.map +1 -0
  105. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.js +131 -0
  106. package/dist/vendor/codali/cognitive/PreferenceExtraction.d.ts +3 -0
  107. package/dist/vendor/codali/cognitive/PreferenceExtraction.d.ts.map +1 -0
  108. package/dist/vendor/codali/cognitive/PreferenceExtraction.js +85 -0
  109. package/dist/vendor/codali/cognitive/Prompts.d.ts +15 -0
  110. package/dist/vendor/codali/cognitive/Prompts.d.ts.map +1 -0
  111. package/dist/vendor/codali/cognitive/Prompts.js +326 -0
  112. package/dist/vendor/codali/cognitive/ProviderRouting.d.ts +16 -0
  113. package/dist/vendor/codali/cognitive/ProviderRouting.d.ts.map +1 -0
  114. package/dist/vendor/codali/cognitive/ProviderRouting.js +24 -0
  115. package/dist/vendor/codali/cognitive/QueryExtraction.d.ts +12 -0
  116. package/dist/vendor/codali/cognitive/QueryExtraction.d.ts.map +1 -0
  117. package/dist/vendor/codali/cognitive/QueryExtraction.js +262 -0
  118. package/dist/vendor/codali/cognitive/RunHistoryIndexer.d.ts +13 -0
  119. package/dist/vendor/codali/cognitive/RunHistoryIndexer.d.ts.map +1 -0
  120. package/dist/vendor/codali/cognitive/RunHistoryIndexer.js +125 -0
  121. package/dist/vendor/codali/cognitive/SmartPipeline.d.ts +92 -0
  122. package/dist/vendor/codali/cognitive/SmartPipeline.d.ts.map +1 -0
  123. package/dist/vendor/codali/cognitive/SmartPipeline.js +4804 -0
  124. package/dist/vendor/codali/cognitive/Types.d.ts +474 -0
  125. package/dist/vendor/codali/cognitive/Types.d.ts.map +1 -0
  126. package/dist/vendor/codali/cognitive/Types.js +7 -0
  127. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts +57 -0
  128. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts.map +1 -0
  129. package/dist/vendor/codali/cognitive/ValidationRunner.js +515 -0
  130. package/dist/vendor/codali/config/Config.d.ts +249 -0
  131. package/dist/vendor/codali/config/Config.d.ts.map +1 -0
  132. package/dist/vendor/codali/config/Config.js +200 -0
  133. package/dist/vendor/codali/config/ConfigLoader.d.ts +56 -0
  134. package/dist/vendor/codali/config/ConfigLoader.d.ts.map +1 -0
  135. package/dist/vendor/codali/config/ConfigLoader.js +1246 -0
  136. package/dist/vendor/codali/docdex/DocdexClient.d.ts +158 -0
  137. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -0
  138. package/dist/vendor/codali/docdex/DocdexClient.js +785 -0
  139. package/dist/vendor/codali/eval/EvalRunner.d.ts +35 -0
  140. package/dist/vendor/codali/eval/EvalRunner.d.ts.map +1 -0
  141. package/dist/vendor/codali/eval/EvalRunner.js +38 -0
  142. package/dist/vendor/codali/eval/EvalTaskExecutor.d.ts +81 -0
  143. package/dist/vendor/codali/eval/EvalTaskExecutor.d.ts.map +1 -0
  144. package/dist/vendor/codali/eval/EvalTaskExecutor.js +371 -0
  145. package/dist/vendor/codali/eval/GateEvaluator.d.ts +31 -0
  146. package/dist/vendor/codali/eval/GateEvaluator.d.ts.map +1 -0
  147. package/dist/vendor/codali/eval/GateEvaluator.js +134 -0
  148. package/dist/vendor/codali/eval/MetricTypes.d.ts +28 -0
  149. package/dist/vendor/codali/eval/MetricTypes.d.ts.map +1 -0
  150. package/dist/vendor/codali/eval/MetricTypes.js +1 -0
  151. package/dist/vendor/codali/eval/MetricsAggregator.d.ts +4 -0
  152. package/dist/vendor/codali/eval/MetricsAggregator.d.ts.map +1 -0
  153. package/dist/vendor/codali/eval/MetricsAggregator.js +97 -0
  154. package/dist/vendor/codali/eval/RegressionComparator.d.ts +29 -0
  155. package/dist/vendor/codali/eval/RegressionComparator.d.ts.map +1 -0
  156. package/dist/vendor/codali/eval/RegressionComparator.js +155 -0
  157. package/dist/vendor/codali/eval/ReportInputAdapter.d.ts +52 -0
  158. package/dist/vendor/codali/eval/ReportInputAdapter.d.ts.map +1 -0
  159. package/dist/vendor/codali/eval/ReportInputAdapter.js +229 -0
  160. package/dist/vendor/codali/eval/ReportSerializer.d.ts +32 -0
  161. package/dist/vendor/codali/eval/ReportSerializer.d.ts.map +1 -0
  162. package/dist/vendor/codali/eval/ReportSerializer.js +33 -0
  163. package/dist/vendor/codali/eval/ReportStore.d.ts +18 -0
  164. package/dist/vendor/codali/eval/ReportStore.d.ts.map +1 -0
  165. package/dist/vendor/codali/eval/ReportStore.js +96 -0
  166. package/dist/vendor/codali/eval/SuiteLoader.d.ts +12 -0
  167. package/dist/vendor/codali/eval/SuiteLoader.d.ts.map +1 -0
  168. package/dist/vendor/codali/eval/SuiteLoader.js +51 -0
  169. package/dist/vendor/codali/eval/SuiteSchema.d.ts +56 -0
  170. package/dist/vendor/codali/eval/SuiteSchema.d.ts.map +1 -0
  171. package/dist/vendor/codali/eval/SuiteSchema.js +357 -0
  172. package/dist/vendor/codali/index.d.ts +11 -0
  173. package/dist/vendor/codali/index.d.ts.map +1 -0
  174. package/dist/vendor/codali/index.js +5 -0
  175. package/dist/vendor/codali/providers/CodexCliProvider.d.ts +8 -0
  176. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -0
  177. package/dist/vendor/codali/providers/CodexCliProvider.js +282 -0
  178. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts +8 -0
  179. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -0
  180. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +300 -0
  181. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts +8 -0
  182. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -0
  183. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +192 -0
  184. package/dist/vendor/codali/providers/ProviderRegistry.d.ts +12 -0
  185. package/dist/vendor/codali/providers/ProviderRegistry.d.ts.map +1 -0
  186. package/dist/vendor/codali/providers/ProviderRegistry.js +28 -0
  187. package/dist/vendor/codali/providers/ProviderTypes.d.ts +81 -0
  188. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -0
  189. package/dist/vendor/codali/providers/ProviderTypes.js +1 -0
  190. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +189 -0
  191. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -0
  192. package/dist/vendor/codali/runtime/CodaliRuntime.js +1435 -0
  193. package/dist/vendor/codali/runtime/DeepInvestigationErrors.d.ts +39 -0
  194. package/dist/vendor/codali/runtime/DeepInvestigationErrors.d.ts.map +1 -0
  195. package/dist/vendor/codali/runtime/DeepInvestigationErrors.js +57 -0
  196. package/dist/vendor/codali/runtime/RunContext.d.ts +27 -0
  197. package/dist/vendor/codali/runtime/RunContext.d.ts.map +1 -0
  198. package/dist/vendor/codali/runtime/RunContext.js +51 -0
  199. package/dist/vendor/codali/runtime/RunLogQuery.d.ts +48 -0
  200. package/dist/vendor/codali/runtime/RunLogQuery.d.ts.map +1 -0
  201. package/dist/vendor/codali/runtime/RunLogQuery.js +36 -0
  202. package/dist/vendor/codali/runtime/RunLogReader.d.ts +19 -0
  203. package/dist/vendor/codali/runtime/RunLogReader.d.ts.map +1 -0
  204. package/dist/vendor/codali/runtime/RunLogReader.js +361 -0
  205. package/dist/vendor/codali/runtime/RunLogger.d.ts +71 -0
  206. package/dist/vendor/codali/runtime/RunLogger.d.ts.map +1 -0
  207. package/dist/vendor/codali/runtime/RunLogger.js +100 -0
  208. package/dist/vendor/codali/runtime/RunTelemetryTypes.d.ts +117 -0
  209. package/dist/vendor/codali/runtime/RunTelemetryTypes.d.ts.map +1 -0
  210. package/dist/vendor/codali/runtime/RunTelemetryTypes.js +299 -0
  211. package/dist/vendor/codali/runtime/Runner.d.ts +66 -0
  212. package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -0
  213. package/dist/vendor/codali/runtime/Runner.js +215 -0
  214. package/dist/vendor/codali/runtime/StoragePaths.d.ts +3 -0
  215. package/dist/vendor/codali/runtime/StoragePaths.d.ts.map +1 -0
  216. package/dist/vendor/codali/runtime/StoragePaths.js +19 -0
  217. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts +30 -0
  218. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -0
  219. package/dist/vendor/codali/runtime/WorkspaceLock.js +141 -0
  220. package/dist/vendor/codali/session/InstructionLoader.d.ts +14 -0
  221. package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -0
  222. package/dist/vendor/codali/session/InstructionLoader.js +107 -0
  223. package/dist/vendor/codali/session/SessionStore.d.ts +81 -0
  224. package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -0
  225. package/dist/vendor/codali/session/SessionStore.js +244 -0
  226. package/dist/vendor/codali/subagents/SubagentOrchestrator.d.ts +68 -0
  227. package/dist/vendor/codali/subagents/SubagentOrchestrator.d.ts.map +1 -0
  228. package/dist/vendor/codali/subagents/SubagentOrchestrator.js +150 -0
  229. package/dist/vendor/codali/tools/ToolRegistry.d.ts +9 -0
  230. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -0
  231. package/dist/vendor/codali/tools/ToolRegistry.js +293 -0
  232. package/dist/vendor/codali/tools/ToolTypes.d.ts +66 -0
  233. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -0
  234. package/dist/vendor/codali/tools/ToolTypes.js +40 -0
  235. package/dist/vendor/codali/tools/diff/DiffTool.d.ts +3 -0
  236. package/dist/vendor/codali/tools/diff/DiffTool.d.ts.map +1 -0
  237. package/dist/vendor/codali/tools/diff/DiffTool.js +34 -0
  238. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +4 -0
  239. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -0
  240. package/dist/vendor/codali/tools/docdex/DocdexTools.js +490 -0
  241. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts +3 -0
  242. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -0
  243. package/dist/vendor/codali/tools/filesystem/FileTools.js +141 -0
  244. package/dist/vendor/codali/tools/search/SearchTool.d.ts +3 -0
  245. package/dist/vendor/codali/tools/search/SearchTool.d.ts.map +1 -0
  246. package/dist/vendor/codali/tools/search/SearchTool.js +46 -0
  247. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +3 -0
  248. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -0
  249. package/dist/vendor/codali/tools/shell/ShellTool.js +104 -0
  250. package/package.json +5 -3
@@ -0,0 +1,785 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ export class DocdexRuntimeError extends Error {
5
+ constructor(code, message, options = {}) {
6
+ super(message);
7
+ this.name = code;
8
+ this.code = code;
9
+ this.status = options.status;
10
+ this.retryable = options.retryable ?? code === "docdex_unavailable";
11
+ this.details = options.details;
12
+ }
13
+ }
14
+ const CAPABILITY_KEYS = [
15
+ "score_breakdown",
16
+ "rerank",
17
+ "snippet_provenance",
18
+ "retrieval_explanation",
19
+ "batch_search",
20
+ ];
21
+ const DOCDEX_RUNTIME_ERROR_CODES = new Set([
22
+ "docdex_context_missing",
23
+ "docdex_api_key_missing",
24
+ "docdex_operation_not_allowed",
25
+ "docdex_auth_failed",
26
+ "docdex_repo_access_denied",
27
+ "docdex_unavailable",
28
+ ]);
29
+ const DOCDEX_RUNTIME_OPERATIONS = new Set([
30
+ "health",
31
+ "initialize",
32
+ "search",
33
+ "snippet",
34
+ "open",
35
+ "symbols",
36
+ "ast",
37
+ "impact_graph",
38
+ "impact_diagnostics",
39
+ "dag_export",
40
+ "tree",
41
+ "memory_save",
42
+ "memory_recall",
43
+ "profile_read",
44
+ "profile_write",
45
+ "web_research",
46
+ "chat_context",
47
+ "rerank",
48
+ "batch_search",
49
+ "capabilities",
50
+ "stats",
51
+ "files",
52
+ "repo_inspect",
53
+ "index_rebuild",
54
+ "index_ingest",
55
+ "delegate",
56
+ "hooks_validate",
57
+ ]);
58
+ const MCP_OPERATION_BY_METHOD = {
59
+ docdex_symbols: "symbols",
60
+ docdex_ast: "ast",
61
+ docdex_stats: "stats",
62
+ docdex_files: "files",
63
+ docdex_repo_inspect: "repo_inspect",
64
+ docdex_memory_save: "memory_save",
65
+ docdex_memory_recall: "memory_recall",
66
+ docdex_tree: "tree",
67
+ docdex_open: "open",
68
+ docdex_get_profile: "profile_read",
69
+ docdex_save_preference: "profile_write",
70
+ docdex_web_research: "web_research",
71
+ docdex_rerank: "rerank",
72
+ docdex_batch_search: "batch_search",
73
+ docdex_capabilities: "capabilities",
74
+ };
75
+ export const isDocdexRuntimeErrorCode = (value) => {
76
+ return typeof value === "string" && DOCDEX_RUNTIME_ERROR_CODES.has(value);
77
+ };
78
+ export const normalizeDocdexRuntimeOperation = (value) => {
79
+ const normalized = value.trim().replace(/[.-]/g, "_").toLowerCase();
80
+ const aliases = {
81
+ impact: "impact_graph",
82
+ diagnostics: "impact_diagnostics",
83
+ impact_diagnostics: "impact_diagnostics",
84
+ web: "web_research",
85
+ web_search: "web_research",
86
+ chat: "chat_context",
87
+ chat_completions: "chat_context",
88
+ context_chat: "chat_context",
89
+ open_file: "open",
90
+ snippet_fetch: "snippet",
91
+ profile: "profile_read",
92
+ get_profile: "profile_read",
93
+ save_preference: "profile_write",
94
+ memory: "memory_recall",
95
+ index: "index_rebuild",
96
+ hooks: "hooks_validate",
97
+ };
98
+ const aliased = aliases[normalized];
99
+ if (aliased)
100
+ return aliased;
101
+ return DOCDEX_RUNTIME_OPERATIONS.has(normalized)
102
+ ? normalized
103
+ : undefined;
104
+ };
105
+ const escapeRegExp = (value) => {
106
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
107
+ };
108
+ export class DocdexClient {
109
+ constructor(options) {
110
+ this.options = options;
111
+ this.healthChecked = false;
112
+ this.repoInitializeAttempted = false;
113
+ this.repoId = options.repoId;
114
+ this.dagSessionId = options.dagSessionId;
115
+ }
116
+ setRepoId(repoId) {
117
+ this.repoId = repoId;
118
+ }
119
+ getRepoId() {
120
+ return this.repoId;
121
+ }
122
+ getRepoRoot() {
123
+ return this.options.repoRoot;
124
+ }
125
+ setDagSessionId(sessionId) {
126
+ this.dagSessionId = sessionId;
127
+ }
128
+ getDagSessionId() {
129
+ return this.dagSessionId;
130
+ }
131
+ clearCapabilityCache() {
132
+ this.capabilitySnapshot = undefined;
133
+ }
134
+ runtimeAllowedOperations() {
135
+ if (!this.options.allowedOperations?.length)
136
+ return undefined;
137
+ const operations = this.options.allowedOperations
138
+ .map((entry) => normalizeDocdexRuntimeOperation(entry))
139
+ .filter((entry) => Boolean(entry));
140
+ return operations.length ? new Set(operations) : new Set();
141
+ }
142
+ runtimeCapability(operation) {
143
+ if (!this.options.capabilities)
144
+ return undefined;
145
+ for (const [key, value] of Object.entries(this.options.capabilities)) {
146
+ const normalized = normalizeDocdexRuntimeOperation(key);
147
+ if (normalized === operation && typeof value === "boolean") {
148
+ return value;
149
+ }
150
+ }
151
+ return undefined;
152
+ }
153
+ redactSensitiveText(text) {
154
+ let output = text;
155
+ for (const secret of [this.options.apiKey, this.options.authToken]) {
156
+ if (typeof secret === "string" && secret.length >= 4) {
157
+ output = output.replace(new RegExp(escapeRegExp(secret), "g"), "[redacted]");
158
+ }
159
+ }
160
+ output = output.replace(/("(?:x-api-key|authorization|api[_-]?key|token|secret)"\s*:\s*")[^"]+(")/gi, "$1[redacted]$2");
161
+ output = output.replace(/((?:x-api-key|authorization|api[_-]?key|token|secret)\s*[:=]\s*)(?:Bearer\s+)?[^\s,;}]+/gi, "$1[redacted]");
162
+ return output;
163
+ }
164
+ runtimeError(code, message, options = {}) {
165
+ return new DocdexRuntimeError(code, this.redactSensitiveText(message), options);
166
+ }
167
+ assertRuntimeContext(operation) {
168
+ const credentialSource = this.options.credentialSource;
169
+ const requiresAttachedKey = credentialSource === "attached_mswarm_api_key";
170
+ if (requiresAttachedKey && (!this.options.apiKey || this.options.apiKey.trim().length === 0)) {
171
+ throw this.runtimeError("docdex_api_key_missing", "Docdex attached mswarm API key is required but was not provided.", { retryable: false, details: { operation, credential_source: credentialSource } });
172
+ }
173
+ if (this.options.required && this.resolveBaseUrl().length === 0) {
174
+ throw this.runtimeError("docdex_context_missing", "Docdex base_url is required for this job.", {
175
+ retryable: false,
176
+ details: { operation },
177
+ });
178
+ }
179
+ if (this.options.required && requiresAttachedKey && !this.repoId) {
180
+ throw this.runtimeError("docdex_context_missing", "Docdex repo_id is required for this job.", {
181
+ retryable: false,
182
+ details: { operation },
183
+ });
184
+ }
185
+ }
186
+ assertOperationAllowed(operation) {
187
+ this.assertRuntimeContext(operation);
188
+ const allowedOperations = this.runtimeAllowedOperations();
189
+ if (allowedOperations && !allowedOperations.has(operation)) {
190
+ throw this.runtimeError("docdex_operation_not_allowed", `Docdex operation is not allowed by this job: ${operation}`, { retryable: false, details: { operation } });
191
+ }
192
+ if (this.runtimeCapability(operation) === false) {
193
+ throw this.runtimeError("docdex_operation_not_allowed", `Docdex operation is disabled by this job capability map: ${operation}`, { retryable: false, details: { operation } });
194
+ }
195
+ }
196
+ resolveBaseUrl() {
197
+ const base = this.options.baseUrl.trim();
198
+ return base.endsWith("/") ? base.slice(0, -1) : base;
199
+ }
200
+ buildHeaders(dagSessionId) {
201
+ const headers = { "content-type": "application/json" };
202
+ if (this.options.apiKey) {
203
+ headers["x-api-key"] = this.options.apiKey;
204
+ }
205
+ else if (this.options.authToken) {
206
+ headers.authorization = `Bearer ${this.options.authToken}`;
207
+ }
208
+ if (this.repoId)
209
+ headers["x-docdex-repo-id"] = this.repoId;
210
+ if (this.options.repoRoot)
211
+ headers["x-docdex-repo-root"] = path.resolve(this.options.repoRoot);
212
+ const resolvedDagSessionId = dagSessionId ?? this.dagSessionId;
213
+ if (resolvedDagSessionId)
214
+ headers["x-docdex-dag-session"] = resolvedDagSessionId;
215
+ return headers;
216
+ }
217
+ async ensureHealth() {
218
+ if (this.healthChecked)
219
+ return;
220
+ let ok = false;
221
+ try {
222
+ ok = await this.healthCheck();
223
+ }
224
+ catch (error) {
225
+ if (error instanceof DocdexRuntimeError)
226
+ throw error;
227
+ throw this.runtimeError("docdex_unavailable", `Docdex health check failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: true });
228
+ }
229
+ if (!ok) {
230
+ throw this.runtimeError("docdex_unavailable", "Docdex health check failed", {
231
+ retryable: true,
232
+ });
233
+ }
234
+ }
235
+ async healthCheck() {
236
+ let response;
237
+ try {
238
+ response = await fetch(`${this.resolveBaseUrl()}/healthz`);
239
+ }
240
+ catch (error) {
241
+ throw this.runtimeError("docdex_unavailable", `Docdex health check failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: true });
242
+ }
243
+ this.healthChecked = response.ok;
244
+ return response.ok;
245
+ }
246
+ async initialize(rootUri) {
247
+ this.assertOperationAllowed("initialize");
248
+ return this.initializeRepo(rootUri);
249
+ }
250
+ async initializeRepo(rootUri) {
251
+ await this.ensureHealth();
252
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/initialize`, {
253
+ method: "POST",
254
+ headers: this.buildHeaders(),
255
+ body: JSON.stringify({ rootUri }),
256
+ });
257
+ if (!response.ok) {
258
+ await this.throwResponseError(response, "initialize");
259
+ }
260
+ const payload = (await response.json());
261
+ const repoId = (payload.repo_id ?? payload.repoId ?? payload.repo);
262
+ const repoRoot = (payload.repo_root ?? payload.repoRoot);
263
+ if (repoId)
264
+ this.repoId = repoId;
265
+ return { repoId, repoRoot };
266
+ }
267
+ async ensureRepoInitialized() {
268
+ if (this.repoId || this.repoInitializeAttempted || !this.options.repoRoot)
269
+ return;
270
+ this.repoInitializeAttempted = true;
271
+ try {
272
+ await this.initializeRepo(pathToFileURL(path.resolve(this.options.repoRoot)).toString());
273
+ }
274
+ catch {
275
+ // Keep endpoint-specific calls responsible for reporting the final failure.
276
+ // Single-repo daemons can still accept repo_root without a prior initialize.
277
+ }
278
+ }
279
+ withRepoId(params) {
280
+ if (this.repoId)
281
+ params.set("repo_id", this.repoId);
282
+ if (this.options.repoRoot)
283
+ params.set("repo_root", path.resolve(this.options.repoRoot));
284
+ }
285
+ extractErrorCode(body) {
286
+ const parsed = this.tryParseJson(body);
287
+ if (!parsed || typeof parsed !== "object")
288
+ return undefined;
289
+ const record = parsed;
290
+ const error = record.error && typeof record.error === "object"
291
+ ? record.error
292
+ : undefined;
293
+ const code = error?.code ?? record.code;
294
+ return typeof code === "string" ? code : undefined;
295
+ }
296
+ mapResponseErrorCode(status, body) {
297
+ const extracted = this.extractErrorCode(body);
298
+ if (isDocdexRuntimeErrorCode(extracted))
299
+ return extracted;
300
+ const normalized = `${extracted ?? ""} ${body}`.toLowerCase();
301
+ if (/introspection_unavailable|unavailable|timeout|timed out|econnrefused|enotfound/.test(normalized)) {
302
+ return "docdex_unavailable";
303
+ }
304
+ if (/repo_access_denied|unknown_repo|repo.*denied|denied.*repo/.test(normalized)) {
305
+ return "docdex_repo_access_denied";
306
+ }
307
+ if (/scope_denied|operation_not_allowed|encrypted_operation_disabled|not allowed|forbidden_operation/.test(normalized)) {
308
+ return "docdex_operation_not_allowed";
309
+ }
310
+ if (status === 401 || status === 403 || /invalid_credentials|missing_credentials|ambiguous_credentials/.test(normalized)) {
311
+ return "docdex_auth_failed";
312
+ }
313
+ return "docdex_unavailable";
314
+ }
315
+ async throwResponseError(response, operation) {
316
+ const body = await response.text();
317
+ const code = this.mapResponseErrorCode(response.status, body);
318
+ throw this.runtimeError(code, `Docdex ${operation} failed (${response.status}): ${body}`, {
319
+ status: response.status,
320
+ retryable: code === "docdex_unavailable" && response.status >= 500,
321
+ details: { operation },
322
+ });
323
+ }
324
+ async search(query, options = {}) {
325
+ this.assertOperationAllowed("search");
326
+ await this.ensureHealth();
327
+ await this.ensureRepoInitialized();
328
+ const params = new URLSearchParams({ q: query });
329
+ if (options.limit !== undefined)
330
+ params.set("limit", String(options.limit));
331
+ const dagSessionId = options.dagSessionId ?? this.dagSessionId;
332
+ if (dagSessionId)
333
+ params.set("dag_session_id", dagSessionId);
334
+ this.withRepoId(params);
335
+ const response = await fetch(`${this.resolveBaseUrl()}/search?${params.toString()}`, {
336
+ headers: this.buildHeaders(dagSessionId),
337
+ });
338
+ if (!response.ok) {
339
+ await this.throwResponseError(response, "search");
340
+ }
341
+ return response.json();
342
+ }
343
+ async openSnippet(docId, options = {}) {
344
+ this.assertOperationAllowed("snippet");
345
+ await this.ensureHealth();
346
+ await this.ensureRepoInitialized();
347
+ const params = new URLSearchParams();
348
+ if (options.window !== undefined)
349
+ params.set("window", String(options.window));
350
+ if (options.textOnly)
351
+ params.set("text_only", "true");
352
+ this.withRepoId(params);
353
+ const response = await fetch(`${this.resolveBaseUrl()}/snippet/${encodeURIComponent(docId)}?${params.toString()}`, {
354
+ headers: this.buildHeaders(),
355
+ });
356
+ if (!response.ok) {
357
+ await this.throwResponseError(response, "snippet");
358
+ }
359
+ const contentType = response.headers.get("content-type") ?? "";
360
+ if (contentType.includes("application/json")) {
361
+ return response.json();
362
+ }
363
+ return response.text();
364
+ }
365
+ async impactGraph(file, options = {}) {
366
+ this.assertOperationAllowed("impact_graph");
367
+ await this.ensureHealth();
368
+ await this.ensureRepoInitialized();
369
+ const params = new URLSearchParams({ file });
370
+ if (options.maxDepth !== undefined)
371
+ params.set("max_depth", String(options.maxDepth));
372
+ if (options.maxEdges !== undefined)
373
+ params.set("max_edges", String(options.maxEdges));
374
+ if (options.edgeTypes?.length)
375
+ params.set("edge_types", options.edgeTypes.join(","));
376
+ this.withRepoId(params);
377
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/graph/impact?${params.toString()}`, {
378
+ headers: this.buildHeaders(),
379
+ });
380
+ if (!response.ok) {
381
+ await this.throwResponseError(response, "impact graph");
382
+ }
383
+ return response.json();
384
+ }
385
+ async impactDiagnostics(options = {}) {
386
+ this.assertOperationAllowed("impact_diagnostics");
387
+ await this.ensureHealth();
388
+ await this.ensureRepoInitialized();
389
+ const params = new URLSearchParams();
390
+ if (options.file)
391
+ params.set("file", options.file);
392
+ if (options.limit !== undefined)
393
+ params.set("limit", String(options.limit));
394
+ if (options.offset !== undefined)
395
+ params.set("offset", String(options.offset));
396
+ this.withRepoId(params);
397
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/graph/impact/diagnostics?${params.toString()}`, {
398
+ headers: this.buildHeaders(),
399
+ });
400
+ if (!response.ok) {
401
+ await this.throwResponseError(response, "impact diagnostics");
402
+ }
403
+ return response.json();
404
+ }
405
+ async indexRebuild(libsSources) {
406
+ this.assertOperationAllowed("index_rebuild");
407
+ await this.ensureHealth();
408
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/index/rebuild`, {
409
+ method: "POST",
410
+ headers: this.buildHeaders(),
411
+ body: JSON.stringify(libsSources ? { libs_sources: libsSources } : {}),
412
+ });
413
+ if (!response.ok) {
414
+ await this.throwResponseError(response, "index rebuild");
415
+ }
416
+ return response.json();
417
+ }
418
+ async indexIngest(file) {
419
+ this.assertOperationAllowed("index_ingest");
420
+ await this.ensureHealth();
421
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/index/ingest`, {
422
+ method: "POST",
423
+ headers: this.buildHeaders(),
424
+ body: JSON.stringify({ file }),
425
+ });
426
+ if (!response.ok) {
427
+ await this.throwResponseError(response, "index ingest");
428
+ }
429
+ return response.json();
430
+ }
431
+ async hooksValidate(files) {
432
+ this.assertOperationAllowed("hooks_validate");
433
+ await this.ensureHealth();
434
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/hooks/validate`, {
435
+ method: "POST",
436
+ headers: this.buildHeaders(),
437
+ body: JSON.stringify({ files }),
438
+ });
439
+ if (!response.ok) {
440
+ await this.throwResponseError(response, "hooks validate");
441
+ }
442
+ return response.json();
443
+ }
444
+ async delegate(payload) {
445
+ this.assertOperationAllowed("delegate");
446
+ await this.ensureHealth();
447
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/delegate`, {
448
+ method: "POST",
449
+ headers: this.buildHeaders(),
450
+ body: JSON.stringify(payload),
451
+ });
452
+ if (!response.ok) {
453
+ await this.throwResponseError(response, "delegate");
454
+ }
455
+ return response.json();
456
+ }
457
+ async chatContext(messages, options = {}) {
458
+ this.assertOperationAllowed("chat_context");
459
+ await this.ensureHealth();
460
+ await this.ensureRepoInitialized();
461
+ const body = {
462
+ messages,
463
+ stream: false,
464
+ };
465
+ if (options.model)
466
+ body.model = options.model;
467
+ if (options.maxTokens !== undefined)
468
+ body.max_tokens = options.maxTokens;
469
+ if (options.temperature !== undefined)
470
+ body.temperature = options.temperature;
471
+ if (options.docdex)
472
+ body.docdex = options.docdex;
473
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/chat/completions`, {
474
+ method: "POST",
475
+ headers: this.buildHeaders(this.dagSessionId),
476
+ body: JSON.stringify(body),
477
+ });
478
+ if (!response.ok) {
479
+ await this.throwResponseError(response, "chat context");
480
+ }
481
+ return response.json();
482
+ }
483
+ async dagExport(sessionId, options = {}) {
484
+ this.assertOperationAllowed("dag_export");
485
+ await this.ensureHealth();
486
+ await this.ensureRepoInitialized();
487
+ const params = new URLSearchParams({ session_id: sessionId });
488
+ if (options.format)
489
+ params.set("format", options.format);
490
+ if (options.maxNodes !== undefined)
491
+ params.set("max_nodes", String(options.maxNodes));
492
+ this.withRepoId(params);
493
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/dag/export?${params.toString()}`, {
494
+ headers: this.buildHeaders(),
495
+ });
496
+ const body = await response.text();
497
+ if (!response.ok) {
498
+ const code = this.mapResponseErrorCode(response.status, body);
499
+ throw this.runtimeError(code, `Docdex dag export failed (${response.status}): ${body}`, {
500
+ status: response.status,
501
+ retryable: code === "docdex_unavailable" && response.status >= 500,
502
+ details: { operation: "dag_export" },
503
+ });
504
+ }
505
+ const contentType = response.headers.get("content-type") ?? "";
506
+ if (contentType.includes("application/json")) {
507
+ try {
508
+ return JSON.parse(body);
509
+ }
510
+ catch {
511
+ return body;
512
+ }
513
+ }
514
+ return body;
515
+ }
516
+ async callMcp(method, params) {
517
+ const operation = MCP_OPERATION_BY_METHOD[method];
518
+ if (operation) {
519
+ this.assertOperationAllowed(operation);
520
+ }
521
+ await this.ensureHealth();
522
+ const payload = {
523
+ jsonrpc: "2.0",
524
+ id: randomUUID(),
525
+ method,
526
+ params,
527
+ };
528
+ const response = await fetch(`${this.resolveBaseUrl()}/v1/mcp`, {
529
+ method: "POST",
530
+ headers: this.buildHeaders(),
531
+ body: JSON.stringify(payload),
532
+ });
533
+ if (!response.ok) {
534
+ await this.throwResponseError(response, "MCP");
535
+ }
536
+ const raw = (await response.json());
537
+ if (raw.error) {
538
+ const body = JSON.stringify(raw.error);
539
+ const code = this.mapResponseErrorCode(500, body);
540
+ throw this.runtimeError(code, raw.error.message ?? "Docdex MCP error", {
541
+ retryable: code === "docdex_unavailable",
542
+ details: { method },
543
+ });
544
+ }
545
+ return this.normalizeMcpResult(raw.result);
546
+ }
547
+ normalizeMcpResult(payload) {
548
+ if (!payload || typeof payload !== "object")
549
+ return payload;
550
+ const record = payload;
551
+ if (record.structuredContent !== undefined) {
552
+ return record.structuredContent;
553
+ }
554
+ if (!Array.isArray(record.content) || record.content.length === 0) {
555
+ return payload;
556
+ }
557
+ const textChunks = record.content
558
+ .map((entry) => {
559
+ if (!entry || typeof entry !== "object")
560
+ return undefined;
561
+ const text = entry.text;
562
+ return typeof text === "string" ? text : undefined;
563
+ })
564
+ .filter((text) => typeof text === "string");
565
+ if (textChunks.length === 0) {
566
+ return payload;
567
+ }
568
+ const joined = textChunks.join("\n").trim();
569
+ if (joined.length === 0) {
570
+ return payload;
571
+ }
572
+ const parsed = this.tryParseJson(joined);
573
+ return parsed ?? joined;
574
+ }
575
+ tryParseJson(text) {
576
+ const trimmed = text.trim();
577
+ if (!trimmed)
578
+ return undefined;
579
+ try {
580
+ return JSON.parse(trimmed);
581
+ }
582
+ catch {
583
+ return undefined;
584
+ }
585
+ }
586
+ buildProjectParams(extra) {
587
+ return {
588
+ project_root: this.options.repoRoot,
589
+ ...extra,
590
+ };
591
+ }
592
+ defaultCapabilityMap(status) {
593
+ return {
594
+ score_breakdown: status,
595
+ rerank: status,
596
+ snippet_provenance: status,
597
+ retrieval_explanation: status,
598
+ batch_search: status,
599
+ };
600
+ }
601
+ toCapabilityStatus(value) {
602
+ if (value === true)
603
+ return "available";
604
+ if (value === false)
605
+ return "unavailable";
606
+ if (typeof value === "number")
607
+ return value > 0 ? "available" : "unavailable";
608
+ if (typeof value !== "string")
609
+ return "unknown";
610
+ const normalized = value.trim().toLowerCase();
611
+ if (["available", "enabled", "supported", "ok", "true", "yes"].includes(normalized)) {
612
+ return "available";
613
+ }
614
+ if (["unavailable", "disabled", "unsupported", "none", "false", "no"].includes(normalized)) {
615
+ return "unavailable";
616
+ }
617
+ return "unknown";
618
+ }
619
+ normalizeCapabilityPayload(payload) {
620
+ if (!payload || typeof payload !== "object")
621
+ return undefined;
622
+ const record = payload;
623
+ const source = ((record.capabilities && typeof record.capabilities === "object"
624
+ ? record.capabilities
625
+ : undefined) ??
626
+ (record.retrieval && typeof record.retrieval === "object"
627
+ ? record.retrieval
628
+ : undefined) ??
629
+ record);
630
+ const scopedSource = (source.retrieval && typeof source.retrieval === "object"
631
+ ? source.retrieval
632
+ : source);
633
+ const aliases = {
634
+ score_breakdown: ["score_breakdown", "structured_scoring", "scoring"],
635
+ rerank: ["rerank", "re_rank"],
636
+ snippet_provenance: ["snippet_provenance", "stable_provenance", "provenance"],
637
+ retrieval_explanation: ["retrieval_explanation", "hit_explanations", "explanations", "retrieval_explanations"],
638
+ batch_search: ["batch_search", "batch_retrieval", "batch", "multi_fetch"],
639
+ };
640
+ const result = this.defaultCapabilityMap("unknown");
641
+ let found = false;
642
+ for (const key of CAPABILITY_KEYS) {
643
+ const aliasKeys = aliases[key];
644
+ const raw = aliasKeys.map((alias) => scopedSource[alias]).find((entry) => entry !== undefined);
645
+ if (raw === undefined)
646
+ continue;
647
+ found = true;
648
+ result[key] = this.toCapabilityStatus(raw);
649
+ }
650
+ return found ? result : undefined;
651
+ }
652
+ symbols(pathValue) {
653
+ return this.callMcp("docdex_symbols", this.buildProjectParams({ path: pathValue }));
654
+ }
655
+ ast(pathValue, maxNodes) {
656
+ return this.callMcp("docdex_ast", this.buildProjectParams({ path: pathValue, max_nodes: maxNodes }));
657
+ }
658
+ stats() {
659
+ return this.callMcp("docdex_stats", this.buildProjectParams({}));
660
+ }
661
+ files(limit, offset) {
662
+ return this.callMcp("docdex_files", this.buildProjectParams({ limit, offset }));
663
+ }
664
+ repoInspect() {
665
+ return this.callMcp("docdex_repo_inspect", this.buildProjectParams({}));
666
+ }
667
+ memorySave(text, metadata) {
668
+ return this.callMcp("docdex_memory_save", this.buildProjectParams({ text, metadata }));
669
+ }
670
+ memoryRecall(query, topK) {
671
+ return this.callMcp("docdex_memory_recall", this.buildProjectParams({ query, top_k: topK }));
672
+ }
673
+ tree(options = {}) {
674
+ return this.callMcp("docdex_tree", this.buildProjectParams({
675
+ path: options.path,
676
+ max_depth: options.maxDepth,
677
+ dirs_only: options.dirsOnly,
678
+ include_hidden: options.includeHidden,
679
+ extra_excludes: options.extraExcludes,
680
+ }));
681
+ }
682
+ openFile(pathValue, options = {}) {
683
+ return this.callMcp("docdex_open", this.buildProjectParams({
684
+ path: pathValue,
685
+ start_line: options.startLine,
686
+ end_line: options.endLine,
687
+ head: options.head,
688
+ clamp: options.clamp,
689
+ }));
690
+ }
691
+ getProfile(agentId) {
692
+ const params = {};
693
+ if (agentId)
694
+ params.agent_id = agentId;
695
+ return this.callMcp("docdex_get_profile", params);
696
+ }
697
+ savePreference(agentId, category, content, metadata) {
698
+ return this.callMcp("docdex_save_preference", {
699
+ agent_id: agentId,
700
+ category,
701
+ content,
702
+ metadata,
703
+ });
704
+ }
705
+ webResearch(query, options = {}) {
706
+ return this.callMcp("docdex_web_research", this.buildProjectParams({
707
+ query,
708
+ force_web: options.forceWeb ?? true,
709
+ skip_local_search: options.skipLocalSearch,
710
+ web_limit: options.webLimit,
711
+ no_cache: options.noCache,
712
+ })).catch(() => this.webResearchHttp(query, options));
713
+ }
714
+ async webResearchHttp(query, options = {}) {
715
+ this.assertOperationAllowed("web_research");
716
+ await this.ensureHealth();
717
+ await this.ensureRepoInitialized();
718
+ const params = new URLSearchParams({ q: query });
719
+ params.set("force_web", String(options.forceWeb ?? true));
720
+ if (options.skipLocalSearch !== undefined) {
721
+ params.set("skip_local_search", String(options.skipLocalSearch));
722
+ }
723
+ if (options.webLimit !== undefined) {
724
+ params.set("max_web_results", String(options.webLimit));
725
+ }
726
+ if (options.noCache !== undefined) {
727
+ params.set("no_cache", String(options.noCache));
728
+ }
729
+ this.withRepoId(params);
730
+ const response = await fetch(`${this.resolveBaseUrl()}/search?${params.toString()}`, {
731
+ headers: this.buildHeaders(this.dagSessionId),
732
+ });
733
+ if (!response.ok) {
734
+ await this.throwResponseError(response, "web research");
735
+ }
736
+ return response.json();
737
+ }
738
+ rerank(query, candidates, limit) {
739
+ return this.callMcp("docdex_rerank", this.buildProjectParams({
740
+ query,
741
+ candidates,
742
+ limit,
743
+ }));
744
+ }
745
+ batchSearch(queries, options = {}) {
746
+ return this.callMcp("docdex_batch_search", this.buildProjectParams({
747
+ queries,
748
+ limit: options.limit,
749
+ include_libs: options.includeLibs,
750
+ }));
751
+ }
752
+ async getCapabilities(forceRefresh = false) {
753
+ if (this.capabilitySnapshot && !forceRefresh) {
754
+ return { ...this.capabilitySnapshot, cached: true };
755
+ }
756
+ try {
757
+ const payload = await this.callMcp("docdex_capabilities", this.buildProjectParams({}));
758
+ const normalizedCapabilities = this.normalizeCapabilityPayload(payload);
759
+ const capabilities = normalizedCapabilities ?? this.defaultCapabilityMap("unknown");
760
+ const warnings = normalizedCapabilities ? undefined : ["probe_missing_capability_fields"];
761
+ const snapshot = {
762
+ cached: false,
763
+ source: "mcp_probe",
764
+ probed_at_ms: Date.now(),
765
+ capabilities,
766
+ warnings,
767
+ };
768
+ this.capabilitySnapshot = snapshot;
769
+ return snapshot;
770
+ }
771
+ catch (error) {
772
+ const snapshot = {
773
+ cached: false,
774
+ source: "fallback",
775
+ probed_at_ms: Date.now(),
776
+ capabilities: this.defaultCapabilityMap("unavailable"),
777
+ warnings: [
778
+ `probe_failed:${error instanceof Error ? error.message : String(error)}`,
779
+ ],
780
+ };
781
+ this.capabilitySnapshot = snapshot;
782
+ return snapshot;
783
+ }
784
+ }
785
+ }