@octocodeai/octocode-tools-core 18.2.0 → 19.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 (242) hide show
  1. package/README.md +19 -19
  2. package/dist/chunks/direct/chunk-3AA4F3QO.js +10 -0
  3. package/dist/chunks/direct/chunk-43RVQWTG.js +8 -0
  4. package/dist/chunks/direct/chunk-7DYE654A.js +8 -0
  5. package/dist/chunks/direct/chunk-A4WMBDEC.js +8 -0
  6. package/dist/chunks/direct/chunk-AWZG43MA.js +8 -0
  7. package/dist/chunks/direct/chunk-BICVXQ5F.js +8 -0
  8. package/dist/chunks/direct/chunk-BMM5H6QF.js +11 -0
  9. package/dist/chunks/direct/chunk-C6HFNIDL.js +8 -0
  10. package/dist/chunks/direct/chunk-CBCZVCTZ.js +8 -0
  11. package/dist/chunks/direct/chunk-CBIKUVP6.js +11 -0
  12. package/dist/chunks/direct/chunk-CKB2ME2J.js +8 -0
  13. package/dist/chunks/direct/chunk-DBI23PBG.js +9 -0
  14. package/dist/chunks/direct/chunk-DBSQWRFS.js +9 -0
  15. package/dist/chunks/direct/chunk-DKGYPFGX.js +8 -0
  16. package/dist/chunks/direct/chunk-EOLHXX5I.js +8 -0
  17. package/dist/chunks/direct/chunk-IFPXDKUV.js +8 -0
  18. package/dist/chunks/direct/chunk-J3WYA3IJ.js +8 -0
  19. package/dist/chunks/direct/chunk-MCMOWPYL.js +8 -0
  20. package/dist/chunks/direct/chunk-MPTAIBY7.js +8 -0
  21. package/dist/chunks/direct/chunk-NQRDACK3.js +8 -0
  22. package/dist/chunks/direct/chunk-O5ETB2W5.js +8 -0
  23. package/dist/chunks/direct/chunk-OA6NU4KO.js +8 -0
  24. package/dist/chunks/direct/chunk-QKDE2HIF.js +10 -0
  25. package/dist/chunks/direct/chunk-RRSY2ZPX.js +13 -0
  26. package/dist/chunks/direct/chunk-UKQLRZEW.js +8 -0
  27. package/dist/chunks/direct/chunk-USZL65FN.js +8 -0
  28. package/dist/chunks/direct/chunk-WH6GL3J2.js +8 -0
  29. package/dist/chunks/direct/chunk-Y5OCKUQX.js +9 -0
  30. package/dist/chunks/direct/chunk-ZO44CZN5.js +8 -0
  31. package/dist/chunks/direct/chunk-ZSXRT7JL.js +12 -0
  32. package/dist/chunks/direct/chunk-ZUNPQVMO.js +8 -0
  33. package/dist/chunks/direct/execution-3T4B776P.js +9 -0
  34. package/dist/chunks/direct/execution-5BJNS7D7.js +8 -0
  35. package/dist/chunks/direct/execution-5O6QHKBR.js +8 -0
  36. package/dist/chunks/direct/execution-A4NK3BQO.js +8 -0
  37. package/dist/chunks/direct/execution-K4UOPXRQ.js +9 -0
  38. package/dist/chunks/direct/execution-SWWZOOA7.js +13 -0
  39. package/dist/chunks/direct/execution-X4MUJL4L.js +8 -0
  40. package/dist/chunks/direct/execution-XA6PXPRB.js +8 -0
  41. package/dist/chunks/direct/historyExecutions-6F3AA5PY.js +14 -0
  42. package/dist/direct.d.ts +6 -1
  43. package/dist/direct.js +2 -46
  44. package/dist/github/canonicalRepo.d.ts +2 -1
  45. package/dist/github/client.d.ts +3 -8
  46. package/dist/github/codeSearch/compactFragment.d.ts +7 -0
  47. package/dist/github/codeSearch.d.ts +2 -3
  48. package/dist/github/commit.d.ts +8 -0
  49. package/dist/github/commitDetail.d.ts +20 -0
  50. package/dist/github/commitSearch.d.ts +17 -0
  51. package/dist/github/compare.d.ts +15 -0
  52. package/dist/github/directoryFetch/cacheMetadata.d.ts +25 -0
  53. package/dist/github/directoryFetch/helpers.d.ts +1 -3
  54. package/dist/github/directoryFetch/snapshot.d.ts +10 -0
  55. package/dist/github/fileContentProcess.d.ts +0 -1
  56. package/dist/github/fileContentRaw/cache.d.ts +9 -0
  57. package/dist/github/fileContentRaw/fetch.d.ts +1 -1
  58. package/dist/github/githubAPI.d.ts +19 -2
  59. package/dist/github/history/commitFiles.d.ts +12 -0
  60. package/dist/github/issues/fetchers.d.ts +1 -1
  61. package/dist/github/issues/types.d.ts +3 -1
  62. package/dist/github/prContentFetcher/collectionPaging.d.ts +27 -0
  63. package/dist/github/prContentFetcher/comments.d.ts +7 -5
  64. package/dist/github/prContentFetcher/commits.d.ts +13 -14
  65. package/dist/github/prContentFetcher/flags.d.ts +0 -1
  66. package/dist/github/prContentFetcher/transform.d.ts +1 -1
  67. package/dist/github/prTransformation.d.ts +3 -1
  68. package/dist/github/queryBuilders/codeAndRepo.d.ts +2 -1
  69. package/dist/github/repoSearch.d.ts +2 -1
  70. package/dist/github/repoStructure/fetchOrchestration.d.ts +1 -1
  71. package/dist/github/repoStructurePagination.d.ts +1 -1
  72. package/dist/github/repoStructureTree.d.ts +4 -2
  73. package/dist/graph/advancedOperations.d.ts +2 -2
  74. package/dist/graph/buildFileGraph.d.ts +8 -13
  75. package/dist/graph/coverage.d.ts +6 -0
  76. package/dist/graph/diagnosticSnapshot.d.ts +10 -0
  77. package/dist/graph/fileImportLinker.d.ts +28 -0
  78. package/dist/graph/importResolver.d.ts +1 -1
  79. package/dist/graph/languageImportResolver.d.ts +5 -0
  80. package/dist/graph/metadataImports.d.ts +7 -0
  81. package/dist/graph/packageExportTargets.d.ts +11 -0
  82. package/dist/graph/rustCargoMetadata.d.ts +31 -0
  83. package/dist/graph/rustCargoProcess.d.ts +16 -0
  84. package/dist/graph/rustModules.d.ts +7 -0
  85. package/dist/graph/rustWorkspace.d.ts +5 -0
  86. package/dist/graph/types.d.ts +94 -3
  87. package/dist/graph/workspacePackageResolver.d.ts +7 -2
  88. package/dist/index.d.ts +46 -19
  89. package/dist/index.js +36 -45
  90. package/dist/providers/github/GitHubProvider.d.ts +3 -1
  91. package/dist/providers/github/githubContent.d.ts +3 -2
  92. package/dist/providers/github/githubPullRequests.d.ts +3 -2
  93. package/dist/providers/github/githubSearch.d.ts +6 -3
  94. package/dist/providers/github/githubStructure.d.ts +3 -2
  95. package/dist/providers/providerQueries.d.ts +4 -0
  96. package/dist/providers/providerResults.d.ts +29 -1
  97. package/dist/providers/types.d.ts +0 -2
  98. package/dist/schema.d.ts +9 -3
  99. package/dist/schema.js +4 -12
  100. package/dist/scheme/fields.d.ts +8 -8
  101. package/dist/scheme/pagination.d.ts +1 -0
  102. package/dist/serverConfig.d.ts +1 -1
  103. package/dist/shared/session/index.d.ts +1 -1
  104. package/dist/shared/session/index.js +1 -1
  105. package/dist/shared/session/storage.d.ts +0 -1
  106. package/dist/toolContract/descriptions.d.ts +6 -6
  107. package/dist/toolContract/input/resources/tools/ghSearch.d.ts +21 -20
  108. package/dist/toolContract/input/resources/tools/githubHistorySchema.d.ts +14 -6
  109. package/dist/toolContract/input/resources/tools/githubRepositoriesOperation.d.ts +3 -3
  110. package/dist/toolContract/input/resources/tools/githubTreeOperation.d.ts +4 -2
  111. package/dist/toolContract/input/resources/tools/historyCommitInput.d.ts +9 -0
  112. package/dist/toolContract/input/resources/tools/historyIssueInput.d.ts +4 -4
  113. package/dist/toolContract/input/resources/tools/historyPullRequestInput.d.ts +13 -5
  114. package/dist/toolContract/input/resources/tools/localAnalyzeGraph.d.ts +74 -32
  115. package/dist/toolContract/input/resources/tools/localFilesOperation.d.ts +2 -2
  116. package/dist/toolContract/input/resources/tools/localSearch.d.ts +44 -44
  117. package/dist/toolContract/input/resources/tools/localTextOperation.d.ts +1 -1
  118. package/dist/toolContract/input/resources/tools/localTreeOperation.d.ts +2 -2
  119. package/dist/toolContract/input/resources/tools/lspGetSemantics.d.ts +11 -2
  120. package/dist/toolContract/input/resources/tools/npmSearch.d.ts +2 -1
  121. package/dist/toolContract/metadata.d.ts +1 -1
  122. package/dist/toolContract/runtime.d.ts +1 -1
  123. package/dist/toolContract/types.d.ts +0 -1
  124. package/dist/tools/directToolCatalog/toolCatalogDefinitions.d.ts +2 -4
  125. package/dist/tools/directToolCatalog/toolInputPreparation.d.ts +2 -5
  126. package/dist/tools/directToolCatalog.exec.d.ts +10 -7
  127. package/dist/tools/github_clone_repo/cache.d.ts +0 -2
  128. package/dist/tools/github_clone_repo/cacheArtifacts.d.ts +3 -1
  129. package/dist/tools/github_clone_repo/cachePaths.d.ts +3 -2
  130. package/dist/tools/github_clone_repo/gitCheckout.d.ts +5 -0
  131. package/dist/tools/github_clone_repo/scheme.d.ts +3 -3
  132. package/dist/tools/github_clone_repo/types.d.ts +6 -1
  133. package/dist/tools/github_fetch_content/finalizer/types.d.ts +10 -2
  134. package/dist/tools/github_fetch_content/scheme.d.ts +3 -4
  135. package/dist/tools/github_fetch_content/types.d.ts +4 -3
  136. package/dist/tools/github_search/scheme.d.ts +24 -23
  137. package/dist/tools/github_search_code/execution.d.ts +1 -1
  138. package/dist/tools/github_search_code/finalizer/groups.d.ts +1 -1
  139. package/dist/tools/github_search_code/finalizer/ranking.d.ts +1 -1
  140. package/dist/tools/github_search_code/scheme.d.ts +3 -3
  141. package/dist/tools/github_search_pull_requests/contentResponse/commentsShaping.d.ts +4 -1
  142. package/dist/tools/github_search_pull_requests/contentResponse/contentView.d.ts +3 -0
  143. package/dist/tools/github_search_pull_requests/contentResponse/fileSurfaces.d.ts +30 -2
  144. package/dist/tools/github_search_pull_requests/contentResponse/nextCalls.d.ts +1 -7
  145. package/dist/tools/github_search_pull_requests/contentResponse/pagination.d.ts +14 -2
  146. package/dist/tools/github_search_pull_requests/historyContinuations.d.ts +1 -1
  147. package/dist/tools/github_search_pull_requests/historyDiffContinuations.d.ts +2 -0
  148. package/dist/tools/github_search_pull_requests/historySchemes.d.ts +23 -22
  149. package/dist/tools/github_search_pull_requests/scheme.d.ts +17 -9
  150. package/dist/tools/github_search_pull_requests/splitSchemes.d.ts +35 -26
  151. package/dist/tools/github_search_pull_requests/types.d.ts +5 -0
  152. package/dist/tools/github_search_repos/execution/pagination.d.ts +0 -17
  153. package/dist/tools/github_search_repos/execution/queryVariants.d.ts +1 -23
  154. package/dist/tools/github_search_repos/execution.d.ts +0 -1
  155. package/dist/tools/github_search_repos/scheme.d.ts +6 -6
  156. package/dist/tools/github_view_repo_structure/execution.d.ts +1 -1
  157. package/dist/tools/github_view_repo_structure/scheme.d.ts +6 -5
  158. package/dist/tools/local_analyze_graph/analysisTypes.d.ts +16 -3
  159. package/dist/tools/local_analyze_graph/analyzeGraph.d.ts +1 -1
  160. package/dist/tools/local_analyze_graph/completeness.d.ts +3 -0
  161. package/dist/tools/local_analyze_graph/deadCodeScan.d.ts +9 -5
  162. package/dist/tools/local_analyze_graph/rootInference.d.ts +2 -0
  163. package/dist/tools/local_analyze_graph/scheme.d.ts +13 -25
  164. package/dist/tools/local_fetch_content/fetchContent/pagination.d.ts +7 -0
  165. package/dist/tools/local_fetch_content/scheme.d.ts +3 -3
  166. package/dist/tools/local_find_files/findFiles.d.ts +1 -1
  167. package/dist/tools/local_find_files/scheme.d.ts +4 -4
  168. package/dist/tools/local_ripgrep/execution.d.ts +0 -1
  169. package/dist/tools/local_ripgrep/rankingProfile/rankingProfiles.d.ts +1 -2
  170. package/dist/tools/local_ripgrep/rankingProfile/rankingResults.d.ts +2 -2
  171. package/dist/tools/local_ripgrep/rankingProfile/rankingScoring.d.ts +1 -3
  172. package/dist/tools/local_ripgrep/ripgrepResultBuilder/buildResult.d.ts +0 -4
  173. package/dist/tools/local_ripgrep/ripgrepResultBuilder/searchNext.d.ts +1 -0
  174. package/dist/tools/local_ripgrep/scheme.d.ts +13 -5
  175. package/dist/tools/local_ripgrep/structuralCompleteness.d.ts +9 -0
  176. package/dist/tools/local_search/execution.d.ts +0 -1
  177. package/dist/tools/local_search/scheme.d.ts +47 -47
  178. package/dist/tools/local_view_structure/scheme.d.ts +5 -5
  179. package/dist/tools/lsp/semantic_content/scheme.d.ts +29 -7
  180. package/dist/tools/lsp/semantic_content/semanticAnchored.d.ts +2 -9
  181. package/dist/tools/lsp/semantic_content/semanticEnvelopes/callEnvelopes.d.ts +2 -2
  182. package/dist/tools/lsp/semantic_content/semanticEnvelopes/envelopeHelpers.d.ts +2 -1
  183. package/dist/tools/lsp/semantic_content/semanticEnvelopes/locationEnvelopes.d.ts +2 -3
  184. package/dist/tools/lsp/semantic_content/semanticFileOps/anchor.d.ts +0 -1
  185. package/dist/tools/lsp/semantic_content/semanticPresentation.d.ts +1 -0
  186. package/dist/tools/lsp/semantic_content/semanticSnapshot.d.ts +16 -0
  187. package/dist/tools/lsp/shared/callHierarchyTraversal.d.ts +2 -1
  188. package/dist/tools/lsp/shared/semanticTypes.d.ts +19 -10
  189. package/dist/tools/package_search/execution.d.ts +3 -4
  190. package/dist/tools/package_search/pagination.d.ts +1 -0
  191. package/dist/tools/package_search/scheme.d.ts +5 -4
  192. package/dist/tools/providerMappers/codeSearch.d.ts +2 -9
  193. package/dist/tools/providerMappers/fileContent.d.ts +1 -1
  194. package/dist/tools/providerMappers/pullRequests.d.ts +24 -4
  195. package/dist/tools/providerMappers/repoSearch.d.ts +4 -4
  196. package/dist/tools/providerMappers/repoStructure.d.ts +4 -3
  197. package/dist/tools/toolAvailability.d.ts +19 -0
  198. package/dist/tools/toolConfig.d.ts +1 -3
  199. package/dist/types/toolResults.d.ts +1 -0
  200. package/dist/utils/contextUtils.d.ts +1 -1
  201. package/dist/utils/core/types.d.ts +0 -2
  202. package/dist/utils/exec/npm.d.ts +2 -0
  203. package/dist/utils/file/byteOffset.d.ts +1 -1
  204. package/dist/utils/package/common.d.ts +0 -3
  205. package/dist/utils/package/npm/npmDeprecation.d.ts +1 -2
  206. package/dist/utils/package/npm/npmDetailsFetchers.d.ts +3 -15
  207. package/dist/utils/package/npm/npmMappers.d.ts +0 -4
  208. package/dist/utils/package/npm/npmRegistry.d.ts +9 -1
  209. package/dist/utils/package/npm/npmSearchStrategies.d.ts +2 -5
  210. package/dist/utils/package/types.d.ts +3 -0
  211. package/dist/utils/pagination/types.d.ts +1 -0
  212. package/dist/utils/response/callToolResult.d.ts +3 -1
  213. package/package.json +23 -19
  214. package/dist/errors/pathUtils.d.ts +0 -1
  215. package/dist/github/directoryFetch.d.ts +0 -3
  216. package/dist/github/fileContentRaw.d.ts +0 -2
  217. package/dist/github/issues.d.ts +0 -3
  218. package/dist/github/prContentFetcher.d.ts +0 -2
  219. package/dist/github/queryBuilders.d.ts +0 -4
  220. package/dist/github/repoStructure.d.ts +0 -1
  221. package/dist/shared/index.d.ts +0 -6
  222. package/dist/shared/languageSelectors.d.ts +0 -3
  223. package/dist/toolContract/schemas.d.ts +0 -31
  224. package/dist/tools/directToolCatalog.d.ts +0 -15
  225. package/dist/tools/directToolCatalog.meta.d.ts +0 -28
  226. package/dist/tools/github_search_code/finalizer.d.ts +0 -2
  227. package/dist/tools/github_search_repos/execution/ranking.d.ts +0 -4
  228. package/dist/tools/local_ripgrep/rankingProfile.d.ts +0 -35
  229. package/dist/tools/local_ripgrep/ripgrepResultBuilder.d.ts +0 -2
  230. package/dist/tools/lsp/semantic_content/index.d.ts +0 -3
  231. package/dist/tools/lsp/semantic_content/semanticEnvelopes.d.ts +0 -3
  232. package/dist/tools/lsp/semantic_content/semanticFileOps.d.ts +0 -8
  233. package/dist/tools/providerMappers.d.ts +0 -11
  234. package/dist/tools/toolMetadata/baseSchema.d.ts +0 -1
  235. package/dist/tools/toolMetadata/descriptions.d.ts +0 -1
  236. package/dist/tools/toolMetadata/proxies.d.ts +0 -4
  237. package/dist/tools/toolSchemaImports.d.ts +0 -16
  238. package/dist/utils/exec/spawn.d.ts +0 -2
  239. package/dist/utils/file/filters.d.ts +0 -2
  240. package/dist/utils/http/cache.d.ts +0 -5
  241. package/dist/utils/package/npm.d.ts +0 -2
  242. package/dist/utils/response/bulk.d.ts +0 -2
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as Y}from"./chunk-O5ETB2W5.js";import{a as q,b as B}from"./chunk-MCMOWPYL.js";import{a as X,b as z,c as J,d as ee}from"./chunk-AWZG43MA.js";import"./chunk-3AA4F3QO.js";import{a as v,c as E}from"./chunk-EOLHXX5I.js";import{I as $,w as F}from"./chunk-RRSY2ZPX.js";import"./chunk-CBIKUVP6.js";import"./chunk-Y5OCKUQX.js";import"./chunk-CBCZVCTZ.js";import{a as te}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{a as re}from"./chunk-WH6GL3J2.js";import{c as M,f as O,h as H,j as A}from"./chunk-ZSXRT7JL.js";import{e as N,ea as Z,ha as k}from"./chunk-BMM5H6QF.js";function oe(e){return{keywords:e.keywords??[],projectId:X(e.owner,e.repo),owner:e.owner,path:e.path,filename:e.filename,extension:e.extension,language:e.language,match:e.match,limit:e.limit,page:e.page,goal:e.goal,reasoning:e.reasoning}}function ne(e,t){let o=t.match==="path",r=new Map;for(let n of e.items){let a=n.repository.name||"",{owner:u,repo:d}=z(a),m=`${u}/${d}`,g=r.get(m);if(g||(g={id:m,owner:u,repo:d,matches:[]},r.set(m,g)),o||!n.matches?.length){g.matches.push({path:n.path,...o?{}:{pathOnly:!0}});continue}let h=!1;for(let p of n.matches){if(!p.context)continue;let S=p.context,x={path:n.path,value:S};if(p.positions?.length>0){let P=p.positions.filter(([w,l])=>w>=0&&l>w&&l<=S.length);P.length>0&&(x.matchIndices=P.map(([w,l])=>({start:w,end:l,lineOffset:(p.context??"").substring(0,w).split(`
9
+ `).length-1})))}g.matches.push(x),h=!0}h||g.matches.push({path:n.path,pathOnly:!0})}let i={results:Array.from(r.values()),...e.nonExistentScope?{nonExistentScope:!0}:{},...e.incompleteResults?{incompleteResults:!0}:{}};return e.pagination&&e.pagination.totalPages>1&&(i.pagination={currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,perPage:e.pagination.entriesPerPage||10,totalMatches:e.pagination.totalMatches||0,...J(e.pagination),hasMore:e.pagination.hasMore,...e.pagination.hasMore?{nextPage:e.pagination.currentPage+1}:{}}),i}function ie(e,t){return e.some(o=>{let r=t[o.index];return typeof r?.owner=="string"&&typeof r?.repo=="string"})}function ae(e){let t=e.data;return{results:Array.isArray(t?.results)?t.results:[],pagination:t?.pagination,...t?.nonExistentScope?{nonExistentScope:!0}:{},...t?.incompleteResults?{incompleteResults:!0}:{},...t?.repoState?{repoState:t.repoState}:{}}}function Ce(e){return[...e].sort((t,o)=>{let r=o.matches.length-t.matches.length;return r!==0?r:t.id.localeCompare(o.id)})}function ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t){let o=(e.path.split("/").pop()??"").toLowerCase(),r=o.replace(/\.[^.]+$/,""),i=e.value??"",n=0;for(let a of t){let u=a.trim();if(!u)continue;let d=u.toLowerCase();if(o===d||r===d)return 2;(/^[A-Za-z0-9_]+$/.test(u)?new RegExp(`\\b${ke(u)}\\b`,"i").test(i):i.toLowerCase().includes(d))&&(n=Math.max(n,1))}return n}function ve(e,t){return{...e,matches:t}}function se(e,t){let o=t.filter(i=>typeof i=="string"&&i.trim());return o.length===0?Ce(e):e.map(i=>{let n=i.matches.map((a,u)=>({match:a,index:u,score:Ge(a,o)}));return n.sort((a,u)=>a.score!==u.score?u.score-a.score:a.index-u.index),{group:ve(i,n.map(a=>a.match)),hasExact:n.some(a=>a.score>0)}}).sort((i,n)=>{if(i.hasExact!==n.hasExact)return i.hasExact?-1:1;let a=n.group.matches.length-i.group.matches.length;return a!==0?a:i.group.id.localeCompare(n.group.id)}).map(i=>i.group)}function ue(e){let t=new Map;for(let{index:o,groups:r}of e)for(let i of r){let n=`${o}\0${i.id}`,a=t.get(n);if(!a){t.set(n,{id:i.id,queryIndex:o,owner:i.owner,repo:i.repo,matches:[...i.matches]});continue}a.matches.push(...i.matches)}return Array.from(t.values())}function ce(e){let t=new Map;for(let o of e)for(let r of o.matches){let i=`${o.queryIndex??-1}\0${o.owner}\0${o.repo}\0${r.path}`,n=t.get(i),{path:a,...u}=r;if(n){n.matches.push(u);continue}t.set(i,{owner:o.owner,repo:o.repo,path:r.path,matches:[u]})}return Array.from(t.values())}function pe(e,t,o){if(t.length===0)return[];if(e.length===1){let n=t[0]?.queryIndex??0,a=o.get(n);return[{index:n,data:{files:ce(t),...a?{pagination:a}:{}}}]}let r=new Map,i=[];for(let n of t){let a=n.queryIndex??0,u=r.get(a);u||(u=[],r.set(a,u),i.push(a)),u.push(n)}return i.map(n=>{let a=o.get(n);return{index:n,data:{files:ce(r.get(n)),...a?{pagination:a}:{}}}})}function le(e,t,o){let r={};for(let i of e){let n=i.data.files[0];if(!n)continue;let a=t[i.index];if(a?.match==="path")continue;let d=(Array.isArray(a?.keywords)?a.keywords.filter(g=>typeof g=="string"):[])[0]??o[0];if(!d)continue;let m=e.length===1?"getLines":`getLines:${i.index}`;r[m]={tool:"ghGetFileContent",query:{owner:n.owner,repo:n.repo,path:n.path,matchString:d},why:"GitHub code search returns no line numbers; fetch the top hit with matchString to get exact file:line anchors",confidence:"low"}}return Object.keys(r).length>0?r:void 0}function L(){return({queries:e,results:t})=>{let o=[],r=new Map,i=[],n=new Set,a=[];t.forEach(s=>{if(s.status==="error")return;let c=ae(s);c.repoState&&a.push({index:s.index,state:c.repoState,query:e[s.index]}),c.incompleteResults&&n.add(s.index),c.results.reduce((T,Q)=>T+Q.matches.length,0)===0&&i.push({index:s.index,...c.nonExistentScope?{nonExistentScope:!0}:{},...c.incompleteResults?{incompleteResults:!0}:{}});let f=c.results;o.push({index:s.index,groups:f}),c.pagination&&r.set(s.index,c.pagination)});let u=Array.from(new Set(e.flatMap(s=>{let c=s.keywords;return Array.isArray(c)?c.filter(y=>typeof y=="string"):[]}))),d=se(ue(o),u),m=q(t),g=e.some(s=>s.concise===!0),h=new Map(t.map(s=>[s.index,s])),p=pe(e,d,r).map(s=>{let c=h.get(s.index)?.meta;return{...s,...c?{meta:c}:{}}}),S=le(p,e,u);if(S)for(let s of p){let c=p.length===1?"getLines":`getLines:${s.index}`,y=S[c];y&&(s.data.next={getLines:y})}if(g)for(let s of p)s.data.files=s.data.files.map(c=>`${c.owner}/${c.repo}:${c.path}`);let x=i.map(({index:s,nonExistentScope:c,incompleteResults:y})=>{let f=h.get(s)?.meta;return{index:s,status:"empty",...f?{meta:f}:{},data:{files:[],pagination:r.get(s),...c?{nonExistentScope:c}:{},...y?{incompleteResults:y}:{}}}}),P=m.map(({index:s,error:c})=>{let y=h.get(s)?.meta;return{index:s,status:"error",...y?{meta:y}:{},data:{error:c}}}),l={results:[...p,...x,...P].sort((s,c)=>s.index-c.index)},R=l.results,b=s=>R.find(c=>c.index===s),C=(s,c,y,f=!1)=>{let T=b(s);if(!T)return;let Q=T.meta,I=Q?.diagnostics;T.meta={evidence:Q?.evidence??{kind:"provider",confidence:"medium"},diagnostics:{...I??{},codes:Array.from(new Set([...I?.codes??[],c])),hints:Array.from(new Set([...I?.hints??[],y])),...f||I?.partial?{partial:!0}:{}}}},G=(s,c,y)=>{let f=b(s);!f||!("files"in f.data)||(f.data.next={...f.data.next??{},[c]:y})};for(let s of n){C(s,"ghIncompleteResults","GitHub reported an incomplete search index result; retry, narrow the scope, or verify locally before concluding absence.",!0);let{goal:c,reasoning:y,...f}=e[s];G(s,"retry",{tool:"github.code",query:f,why:"Retry the same query because GitHub marked the result incomplete",confidence:"exact"})}let j=new Set(a.map(({index:s})=>s));for(let s of i){if(j.has(s.index)||!ie([s],e))continue;let c=e[s.index];C(s.index,"ghScopedZeroUnproven","No indexed matches is unproven absence; verify the repository structure and search a bounded local copy before concluding."),G(s.index,"viewStructure",{tool:"github.tree",query:{owner:c.owner,repo:c.repo,path:""},why:"Verify that the scoped repository and path exist before concluding absence",confidence:"exact"})}let _=8,K=i.filter(({index:s,nonExistentScope:c,incompleteResults:y})=>{if(c||y)return!1;let f=e[s]?.keywords;return Array.isArray(f)&&f.length>_});if(K.length>0)for(let{index:s}of K){let c=e[s],y=Array.isArray(c.keywords)?c.keywords.filter(f=>typeof f=="string").slice(0,_):[];C(s,"ghQueryPossiblyTooComplex",`The query used more than ${_} keywords; narrow it before treating zero matches as absence.`),G(s,"retryNarrow",{tool:"github.code",query:{keywords:y,...typeof c.owner=="string"?{owner:c.owner}:{},...typeof c.repo=="string"?{repo:c.repo}:{},...typeof c.path=="string"?{path:c.path}:{},...typeof c.filename=="string"?{filename:c.filename}:{},...typeof c.extension=="string"?{extension:c.extension}:{},...typeof c.language=="string"?{language:c.language}:{},...c.match==="file"||c.match==="path"?{match:c.match}:{}},why:"Retry with a bounded keyword set to avoid silent under-matching",confidence:"low"})}for(let{index:s,state:c,query:y}of a)if(c.kind==="renamed"){let[f,T]=c.fullName.split("/");C(s,"ghRepoRenamed",`The repository was renamed to ${c.fullName}; retry against the renamed repository.`);let Q=y?.keywords;G(s,"retryRenamed",{tool:"github.code",query:{owner:f,repo:T,...Array.isArray(Q)?{keywords:Q}:{}},why:"Re-run the same search against the renamed repository",confidence:"exact"})}else if(c.kind==="archived"){C(s,"ghRepoArchived","The repository is archived, so its code-search index may lag or be incomplete; verify its structure and search locally.");let f=y;typeof f?.owner=="string"&&typeof f.repo=="string"&&G(s,"viewStructure",{tool:"github.tree",query:{owner:f.owner,repo:f.repo,path:""},why:"Inspect the archived repository outside the code-search index",confidence:"exact"})}else{C(s,"ghRepoNotFound","The repository was not found or is private to this token; verify the spelling or discover the current repository name.");let f=y;typeof f?.repo=="string"&&G(s,"findRepository",{tool:"github.repositories",query:{keywords:[f.repo]},why:"Find the repository by name in case it moved or was renamed",confidence:"low"})}return B(l,["results","index","status","meta","evidence","diagnostics","data","files","path","owner","repo","queryIndex","matches","value","pathOnly","matchIndices","pagination","next","tool","query","why","confidence","nonExistentScope","incompleteResults","error"],d.length===0&&m.length>0)}}function Te(e){return!!((e.keywords??[]).some(o=>o.trim().length>0)||e.owner||e.path||e.extension||e.filename||e.language)}function Qe(e){if(e.repo&&!e.owner)return{error:"Repository scope requires owner. Provide both owner and repo, or omit repo for a broader search."}}async function Ee(e,t,o){try{let r=await F(o),{data:i}=await r.rest.repos.get({owner:e,repo:t}),n=`${e}/${t}`.toLowerCase();return i.full_name&&i.full_name.toLowerCase()!==n?{kind:"renamed",fullName:i.full_name}:i.archived?{kind:"archived"}:void 0}catch(r){return r.status===404?{kind:"notFound"}:void 0}}async function de(e,t,o=v(t.authInfo)){try{let r=Qe(e);if(r)return O(r.error,e);if(!Te(e))return O("At least one search term or scope filter is required.",e);let i=o(),n=await E(e,()=>i.provider.searchCode(oe(e)));if(n.ok===!1)return n.result;let a=ne(n.response.data,e);if(a.results.length===0&&e.owner&&e.repo){let u=await Ee(String(e.owner),String(e.repo),t.authInfo);u&&(a.repoState=u)}return H(e,a,a.results.length>0,k.GITHUB_SEARCH_CODE,{rawResponse:n.response.rawResponseChars})}catch(r){return A(r,e,void 0,k.GITHUB_SEARCH_CODE)}}function he(e){let t=e;return{keywords:e.keywords,topics:e.topicsToSearch,owner:e.owner,stars:e.stars,size:t.size,created:t.created,updated:e.updated,language:e.language,archived:t.archived,visibility:t.visibility,license:t.license,forks:t.forks,goodFirstIssues:t.goodFirstIssues,match:e.match,sort:e.sort,limit:e.limit,page:e.page,goal:e.goal,reasoning:e.reasoning}}function fe(e){return e.map(t=>{let{owner:o,repo:r}=z(t.fullPath);return{owner:o||"",repo:r||t.name,defaultBranch:t.defaultBranch,stars:t.stars,description:t.description||"",url:t.url,createdAt:t.createdAt,updatedAt:t.updatedAt,pushedAt:t.lastActivityAt,visibility:t.visibility,topics:t.topics,forksCount:t.forks,openIssuesCount:t.openIssuesCount,...t.language&&{language:t.language},...t.license&&{license:t.license},...t.homepage&&{homepage:t.homepage}}})}function He(e){return!!(e.topicsToSearch&&(Array.isArray(e.topicsToSearch)?e.topicsToSearch.length>0:e.topicsToSearch))}function D(e){return!!(e.keywords&&e.keywords.length>0)}function me(e){return!!(D(e)||He(e)||e.owner||e.language||e.stars||e.updated||e.created||e.size||e.forks||e.license||e.goodFirstIssues||e.visibility||e.archived!==void 0)}function ge(e){return{currentPage:e.currentPage,...e.totalMatchesKind!=="lowerBound"&&e.totalPages!==void 0?{totalPages:e.totalPages}:{},perPage:e.entriesPerPage??10,...e.totalMatches!==void 0?{totalMatches:e.totalMatches}:{},...e.reportedTotalMatches!==void 0?{reportedTotalMatches:e.reportedTotalMatches}:{},...e.reachableTotalMatches!==void 0?{reachableTotalMatches:e.reachableTotalMatches}:{},...e.totalMatchesKind!==void 0?{totalMatchesKind:e.totalMatchesKind}:{},...e.totalMatchesCapped!==void 0?{totalMatchesCapped:e.totalMatchesCapped}:{},hasMore:e.hasMore,...e.hasMore?{nextPage:e.currentPage+1}:{}}}function Ae(e){let t=e,o={owner:t.owner??"",repo:t.repo,stars:t.stars,forks:t.forksCount,openIssuesCount:t.openIssuesCount,language:t.language,license:t.license||void 0,description:t.description&&t.description!=="No description"?t.description:void 0,homepage:t.homepage||void 0,pushedAt:t.pushedAt?t.pushedAt.slice(0,10):void 0,createdAt:t.createdAt?t.createdAt.slice(0,10):void 0,updatedAt:t.updatedAt?t.updatedAt.slice(0,10):void 0,defaultBranch:t.defaultBranch&&t.defaultBranch!=="main"&&t.defaultBranch!=="master"?t.defaultBranch:void 0,topics:t.topics?.length?t.topics:void 0,visibility:t.visibility&&t.visibility!=="public"?t.visibility:void 0};return Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0))}function Me(e,t){let o=t.concise===!0,r=e.repositories[0],i=r?.owner&&r?.repo?{viewStructure:{tool:"github.tree",query:{owner:r.owner,repo:r.repo,path:""},why:"Orient in the top-ranked repository before reading code",confidence:"low"},searchCode:{tool:"github.code",query:{owner:r.owner,repo:r.repo},why:"Scope a code search to the top-ranked repository",confidence:"low"}}:void 0;return{data:{pagination:e.pagination,repositories:o?e.repositories.map(n=>`${n.owner?`${n.owner}/`:""}${n.repo}`):e.repositories.map(Ae),...i?{next:i}:{}}}}async function ye(e,t,o=v(t.authInfo)){let{authInfo:r}=t;try{if(!me(e))return O("At least one repository search term or filter is required.",e);let i=o(),n=await E(e,()=>i.provider.searchRepos(he(e)));if(n.ok===!1)return n.result;let{response:a}=n,u=fe(a.data.repositories),d=a.data.pagination,m=d?ge(d):void 0,g=u.length>0,h=Me({repositories:u,pagination:m},e),p;if(e.owner&&D(e)&&(e.page??1)===1){let P=(Array.isArray(e.keywords)?e.keywords:[e.keywords]).filter(l=>typeof l=="string"&&/^[A-Za-z0-9_.-]+$/.test(l)).slice(0,3),w=P.some(l=>u.some(R=>R.repo?.toLowerCase()===l.toLowerCase()));if(P.length>0&&!w)try{let l=await F(r);for(let R of P){let b=await ee(l,String(e.owner),R,r);if(b.renamed){p={warning:`Repository "${e.owner}/${R}" now resolves to "${b.owner}/${b.repo}" \u2014 the repository may have been transferred. Retry scoped to owner:"${b.owner}" (see next.retryUnderCanonicalOwner).`,next:{retryUnderCanonicalOwner:{tool:"github.repositories",query:{...e,owner:b.owner,keywords:[b.repo]},why:"Re-run scoped to the repository's current owner after a detected transfer.",confidence:"exact"}}};break}}}catch{}}let S=[...p?[p.warning]:[],...!g&&!p?['No repositories matched. Keywords are ANDed \u2014 try fewer or broader keywords, drop a topic/filter (topics are sparse), or add match:"readme" for full-text search.']:[]],x={...h.data,...a.data.incompleteResults?{incompleteResults:!0}:{},...S.length>0?{warnings:S}:{},...p?{next:p.next}:{}};return H(e,x,g,k.GITHUB_SEARCH_REPOSITORIES,{rawResponse:a.rawResponseChars??Z(a.data)})}catch(i){return A(i,e,void 0,k.GITHUB_SEARCH_REPOSITORIES)}}import{shouldIgnoreDiscoveryFile as Oe,shouldIgnoreDiscoveryDir as be}from"@octocodeai/octocode-engine/security";function W(e,t){let o=e.include??[];return{projectId:`${e.owner}/${e.repo}`,ref:t,path:e.path?String(e.path):void 0,depth:typeof e.maxDepth=="number"?e.maxDepth:void 0,itemsPerPage:e.itemsPerPage??$.ENTRIES_PER_PAGE,page:(()=>{let r=e.page;return typeof r=="number"?r:void 0})(),includeSizes:o.includes("sizes"),includeLanguages:o.includes("languages"),includeContributors:o.includes("contributors"),includeBranches:o.includes("branches"),includeTags:o.includes("tags"),metadataPage:e.metadataPage,goal:e.goal,reasoning:e.reasoning}}function Re(e,t,o,r){let i=r,n=e.branch??r,a=i&&n&&i!==n&&i!=="HEAD",u=Object.entries(o).sort(([l],[R])=>l==="."?-1:R==="."?1:l.localeCompare(R)).map(([l,R])=>({dir:l,files:R.files,folders:R.folders})),d=e.fileSizeMap,m={};if(d){for(let[l,R]of Object.entries(d))if(o[l]){let b=new Set(o[l].files);for(let[C,G]of Object.entries(R))if(b.has(C)){let j=l==="."?C:`${l}/${C}`;m[j]=G}}}let g=Object.values(o).reduce((l,R)=>(l.totalFiles+=R.files.length,l.totalFolders+=R.folders.length,l),{totalFiles:0,totalFolders:0}),h=e,p=e.summary.incompleteTree===!0,S=e.partialReasons&&e.partialReasons.length>0?e.partialReasons:p?["providerTreeTruncated"]:void 0,x=e.isPartial===!0||p,P=e.terminalLimit===!0||p,w={structure:u,...Object.keys(m).length>0&&{fileSizes:m},...h.languages?{languages:h.languages,dominantLanguage:h.dominantLanguage}:{},...h.contributors?{contributors:h.contributors,returnedContributors:h.contributors.length}:{},...h.branches?{branches:h.branches,returnedBranches:h.branches.length}:{},...h.tags?{tags:h.tags,returnedTags:h.tags.length}:{},summary:{totalFiles:g.totalFiles,totalFolders:g.totalFolders,...p?{incompleteTree:!0}:{}},...x?{isPartial:!0}:{},...P?{terminalLimit:!0}:{},...S?{partialReasons:S}:{}};if(e.metadataPagination){w.metadataPagination=e.metadataPagination;let l={};for(let[R,b]of Object.entries(e.metadataPagination))!b.hasMore&&!b.failed||b.terminalLimit||(l[R]=te("ghSearch",{operation:"tree",owner:t.owner,repo:t.repo,branch:n,...t.path!==void 0?{path:t.path}:{},...t.maxDepth!==void 0?{maxDepth:t.maxDepth}:{},page:t.page??1,pageSize:t.itemsPerPage??$.ENTRIES_PER_PAGE,include:[R],metadataPage:b.currentPage+(b.failed?0:1)},b.failed?`Retry the failed ${R} page.`:`Continue the ${R} list.`));Object.keys(l).length>0&&(w.next=l)}return n&&(w.resolvedBranch=n),a&&(w.branchFallback={requestedBranch:i,actualBranch:n,...e.defaultBranch!==void 0&&{defaultBranch:e.defaultBranch},warning:`Branch '${i}' not found. Showing '${n}' (default branch). Re-query with the correct branch name if branch-specific results are required.`}),e.pagination&&(e.pagination.hasMore||e.pagination.totalPages>1)&&(w.pagination=e.pagination),w}function Ie(e,t){let o=e.error,r=typeof o=="object"&&o!==null?o:void 0,i=typeof r?.status=="number"?r.status:void 0,n=typeof t.path=="string"?t.path.replace(/\/+$/,""):"",a=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"",u=n.split("/").pop()||t.repo,d=i===404?{retryParent:{tool:"github.tree",query:{owner:t.owner,repo:t.repo,...a?{path:a}:{},...t.branch?{branch:t.branch}:{}},why:"Retry at the parent directory \u2014 the path or branch may be wrong.",confidence:"low"},searchPath:{tool:"github.code",query:{owner:t.owner,repo:t.repo,match:"path",keywords:[u]},why:"Locate the path by name in case it moved or was renamed.",confidence:"low"}}:void 0;return{status:"error",owner:t.owner,repo:t.repo,path:t.path,branch:t.branch,error:typeof r?.error=="string"?r.error:typeof o=="string"?o:"Failed to explore repository structure",...typeof r?.status=="number"?{statusCode:r.status}:{},...typeof r?.type=="string"?{errorType:r.type}:{},...d?{next:d}:{}}}function Fe(e){let t={};for(let[o,r]of Object.entries(e)){let i=o.split("/").pop()??o;if(o!==""&&o!=="."&&be(i))continue;let n=r.files.filter(u=>!Oe(u)),a=r.folders.filter(u=>!be(u));(n.length>0||a.length>0)&&(t[o]={files:n,folders:a})}return t}async function Se(e,t,o=v(t.authInfo)){try{let r=o(),i=`${e.owner}/${e.repo}`,n=e.branch,a=n??await r.provider.resolveDefaultBranch(i),u=await E(e,()=>r.provider.getRepoStructure(W(e,a))),d=a,m;if(u.ok===!1&&n){let l=u.result.error;if((typeof l=="object"&&l!==null?l.status:void 0)===404){let b=await r.provider.resolveDefaultBranch(i);if(b!==n){let C=await E(e,()=>r.provider.getRepoStructure(W(e,b)));C.ok!==!1&&(u=C,d=b,m=`Branch/ref '${n}' was not found. Showing '${b}' (default branch) instead. Re-query with the correct branch name if branch-specific results are required.`)}}}if(u.ok===!1)return Ie(u.result,e);let g=Fe(u.response.data.structure),h=Re(u.response.data,e,g,d),p=Object.keys(g).length>0||h.isPartial===!0||h.languages!==void 0||["contributors","branches","tags"].some(l=>Array.isArray(h[l])&&h[l].length>0);m&&(h.branchFallback={requestedBranch:n,actualBranch:d,warning:m});let x=h.structure?.find(l=>(l.files?.length??0)>0),P=String(e.path??"").replace(/\/+$/,""),w=x?(()=>{let l=x.dir==="."?x.files[0]:`${x.dir}/${x.files[0]}`;return P?`${P}/${l}`:l})():void 0;return h.next={...h.next,...w?{fetchFile:{tool:"ghGetFileContent",query:{owner:e.owner,repo:e.repo,path:w,...d?{branch:d}:{}},why:"Read the first listed file",confidence:"low"}}:{},materialize:{tool:"ghGetFileContent",query:{owner:e.owner,repo:e.repo,path:String(e.path??""),type:"directory",...d?{branch:d}:{}},why:"Materialize this directory locally for exact line anchors, local search, or LSP",confidence:"exact"}},H(e,h,p,k.GITHUB_VIEW_REPO_STRUCTURE,{rawResponse:u.response.rawResponseChars})}catch(r){return A(r,e,"Failed to explore repository structure",k.GITHUB_VIEW_REPO_STRUCTURE)}}var U=1e3,ze={"github.code":"code","github.repositories":"repositories","github.tree":"tree"};function xe(){return({queries:e,results:t})=>{let o=e.flatMap((p,S)=>p.operation==="code"?[{query:p,originalIndex:S}]:[]),r=new Map(o.map((p,S)=>[p.originalIndex,S])),i=o.map(p=>p.originalIndex),n=o.map(({query:p})=>{let{operation:S,...x}=p;return x}),a=t.filter(p=>r.has(p.index)).map(p=>({...p,index:r.get(p.index)})),u=Be(n,a).map(p=>({...p,index:i[p.index]??p.index})),d=new Set(i),m=t.filter(p=>!d.has(p.index)),g=[...u,...m].map(p=>je(p,e[p.index])).sort((p,S)=>p.index-S.index);return B({results:g},["results","index","status","meta","data","operation","files","repositories","structure","pagination","next","tool","query","why","confidence","error"],g.length>0&&g.every(p=>p.status==="error"))}}function Be(e,t){return e.length===0?[]:L()({queries:e,results:t,config:{toolName:"github.code"}}).structuredContent.results??[]}function je(e,t){let o=t?.operation;if(!o||!t)return e;let r=V({operation:o,...e.data}),i=Ne(r),n=_e(i,o,t);return{...e,data:$e(n,o,t)}}function Pe(e,t){let{goal:o,reasoning:r,...i}=e;return{...i,page:t}}function _e(e,t,o){if(!o)return e;let r=e.pagination;if(!r||typeof r!="object")return e;let i=r;if(i.hasMore!==!0)return e;let{nextPage:n,...a}=i,u=typeof i.perPage=="number"&&i.perPage>0?i.perPage:typeof o.pageSize=="number"&&o.pageSize>0?o.pageSize:void 0;if(i.totalMatchesCapped===!0&&typeof n=="number"&&u!==void 0&&(n-1)*u>=U){let m=e.next&&typeof e.next=="object"?e.next:void 0,{nextPage:g,...h}=m??{};return{...e,pagination:{...a,continuationUnavailable:{reason:"providerResultCap",maxResults:U}},...Object.keys(h).length>0?{next:h}:{}}}if(typeof n!="number"||!Number.isInteger(n))return{...e,terminalLimit:!0,pagination:{...a,continuationUnavailable:{reason:"missingProviderCursor"}}};if(n>1e3)return{...e,terminalLimit:!0,pagination:{...a,continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}};let d=e.next&&typeof e.next=="object"?e.next:{};return{...e,next:{...d,nextPage:{tool:"ghSearch",query:Pe(o,n),why:`Continue ${t} results on page ${n}.`,confidence:"exact"}}}}function Ne(e){let t=e.pagination;if(!t||typeof t!="object"||t.totalMatchesCapped!==!0)return e;let o=Array.isArray(e.partialReasons)?e.partialReasons.filter(r=>typeof r=="string"):[];return{...e,isPartial:!0,terminalLimit:!0,partialReasons:o.includes("providerResultCap")?o:[...o,"providerResultCap"],providerLimit:{reason:"providerResultCap",maxResults:U}}}function $e(e,t,o){let r=e.incompleteResults===!0,i=Array.isArray(e.partialReasons)?e.partialReasons.filter(m=>typeof m=="string"):[],n=i.includes("partialTreeFailures");if(!r&&!n)return e;let a=[...i,...r&&!i.includes("providerIncompleteResults")?["providerIncompleteResults"]:[]],u=e.next&&typeof e.next=="object"?e.next:{},d=typeof o.page=="number"&&Number.isInteger(o.page)?o.page:1;return{...e,isPartial:!0,partialReasons:a,next:{...u,...u.retry?{}:{retry:{tool:"ghSearch",query:Pe(o,d),why:`Retry the same ${t} provider page because the provider reported incomplete results.`,confidence:"exact"}}}}}function V(e){if(Array.isArray(e))return e.map(V);if(!e||typeof e!="object")return e;let t=Object.fromEntries(Object.entries(e).map(([r,i])=>[r,V(i)])),o=typeof t.tool=="string"?ze[t.tool]:void 0;if(o&&(t.tool="ghSearch",t.query&&typeof t.query=="object")){let r={...t.query};o==="tree"?(r.itemsPerPage!==void 0&&(r.pageSize=r.itemsPerPage),delete r.itemsPerPage):o==="repositories"?(r.limit!==void 0&&(r.pageSize=r.limit),delete r.limit,r.topicsToSearch!==void 0&&(r.topics=r.topicsToSearch),delete r.topicsToSearch):o==="code"&&(r.limit!==void 0&&(r.pageSize=r.limit),delete r.limit),t.query={operation:o,...r}}return t}async function Dt(e){let t=v(e.authInfo);return M(e.queries,o=>re({toolName:N,query:o,contextMessage:"ghSearch execution failed",execute:async()=>{let r=Y.safeParse(o);if(!r.success)throw r.error;return Le(r.data,e,t)}}),{toolName:N,finalize:xe()},e)}async function Le(e,t,o){let{operation:r,...i}=e;switch(r){case"code":{let{pageSize:n,...a}=i,u={...a,limit:n};return de(u,{...t,queries:[u]},o)}case"repositories":{let{topics:n,pageSize:a,...u}=i,d={...u,topicsToSearch:n,limit:a};return ye(d,{...t,queries:[d]},o)}case"tree":{let{pageSize:n,...a}=i;return Se({...a,itemsPerPage:n},{...t,queries:[{...a,itemsPerPage:n}]},o)}default:throw new Error("Unsupported ghSearch operation")}}export{Dt as executeGitHubSearch};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as ze}from"./chunk-UKQLRZEW.js";import{a as he}from"./chunk-43RVQWTG.js";import{b as Pe}from"./chunk-MCMOWPYL.js";import{a as z}from"./chunk-7DYE654A.js";import"./chunk-3AA4F3QO.js";import"./chunk-OA6NU4KO.js";import{a as Le,b as Re,c as De}from"./chunk-EOLHXX5I.js";import{D as U,b as ye,e as Q,f as ge,g as Ce,h as Fe,j as H,k as G,o as $,s as be,w as Se,x as ee}from"./chunk-RRSY2ZPX.js";import"./chunk-CBIKUVP6.js";import"./chunk-Y5OCKUQX.js";import"./chunk-CBCZVCTZ.js";import"./chunk-DKGYPFGX.js";import{b as Te}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{c as xe,f as O,g as Ee,h as te,j as ne}from"./chunk-ZSXRT7JL.js";import{P as B,ea as we,ha as T}from"./chunk-BMM5H6QF.js";import{writeFileSync as gt,existsSync as He,rmSync as Ge,readdirSync as Ct}from"node:fs";import{join as A,resolve as $e,relative as Ft,sep as Ue}from"node:path";import{getDiscoveryExtension as bt}from"@octocodeai/octocode-engine/security";import{readdirSync as ct,statSync as Ie}from"node:fs";import{join as at}from"node:path";import{readFileSync as ot,writeFileSync as it}from"node:fs";import{join as ve}from"node:path";import{z as E}from"zod";var Y=".octocode-directory-meta.json",F=E.number().int().nonnegative(),st=E.object({commitSha:E.string(),complete:E.boolean(),directoryEntryCount:F,eligibleFileCount:F,skipped:E.object({nonFile:F,oversized:F,binary:F,fileLimit:F,fetchFailed:F,totalSizeLimit:F,pathTraversal:F}),files:E.array(E.object({path:E.string(),size:F}))});function Me(e,t){try{let n=st.safeParse(JSON.parse(ot(ve(e,Y),"utf8")));if(n.success&&n.data.commitSha===t)return n.data}catch{}}function ke(e,t){it(ve(e,Y),JSON.stringify(t),{encoding:"utf8",mode:384})}var X=50,re=5*1024*1024,oe=300*1024,Oe=5,_e=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".eot",".otf",".pyc",".class",".o",".obj"]),ie={maxDirectoryFiles:X,maxTotalSize:re,maxFileSize:oe};function se(){return{nonFile:0,oversized:0,binary:0,fileLimit:0,fetchFailed:0,totalSizeLimit:0,pathTraversal:0}}function ce(e){return Object.values(e).every(t=>t===0)}function ae(e,t){if(!t&&e)return["Cannot verify completeness against remote tree; use forceRefresh or ghCloneRepo if completeness matters."];if(!e)return["Directory materialization is partial; inspect skipped counts or use ghCloneRepo before repo-wide reachability/dead-code conclusions."]}async function Ae(e,t,n){let i=[];for(let r=0;r<e.length;r+=t){let c=e.slice(r,r+t),s=await Promise.allSettled(c.map(async o=>{let a=await n(o);return{entry:o,content:a}}));for(let o of s)o.status==="fulfilled"&&i.push(o.value)}return i}function Ne(e,t){let n=[],i=0;function r(c){let s;try{s=ct(c)}catch{return}for(let o of s){if(o===Y||o===".octocode-clone-meta.json")continue;let a=at(c,o);try{let l=Ie(a);if(l.isDirectory())r(a);else if(l.isFile()){let m=a.substring(t.length+1);i+=l.size,n.push({path:m,size:l.size,type:"file"})}}catch{}}}return r(e),{files:n,fileCount:n.length,totalSize:i}}function je(e){try{return Ie(e).size}catch{return 0}}import{cpSync as lt,existsSync as ft,lstatSync as ut,mkdirSync as _,mkdtempSync as pt,renameSync as Be,rmSync as V,statSync as mt,writeFileSync as dt}from"node:fs";import{dirname as Qe,join as R}from"node:path";import{randomUUID as ht}from"node:crypto";var yt=".octocode-clone-meta.json";async function W(e,t,n){let i=ye(e,t);_(Qe(i),{recursive:!0,mode:448});let r=Date.now();for(;;)try{_(i,{mode:448}),ge(i);break}catch(c){if(c.code!=="EEXIST")throw c;if(Ce(i))continue;if(Date.now()-r>3e4)throw new Error("Timed out waiting for tree materialization lock.",{cause:c});await new Promise(s=>setTimeout(s,25))}try{return await n()}finally{V(i,{recursive:!0,force:!0})}}function J(e,t){let n=e;for(let i of t.split("/").filter(Boolean)){if(i===".."||i===".")throw new Error("Invalid snapshot directory path.");if(n=R(n,i),ft(n)&&ut(n).isSymbolicLink())throw new Error("Snapshot paths cannot traverse symbolic links.");_(n,{recursive:!0,mode:448})}return n}function Z(e){let t=Fe(e)?.snapshotId;if(!t||!/^[0-9a-f-]{36}$/.test(t))return;let n=R(e,"snapshots",t);try{return mt(n).isDirectory()?n:void 0}catch{return}}function K(e,t,n,i,r){let c=R(e,"tmp","tree-staging");_(c,{recursive:!0,mode:448});let s=pt(R(c,"snapshot-")),o=ht(),a=R(t,"snapshots",o),l=R(t,`.snapshot-${o}.tmp`),m=!1;try{return n&&lt(n,s,{recursive:!0,dereference:!1}),r(s),_(Qe(a),{recursive:!0,mode:448}),Be(s,a),dt(l,JSON.stringify({...i,snapshotId:o}),{encoding:"utf8",mode:384}),Be(l,R(t,yt)),m=!0,a}finally{V(s,{recursive:!0,force:!0}),V(l,{force:!0}),m||V(a,{recursive:!0,force:!0})}}async function Ye(e,t,n,i,r,c=!1){let s=B(),{commitSha:o,resolvedRef:a}=await z(e,t,i,r,c),l=Q(s,e,t,o);return $(s),W(s,l,async()=>{let m=Z(l),u=m??l,h=$e(A(u,n));if(!h.startsWith(u+Ue)&&h!==u)throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let L=H(l);if(L.hit&&L.meta.commitSha===o&&!c&&m&&He(h)){let f=Ne(h,u),p=Me(h,o),d=p?.skipped??se(),D=new Map(f.files.map(I=>[I.path,I.size])),P=p?.complete===!0&&ce(d)&&p.files.length===f.fileCount&&p.files.every(I=>D.get(I.path)===I.size);return{localPath:h,repoRoot:u,files:f.files,fileCount:f.fileCount,totalSize:f.totalSize,complete:P,verified:!1,commitSha:o,...d.nonFile>0?{hasSubdirectories:!0}:{},directoryEntryCount:p?.directoryEntryCount??f.fileCount,eligibleFileCount:p?.eligibleFileCount??f.fileCount,savedFileCount:f.fileCount,skipped:d,limits:ie,warnings:ae(P,!1),cached:!0,expiresAt:L.meta.expiresAt,owner:e,repo:t,branch:a,directoryPath:n}}let w=await Se(r),{data:v}=await w.rest.repos.getContent({owner:e,repo:t,path:n,ref:o});if(!Array.isArray(v))throw new Error(`Path "${n}" is not a directory. Use type "file" to fetch file content.`);let x=v,g=se(),S=[];for(let f of x){if(f.type!=="file"){g.nonFile+=1;continue}if(f.size>oe){g.oversized+=1;continue}let p=bt(f.name,{lowercase:!0,leadingDot:!0});if(_e.has(p)){g.binary+=1;continue}S.push(f)}g.fileLimit=Math.max(0,S.length-X);let fe=S.slice(0,X),N=await Ae(fe,Oe,async f=>{let{rawResult:p}=await U({owner:e,repo:t,path:f.path,branch:o,type:"file",fullContent:!0,minify:"none",contextLines:0,forceRefresh:c},r);if(!("data"in p)||!p.data)throw new Error("Directory file read failed");return p.data.rawContent});g.fetchFailed=fe.length-N.length;let M=0,ue=[];for(let f=0;f<N.length;f+=1){let{entry:p,content:d}=N[f],D=Buffer.byteLength(d,"utf8");if(M+D>re){g.totalSizeLimit=N.length-f;break}M+=D,ue.push({entry:p,content:d})}let k=[],pe=ue.filter(({entry:f})=>{let p=$e(A(u,f.path)),d=Ft(h,p);return!d||d.startsWith("..")||d.includes(Ue)||f.name===".octocode-directory-meta.json"?(g.pathTraversal+=1,!1):!0});M=0;for(let{entry:f,content:p}of pe){let d=Buffer.byteLength(p,"utf8");M+=d,k.push({path:f.path,size:d,type:"file"})}let me=G(e,t,a,"treeFetch",void 0,void 0,o),j=ce(g),de=j,rt=g.nonFile>0;return u=K(s,l,m,me,f=>{let p=J(f,n);for(let d of Ct(p,{withFileTypes:!0}))d.isDirectory()||Ge(A(p,d.name),{force:!0});for(let{entry:d,content:D}of pe){let P=A(f,d.path);He(P)&&Ge(P,{recursive:!0,force:!0}),gt(P,D,"utf-8")}ke(p,{commitSha:o,complete:j,directoryEntryCount:x.length,eligibleFileCount:S.length,skipped:g,files:k})}),h=A(u,n),{localPath:h,repoRoot:u,files:k,fileCount:k.length,totalSize:M,complete:j,verified:de,commitSha:o,...rt?{hasSubdirectories:!0}:{},directoryEntryCount:x.length,eligibleFileCount:S.length,savedFileCount:k.length,skipped:g,limits:ie,warnings:ae(j,de),cached:!1,expiresAt:me.expiresAt,owner:e,repo:t,branch:a,directoryPath:n}})}import{writeFileSync as St,existsSync as wt,statSync as xt,lstatSync as Et,rmSync as Lt}from"node:fs";import{join as le,dirname as Rt,resolve as Dt,sep as Pt}from"node:path";async function Xe(e,t,n,i,r,c=!1){let s=B(),{commitSha:o,resolvedRef:a}=await z(e,t,i,r,c),l=Q(s,e,t,o);return $(s),W(s,l,async()=>{let m=Z(l),u=m??l,h=Dt(le(u,n));if(!h.startsWith(u+Pt))throw new Error(`Path "${n}" escapes the repository directory. Path traversal is not allowed.`);let L=H(l);if(!c&&L.hit&&L.meta.commitSha===o&&m&&wt(h)&&xt(h).isFile())return{localPath:h,repoRoot:u,path:n,size:je(h),cached:!0,expiresAt:L.meta.expiresAt,owner:e,repo:t,branch:a,commitSha:o};let{rawResult:w}=await U({owner:e,repo:t,path:n,type:"file",branch:o,fullContent:!0,contextLines:0,minify:"none",goal:`Save ${e}/${t}/${n} locally`,reasoning:"GitHub file materialization"},r);if(!("data"in w)||!w.data){let x="error"in w?w.error:void 0;throw new Error(x||`Failed to fetch ${e}/${t}/${n}`)}let v=G(e,t,a,"treeFetch",void 0,void 0,o);return u=K(s,l,m,v,x=>{let g=Rt(n);J(x,g==="."?"":g);let S=le(x,n);Et(S,{throwIfNoEntry:!1})&&Lt(S,{recursive:!0,force:!0}),St(S,w.data.rawContent,"utf8")}),h=le(u,n),{localPath:h,repoRoot:u,path:n,size:Buffer.byteLength(w.data.rawContent,"utf8"),cached:!1,expiresAt:v.expiresAt,owner:e,repo:t,branch:a,commitSha:o}})}function Ve(e){let t=!!e.fullContent;return{projectId:`${e.owner}/${e.repo}`,path:String(e.path),ref:e.branch?String(e.branch):void 0,startLine:t?void 0:e.startLine,endLine:t?void 0:e.endLine,matchString:t||!e.matchString?void 0:String(e.matchString),contextLines:e.contextLines??5,fullContent:t,forceRefresh:!!e.forceRefresh,charOffset:e.charOffset,charLength:e.charLength,minify:e.minify,matchStringIsRegex:e.matchStringIsRegex,matchStringCaseSensitive:e.matchStringCaseSensitive,goal:e.goal,reasoning:e.reasoning}}function We(e,t){return{path:e.path,content:e.content,...typeof e.size=="number"&&e.size>0&&{fileSize:e.size},...typeof e.totalLines=="number"&&{totalLines:e.totalLines},...typeof e.sourceChars=="number"&&{sourceChars:e.sourceChars},...typeof e.sourceBytes=="number"&&{sourceBytes:e.sourceBytes},...e.contentView&&{contentView:e.contentView},...e.isPartial&&{isPartial:e.isPartial},...e.errorCode&&{errorCode:e.errorCode},...e.terminalLimit&&{terminalLimit:e.terminalLimit},...e.partialReasons?.length&&{partialReasons:e.partialReasons},...e.startLine&&{startLine:e.startLine},...e.endLine&&{endLine:e.endLine},...e.matchRanges?.length&&{matchRanges:e.matchRanges},...e.matchedLines?.length&&{matchedLines:e.matchedLines},...e.lastModified&&{lastModified:e.lastModified},...e.lastModifiedBy&&{lastModifiedBy:e.lastModifiedBy},...e.pagination&&{pagination:e.pagination},...e.warnings?.length&&{warnings:e.warnings},...e.matchNotFound===!0&&{matchNotFound:!0},...e.searchedFor&&{searchedFor:e.searchedFor},...e.ref&&t.branch!==e.ref?{resolvedBranch:e.ref}:{}}}function q(e){return typeof e=="object"&&e!==null}function C(e){return typeof e=="string"&&e.length>0?e:void 0}function y(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Je(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string");return t.length>0?t:void 0}function b(e,t){return y(e[t])??0}function Tt(e){if(q(e))return{nonFile:b(e,"nonFile"),oversized:b(e,"oversized"),binary:b(e,"binary"),fileLimit:b(e,"fileLimit"),fetchFailed:b(e,"fetchFailed"),totalSizeLimit:b(e,"totalSizeLimit"),pathTraversal:b(e,"pathTraversal")}}function zt(e){if(q(e))return{maxDirectoryFiles:b(e,"maxDirectoryFiles"),maxTotalSize:b(e,"maxTotalSize"),maxFileSize:b(e,"maxFileSize")}}var vt=["charOffset","charLength","totalChars","nextCharOffset","nextBlockChar","nextPage","nextMatchPage","filesPerPage","totalFiles","entriesPerPage","totalEntries","matchesPerPage","totalMatches"];function Mt(e){if(!q(e))return;let{currentPage:t,totalPages:n,hasMore:i}=e;if(typeof t!="number"||typeof n!="number"||typeof i!="boolean")return;let r={currentPage:t,totalPages:n,hasMore:i};e.pageCountsKind==="estimated"&&(r.pageCountsKind="estimated"),(e.chunkMode==="semantic"||e.chunkMode==="char-limit")&&(r.chunkMode=e.chunkMode);for(let c of vt){let s=e[c];typeof s=="number"&&Number.isFinite(s)&&(r[c]=s)}return r}function kt(e,t){let{goal:n,reasoning:i,charOffset:r,...c}=t;return Te("ghGetFileContent",{...c,charLength:t.charLength??e?.charLength},e)}function It(e,t){if(t.matchString!==void 0)return;let n=y(e.startLine),i=y(e.endLine),r=y(e.totalLines);if(e.isPartial!==!0||n===void 0||i===void 0||r===void 0||i>=r)return;let c=Math.max(1,i-n+1),s=i+1,o=Math.min(r,i+c);return{tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,...t.branch!==void 0?{branch:t.branch}:{},path:t.path,startLine:s,endLine:o,...t.minify!==void 0?{minify:t.minify}:{}},why:`Continue the file at lines ${s}-${o}.`,confidence:"exact"}}function Ot(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"lspGetSemantics (definitions/references) only works on local files \u2014 clone this path locally, then run localSearch or lspGetSemantics on it",confidence:"exact"}}function Ze(){try{return be()}catch{return!1}}function _t(e){return{tool:"ghCloneRepo",query:{owner:e.owner,repo:e.repo,...e.branch!==void 0?{branch:e.branch}:{},sparsePath:e.path},why:"Clone this directory to retrieve content omitted by remote directory-fetch limits or failures.",confidence:"exact"}}function Ke(e,t){let n=Mt(e.pagination),i=Ze(),r=n?.hasMore===!0?void 0:It(e,t),c={...kt(n,t),...r?{continueLines:r}:{},...i?{cloneForSemantics:Ot(t)}:{}};if(e.errorCode==="contentSecurityLimit"&&(y(e.totalLines)??0)>1&&(t.startLine===void 0||t.startLine!==t.endLine)){let a=t.startLine??1;c.readBoundedLines={tool:"ghGetFileContent",query:{owner:t.owner,repo:t.repo,path:t.path,...t.branch!==void 0?{branch:t.branch}:{},startLine:a,endLine:a,minify:"none"},why:"The selected view is too large to scan safely. Read one source line; this starts a different source-line view, not a continuation of the rejected character view.",confidence:"exact"}}let s=C(e.path)??String(t.path??""),o=s?ze(s):void 0;return{path:s,content:typeof e.content=="string"?e.content:"",...e.errorCode==="contentSecurityLimit"?{errorCode:"contentSecurityLimit",terminalLimit:!0,partialReasons:["security-selected-view-size-limit"]}:{},...o?{fileType:o}:{},localPath:C(e.localPath),repoRoot:C(e.repoRoot),contentView:e.contentView==="none"||e.contentView==="standard"||e.contentView==="symbols"?e.contentView:void 0,totalLines:y(e.totalLines),sourceChars:y(e.sourceChars),resolvedBranch:C(e.resolvedBranch),...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},pagination:n,...Object.keys(c).length>0?{next:c}:{},...e.isPartial===!0||n?.hasMore===!0?{isPartial:!0}:{},startLine:y(e.startLine),endLine:y(e.endLine),...Array.isArray(e.matchRanges)&&e.matchRanges.length>0?{matchRanges:e.matchRanges}:{},...Array.isArray(e.matchedLines)&&e.matchedLines.length>0?{matchedLines:e.matchedLines}:{},lastModified:C(e.lastModified),lastModifiedBy:C(e.lastModifiedBy),warnings:Je(e.warnings),...e.matchNotFound===!0?{matchNotFound:!0}:{},searchedFor:C(e.searchedFor),...e.cached===!0?{cached:!0}:{}}}function qe(e,t){let i=(Array.isArray(e.files)?e.files:[]).filter(q).map(u=>({path:C(u.path)??"",size:y(u.size)??0,type:C(u.type)??"file"})),r=Tt(e.skipped),c=e.hasSubdirectories===!0||(r?r.nonFile>0:!1),s=r?Object.entries(r).filter(([,u])=>u>0):[],o=s.length>0?Object.fromEntries(s):void 0,a=e.complete===!1,l=a?s.length>0?s.map(([u])=>u):["providerDirectoryIncomplete"]:[],m=a&&Ze();return{path:String(t.path??""),localPath:C(e.localPath)??"",repoRoot:C(e.repoRoot),fileCount:y(e.fileCount)??i.length,totalSize:y(e.totalSize)??0,complete:e.complete===!0,verified:e.verified===!0,...typeof e.commitSha=="string"&&e.commitSha.length===40?{commitSha:e.commitSha}:{},...c?{hasSubdirectories:!0}:{},...o?{skippedSummary:o}:{},directoryEntryCount:y(e.directoryEntryCount),eligibleFileCount:y(e.eligibleFileCount),savedFileCount:y(e.savedFileCount),skipped:r,limits:zt(e.limits),warnings:Je(e.warnings),...i.length>0?{files:i}:{},...e.cached===!0?{cached:!0}:{},resolvedBranch:C(e.resolvedBranch),...a?{isPartial:!0,partialReasons:l,...m?{next:{escalateToClone:_t(t)}}:{terminalLimit:!0}}:{}}}function et(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e;return typeof t.message=="string"?t.message:t.error===e?void 0:et(t.error)}function At(e,t){let n=typeof t?.owner=="string"?t.owner:void 0,i=typeof t?.repo=="string"?t.repo:void 0;if(e.status==="error"){let c=e.data.error,s=et(c)??"File content query failed",o=/\b404\b|not found/i.test(s);return{...n?{owner:n}:{},...i?{repo:i}:{},...t?.path?{path:String(t.path)}:{},error:o&&n&&i?`${s} \u2014 verify the path (exact case, no leading slash) and branch; use ghSearch with operation:"tree", owner:"${n}", repo:"${i}"`:s}}let r={owner:n??"",repo:i??""};return t?.type==="directory"?r.directories=[qe(e.data,t)]:r.files=[Ke(e.data,t??{})],r}function tt(){return({queries:e,results:t})=>{let n=t.map(r=>({...r,data:At(r,e[r.index])}));return Pe({results:n},["results","index","status","meta","data","owner","repo","files","directories","path","content","fileType","totalLines","startLine","endLine","isPartial","pagination","error"],n.length>0&&n.every(r=>r.status==="error"))}}import{getConfigSync as nt}from"@octocodeai/config";async function Xn(e){let{queries:t,authInfo:n}=e,i=Le(n);return xe(t,async(r,c)=>{try{let s=Ee(he,r,{prefix:!1});if(s.ok===!1)return s.error;let o=s.data,a=o.minify??(o.fullContent===!0?"none":"standard"),l={...o,minify:a};if(l.type==="directory"){let u=Nt(l);if(u)return u}let m=i();return l.type==="directory"?jt(l,n,m):Bt(l,n,m)}catch(s){return ne(s,r,void 0,T.GITHUB_FETCH_CONTENT)}},{toolName:T.GITHUB_FETCH_CONTENT,finalize:tt()},e)}function Nt(e){let t=nt();if(!t.local.enabled)return O('Directory fetch requires local materialization. Set ENABLE_LOCAL=true to use type: "directory".',e,{extra:{errorCode:"localToolsDisabled"},rawResponse:0});if(!t.local.enableClone)return O('Directory fetch requires clone/materialization support. Set ENABLE_CLONE=true to use type: "directory".',e,{extra:{errorCode:"cloneDisabled"},rawResponse:0});if(t.storage.mode==="memory")return O('Directory fetch requires persistent local materialization. Set storage.mode="persistent" or OCTOCODE_STORAGE_MODE=persistent to use type: "directory".',e,{extra:{errorCode:"persistentStorageDisabled"},rawResponse:0})}async function jt(e,t,n){if(!Re(n,"fetchDirectoryToDisk"))return ne(new Error('Directory fetch (type: "directory") is only available with the GitHub provider. Use file mode (type: "file") instead.'),e,"Provider not supported",T.GITHUB_FETCH_CONTENT);if(!e.owner||!e.repo)return O("Directory fetch requires both owner and repo.",e,{rawResponse:0});let i=e.branch??await ee(e.owner,e.repo,t),r=await Ye(e.owner,e.repo,String(e.path),i,t,!!e.forceRefresh),c=r.skipped?Object.fromEntries(Object.entries(r.skipped).filter(([,o])=>o>0)):void 0,s={localPath:r.localPath,repoRoot:r.repoRoot,fileCount:r.fileCount,totalSize:r.totalSize,complete:r.complete,verified:r.verified,...r.commitSha?{commitSha:r.commitSha}:{},directoryEntryCount:r.directoryEntryCount,eligibleFileCount:r.eligibleFileCount,savedFileCount:r.savedFileCount,...c&&Object.keys(c).length>0?{skipped:r.skipped}:{},limits:r.limits,...r.warnings?{warnings:r.warnings}:{},files:r.files,...r.cached?{cached:!0}:{},...e.branch!==r.branch?{resolvedBranch:r.branch}:{}};return te(e,s,!0,T.GITHUB_FETCH_CONTENT,{rawResponse:r.totalSize??we(r)})}async function Bt(e,t,n){let i=nt(),c=e.fullContent===!0&&e.minify==="none"&&i.local.enabled&&i.local.enableClone&&i.storage.mode==="persistent"&&n.provider.type==="github"?await z(e.owner,e.repo,e.branch??await ee(e.owner,e.repo,t),t,e.forceRefresh===!0):void 0,s=c?{...e,branch:c.commitSha}:e,o=await De(e,()=>n.provider.getFileContent(Ve(s)));if(o.ok===!1)return o.result;let a=c?await Xe(e.owner,e.repo,e.path,c.commitSha,t,e.forceRefresh===!0):void 0,l={...We(o.response.data,s),...a?{localPath:a.localPath,repoRoot:a.repoRoot,cached:a.cached,commitSha:a.commitSha,...c?{resolvedBranch:c.resolvedRef}:{}}:{}},m=!!(o.response.data.matchNotFound===!0||o.response.data.content&&o.response.data.content.length>0);return te(e,l,m,T.GITHUB_FETCH_CONTENT,{rawResponse:o.response.rawResponseChars})}export{Xn as fetchMultipleGitHubFileContents};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as K,b as Y}from"./chunk-QKDE2HIF.js";import"./chunk-J3WYA3IJ.js";import{a as X,b as ee}from"./chunk-BICVXQ5F.js";import"./chunk-MPTAIBY7.js";import"./chunk-DKGYPFGX.js";import{a as v,b as U}from"./chunk-NQRDACK3.js";import{a as D}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{a as ie}from"./chunk-WH6GL3J2.js";import{c as te,f as b}from"./chunk-ZSXRT7JL.js";import{X as I,d as $,fa as W,ha as g}from"./chunk-BMM5H6QF.js";import{access as Be}from"node:fs/promises";function M(e){return e===0?"0.0B":e<1024?`${e}.0B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)}MB`:e<1024*1024*1024*1024?`${(e/(1024*1024*1024)).toFixed(1)}GB`:`${(e/(1024*1024*1024*1024)).toFixed(1)}TB`}function A(e){let i=e.trim();if(/^\d+$/.test(i))return parseInt(i,10);let r=i.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB|TB)$/i);if(r&&r[1]&&r[2]){let s=parseFloat(r[1]);switch(r[2].toUpperCase()){case"B":return Math.round(s);case"KB":return Math.round(s*1024);case"MB":return Math.round(s*1024*1024);case"GB":return Math.round(s*1024*1024*1024);case"TB":return Math.round(s*1024*1024*1024*1024)}}let t=i.match(/^(\d+(?:\.\d+)?)([KMGT])$/i);if(!t||!t[1]||!t[2])throw new Error(`Invalid size format: ${e}`);let n=parseFloat(t[1]);switch(t[2].toUpperCase()){case"K":return Math.round(n*1024);case"M":return Math.round(n*1024*1024);case"G":return Math.round(n*1024*1024*1024);default:return Math.round(n*1024*1024*1024*1024)}}function re(e){let i=e.filter(n=>n.type==="file").length,r=e.filter(n=>n.type==="directory").length,t=e.reduce((n,o)=>o.type==="file"&&o.size?n+A(o.size):n,0);return`${e.length} entries (${i} files, ${r} dirs, ${M(t)})`}function ne(e,i){let r=e.length,t=i.itemsPerPage||20,n=Math.max(1,Math.ceil(r/t)),o=i.page||1,s=Math.min(o,n),f=o>n,a=(s-1)*t,c=Math.min(a+t,r),x=s<n;return{paginatedEntries:e.slice(a,c),endIdx:c,pagination:{currentPage:s,totalPages:n,entriesPerPage:t,totalEntries:r,hasMore:x,...x&&s<1e3?{nextPage:s+1}:{},...f?{outOfRange:!0}:{}}}}function G(e){if(e.skipped<=0)return[];let i=e.skipped-e.permissionDenied;return e.permissionDenied>0&&i>0?[`${e.skipped} entries skipped (${e.permissionDenied} permission denied, ${i} other errors)`]:e.permissionDenied>0?[`${e.permissionDenied} ${e.permissionDenied===1?"entry":"entries"} skipped due to permission denied`]:[`${e.skipped} ${e.skipped===1?"entry":"entries"} skipped due to access errors`]}function oe(e){let i=e.find(t=>t.type==="file");if(i)return{fetch:{tool:"localGetFileContent",query:{path:i.path,minify:"standard"},why:'Read the first matched file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"}};let r=e.find(t=>t.type==="directory");if(r)return{viewStructure:{tool:"local.tree",query:{path:r.path},why:"Orient inside the first matched directory before reading files.",confidence:"exact"}}}var ye=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function xe(e,i){let r=i??ye,t=new Set(e.split("/").filter(Boolean));return r.filter(n=>!t.has(n))}async function se(e){let i=e.detail==="full",r=e.detail==="modified"||i,t=r||(e.sortBy||"modified")==="modified";try{let n=U(e,g.LOCAL_FIND_FILES);if(!n.isValid)return n.errorResult;let o={...e,path:n.sanitizedPath},s={...o,excludeDir:xe(o.path,o.excludeDir)},{warnings:f,query:a}=Le(s),c=e.limit??1e4,x={path:a.path,recursive:!0,includeRoot:!0,showHidden:!0,maxDepth:a.maxDepth,minDepth:a.minDepth,names:a.names,extensions:a.extensions,regex:a.regex,entryType:a.entryType,empty:a.empty,modifiedWithin:a.time?.modifiedWithin,modifiedBefore:a.time?.modifiedBefore,accessedWithin:a.time?.accessedWithin,sizeGreater:a.size?.greater,sizeLess:a.size?.less,permissions:a.permissions,executable:a.access==="executable",readable:a.access==="readable",writable:a.access==="writable",excludeDir:a.excludeDir,limit:1e4},u=await I.queryFileSystem({...x,pathPattern:a.pathPattern}),L=u.totalDiscovered,S=u.wasCapped,E=u.entries.map(H=>Ee(H,t)),T=e.sortBy||"modified";Fe(E,T,t);let B=E.slice(0,c),w=B.length<E.length,d=S,j=we(B,i,r),h=j.length,R=e.itemsPerPage||20,F=e.page||1,P=Math.max(1,Math.ceil(h/R)),_=(F-1)*R,C=Math.min(_+R,h),V=j.slice(_,C),N=h>0&&_>=h,z=V,l=[...u.warnings,...G(u),...S?[`results capped at ${1e4} during the walk before sorting \u2014 sortBy:"${T}" only orders that partial set, not the true top-N across the whole tree`]:[],...N?[`page:${F} is out of range (only ${P} page(s), ${h} total file(s)) \u2014 returned 0 files. Use page:1..${P}.`]:[]],p=[...f,...l],m=F<P,Q=w&&c<1e4,O=m&&F>=1e3||(w||d)&&!Q,q={...oe(z)??{},...m&&!O?{nextPage:D(g.LOCAL_FIND_FILES,{...o,page:F+1},"Continue to the next page of matched files.")}:{},...Q?{expandLimit:D(g.LOCAL_FIND_FILES,{...o,limit:Math.min(1e4,Math.max(c+1,c*2)),page:1},"Re-run with a larger file limit because matched files remain.")}:{}},he={...h===0?{status:"empty"}:{},path:o.path,files:z,pagination:{currentPage:F,totalPages:P,filesPerPage:R,totalFiles:h,hasMore:m,...m&&!O?{nextPage:F+1}:{},...S||L>h?{totalFilesFound:L}:{},...N?{outOfRange:!0}:{}},...O?{terminalLimit:!0}:{},...w||d?{truncated:!0,partialReasons:[...w?["limit"]:[],...d?["walkLimit"]:[]],totalAvailable:Math.max(L,E.length)}:{},...Object.keys(q).length>0?{next:q}:{},...p.length>0&&{warnings:p}};return W(he,u.entries.reduce((H,ge)=>H+ge.path.length,0))}catch(n){return b(n,e,{toolName:g.LOCAL_FIND_FILES})}}function Ee(e,i){let r={path:e.path,type:e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",...e.size!==void 0?{size:e.size}:{},...e.permissions?{permissions:e.permissions}:{}};return i&&e.modifiedMs!==void 0&&(r.modified=new Date(e.modifiedMs).toISOString()),r}function Fe(e,i,r){e.sort((t,n)=>{switch(i){case"size":return(n.size??0)-(t.size??0);case"name":return(t.path.split("/").pop()||"").localeCompare(n.path.split("/").pop()||"");case"path":return t.path.localeCompare(n.path);default:return r&&t.modified&&n.modified?new Date(n.modified).getTime()-new Date(t.modified).getTime():t.path.localeCompare(n.path)}})}function we(e,i,r){return e.map(t=>{let n={path:t.path,type:t.type};return t.size!==void 0&&t.type!=="directory"&&(i?n.size=t.size:n.sizeFormatted=M(t.size)),i&&t.permissions&&(n.permissions=t.permissions),t.modified&&(n.modified=t.modified),n})}var Re=/^\d+[hdwm]$/;function Le(e){let i=[],r=e.time;if(!r)return{warnings:i,query:e};let t={...r},n=[{key:"modifiedBefore",value:r.modifiedBefore},{key:"modifiedWithin",value:r.modifiedWithin},{key:"accessedWithin",value:r.accessedWithin}];for(let{key:o,value:s}of n)s&&!Re.test(s)&&(i.push(`time.${o}="${s}" has an unsupported format \u2014 filter was skipped. Use a relative duration like "7d", "2h", "1w", or "3m".`),delete t[o]);return{warnings:i,query:{...e,time:t}}}var Se=new Set(["+","*","?"]),Te=1e3;function Pe(e,i){let r=i+1;for(;r<e.length&&e[r]!=="]";)e[r]==="\\"&&r++,r++;return r+1}function ae(e,i){let r=e[i];return r===void 0?!1:Se.has(r)||r==="{"&&Me(e,i)}function be(e,i,r){let t=r.pop()??!1,n=ae(e,i+1);return n&&t?{unsafe:!0,next:i+1}:((n||t)&&r.length>0&&(r[r.length-1]=!0),{unsafe:!1,next:n?le(e,i+1):i+1})}function De(e,i,r){return r.some(t=>t)?{unsafe:!0,next:i+1}:(r.length>0&&(r[r.length-1]=!0),{unsafe:!1,next:le(e,i)})}function ce(e){if(e.length>Te)return{safe:!1,reason:"Pattern too long (max 1000 characters)"};let i="Nested quantifiers detected (potential ReDoS). Simplify the pattern.",r=[],t=0;for(;t<e.length;){let n=e[t];if(n==="\\"){t+=2;continue}if(n==="["){t=Pe(e,t);continue}if(n==="("){r.push(!1),t++;continue}if(n===")"){let o=be(e,t,r);if(o.unsafe)return{safe:!1,reason:i};t=o.next;continue}if(ae(e,t)){let o=De(e,t,r);if(o.unsafe)return{safe:!1,reason:i};t=o.next;continue}t++}return{safe:!0}}function Me(e,i){if(e[i]!=="{")return!1;let r=e.indexOf("}",i);return r===-1?!1:/^\{\d+,?\d*\}$/.test(e.slice(i,r+1))}function le(e,i){return e[i]==="{"?i=e.indexOf("}",i)+1:i++,i<e.length&&(e[i]==="?"||e[i]==="+")&&i++,i}function ue(e,i){let r=e;if(i.pattern){let t=i.pattern;if(t.includes("*")||t.includes("?")||t.includes("[")){let o=t.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");o=o.replace(/\\\*/g,".*").replace(/\\\?/g,".").replace(/\\\[!/g,"[^").replace(/\\\[/g,"[").replace(/\\\]/g,"]");try{let s=`^${o}$`;if(!ce(s).safe)return r=r.filter(c=>(c.name.includes("/")?c.name.split("/").pop():c.name).includes(t)),r;let a=new RegExp(s,"i");r=r.filter(c=>{let x=c.name.includes("/")?c.name.split("/").pop():c.name;return a.test(x)})}catch{r=r.filter(s=>(s.name.includes("/")?s.name.split("/").pop():s.name).includes(t))}}else r=r.filter(o=>(o.name.includes("/")?o.name.split("/").pop():o.name).includes(t))}return r}function de(e){let i=[],r=[],t=[];for(let n of e)n.type==="directory"?r.push(n.name):n.type==="symlink"?t.push(n.name):i.push(n.size?`${n.name} (${n.size})`:n.name);return{...i.length>0&&{files:i},...r.length>0&&{folders:r},...t.length>0&&{links:t}}}function pe(e){let i={type:e.type==="directory"?"dir":e.type==="symlink"?"link":"file"};return e.depth!==void 0&&e.depth>0&&(i.depth=e.depth),e.size&&e.type==="file"&&(i.size=e.size),e.modified&&(i.modified=e.modified),e.permissions&&(i.permissions=e.permissions),i}function me(e){let i={},r=e.find(n=>n.type==="file"&&n.path);r?.path&&(i.fetch={tool:"localGetFileContent",query:{path:r.path,minify:"standard"},why:'Read the first listed file (minify:"symbols" for a skeleton, minify:"none" for exact bytes).',confidence:"exact"});let t=e.find(n=>n.type==="directory"&&n.path);return t?.path&&(i.viewDeeper={tool:"local.tree",query:{path:t.path},why:"Descend into the first listed subdirectory.",confidence:"exact"}),i.fetch||i.viewDeeper?i:void 0}var _e=["node_modules",".git","dist","build","out","coverage","target",".next",".cache"];function Ce(e,i){let r=i??_e,t=new Set(e.split("/").filter(Boolean));return r.filter(n=>!t.has(n))}async function fe(e){try{let i=U(e,g.LOCAL_VIEW_STRUCTURE);if(!i.isValid)return i.errorResult;let r=e.detail==="modified"||e.detail==="full"||e.sortBy==="time";return await Ne(e,i.sanitizedPath,r)}catch(i){let r=v.toolExecutionFailed("LOCAL_VIEW_STRUCTURE",i instanceof Error?i:void 0);return{status:"error",error:r.message,errorCode:r.errorCode}}}async function Ne(e,i,r=!1){let t=!!(e.maxDepth||e.recursive),n=t?e.maxDepth||(e.recursive?5:2):1,o=Oe(e),s=ze(e,o),f=t&&s?1e4:1e4,a=Ce(i,e.excludeDir),c;try{c=await I.queryFileSystem({path:i,recursive:t,includeRoot:!1,showHidden:e.hidden??!1,maxDepth:n,names:o,extensions:e.extensions,entryType:$e(e),excludeDir:a,limit:f})}catch(l){return ke(l,e,i)}let x=c.entries.map(l=>ve(l,r,e.detail==="full")),u=ue(x,e),L=e.sortBy??"name";u=u.sort((l,p)=>{let m;switch(L){case"size":{let Q=l.sizeBytes??(l.size?A(l.size):0),O=p.sizeBytes??(p.size?A(p.size):0);m=Q-O;break}case"time":r&&l.modified&&p.modified?m=l.modified.localeCompare(p.modified):m=l.name.localeCompare(p.name);break;case"extension":m=(l.extension||"").localeCompare(p.extension||"");break;default:m=l.name.localeCompare(p.name);break}return e.reverse?-m:m});let S=u.length;e.limit&&(u=u.slice(0,e.limit));let E=u.length<S,T=c.wasCapped,B=u.length,{paginatedEntries:w,pagination:d}=ne(u,e),h=e.detail==="full"||e.detail==="modified"?{path:i,entries:w.map(l=>({...pe(l),path:l.path??`${i.replace(/\/$/,"")}/${l.name}`}))}:{path:i,...de(w)},R=[...c.warnings,...G({skipped:c.skipped,permissionDenied:c.permissionDenied}),...c.wasCapped?[`Results capped at ${f} entries during the walk before sorting \u2014 sortBy:"${L}" only orders that partial set, not the true top-N across the whole tree. Add pattern/extensions/entryType/excludeDir or reduce depth to narrow the scope.`]:[],...d.outOfRange?[`page:${e.page} is out of range (only ${d.totalPages} page(s), ${d.totalEntries} total entries) \u2014 returned page ${d.currentPage} instead.`]:[]],F=B===0,P=re(u),_=me(w)??{},C=e.limit??1e4,V=E&&C<1e4,N=d.hasMore&&d.currentPage>=1e3||(E||T)&&!V,z={..._,...d.hasMore&&!N?{nextPage:D(g.LOCAL_VIEW_STRUCTURE,{...e,page:d.currentPage+1},"Continue to the next page of directory entries.")}:{},...V?{expandLimit:D(g.LOCAL_VIEW_STRUCTURE,{...e,limit:Math.min(1e4,Math.max(C+1,C*2)),page:1},"Re-run with a larger entry limit because directory entries remain.")}:{}};return W({...F?{status:"empty"}:{},...h,summary:P,...d.hasMore||d.totalPages>1||d.outOfRange?{pagination:d}:{},...Object.keys(z).length>0?{next:z}:{},...N?{terminalLimit:!0}:{},...E||T?{truncated:!0,partialReasons:[...E?["limit"]:[],...T?["walkLimit"]:[]],totalAvailable:Math.max(c.totalDiscovered,S)}:{},...R.length>0&&{warnings:R}},c.entries.reduce((l,p)=>l+p.path.length,0))}function ze(e,i){return!!((typeof e.pattern=="string"?e.pattern:void 0)&&!i)}function Oe(e){let i=typeof e.pattern=="string"?e.pattern:void 0;if(i&&!i.includes("["))return i.includes("*")||i.includes("?")?[i]:[`*${i}*`]}function $e(e){return e.entryType}function ve(e,i,r){let t=e.entryType==="directory"?"directory":e.entryType==="symlink"?"symlink":"file",n={name:e.relativePath||e.name,path:e.path,type:t,...e.size!==void 0?{size:M(e.size),sizeBytes:e.size}:{},...e.extension?{extension:e.extension}:{},depth:e.depth};return(r||i)&&e.modifiedMs!==void 0&&(n.modified=new Date(e.modifiedMs).toISOString()),r&&e.permissions&&(n.permissions=Ae(e.permissions)),n}function Ae(e){let i=Number.parseInt(e,8);if(!Number.isFinite(i))return e;let r=["---","--x","-w-","-wx","r--","r-x","rw-","rwx"];return`${r[i>>6&7]}${r[i>>3&7]}${r[i&7]}`}function ke(e,i,r){let t=e instanceof Error?e.message:String(e),n=/ENOENT|not found|no such file/i.test(t),o=/EACCES|permission denied/i.test(t),s=/ENOTDIR|not a directory/i.test(t),f=v.pathValidationFailed(r,n?`Directory not found: ${r}`:o?`Permission denied: ${r}`:s?`Not a directory: ${r}`:`Cannot access path: ${r}`);return b(f,i,{toolName:g.LOCAL_VIEW_STRUCTURE})}var Ve={"local.text":"text","local.files":"files","local.tree":"tree"};async function Ct(e){return te(e.queries||[],i=>ie({toolName:$,query:i,contextMessage:"localSearch execution failed",execute:async()=>{let r=ee.safeParse(i);if(!r.success)throw r.error;try{await Be(r.data.path)}catch(t){throw v.fileAccessFailed(r.data.path,t instanceof Error?t:void 0)}return Z(await Qe(r.data))}}),{toolName:$},e)}async function Qe(e){switch(e.operation){case"text":{let{operation:i,resultView:r,...t}=e;return Y(K.parse(X(t,r)))}case"structural":{let{operation:i,resultView:r,...t}=e,n=K.safeParse({...X(t,r),mode:"structural",output:r});return n.success?Y(n.data):b(n.error.issues.map(o=>o.message).join("; "),e,{toolName:$,extra:{errorCode:"structural.query.invalid"}})}case"files":{let{operation:i,pathRegex:r,limit:t,sort:n,pageSize:o,...s}=e;return se({...s,regex:r,limit:t,sortBy:n,itemsPerPage:o})}case"tree":{let{operation:i,namePattern:r,limit:t,sort:n,pageSize:o,...s}=e;return fe({...s,pattern:r,limit:t,sortBy:n,itemsPerPage:o})}default:throw new Error("Unsupported localSearch operation")}}function Z(e){if(Array.isArray(e))return e.map(Z);if(!e||typeof e!="object")return e;let i=Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Z(n)])),r=typeof i.tool=="string"?Ve[i.tool]:void 0;if(i.tool==="local.text"&&i.query&&typeof i.query=="object"&&i.query.mode==="structural"&&(r="structural"),r&&(i.tool=$,i.query&&typeof i.query=="object")){let t={...i.query};delete t.goal,delete t.reasoning,r==="text"?(t.resultView=typeof t.output=="string"&&t.output!=="content"?t.output:typeof t.mode=="string"&&t.mode!=="structural"?t.mode:"paginated",delete t.mode,delete t.output):r==="structural"&&(t.resultView=typeof t.output=="string"?t.output:"content",delete t.mode,delete t.output,delete t.searchText,delete t.regex,delete t.caseMode,delete t.wholeWord,delete t.invertMatch,delete t.multiline,delete t.unique,delete t.matchWindow),r==="text"||r==="structural"?(t.pageSize=t.itemsPerPage,t.reverse=t.sortReverse,delete t.itemsPerPage,delete t.sortReverse):(t.pageSize=t.itemsPerPage,t.sort=t.sortBy,delete t.itemsPerPage,delete t.sortBy,r==="files"?(t.pathRegex=t.regex,delete t.regex):(t.namePattern=t.pattern,delete t.pattern)),i.query={operation:r,...t}}return i}export{Ct as executeLocalSearch};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as F,b as K}from"./chunk-EOLHXX5I.js";import{a as k,c as v,d as D,f as M,g as z,i as H,j as I,k as G,l as E,m as y,n as N,r as B,x as U}from"./chunk-RRSY2ZPX.js";import"./chunk-CBIKUVP6.js";import"./chunk-Y5OCKUQX.js";import{a as X,c as P}from"./chunk-ZO44CZN5.js";import"./chunk-CBCZVCTZ.js";import{a as J}from"./chunk-WH6GL3J2.js";import{c as W,f as T,h as j,j as V}from"./chunk-ZSXRT7JL.js";import{P as L,da as Q,ha as C}from"./chunk-BMM5H6QF.js";import{existsSync as ne,readdirSync as se,lstatSync as ce}from"node:fs";import{join as ae}from"node:path";function Y(o){if(!ne(o))return 0;let r;try{r=se(o)}catch{return 0}let n=0;for(let t of r){if(t===".git")continue;let e=ae(o,t);try{let i=ce(e);if(i.isSymbolicLink())continue;i.isDirectory()?n+=k(e):i.isFile()&&(n+=i.size)}catch{}}return n}import{existsSync as re,mkdirSync as _,renameSync as O,rmSync as pe}from"fs";import{basename as ue,dirname as me,join as b}from"path";var g=120*1e3,S=30*1e3,Z=[...X,"GIT_TERMINAL_PROMPT"];async function x(o){let r=(await p(["-C",o,"rev-parse","--verify","HEAD^{commit}"],5e3,"read checkout HEAD")).trim().toLowerCase();if(!/^[a-f0-9]{40}$/.test(r))throw new Error("Git returned an invalid checkout HEAD commit SHA.");return r}async function q(o,r,n,t,e){await p(["init","--",r],g,"initialize commit checkout",e);let i=[...R(t,e),"-C",r];await p([...i,"remote","add","origin",t],g,"configure commit remote",e),n&&(await p([...i,"config","remote.origin.promisor","true"],S,"configure sparse promisor",e),await p([...i,"config","remote.origin.partialclonefilter","blob:none"],S,"configure sparse filter",e)),await p([...i,"fetch","--depth","1",...n?["--filter","blob:none"]:[],"--","origin",o],g,"fetch requested commit",e),n&&await p([...i,"sparse-checkout","set","--cone","--skip-checks","--",n],S,"set sparse commit paths",e),await p([...i,"checkout","--detach","FETCH_HEAD","--"],g,"check out requested commit",e)}async function ee(o,r,n,t,e,i){let c=R(e,i);c.push("clone","--depth","1","--single-branch","--branch",n,"--",e,t),await p(c,g,`full clone of ${o}/${r}`,i)}async function te(o,r,n,t,e,i,c){let s=R(i,c);s.push("clone","--filter","blob:none","--sparse","--depth","1","--single-branch","--branch",n,"--",i,t),await p(s,g,`sparse clone of ${o}/${r}`,c);let a=[...R(i,c),"-C",t,"sparse-checkout","set","--skip-checks","--",e];await p(a,S,`sparse-checkout set ${e}`,c)}function R(o,r){return r?["-c",`http.${o}.extraHeader=Authorization: Bearer ${r}`]:[]}async function oe(){try{if(!(await P("git",["--version"],{timeout:5e3,maxOutputSize:1024,allowEnvVars:Z,env:{GIT_TERMINAL_PROMPT:"0"}})).success)throw new Error("git --version returned non-zero")}catch{throw new Error("git is not installed or not on PATH. The ghCloneRepo tool requires git to be available.")}}function le(o,r){let n=o;return r&&(n=n.replaceAll(r,"[REDACTED]")),n=n.replace(/Authorization:\s*Bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]"),n=n.replace(/Authorization:\s*token\s+\S+/gi,"Authorization: token [REDACTED]"),n}async function p(o,r,n,t){let e=await P("git",o,{timeout:r,maxOutputSize:5242880,allowEnvVars:Z,env:{GIT_TERMINAL_PROMPT:"0"}});if(!e.success){let i=le(e.stderr?.trim()||"",t),c=i?`: ${i}`:"";throw new Error(`git ${n} failed${c}`)}return e.stdout??""}var he=300*1e3,fe=100,de="clone-tmp";async function ie(o,r,n){let t=o.owner,e=o.repo,{sparsePath:i,forceRefresh:c}=o,s=ye(t,e);await oe();let a=o.branch??await U(t,e,r),h=/^[a-f0-9]{40}$/i.test(a)?a.toLowerCase():void 0,f=L(),u=D(f,t,e,a,i,s);return ge(f,u,async()=>{let d=I(u);if(!c&&d.hit&&d.meta.source==="clone"){let l;try{l=await x(u)}catch{}if(l&&(!h||l===h))return{localPath:u,cached:!0,commitSha:l,verified:!1,owner:t,repo:e,branch:a,...i?{sparsePath:i}:{}}}N(f),E(u);let w=Se(r,n),m=we(f,u);y(m);try{if(h?await q(h,m,i,s,w):i?await te(t,e,a,m,i,s,w):await ee(t,e,a,m,s,w),i&&!re(b(m,i)))throw new Error(`sparsePath "${i}" does not exist in ${t}/${e}@${a} \u2014 nothing was checked out for it. Verify the path with ghSearch operation:"tree", then retry with the correct sparsePath (or omit it for a full clone).`);let l=await x(m);if(h&&l!==h)throw new Error(`Checkout HEAD ${l} does not match requested commit ${a}.`);let $=G(t,e,a,"clone",i);return $.commitSha=l,H(m,$),Ce(m,u),{localPath:u,cached:!1,commitSha:l,verified:!0,owner:t,repo:e,branch:a,...i?{sparsePath:i}:{}}}catch(l){throw y(m),l}})}async function ge(o,r,n){E(r);let t=v(o,r);_(me(t),{recursive:!0,mode:448});let e=Date.now();for(;;)try{_(t,{mode:448}),M(t);break}catch(i){if(i.code!=="EEXIST")throw i;if(z(t))continue;if(Date.now()-e>he)throw new Error(`Timed out waiting for clone cache lock '${t}'.`,{cause:i});await Ee(fe)}try{return await n()}finally{pe(t,{recursive:!0,force:!0})}}function we(o,r){let n=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,t=b(o,"tmp",de);return _(t,{recursive:!0,mode:448}),b(t,`${ue(v(o,r))}-${n}`)}function Ce(o,r){E(r);let n=`${o}.previous`,t=re(r);t&&O(r,n);try{O(o,r)}catch(e){if(t)try{O(n,r)}catch(i){throw new AggregateError([e,i],`Clone publication failed; the previous checkout is preserved at ${n}.`,{cause:i})}throw e}t&&y(n)}function Ee(o){return new Promise(r=>setTimeout(r,o))}function ye(o,r){let n=B().githubApiUrl||"https://api.github.com",t;try{t=new URL(n)}catch{throw A()}if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash)throw A();let e=t.pathname.replace(/\/$/,"");if(t.origin==="https://api.github.com"&&!e)return`https://github.com/${o}/${r}.git`;if(!e.endsWith("/api/v3"))throw A();return`${t.origin}${e.slice(0,-7)}/${o}/${r}.git`}function A(){return new Error("ghCloneRepo requires an HTTPS GitHub API endpoint: https://api.github.com or a GitHub Enterprise endpoint ending in /api/v3, without credentials or query parameters. Use ghGetFileContent for other API proxies.")}function Se(o,r){return o?.token&&typeof o.token=="string"?o.token:r}import{getConfigSync as Re}from"@octocodeai/config";async function Je(o){let{queries:r,authInfo:n}=o,t=F(n);return W(r,async(e,i)=>J({toolName:C.GITHUB_CLONE_REPO,query:e,contextMessage:`Clone failed for ${e.owner}/${e.repo}`,execute:async()=>{if(Re().storage.mode==="memory")return T('Clone requires persistent local storage. Set storage.mode="persistent" or OCTOCODE_STORAGE_MODE=persistent to use ghCloneRepo.',e,{extra:{errorCode:"persistentStorageDisabled"}});let c=t();if(!K(c,"cloneRepo"))return V(new Error("ghCloneRepo is only available with the GitHub provider."),e,"Provider not supported",C.GITHUB_CLONE_REPO);let s;try{s=await ie(e,n,c.token)}catch(d){let w=d instanceof Error?d.message:String(d);return T(`Clone failed for ${e.owner}/${e.repo}: ${w}`,e)}s.cached&&Q();let a=Y(s.localPath),h={kind:e.sparsePath?"tree":"repo",localPath:s.localPath,source:"clone",cached:s.cached,commitSha:s.commitSha,verified:s.verified,complete:!0,resolvedBranch:s.branch,...e.sparsePath?{requestedPath:e.sparsePath}:{}},f={viewStructure:{tool:"localSearch",query:{operation:"tree",path:s.localPath},why:"Browse the cloned directory before choosing a text, structural, or file-discovery operation.",confidence:"exact"}},u={owner:e.owner,repo:e.repo,totalSize:a,location:h,next:f};return j(e,u,!0,C.GITHUB_CLONE_REPO,{rawResponse:a})}}),{toolName:C.GITHUB_CLONE_REPO,keysPriority:["totalSize","location","error"],minQueryTimeoutMs:13e4},o)}export{Je as executeCloneRepo};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as k,b as z,c as ne}from"./chunk-DBSQWRFS.js";import"./chunk-OA6NU4KO.js";import{a as ae,d as ie}from"./chunk-Y5OCKUQX.js";import{b as de}from"./chunk-QKDE2HIF.js";import"./chunk-J3WYA3IJ.js";import"./chunk-MPTAIBY7.js";import"./chunk-DKGYPFGX.js";import{a as fe}from"./chunk-C6HFNIDL.js";import{b as me}from"./chunk-NQRDACK3.js";import{a as $}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{a as pe}from"./chunk-WH6GL3J2.js";import{c as se,d as ce,e as le,g as ue}from"./chunk-ZSXRT7JL.js";import{X as E,ea as re,fa as oe,i as R}from"./chunk-BMM5H6QF.js";import{acquirePooledClientDetailed as Rn,isLanguageServerAvailable as kn}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as Ln}from"@octocodeai/octocode-engine/lsp/workspaceRoot";var dt=new Set(["noLocations","noReferences","noCalls","noTypeHierarchy","noHover"]);function ft(e){let t=e.payload;return t.kind==="empty"?t.category:t.empty?.category}function ye(e,t){if(t===void 0||t==="progressIdle")return e;let n=ft(e);if(!n||!dt.has(n))return e;let r=`Language server did not confirm indexing completion (readiness: ${t}) \u2014 zero results may mean the project is not yet indexed, not that the symbol is absent. Retry the query, or warm the relevant consumer files first.`;return{...e,incompleteResults:!0,partialReasons:[...new Set([...e.partialReasons??[],"readinessUnconfirmed"])],warnings:[...e.warnings??[],r]}}import{open as yt,stat as gt}from"node:fs/promises";import{SymbolResolver as ht,SymbolResolutionError as St}from"@octocodeai/octocode-engine/lsp/resolver";import{toUri as bt}from"@octocodeai/octocode-engine/lsp/uri";import{LSP_ERROR_CODES as I}from"@octocodeai/octocode-engine/lsp/lspErrorCodes";var H=1e6,Y="[lspSourceTooLarge] Semantic source exceeds 1000000 bytes; choose a smaller source file.";async function vt(e){let t=await yt(e,"r");try{let n=await t.stat();if(!n.isFile())throw new Error("Semantic source must be a regular file.");if(n.size>H)throw new Error(Y);let r=Buffer.alloc(H+1),o=0;for(;o<r.length;){let{bytesRead:a}=await t.read(r,o,r.length-o,null);if(a===0)break;o+=a}if(o>H)throw new Error(Y);return r.toString("utf8",0,o)}finally{await t.close()}}async function _(e,t){let n=e.uri,r=me({...e,path:n},t);if(!r.isValid)return{ok:!1,error:r.errorResult};let o=r.sanitizedPath;try{let a=await gt(o);if(!a.isFile())return{ok:!1,error:{status:"error",error:`Path is not a regular source file: ${o}.`,errorType:"not_a_file",errorCode:I.LSP_REQUEST_FAILED,hints:["Choose a source file, or use workspaceSymbol with symbolName."]}};if(a.size>H)return{ok:!1,error:{status:"error",error:Y,errorType:"source_limit",errorCode:I.LSP_REQUEST_FAILED}}}catch{return{ok:!1,error:{status:"error",error:`File not found: ${o}.`,errorType:"file_not_found",errorCode:I.LSP_REQUEST_FAILED,hints:['Use localSearch with operation:"files" to resolve the path.']}}}try{return{ok:!0,value:{uri:bt(o),absolutePath:o,content:await vt(o)}}}catch(a){return{ok:!1,error:{status:"error",error:a instanceof Error?a.message:String(a),errorType:a instanceof Error&&a.message.includes("[lspSourceTooLarge]")?"source_limit":"file_not_found",errorCode:I.LSP_REQUEST_FAILED,hints:[`Could not read file: ${n??"<missing>"}`]}}}}async function ge(e,t){let n=await _(e,t);if(n.ok===!1)return n;if(e.type==="documentSymbols")return{ok:!1,error:{status:"error",error:"documentSymbols is file-level and does not use a symbol anchor"}};let r=new ht;try{let o=r.resolvePositionFromContent(n.value.content,{symbolName:e.symbolName,lineHint:e.lineHint,orderHint:e.orderHint??0}),a=e.symbolName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i="[\\p{ID_Continue}$\\u200C\\u200D]",l=new RegExp(`(?<!${i})${a}(?!${i})`,"gu"),c=(n.value.content.match(l)??[]).length,s=e.lineHint!==void 0?Math.abs(o.foundAtLine-e.lineHint):void 0,u=c>1&&s!==void 0&&s>0?!0:void 0;return{ok:!0,value:{...n.value,resolvedSymbol:{name:e.symbolName,uri:n.value.uri,range:Ct(o.position),foundAtLine:o.foundAtLine,orderHint:e.orderHint,position:o.position,...u&&{isAmbiguous:u},...s!==void 0&&s>0?{lineDeviation:s}:{}}}}}catch(o){if(o instanceof St)return{ok:!1,error:{status:"empty",error:o.message,errorType:"symbol_not_found",errorCode:I.SYMBOL_NOT_FOUND,searchRadius:o.searchRadius,hints:[`Symbol "${e.symbolName}" was not found near line ${e.lineHint}.`,'Run localSearch with operation:"text" and the exact symbol name to refresh lineHint, then retry.']}};throw o}}function Ct(e){return{start:e,end:{line:e.line,character:e.character}}}import Z from"node:path";import{readFile as Wt}from"node:fs/promises";import{safeReadLineWindow as wt}from"@octocodeai/octocode-engine/lsp/validation";var Rt={maxNodes:100,maxRequests:50},he={truncatedByDepth:!1,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,cycleCount:0,failedRequestCount:0};function Se(e){return{...Rt,...e,visitedNodeCount:0,requestCount:0,truncatedByBudget:!1}}function be(e){return e.requestCount>=e.maxRequests?(e.truncatedByBudget=!0,!1):(e.requestCount+=1,!0)}function ve(e){return e.visitedNodeCount>=e.maxNodes?(e.truncatedByBudget=!0,!1):(e.visitedNodeCount+=1,!0)}function w(e,t){return{...e,truncatedByBudget:t.truncatedByBudget,visitedNodeCount:t.visitedNodeCount,requestCount:t.requestCount}}function O(e){return`${e.uri}:${e.range.start.line}:${e.name}`}async function Ce(e,t,n){if(t<=0)return e;let r=n?.[0]?.start.line??e.range.start.line,o=await wt(e.uri,r,t);if(!o)return e;let a=ae(o).length,i=Math.max(0,r-t),l=i+Math.max(0,a-1);return{...e,content:o,displayRange:{startLine:i+1,endLine:l+1}}}async function kt(e,t){return Promise.all(e.map(async n=>({...n,from:await Ce(n.from,t,n.fromRanges)})))}async function Lt(e,t){return Promise.all(e.map(async n=>({...n,to:await Ce(n.to,t)})))}async function V(e,t,n,r,o,a=Se(void 0)){if(n<=0||!e)return{calls:[],...he};if(!be(a))return w({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a);try{let i=await e.getIncomingCalls(t),l=o>0?await kt(i,o):i;if(n===1)return w({calls:l,truncatedByDepth:l.length>0,cycleCount:0,failedRequestCount:0},a);let c=[];for(let s of l){let u=O(s.from);if(r.has(u)){c.push(w({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},a));continue}if(!ve(a)||(r.add(u),c.push(await V(e,s.from,n-1,r,o,a)),a.truncatedByBudget))break}return w({calls:[...l,...c.flatMap(s=>s.calls)],truncatedByDepth:c.some(s=>s.truncatedByDepth),cycleCount:c.reduce((s,u)=>s+u.cycleCount,0),failedRequestCount:c.reduce((s,u)=>s+u.failedRequestCount,0)},a)}catch{return w({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},a)}}async function K(e,t,n,r,o,a=Se(void 0),i){if(n<=0||!e)return{calls:[],...he};if(!be(a))return w({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0},a);try{let l=await e.getOutgoingCalls(t),c=i?l.filter(m=>!i(m)):l,s=l.length-c.length,u=o>0?await Lt(c,o):c;if(n===1)return w({calls:u,truncatedByDepth:u.length>0,cycleCount:0,failedRequestCount:0,...s>0&&{excludedCallCount:s}},a);let p=[];for(let m of u){let f=O(m.to);if(r.has(f)){p.push(w({calls:[],truncatedByDepth:!1,cycleCount:1,failedRequestCount:0},a));continue}if(!ve(a)||(r.add(f),p.push(await K(e,m.to,n-1,r,o,a,i)),a.truncatedByBudget))break}let d=s+p.reduce((m,f)=>m+(f.excludedCallCount??0),0);return w({calls:[...u,...p.flatMap(m=>m.calls)],truncatedByDepth:p.some(m=>m.truncatedByDepth),cycleCount:p.reduce((m,f)=>m+f.cycleCount,0),failedRequestCount:p.reduce((m,f)=>m+f.failedRequestCount,0),...d>0&&{excludedCallCount:d}},a)}catch{return w({calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:1},a)}}var xt=8;function Re(e){return oe(e,re(e))}function ke(e){return G(e)&&e.payload.kind==="empty"&&["unsupportedOperation","symbolNotFound","anchorFailed"].includes(e.payload.category)?{...e,status:"empty",confidence:"low"}:e}function Le(e,t){return e.format!=="compact"||!G(t)?t:Pt(t)}function G(e){return S(e)&&typeof e.type=="string"&&typeof e.uri=="string"&&S(e.payload)}function Pt(e){return{...e,format:"compact",payload:Et(e.payload)}}function Et(e){switch(e.kind){case"definition":case"typeDefinition":case"implementation":return{...e,locations:e.locations.map(we)};case"references":return{...e,...e.byFile?{byFile:e.byFile.map(Tt)}:{locations:(e.locations??[]).map(we)}};case"callers":case"callees":case"callHierarchy":return{...e,...e.root?{root:xe(e.root)}:{},direction:e.direction,calls:e.calls.map(Dt),...e.incomingCalls!==void 0?{incomingCalls:e.incomingCalls}:{},...e.outgoingCalls!==void 0?{outgoingCalls:e.outgoingCalls}:{},completeness:e.completeness};case"documentSymbols":return{...e,symbols:e.symbols.map(At)};case"hover":case"empty":case"workspaceSymbol":case"typeHierarchy":case"diagnostic":return e}}function At(e){if(!S(e))return String(e);let t=g(e,"line"),n=g(e,"character"),r=g(e,"endLine"),o=L(e,"kind"),a=L(e,"name"),i=g(e,"childCount"),l=L(e,"containerName");return[`${t}:${n}${r!==t?`-${r}`:""}`,o,a,l?`< ${l}`:"",i>0?`children=${i}`:""].filter(Boolean).join(" ")}function we(e){if(typeof e=="string")return e;let t=e.displayRange?`${e.displayRange.startLine}-${e.displayRange.endLine}`:"?",n=e.isDefinition?" def":"",r=e.content?` | ${Ee(e.content,180)}`:"";return`${e.uri}:${t}${n}${r}`}function Tt(e){if(!S(e))return String(e);let t=L(e,"uri"),n=g(e,"firstLine"),r=g(e,"firstCharacter"),o=g(e,"count"),a=Pe(e,"lines").map(l=>typeof l=="number"?l:void 0).filter(l=>l!==void 0).join(","),i=e.hasDefinition===!0?" def":"";return`${t}:${n}:${r} count=${o} lines=${a}${i}`}function Dt(e){if(!S(e))return String(e);let t=L(e,"direction"),n=xe(e.item),r=Pe(e,"ranges").map(_t).join(","),o=g(e,"rangeCount"),a=g(e,"rangeSampleCount"),i=L(e,"contentPreview");return[t,n,r?`ranges=${r}`:"",o>a?`totalRanges=${o}`:"",i?`| ${Ee(i,180)}`:""].filter(Boolean).join(" ")}function xe(e){if(!S(e))return String(e);let t=L(e,"name"),n=L(e,"kind"),r=L(e,"uri"),o=g(e,"line"),a=g(e,"endLine"),i=g(e,"selectionLine"),l=i>0?` sel=${i}`:"";return`${t} ${n} ${r}:${o}-${a}${l}`}function _t(e){return S(e)?`${g(e,"line")}:${g(e,"character")}`:String(e)}function S(e){return typeof e=="object"&&e!==null}function L(e,t,n=""){let r=e[t];return typeof r=="string"?r:n}function g(e,t,n=0){let r=e[t];return typeof r=="number"?r:n}function Pe(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ee(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(0,t-3))}... (truncated for single-line display \u2014 use charOffset or startLine to read full content)`:n}function Ae(e,t){let n=De(e.fromRanges);return{direction:"incoming",item:Q(e.from),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,..._e(e.from,t)}}function Te(e,t){let n=De(e.fromRanges);return{direction:"outgoing",item:Q(e.to),ranges:n,rangeCount:e.fromRanges.length,rangeSampleCount:n.length,..._e(e.to,t)}}function Q(e){return{name:e.name,kind:B(e.kind),uri:e.uri,line:e.range.start.line+1,endLine:e.range.end.line+1,...e.selectionRange?{selectionLine:e.selectionRange.start.line+1}:{}}}function De(e){let t=new Set,n=[];for(let r of e){let o=r.start.line+1,a=r.start.character,i=`${o}:${a}`;if(!t.has(i)&&(t.add(i),n.push({line:o,character:a}),n.length>=xt))break}return n}function _e(e,t){return t<=0||!e.content?{}:{contentPreview:e.content}}function B(e){if(typeof e=="string")return e;switch(typeof e=="number"?e:void 0){case 1:return"file";case 2:return"module";case 3:return"namespace";case 4:return"package";case 5:return"class";case 6:return"method";case 7:return"property";case 8:return"field";case 9:return"constructor";case 10:return"enum";case 11:return"interface";case 12:return"function";case 13:return"variable";case 14:return"constant";case 15:return"string";case 16:return"number";case 17:return"boolean";case 18:return"array";case 19:return"object";case 20:return"key";case 21:return"null";case 22:return"enumMember";case 23:return"struct";case 24:return"event";case 25:return"operator";case 26:return"typeParameter";default:return"unknown"}}import{createHash as Ne}from"node:crypto";import Bt from"node:path";import{fileURLToPath as Nt}from"node:url";function J(e){return JSON.stringify(e,(t,n)=>!n||typeof n!="object"||Array.isArray(n)?n:Object.fromEntries(Object.entries(n).sort(([r],[o])=>r<o?-1:r>o?1:0)))}function Be(e){if(e)return Bt.resolve(e.startsWith("file:")?Nt(e):e)}function j(e){if(!e.rustContext)return;let t=e.rustContext,n={features:t.features==="all"?"all":[...new Set(t.features??[])].sort(),noDefaultFeatures:t.noDefaultFeatures??!1,target:t.target??null,cfgs:[...new Set(t.cfgs??[])].sort(),buildScripts:t.buildScripts??!1,procMacros:t.procMacros??!1};return{...n,fingerprint:`rust-v1:${Ne("sha256").update(J(n)).digest("hex")}`}}function Ft(e){let t=e;return{type:e.type,uri:Be(e.uri),workspaceRoot:Be(e.workspaceRoot)??process.cwd(),symbolName:t.symbolName,lineHint:t.lineHint,orderHint:t.orderHint??0,depth:t.depth??1,includeDeclaration:t.includeDeclaration??!0,groupByFile:t.groupByFile??!1,contextLines:e.contextLines??0,rustContext:j(e)}}function It(e){let t=e,n=t?.item??t?.from??t?.to??t;return[String(n?.uri??n?.path??""),Number(n?.range?.start?.line??n?.displayRange?.startLine??n?.firstLine??n?.line??0),Number(n?.range?.start?.character??n?.firstCharacter??n?.character??0),String(n?.name??"")]}function Fe(e,t,n=e){let r=e.map((a,i)=>({item:a,identity:J(n[i]),order:It(a)}));r.sort((a,i)=>{for(let l=0;l<a.order.length;l++){let c=a.order[l],s=i.order[l];if(c<s)return-1;if(c>s)return 1}return a.identity<i.identity?-1:a.identity>i.identity?1:0});let o=Ne("sha256").update(J([Ft(t),r.map(a=>a.identity)])).digest("hex");return{items:r.map(a=>a.item),snapshot:`lsp-v1:${o}`}}function Ie(e,t){if(!t.payload||typeof t.payload!="object"||"status"in t&&t.status==="error")return t;let n=t,r=n.pagination,o=(e.page??1)>1&&!e.snapshot&&!!r;if(!o&&(!e.snapshot||e.snapshot===r?.snapshot))return t;let{snapshot:a,...i}=e;return{type:n.type,uri:n.uri,lsp:n.lsp,...e.rustContext?{rustContext:j(e)}:{},...n.workspaceRoot?{workspaceRoot:n.workspaceRoot}:{},status:"empty",confidence:"low",payload:{kind:"empty",category:o?"paginationSnapshotRequired":"paginationChanged",reason:o?"Later pages require the snapshot from next.nextPage. Restart at page 1.":"The semantic result set or query changed. Discard earlier pages and restart at page 1; no rows from a different snapshot were returned."},snapshot:{...e.snapshot?{expected:e.snapshot}:{},...r?.snapshot?{actual:r.snapshot}:{}},next:{restartPagination:{tool:"lspGetSemantics",query:{...i,page:1},why:"Discard earlier pages and restart semantic pagination from the current result set.",confidence:"exact"}}}}var A=40,X=40,Oe=10;function Me(e,t){return/unsupported/i.test(t)?"unsupportedOperation":/could not find symbol|symbol.*not found/i.test(t)?"symbolNotFound":/call/i.test(t)?"noCalls":e==="references"?"noReferences":e==="hover"?"noHover":e==="documentSymbols"?"anchorFailed":"noLocations"}function $e(e,t){let n=e.uri??"";return{type:e.type,uri:n,lsp:{},payload:{kind:"empty",category:Me(e.type,t),reason:t}}}function b(e,t,n,r=!1){return{type:e,uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:r},payload:{kind:"empty",category:Me(e,n),reason:n}}}function v(e,t,n,r,o){let a=r?Fe(e,r,o):void 0;e=a?.items??e;let i=Math.max(1,n),l=Math.max(1,Math.ceil(e.length/i)),c=Math.min(Math.max(1,t),l),s=(c-1)*i,u=e.slice(s,s+i),p=c<l;return{pageItems:u,pagination:{currentPage:c,totalPages:l,totalResults:e.length,hasMore:p,pageSize:i,...a?{snapshot:a.snapshot}:{},...p&&c<1e3?{nextPage:c+1}:{}}}}function Ot(e){return/node_modules\/typescript\/lib\/lib\.[^/]*\.d\.ts$/.test(e.to.uri)}async function He(e,t,n,r){let a=(await n.prepareCallHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!a)return b(e.type,t,"No callable symbol found",!0);let i=e.depth??1,l={calls:[],truncatedByDepth:!1,cycleCount:0,failedRequestCount:0,truncatedByBudget:!1,visitedNodeCount:0,requestCount:0,excludedCallCount:0},c=e.type==="callers"||e.type==="callHierarchy"?await V(n,a,i,new Set([O(a)]),e.contextLines??0):l,s=e.type==="callees"||e.type==="callHierarchy"?await K(n,a,i,new Set([O(a)]),e.contextLines??0,void 0,Ot):l,u=s.excludedCallCount??0,p=[...c.calls.map(y=>({direction:"incoming",...y})),...s.calls.map(y=>({direction:"outgoing",...y}))],d=p.map(y=>y.direction==="incoming"?Ae(y,e.contextLines??0):Te(y,e.contextLines??0)),{pageItems:m,pagination:f}=v(d,e.page??1,e.pageSize??Oe,e,p),D=e.type==="callers"?"incoming":e.type==="callees"?"outgoing":"both",h=!c.truncatedByDepth&&!s.truncatedByDepth&&!c.truncatedByBudget&&!s.truncatedByBudget&&c.failedRequestCount+s.failedRequestCount===0;return{type:e.type,uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"callHierarchyProvider"},payload:{kind:e.type,root:Q(a),direction:D,calls:m,incomingCalls:c.calls.length,outgoingCalls:s.calls.length,...r?{warmup:r}:{},completeness:{complete:h&&!r?.possiblyTruncated,...r?.possiblyTruncated?{consumerWarmupIncomplete:!0}:{},truncatedByDepth:c.truncatedByDepth||s.truncatedByDepth,truncatedByBudget:c.truncatedByBudget||s.truncatedByBudget,visitedNodeCount:c.visitedNodeCount+s.visitedNodeCount,requestCount:c.requestCount+s.requestCount,cycleCount:c.cycleCount+s.cycleCount,failedRequestCount:c.failedRequestCount+s.failedRequestCount,dynamicCallsExcluded:!0,...u>0&&{stdlibCallsExcluded:u}},...p.length===0?{empty:{category:"noCalls",reason:u>0?"No project calls remain after excluding TypeScript standard-library targets.":"callHierarchyProvider returned no calls"}}:{}},pagination:f}}async function Ge(e,t,n){let o=(await n.prepareTypeHierarchy(t.absolutePath,t.resolvedSymbol.position,t.content))[0];if(!o)return b(e.type,t,"No type-hierarchy item found at position",!0);let a=e.type==="supertypes"?"supertypes":"subtypes",i=a==="supertypes"?await n.typeHierarchySupertypes(o):await n.typeHierarchySubtypes(o),{pageItems:l,pagination:c}=v(i,e.page??1,e.pageSize??A,e);return{type:e.type,uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"typeHierarchyProvider"},payload:i.length>0?{kind:"typeHierarchy",direction:a,root:o,items:l,totalItems:i.length}:{kind:"empty",category:"noTypeHierarchy",reason:`typeHierarchyProvider returned no ${a} for this symbol`},pagination:c}}import Qe from"node:path";import{fileURLToPath as jt,pathToFileURL as je}from"node:url";function U(e,t,n,r,o,a){let i=o.length>0,l=n==="implementation"&&a?{warmup:a}:{},c=o.map(z),{pageItems:s,pagination:u}=v(c,e.page??1,e.pageSize??X,e,o);return{type:e.type,uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:r},payload:i?{kind:n,locations:s,...l}:{kind:"empty",category:"noLocations",reason:`${r} returned no locations`,...l},...i?{pagination:u}:{}}}function We(e,t,n,r){let o=$t(n),a=e.groupByFile?Ht(o):void 0,i=new Map;if(a)for(let d of o){let m=i.get(d.uri)??[];m.push(d),i.set(d.uri,m)}let l=a??o.map(z),{pageItems:c,pagination:s}=v(l,e.page??1,e.pageSize??X,e,a?a.map(d=>i.get(d.uri)):o),u=o.length===0?{category:"noReferences",reason:"referencesProvider returned no references"}:void 0,p=r?.possiblyTruncated===!0?[`Reference warmup opened ${r.warmedFiles}/${r.candidates} candidate file(s) and was incomplete (${r.incompleteReasons?.join(", ")??"file cap"}); narrow workspaceRoot/path or confirm with localSearch operation:"text" before unused/safe-delete claims.`]:[];return{type:"references",uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"referencesProvider",source:"lsp"},payload:{kind:"references",...a?{byFile:c}:{locations:c},totalReferences:o.length,totalFiles:new Set(o.map(d=>d.uri)).size,...o.length>0&&o.every(d=>d.isDefinition)?{definitionOnly:!0}:{},...r?{warmup:r}:{},...u?{empty:u}:{}},pagination:s,...p.length>0?{warnings:p}:{}}}function Mt(e){return e.startsWith("file:")?je(jt(e)).href:Qe.isAbsolute(e)?je(Qe.normalize(e)).href:e}function $t(e){let t=new Map;for(let n of e){let{start:r,end:o}=n.range,a=Mt(n.uri),i=JSON.stringify([a,r.line,r.character,o.line,o.character]);t.has(i)||t.set(i,{...n,uri:a})}return[...t.values()].sort((n,r)=>(n.uri<r.uri?-1:n.uri>r.uri?1:0)||n.range.start.line-r.range.start.line||n.range.start.character-r.range.start.character||n.range.end.line-r.range.end.line||n.range.end.character-r.range.end.character)}async function Ue(e,t,n){let r=Gt(n),o=!!(r.markdown||r.text);return{type:"hover",uri:t.uri,resolvedSymbol:k(t.resolvedSymbol),lsp:{serverAvailable:!0,provider:"hoverProvider"},payload:o?{kind:"hover",...r}:{kind:"empty",category:"noHover",reason:"hoverProvider returned no hover content"}}}function Ht(e){let t=new Map;for(let n of e){let r=n.range.start.line+1,o=t.get(n.uri);if(o){o.count+=1,o.lines.push(r),n.isDefinition&&(o.hasDefinition=!0);continue}t.set(n.uri,{uri:n.uri,count:1,firstLine:r,firstCharacter:n.range.start.character,lines:[r],...n.isDefinition?{hasDefinition:!0}:{}})}return[...t.values()]}function Gt(e){if(!e||typeof e!="object")return{};let n=e.contents;if(typeof n=="string")return{text:n.trim()};if(Array.isArray(n))return{markdown:n.map(r=>Qt(r)).join(`
9
+ `).trim()};if(n&&typeof n=="object"){let r=n;if(typeof r.value=="string")return r.kind==="markdown"?{markdown:r.value.trim()}:{text:r.value.trim()}}return{}}function Qt(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){let t=e.value;if(typeof t=="string")return t}return String(e)}var Ye={references:"referencesProvider",callers:"callHierarchyProvider",callees:"callHierarchyProvider",callHierarchy:"callHierarchyProvider",implementation:"implementationProvider"},T=100,Ut=512*1024,ze=["ts","tsx","mts","cts","js","jsx","mjs","cjs"];async function Ve(e,t,n){let r={candidates:0,warmedFiles:0,skippedLarge:0,possiblyTruncated:!1},o=new Set,a=new Set;try{let i=Z.extname(t.absolutePath).slice(1),l=ze.includes(i)?ze:[i],c={path:n,searchText:t.resolvedSymbol.name,regex:"fixed",wholeWord:!0,output:"files",maxFiles:T,itemsPerPage:T,sort:"path",include:l.filter(Boolean).map(u=>`*.${u}`)},s=1;for(let u=0;u<T;u+=1){let p=await de({...c,page:s});if(p.status==="error"){o.add("search");break}let d=p.pagination,m=p.stats,f=p.files??[],D=d?.totalFiles??m?.filesMatched;typeof D=="number"&&(r.candidates=Math.max(r.candidates,D)),m?.capped&&o.add("search");for(let y of f){let x=typeof y.path=="string"?y.path:void 0;if(!x){o.add("fileRead");continue}let P=Z.resolve(n,x);if(!a.has(P)){if(a.size>=T){o.add("fileCap");break}if(a.add(P),r.candidates=Math.max(r.candidates,a.size),P!==Z.resolve(t.absolutePath))try{let M=await Wt(P,"utf-8");if(Buffer.byteLength(M,"utf8")>Ut){r.skippedLarge+=1,o.add("fileRead");continue}await e.openDocument(P,M),r.warmedFiles+=1}catch{o.add("fileRead")}}}if(!d?.hasMore){!d&&f.length>=T&&o.add("fileCap");break}if(a.size>=T){o.add("fileCap");break}let h=d.nextPage;if(typeof h!="number"||h<=s||u+1>=T){o.add("search");break}s=h}}catch{o.add("search")}return r.possiblyTruncated=o.size>0,o.size&&(r.incompleteReasons=[...o]),r}async function Ke(e,t,n,r){switch(e.type){case"definition":return n.hasCapability("definitionProvider")?U(e,t,"definition","definitionProvider",await n.gotoDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):b(e.type,t,"definitionProvider unsupported",!0);case"typeDefinition":return n.hasCapability("typeDefinitionProvider")?U(e,t,"typeDefinition","typeDefinitionProvider",await n.typeDefinition(t.absolutePath,t.resolvedSymbol.position,t.content)):b(e.type,t,"typeDefinitionProvider unsupported",!0);case"implementation":return n.hasCapability("implementationProvider")?U(e,t,"implementation","implementationProvider",await n.implementation(t.absolutePath,t.resolvedSymbol.position,t.content),r):b(e.type,t,"implementationProvider unsupported",!0);case"references":return n.hasCapability("referencesProvider")?We(e,t,await n.findReferences(t.absolutePath,t.resolvedSymbol.position,e.includeDeclaration??!0,t.content),r):b(e.type,t,"referencesProvider unsupported",!0);case"hover":return n.hasCapability("hoverProvider")?Ue(e,t,await n.hover(t.absolutePath,t.resolvedSymbol.position,t.content)):b(e.type,t,"hoverProvider unsupported",!0);case"callers":case"callees":case"callHierarchy":return n.hasCapability("callHierarchyProvider")?He(e,t,n,r):b(e.type,t,"callHierarchyProvider unsupported",!0);case"supertypes":case"subtypes":return n.hasCapability("typeHierarchyProvider")?Ge(e,t,n):b(e.type,t,"typeHierarchyProvider unsupported",!0)}}import{acquirePooledClientDetailed as tn,isLanguageServerAvailable as nn}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as rn}from"@octocodeai/octocode-engine/lsp/workspaceRoot";import ee from"node:path";import{fileURLToPath as zt}from"node:url";import{unavailableHintFor as Yt}from"@octocodeai/octocode-engine/lsp/manager";import{detectLanguageId as Vt}from"@octocodeai/octocode-engine/lsp/config";var q;function Je(e){return q||(q=new Set(E.getSupportedJsTsExtensions().map(t=>`.${t}`))),q.has(ee.extname(e).toLowerCase())}function C(e,t,n){let r=Vt(e),o=Yt(r,void 0),a=n?.message?` LSP startup detail (${n.kind??"startupFailed"}): ${n.message}.`:"";throw new le(ce.LSP_SERVER_UNAVAILABLE,`No ${r} language server is available for ${e}, so "${t}" cannot be answered semantically.${a} ${o} Meanwhile, use localSearch operation:"text" or "structural" to find occurrences, then localGetFileContent for surrounding code.`)}var Kt=["py","rs","go","java","kt","cs","c","cc","cpp","h","hpp","rb","php","swift","scala","dart","ex","exs","erl","hrl","clj","cljs"];function Jt(e,t){let n=e.startsWith("file://")?zt(e):e;return ee.isAbsolute(n)?n:ee.resolve(t,n)}function Xe(){return[...E.getSupportedJsTsExtensions(),...Kt]}function Xt(){return Xe().map(e=>`**/*.${e}`)}var Zt=[".git","node_modules","dist","out","coverage","target"];async function qt(e,t){let n=e.symbolName?.trim();if(n)try{return(await E.searchRipgrep({path:t,pattern:n,fixedString:!0,caseSensitive:!0,filesOnly:!0,include:Xt(),excludeDir:[...Zt],maxSnippetChars:1})).files[0]?.path}catch{return}}async function Ze(e,t){if(e.uri)return Jt(e.uri,t);let n=await qt(e,t);if(n)return n;try{let o=(await E.queryFileSystem({path:t,recursive:!0,includeRoot:!1,showHidden:!1,entryType:"f",extensions:Xe(),maxDepth:5,limit:1})).entries[0];if(o)return o.path}catch{}return t}function qe(e,t){if(!Je(e))return null;try{let n=E.extractJsSymbols(t,e);if(!n)return null;let r=JSON.parse(n);return Array.isArray(r)?r:null}catch{return null}}function en(e){if(!e||typeof e!="object")return!1;let t=e,n=r=>!!r&&typeof r=="object"&&typeof r.line=="number"&&typeof r.character=="number";return n(t.start)&&n(t.end)}function et(e,t){if(!Je(e))return null;try{let n=E.extractGraphFacts(t,e);if(!n)return null;let r=JSON.parse(n),a=(Array.isArray(r.declarations)?r.declarations:[]).filter(i=>typeof i.name=="string"&&fe(i.name)&&typeof i.kind=="string"&&en(i.range)).map(i=>({name:i.name,kind:i.kind,range:i.range}));return a.length>0?a:null}catch{return null}}async function rt(e){let t=await _(e,R);if(t.ok===!1)return t.error;let n=[],r,o=qe(t.value.uri,t.value.content),a=o?.length?null:et(t.value.uri,t.value.content);if(o?.length)n=o,r="native";else if(a?.length)n=a,r="native-graph-facts";else{let p=ie(t.value.content,t.value.uri);p&&(n=p,r="markdown")}if(!r){let p=e.workspaceRoot??await rn(t.value.absolutePath);await nn(t.value.absolutePath,p)||C(t.value.uri,"documentSymbols");let d=await tn(p,t.value.absolutePath,e.rustContext);if(d.ok===!1&&C(t.value.uri,"documentSymbols",d),!d.client.hasCapability("documentSymbolProvider"))return{type:"documentSymbols",uri:t.value.uri,lsp:{serverAvailable:!0,provider:"documentSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"documentSymbolProvider unsupported"}};let m=await d.client.documentSymbols(t.value.absolutePath,t.value.content);n=Array.isArray(m)?m:[],r="lsp"}let i=on(n),l=cn(n),{pageItems:c,pagination:s}=v(i,e.page??1,e.pageSize??A,e),u=ln(i,p=>p.kind);return{type:"documentSymbols",uri:t.value.uri,lsp:{...r==="lsp"?{serverAvailable:!0,provider:"documentSymbolProvider"}:{},...r?{source:r}:{}},summary:{totalSymbols:i.length,returnedSymbols:c.length,topLevelSymbols:l,kinds:u},payload:{kind:"documentSymbols",symbols:c},pagination:s}}function on(e){let t=[];for(let n of e)ot(n,t);return t.sort((n,r)=>n.line-r.line||n.character-r.character)}function ot(e,t,n){if(!e||typeof e!="object")return;let r=e,o=sn(r);if(typeof r.name=="string"&&o&&t.push({name:r.name,kind:B(r.kind),line:o.start.line+1,character:o.start.character,endLine:o.end.line+1,childCount:Array.isArray(r.children)?r.children.length:0,...n?{containerName:n}:{}}),Array.isArray(r.children)&&an.has(B(r.kind))){let a=typeof r.name=="string"?r.name:n;for(let i of r.children)ot(i,t,a)}}var an=new Set(["file","module","namespace","package","class","enum","interface","markdownHeading","struct"]);function sn(e){if(tt(e.range))return e.range;let t=e.location;return t&&tt(t.range)?t.range:void 0}function tt(e){if(!e||typeof e!="object")return!1;let t=e;return nt(t.start)&&nt(t.end)}function nt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.line=="number"&&typeof t.character=="number"}function cn(e){return e.filter(t=>t&&typeof t=="object"&&"name"in t).length}function ln(e,t){let n={};for(let r of e){let o=t(r),a=n[o];n[o]=typeof a=="number"?a+1:1}return n}import at from"node:path";import{readFile as un}from"node:fs/promises";import{acquirePooledClientDetailed as it,isLanguageServerAvailable as st}from"@octocodeai/octocode-engine/lsp/manager";import{resolveWorkspaceRootForFile as ct}from"@octocodeai/octocode-engine/lsp/workspaceRoot";async function lt(e){if(e.uri){let p=await _(e,R);if(p.ok===!1)return p.error;e={...e,uri:p.value.absolutePath}}let t=e.symbolName??"",n=at.resolve(e.workspaceRoot??(e.uri?await ct(e.uri):process.cwd())),r=await Ze(e,n);await st(r,n)||C(r,"workspaceSymbol");let a=await it(n,r,e.rustContext);a.ok===!1&&C(r,"workspaceSymbol",a);let i=a.client;if(!i.hasCapability("workspaceSymbolProvider"))return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"workspaceSymbolProvider unsupported"}};at.extname(r)&&await i.openDocument(r);let l=await i.workspaceSymbol(t),c=await mn(i,dn(l)),{pageItems:s,pagination:u}=v(c,e.page??1,e.pageSize??A,e);return{type:"workspaceSymbol",uri:r,lsp:{serverAvailable:!0,provider:"workspaceSymbolProvider"},summary:{query:t,totalSymbols:c.length},payload:c.length>0?{kind:"workspaceSymbol",query:t,symbols:s,totalSymbols:c.length}:{kind:"empty",category:"noWorkspaceSymbols",reason:`workspaceSymbolProvider returned no symbols for query "${t}"`},pagination:u}}var pn=10;async function mn(e,t){return t.length===0||t.length>pn?t:Promise.all(t.map(async n=>{try{if(!n.uri)return n;let r=n.uri.startsWith("file://")?decodeURIComponent(n.uri.slice(7)):n.uri,o=await un(r,"utf8");await e.openDocument(r);let a=await e.gotoDefinition(r,{line:n.line-1,character:n.character},o);if(!Array.isArray(a)||a.length!==1)return n;let i=a[0],l=(i.range?.start?.line??-1)+1;return!i.uri||l<1||i.uri===n.uri&&l===n.line?n:{...n,uri:i.uri,line:l,endLine:(i.range?.end?.line??i.range?.start?.line??l-1)+1,character:i.range?.start?.character??n.character}}catch{return n}}))}function dn(e){return e.flatMap(t=>{if(!t||typeof t!="object")return[];let n=t,r=typeof n.name=="string"?n.name:void 0;if(!r)return[];let o=n.kind,a=n.location,i=a?.range,l=typeof a?.uri=="string"?a.uri:"",c=(i?.start?.line??0)+1,s=(i?.end?.line??i?.start?.line??0)+1,u=typeof n.containerName=="string"?n.containerName:void 0;return[{name:r,kind:B(o),line:c,character:i?.start?.character??0,endLine:s,childCount:0,...u?{containerName:u}:{},uri:l}]})}async function ut(e){let t=await _(e,R);if(t.ok===!1)return t.error;let n=t.value.absolutePath,r=e.workspaceRoot??(n?await ct(n):process.cwd());await st(n,r)||C(n,"diagnostic");let a=await it(r,n,e.rustContext);a.ok===!1&&C(n,"diagnostic",a);let i=a.client;if(!i.hasCapability("diagnosticProvider"))return{type:"diagnostic",uri:n,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},payload:{kind:"empty",category:"unsupportedOperation",reason:"diagnosticProvider (pull) unsupported \u2014 server uses push (publishDiagnostics) instead"},warnings:['This server pushes diagnostics via textDocument/publishDiagnostics. Pull diagnostics (type: "diagnostic") require LSP 3.17 pull support. Check server docs to enable it.']};let l=await i.getDiagnostics(n),c=fn(l),s=c.filter(m=>m.severity===1).length,u=c.filter(m=>m.severity===2).length,{pageItems:p,pagination:d}=v(c,e.page??1,e.pageSize??A,e);return{type:"diagnostic",uri:n,lsp:{serverAvailable:!0,provider:"diagnosticProvider"},summary:{totalDiagnostics:c.length,errorCount:s,warningCount:u},payload:c.length>0?{kind:"diagnostic",diagnostics:p,totalDiagnostics:c.length,errorCount:s,warningCount:u}:{kind:"empty",category:"noDiagnostics",reason:"No diagnostics \u2014 file has no errors or warnings"},pagination:d}}function fn(e){if(e&&typeof e=="object"){let t=e;return(Array.isArray(t.items)?t.items:[]).flatMap(r=>yn(r))}return[]}function yn(e){if(!e||typeof e!="object")return[];let t=e,n=t.range,r=typeof t.message=="string"?t.message:"";return r?[{severity:typeof t.severity=="number"?t.severity:void 0,message:r,line:(n?.start?.line??0)+1,endLine:(n?.end?.line??n?.start?.line??0)+1,character:n?.start?.character??0,...t.code!==void 0?{code:t.code}:{},...typeof t.source=="string"?{source:t.source}:{}}]:[]}var gn=new Set(["unsupportedOperation","symbolNotFound","anchorFailed","noLocations","noReferences","noHover","noCalls","noWorkspaceSymbols","noTypeHierarchy","noDiagnostics"]),hn=new Set(["symbolNotFound","anchorFailed"]);function Sn(e){if(e.kind==="empty"&&typeof e.category=="string")return{category:e.category,...typeof e.reason=="string"?{reason:e.reason}:{}};let t=e.empty;if(S(t)&&typeof t.category=="string")return{category:t.category,...typeof t.reason=="string"?{reason:t.reason}:{}}}function bn(e){switch(e.slice(e.lastIndexOf(".")+1).toLowerCase()){case"rs":return"^\\s*pub\\s";case"py":case"pyi":return"^\\s*(def|class)\\s";case"go":return"^(func|type|var|const)\\s";case"java":case"kt":case"scala":case"cs":return"^\\s*(public|protected|internal)\\s";case"rb":return"^\\s*(def|class|module)\\s";default:return"^\\s*export\\s"}}function vn(e,t){let n=e.symbolName;if(typeof n=="string"&&n.trim())return n.trim();let r=t.resolvedSymbol?.name;if(typeof r=="string"&&r.trim())return r.trim()}function N(e){return e.startsWith("file://")?decodeURIComponent(e.slice(7)):e}function Cn(e,t){if(/^\s*import(?:\s|\{|\*)/.test(e))return!0;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^(?:type\\s+)?(?:${n}|[$\\w]+\\s+as\\s+${n})\\s*,?$`).test(e.trim())}function wn(e,t){if(!S(t.pagination))return;let{hasMore:n,nextPage:r}=t.pagination;if(!(n!==!0||typeof r!="number"||r>1e3))return $("lspGetSemantics",{...e,page:r,...typeof t.pagination.snapshot=="string"?{snapshot:t.pagination.snapshot}:{}},`Continue semantic ${e.type} results on page ${r}.`)}function pt(e,t){if(!G(t))return t;let n=t;if(S(n.pagination)&&n.pagination.hasMore===!0&&typeof n.pagination.currentPage=="number"&&n.pagination.currentPage>=1e3){let{nextPage:F,...mt}=n.pagination;n={...n,pagination:mt,terminalLimit:!0}}let r=n.payload,o=r.warmup?.possiblyTruncated===!0,a=r.completeness?.truncatedByDepth===!0,i=r.completeness?.truncatedByBudget===!0,l="depth"in e?e.depth??1:1,c=a&&l<20,s=vn(e,n),u=n.workspaceRoot??e.workspaceRoot??(n.uri?N(n.uri):void 0),p=[...o?[r.warmup?.incompleteReasons&&!r.warmup.incompleteReasons.includes("fileCap")?"warmupIncomplete":"warmupCap"]:[],...a?["depth"]:[],...i?["budget"]:[]];p.length>0&&(n={...n,truncated:!0,partialReasons:p,...(i||a&&!c)&&{terminalLimit:!0}});let d=wn(e,n),m=n.workspaceRoot??e.workspaceRoot,f=r.locations?.[0],D=e.type==="definition"&&s&&f?.uri&&typeof f.content=="string"&&N(f.uri)===N(n.uri)&&Cn(f.content,s),h={...n.next??{},...d?{nextPage:d}:{},...D?{verifyDefinition:{tool:"lspGetSemantics",query:{type:"workspaceSymbol",uri:n.uri,symbolName:s,...m&&{workspaceRoot:m},...e.format&&{format:e.format}},why:"Search workspace symbol candidates to verify this binding; a cold server may return the same import binding.",confidence:"medium"},...m&&{searchDefinitionCandidates:{tool:"localSearch",query:{operation:"text",path:m,searchText:s,regex:"fixed",wholeWord:!0,resultView:"content",maxFiles:100,pageSize:20,maxMatchesPerFile:20},why:"Find lexical declaration candidates when the language server only resolves the import binding.",confidence:"low"}}}:{},...c?{expandDepth:$("lspGetSemantics",{...e,snapshot:void 0,depth:Math.min(20,Math.max(l+1,l*2)),page:1},"Re-run with a larger call-hierarchy depth to inspect possible calls beyond the current depth.")}:{},...o&&s&&u?{verifyCompleteness:$("localSearch",{operation:"text",path:u,searchText:s,wholeWord:!0,resultView:"files"},"The LSP consumer warmup was incomplete; search the complete workspace lexically for additional consumer files.")}:{}},y=f?.displayRange?.startLine;if(f?.uri&&typeof y=="number"){let F=N(f.uri);return{...n,next:{...h,readSite:{tool:"localGetFileContent",query:{path:F,startLine:Math.max(1,y-3),endLine:(f.displayRange?.endLine??y)+10},why:"Read the top result location with surrounding context",confidence:"exact"}}}}let x=Sn(r);if(x?.category==="unsupportedOperation"&&n.type==="documentSymbols"&&n.uri){let F=N(n.uri);return{...n,next:{...h,textSearch:{tool:"localSearch",query:{operation:"text",path:F,searchText:bn(F),regex:"perl"},why:"documentSymbols is unsupported for this file's language server \u2014 fall back to a regex search over top-level declarations for an outline.",confidence:"low"}}}}if(!x||!s||!gn.has(x.category))return Object.keys(h).length>0?{...n,next:h}:n;let P=n.type==="workspaceSymbol"?n.workspaceRoot??e.workspaceRoot??n.uri??e.uri:n.uri??e.uri??n.workspaceRoot??e.workspaceRoot;if(!P)return n;let M=N(P),te={...h,textSearch:{tool:"localSearch",query:{operation:"text",path:M,searchText:s},why:`Semantic ${n.type} returned no result (${x.category}) \u2014 fall back to a text search for "${s}"`,confidence:"low"}};return hn.has(x.category)&&n.uri&&(te.reAnchor={tool:"lspGetSemantics",query:{type:"documentSymbols",uri:n.uri},why:"Re-anchor: list this file's symbols to find the correct lineHint, then retry the semantic query",confidence:"medium"}),{...n,next:te}}async function ao(e){return se(e.queries||[],async t=>{let n=ue(ne,t);if(n.ok===!1)return n.error;let r=n.data;return pe({toolName:R,query:r,contextMessage:"lspGetSemantics execution failed",execute:async()=>{let o=await xn(r),a=r.rustContext?{...o,rustContext:j(r)}:o;return Re(Le(r,pt(r,ke(Ie(r,a)))))}})},{toolName:R,minQueryTimeoutMs:3e4},e)}async function xn(e){if(e.type==="documentSymbols")return rt(e);if(e.type==="workspaceSymbol")return lt(e);if(e.type==="diagnostic")return ut(e);let t=await ge(e,R);if(t.ok===!1){if(t.error.status==="error")return t.error;let u=typeof t.error.error=="string"?t.error.error:"Symbol anchor resolution failed";return $e(e,u)}let n=e.workspaceRoot??await Ln(t.value.absolutePath);await kn(t.value.absolutePath,n)||C(t.value.uri,e.type);let o=await Rn(n,t.value.absolutePath,e.rustContext);o.ok===!1&&C(t.value.uri,e.type,o);let a=o.client,i=Ye[e.type],l=i&&a.hasCapability(i)?await Ve(a,t.value,n):void 0,c=a.getReadiness?.(),s=await Ke(e,t.value,a,l);return ye({...s,workspaceRoot:n},c)}export{ao as executeLspGetSemantics};
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as W}from"./chunk-DBI23PBG.js";import{a as rt}from"./chunk-UKQLRZEW.js";import"./chunk-OA6NU4KO.js";import{a as I,b as D,c as B,d as U,e as K,f as J,g as X}from"./chunk-CBIKUVP6.js";import{b as x,c as Y}from"./chunk-Y5OCKUQX.js";import{a as $}from"./chunk-J3WYA3IJ.js";import"./chunk-DKGYPFGX.js";import{a as O,b as at}from"./chunk-NQRDACK3.js";import{a as z,b as ot}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{a as it}from"./chunk-WH6GL3J2.js";import{a as q,b as tt,c as et,d as v,f as S,g as nt}from"./chunk-ZSXRT7JL.js";import{X as E,fa as y,ha as p,ia as Z,ka as Q}from"./chunk-BMM5H6QF.js";import{open as Tt,readFile as bt,stat as Et}from"fs/promises";function st(t,e){return n=>e}function A(t,e){let n=Math.abs(e-t);return n>=50&&n/t>=.02?{sourceChars:t,sourceBytes:e}:{sourceChars:t}}function G(t,e,n){return{...t,...A(e,n)}}function lt(t){let e=t.fullContent===!0,n=t.matchString!==void 0,o=t.startLine!==void 0||t.endLine!==void 0;if(t.minify==="symbols"&&(n||o))return{status:"error",error:'minify:"symbols" returns a whole-file signature skeleton and cannot be combined with matchString/startLine/endLine \u2014 remove the line/match constraints, or use minify:"standard" (or "none") to extract a specific range.'};if(e&&n)return{status:"error",error:"Cannot use fullContent with matchString \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR matchString to extract matching sections, OR startLine+endLine for a known line range."};if(e&&o)return{status:"error",error:"Cannot use fullContent with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: fullContent=true to read the entire file, OR startLine+endLine for a known line range, OR matchString to extract matching sections."};if(n&&o)return{status:"error",error:"Cannot use matchString with startLine/endLine \u2014 these are mutually exclusive extraction methods. Choose ONE: matchString to extract matching sections, OR startLine+endLine for a known line range, OR fullContent=true to read the entire file."};let r=t.startLine!==void 0,i=t.endLine!==void 0;return r&&!i?{status:"error",error:`startLine=${t.startLine} provided without endLine \u2014 both are required for line-range extraction.`}:i&&!r?{status:"error",error:`endLine=${t.endLine} provided without startLine \u2014 both are required for line-range extraction.`}:null}async function ct(t,e){try{return{fileStats:await Et(e)}}catch(n){let o=O.fileAccessFailed(t.path,n instanceof Error?n:void 0);return{errorResult:S(o,t,{toolName:p.LOCAL_FETCH_CONTENT,extra:{resolvedPath:e}})}}}function ut(t){let e=t.startLine!==void 0&&t.endLine!==void 0;return t.minify??(t.fullContent===!0||e?"none":"standard")}function dt(t,e,n){return n!=="none"?!1:e>$.LARGE_FILE_THRESHOLD_KB&&!t.matchString&&!t.startLine&&!t.charLength}function ft(t,e,n){let o=O.fileTooLarge(t.path,n,$.LARGE_FILE_THRESHOLD_KB);return S(o,t,{toolName:p.LOCAL_FETCH_CONTENT,extra:{resolvedPath:e}})}function ht(t,e){let n=O.binaryFileUnsupported(t.path);return S(n,t,{toolName:p.LOCAL_FETCH_CONTENT,extra:{resolvedPath:e}})}async function mt(t){let n=Buffer.alloc(8192),o;try{o=await Tt(t,"r");let{bytesRead:r}=await o.read(n,0,8192,0);if(r===0)return!1;let i=n.subarray(0,r);if(i.includes(0))return!0;try{new TextDecoder("utf-8",{fatal:!0}).decode(i,{stream:!0})}catch{return!0}let a=0,s=0,l=0;for(;l<i.length;){let h=i[l];if(h===27&&l+1<i.length&&i[l+1]===91){for(l+=2;l<i.length&&(i[l]<64||i[l]>126);)l+=1;l+=1;continue}a+=1;let f=h===9||h===10||h===13;h<32&&!f&&(s+=1),l+=1}return a>0&&s/a>.05}catch{return!1}finally{await o?.close().catch(st("binary sample handle close",void 0))}}async function gt(t,e){try{return{content:await bt(e,"utf-8")}}catch(n){let o=n instanceof Error?n:void 0,i=o?.code==="EISDIR"?O.fileAccessFailed(t.path,o):O.fileReadFailed(t.path,o);return{errorResult:S(i,t,{toolName:p.LOCAL_FETCH_CONTENT,extra:{resolvedPath:e}})}}}function pt(t,e){return{status:"empty",errorCode:v.NO_MATCHES,totalLines:e}}function Ot(t,e,n){let o=X(e,t.matchString,t.contextLines??5,t.matchStringIsRegex??!1,t.matchStringCaseSensitive??!1);if(o.lines.length===0)return{isPartial:!1,earlyResult:pt(t,n)};let r=o.lines.join(`
9
+ `),i=t.contextLines??5,a=o.matchingLines.slice(0,10).join(", "),s=o.matchingLines.length>10?` (+${o.matchingLines.length-10} more)`:"",l=`Found ${o.matchCount} occurrence${o.matchCount===1?"":"s"} of "${t.matchString}" on line${o.matchingLines.length===1?"":"s"} ${a}${s} \u2014 all shown as ${o.matchRanges.length} slice${o.matchRanges.length===1?"":"s"}, \xB1${i} lines of context each; these lines are lineHint anchors for lspGetSemantics.`,h,f,c;if(o.matchRanges.length>0){let d=o.matchRanges[0],u=o.matchRanges[o.matchRanges.length-1];d&&u&&(h=d.start,f=u.end,c=o.matchRanges)}return{resultContent:r,isPartial:!1,actualStartLine:h,actualEndLine:f,matchRanges:c,matchedLines:o.matchingLines,warnings:[l]}}function Pt(t){return t.startLine!==void 0&&t.endLine!==void 0}function kt(t,e,n){let o=String(n).length;return t.slice(e-1,n).map((r,i)=>`${String(e+i).padStart(o," ")}\u2192 ${r}`).join(`
10
+ `)}function vt(t,e,n){let o=t.startLine,r=t.endLine,i=Math.max(1,o),a=Math.min(r,n);if(r<o)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:v.NO_MATCHES,warnings:[`startLine ${o} is greater than endLine ${r} \u2014 startLine must be \u2264 endLine`,`Use startLine=1 to ${n} with startLine \u2264 endLine for a valid range`]}};if(i>n)return{isPartial:!1,earlyResult:{status:"empty",totalLines:n,errorCode:v.NO_MATCHES,warnings:[`Requested startLine ${o} exceeds file length (${n} lines)`,`Use startLine=1 to ${n} for valid range`]}};let s=[];return r>n&&s.push(`Requested endLine ${r} adjusted to ${n} (file end)`),{resultContent:kt(e,i,a),isPartial:a<n,actualStartLine:i,actualEndLine:a,warnings:s}}function Ct(t,e,n){let o=e.split(`
11
+ `),r=x(e);return t.matchString?Ot(t,o,r):Pt(t)?vt(t,o,r):{resultContent:e,isPartial:!1}}import{ContentSanitizer as Gt}from"@octocodeai/octocode-engine/contentSanitizer";function N(t,e){let n=Gt.sanitizeContent(t,e);return{text:n.content,limited:n.secretsDetected.includes("content-size-exceeded"),warning:n.hasSecrets?`Secrets detected and redacted: ${n.secretsDetected.join(", ")}`:void 0}}function M(t,e,n=t.startLine??1){let o=e>1&&(t.startLine===void 0||t.startLine!==t.endLine);return{path:t.path,status:"error",errorCode:"contentSecurityLimit",error:"The selected content view exceeds the secret scanner size limit. Character windows cannot safely split unscanned content. Select a smaller source-line range.",totalLines:e,isPartial:!0,terminalLimit:!0,partialReasons:["security-selected-view-size-limit"],...o&&{next:{readBoundedLines:z("localGetFileContent",{path:t.path,startLine:n,endLine:n,minify:"none"},"The selected view is too large to scan safely. Read one source line; this starts a different source-line view, not a continuation of the rejected character view.")}}}}async function Lt(t,e,n){let o=String(e.path),r=e.charLength,i=e.charOffset??0,a=r,s=!1,l,h=i;a===void 0&&!e.fullContent&&t.length>n&&(a=n,s=!0,l=`Auto-paginated: Content (${t.length} chars) exceeds ${n} char limit`);let f="char-limit",c=a;if(a!==void 0){let F=await J(t,h,a,o);f=F.chunkMode,c=F.length}let d=D(t,h,c,a!==void 0?{pageSize:a}:void 0);d.pageCountsKind="estimated";let u;if(d.hasMore&&f==="char-limit"&&U(d.paginatedContent)){let F=d.charOffset+d.charLength;u=await K(t,F,o)}let{goal:C,reasoning:m,charOffset:_,...P}=e,w=ot("localGetFileContent",{...P,path:o,charLength:a??d.charLength},d);return{windowedContent:d.paginatedContent,pagination:d,effectiveCharLength:a,explicitCharOffset:i,autoPaginated:s,autoPaginateWarning:l,chunkMode:f,nextBlockChar:u,next:w,showPagination:a!==void 0||i>0||s}}async function Rt(t,e,n,o,r,i=!0,a=i?"standard":"none"){if(!e.resultContent||e.resultContent.trim().length===0)return{status:"empty",totalLines:o};let s=[...e.warnings??[]],l=String(t.path),h=i?E.applyContentViewMinification(e.resultContent,l):e.resultContent,f=N(h,l);if(f.limited)return M(t,o,e.actualStartLine);f.warning&&s.push(f.warning);let c=await Lt(f.text,t,r);c.autoPaginateWarning&&s.push(c.autoPaginateWarning);let d=e.isPartial||c.pagination.hasMore,u=e.actualStartLine!==void 0&&e.actualEndLine!==void 0?e.actualEndLine-e.actualStartLine+1:void 0,C=e.isPartial&&!c.pagination.hasMore&&e.actualEndLine!==void 0&&u!==void 0?z("localGetFileContent",{path:l,startLine:e.actualEndLine+1,endLine:Math.min(o,e.actualEndLine+u),...t.minify!==void 0?{minify:t.minify}:{}},"Continue with the next source-line window."):void 0,m={...c.next??{},...C?{continueLines:C}:{}};return{path:l,content:c.windowedContent,contentView:a,returnedChars:c.windowedContent.length,...d&&{isPartial:d},totalLines:o,...e.actualStartLine!==void 0&&e.actualEndLine!==void 0&&{startLine:e.actualStartLine,endLine:e.actualEndLine,...e.matchRanges!==void 0&&{matchRanges:e.matchRanges},...e.matchedLines!==void 0&&{matchedLines:e.matchedLines}},...n.mtime&&{modified:n.mtime.toISOString()},...c.showPagination&&{pagination:{...B(c.pagination),chunkMode:c.chunkMode,...c.nextBlockChar!==void 0&&{nextBlockChar:c.nextBlockChar}}},...Object.keys(m).length>0?{next:m}:{},...s.length>0&&{warnings:s}}}async function H(t,e,n,o,r,i,a){let s=await Lt(e,t,a),l=[...s.autoPaginateWarning?[s.autoPaginateWarning]:[],...i?[i]:[]];return{path:t.path,content:s.windowedContent,contentView:"symbols",returnedChars:s.windowedContent.length,...s.pagination.hasMore&&{isPartial:!0},totalLines:n,...A(o,r),...s.showPagination&&{pagination:{...B(s.pagination),chunkMode:s.chunkMode,...s.nextBlockChar!==void 0&&{nextBlockChar:s.nextBlockChar}}},...s.next?{next:s.next}:{},...l.length>0&&{warnings:l}}}function Ft(t,e){return typeof t.content!="string"?t:{...t,contentView:e}}async function wt(t){let e=I();try{let n=at(t,p.LOCAL_FETCH_CONTENT);if(!n.isValid)return n.errorResult;let o=lt(t);if(o)return o;let r=n.sanitizedPath,i=String(t.path),{fileStats:a,errorResult:s}=await ct(t,r);if(s||!a)return s;let l=typeof a.size=="bigint"?Number(a.size):a.size,h=l/1024;if(await mt(r))return y(ht(t,r),l);let f=ut(t);if(dt(t,h,f))return y(ft(t,r,h),l);let{content:c,errorResult:d}=await gt(t,r);if(d||c===void 0)return d;let u=c.length,C=Buffer.byteLength(c,"utf-8"),m=c,_=t.matchString!==void 0&&f!=="none",P=_?"none":f,w=_&&t.minify!==void 0?`minify:"${t.minify}" is not applied to matchString extractions \u2014 matched slices are returned verbatim so the content always contains the matched text.`:void 0,F=P==="standard"||P==="symbols",V=F?"standard":"none",T;if(P==="symbols"){let g=E.extractSignatures(m,i);if(g===null){let L=Y(m,i);if(L!==null){let R=N(L,i);return R.limited?G(M(t,x(m)),u,C):y(await H(t,R.text,x(m),u,C,R.warning,e),u)}T=`No smaller outline is available for ${i}; using the standard content view. The outline may be unsupported, oversized, or unavailable for this source.`}if(g!==null){let L=x(m),R=E.applyContentViewMinification(g,i),b=N(R,i);return b.limited?G(M(t,L),u,C):y(await H(t,b.text,L,u,C,b.warning,e),u)}}let yt=x(m),k=Ct(t,m,e),xt=g=>{let L=g.content;if(typeof L!="string")return g;let R=N(L,i),b=[...T?[T]:[],...w?[w]:[],...R.warning?[R.warning]:[]],St=g.warnings??[];return{...g,content:R.text,returnedChars:R.text.length,...b.length>0&&{warnings:[...St,...b]}}};if(k.earlyResult){let g=k.earlyResult.content,L=F&&typeof g=="string"?{...k.earlyResult,content:E.applyContentViewMinification(g,i)}:k.earlyResult;return y(G(xt(Ft(L,V)),u,C),u)}let j=await Rt(t,k,a,yt,e,F,V);return y(G({...j,...(T||w)&&{warnings:[...j.warnings??[],...T?[T]:[],...w?[w]:[]]}},u,C),u)}catch(n){return S(n,t,{toolName:p.LOCAL_FETCH_CONTENT})}}async function xe(t){let{queries:e}=t;return et(e||[],async n=>it({toolName:p.LOCAL_FETCH_CONTENT,query:n,contextMessage:"localGetFileContent execution failed",execute:async()=>{let o=nt(W,n);return o.ok===!1?o.error:await wt(o.data)}}),{toolName:p.LOCAL_FETCH_CONTENT,finalize:Nt()},t)}function Nt(){return({results:t})=>{let e={results:Mt(t)},n=q(e.results);n&&(e.base=n);let o=tt(e.results);return o&&(e.shared=o),{structuredContent:Z(e),renderText:r=>_t(r),isError:e.results.length>0&&e.results.every(r=>r.status==="error")}}}function Mt(t){return t.map(e=>{let n=structuredClone(e.data),o=typeof n.path=="string"?n.path:void 0;if(e.status!=="error"&&o){let r=rt(o);r&&(n.fileType=r)}return{...e,data:n}})}function _t(t){let e=[];t.base&&e.push(`base: ${t.base}`,"");for(let n of t.results){let o=n.data,r=typeof o.content=="string"?o.content:void 0,i={...o};delete i.content,e.push(`result: ${n.index}${n.status?` (${n.status})`:""}`);let a=Q({data:i},["data","path","resolvedPath","contentView","startLine","endLine","totalLines","isPartial","pagination","sourceChars","sourceBytes","returnedChars","fileType","warnings","error"]).trimEnd();a&&e.push(a),r!==void 0&&e.push("content (copy-safe):",r),e.push("")}return t.shared&&e.push(Q({shared:t.shared},["shared"]).trimEnd()),e.join(`
12
+ `).trimEnd()+`
13
+ `}export{xe as executeFetchContent};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as nt}from"./chunk-C6HFNIDL.js";import{a as Xe}from"./chunk-IFPXDKUV.js";import{b as tt}from"./chunk-NQRDACK3.js";import{a as X}from"./chunk-CKB2ME2J.js";import"./chunk-USZL65FN.js";import{a as et}from"./chunk-WH6GL3J2.js";import{c as Ve,f as Ye,g as Ze}from"./chunk-ZSXRT7JL.js";import{X as qe,ha as se,i as He}from"./chunk-BMM5H6QF.js";import{isAbsolute as $n}from"node:path";import{posix as It}from"node:path";import{posix as cn}from"node:path";import{posix as T}from"node:path";var L=()=>({target:null,status:"unsupported"}),st=()=>({target:null,status:"unresolvedInternal"}),K=(e,t)=>JSON.stringify([e,t]),V=(e,t)=>JSON.stringify([e,t]);function rt(e,t,r,n=new Map,c=new Map){let o=new Map,s=new Map,a=new Map;for(let[p,u]of e)for(let i of u.imports??[]){if(i.importKind==="module")continue;let h=V(p,i.moduleScope??[]),x=a.get(h)??[];x.push(i),a.set(h,x)}let l=[],d=Math.max(64,t.size*8),f=!1,g=p=>{let u=K(p.root,p.path);if(!e.has(p.file)||e.get(p.file)?.rustRootUnsupported){o.set(u,null);return}if(o.has(u)){o.set(u,null);return}if(p.depth>64||l.length>=d){o.set(u,null),f=!0;return}o.set(u,p);let i=V(p.file,p.scope),h=s.get(i)??[];h.push(p),s.set(i,h),l.push(p)};for(let p of new Set(r))t.has(p)&&g({root:p,path:[],file:p,scope:[],directory:T.dirname(p),attributeDirectory:T.dirname(p),depth:0});for(let p=0;p<l.length;p++){let u=l[p];if(o.get(K(u.root,u.path))===u)for(let i of e.get(u.file)?.modules??[]){if(V(u.file,i.scope)!==V(u.file,u.scope))continue;let h=[...u.path,i.name],x=K(u.root,h);if(i.unsupported||i.path!==void 0&&T.isAbsolute(i.path)||i.path?.includes("\\")||i.path?.includes("\0")){o.set(x,null);continue}if(i.inline){let C=i.path===void 0?T.join(u.directory,i.name):T.normalize(T.join(u.attributeDirectory,i.path));g({...u,path:h,scope:[...u.scope,i.name],directory:C,attributeDirectory:C,depth:u.depth+1});continue}let w=(i.path===void 0?[T.join(u.directory,`${i.name}.rs`),T.join(u.directory,i.name,"mod.rs")]:[T.normalize(T.join(u.attributeDirectory,i.path))]).filter(C=>t.has(C)&&!T.isAbsolute(C)&&C!==".."&&!C.startsWith("../"));if(w.length!==1){o.set(x,null);continue}let k=w[0],R=T.dirname(k),v=i.path!==void 0||T.basename(k)==="mod.rs"?R:T.join(R,i.name);g({root:u.root,path:h,file:k,scope:[],directory:v,attributeDirectory:R,depth:u.depth+1})}}return(p,u,i=[],h=!1,x)=>{let y=(F,I,S)=>(a.get(V(F,I))??[]).some(M=>!(F===u&&M.line===x&&M.specifier===p)&&(M.localName===S||M.importedName==="*")),w=p.split("::");if(w.some(F=>!/^(?:[\p{L}_][\p{L}\p{N}_]*|\*)$/u.test(F)))return L();let k=w[0],R=["std","core","alloc"].includes(k),v=s.get(V(u,i));if(!v?.length)return R&&!y(u,i,k)&&!e.get(u)?.modules?.some(F=>F.name===k)?{target:null,status:"external"}:L();let C=v.map(F=>{if(o.get(K(F.root,F.path))!==F)return L();let I=F.root,S=[...F.path],M=[...w];if(k==="crate")S=[],M.shift();else if(k==="self")M.shift();else if(k==="super")for(;M[0]==="super";){if(!S.length)return st();S.pop(),M.shift()}else{let A=c.get(I),$=["2018","2021","2024"].includes(A??"");if(S.length>0&&!$&&A!=="2015"&&(o.has(K(I,[...S,k]))||o.has(K(I,[k]))))return L();if(A==="2015"&&(S=[]),!o.has(K(I,[...S,k]))){let W=o.get(K(I,S));if(W&&y(W.file,W.scope,k))return L();let D=n.get(I)?.get(k);if(!D)return R?{target:null,status:"external"}:L();if(A==="2015")return L();if(D.external)return{target:null,status:"external"};if(!D.root)return L();I=D.root,S=[],M.shift()}}let P=o.get(K(I,S));if(!P)return L();for(let A=0;A<M.length;A++){let $=M[A];if($==="*"&&A===M.length-1)break;let W=K(I,[...S,$]);if(!o.has(W)){if(A<M.length-1&&y(P.file,P.scope,$))return L();if(A===M.length-1&&!h)break;return f?L():st()}let D=o.get(W);if(!D)return L();P=D,S.push($)}return{target:P.file,status:"resolved"}}),N=C[0];return C.every(F=>F.target===N.target&&F.status===N.status)?N:L()}}import{realpath as oe}from"node:fs/promises";import{dirname as Ae,isAbsolute as Pe,relative as gt,resolve as Y,sep as ft}from"node:path";import{z as G}from"zod";import{execFile as Vt}from"node:child_process";import{access as ot,realpath as le,stat as Fe}from"node:fs/promises";import{constants as it}from"node:fs";import{homedir as Yt}from"node:os";import{basename as at,delimiter as ct,dirname as lt,isAbsolute as Me,join as Ee,relative as Zt,resolve as en,sep as tn}from"node:path";var pt=5e3,pe=1048576,nn=64,O=class extends Error{constructor(r,n){super(n);this.code=r}code};function J(e,t){let r=Zt(e,t);return r===""||!r.startsWith(`..${tn}`)&&r!==".."&&!Me(r)}function U(e){let t=e-Date.now();if(t<=0)throw new O("cargo-metadata-limit","Cargo metadata exceeded its five-second execution budget.");return t}function Ge(e,t,r,n,c){return new Promise((o,s)=>{Vt(e,t,{cwd:r,env:n,encoding:"utf8",shell:!1,timeout:U(c),maxBuffer:pe},(a,l)=>{if(a){let d=a.killed||a.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER";s(new O(d?"cargo-metadata-limit":a.code==="ENOENT"?"cargo-unavailable":"cargo-metadata-failed",d?"Cargo metadata exceeded its time or output budget.":"The host Cargo command could not provide offline, locked workspace metadata."))}else Buffer.byteLength(l,"utf8")>pe?s(new O("cargo-metadata-limit","Cargo metadata exceeded its output budget.")):o(l)})})}async function dt(e,t){let r=[];for(let s of(process.env.PATH??"").split(ct))if(Me(s)){try{let a=await le(s);J(e,a)||r.push(a)}catch{}U(t)}let n=Yt(),c={PATH:[...new Set(r)].join(ct),HOME:n,USERPROFILE:n,RUSTUP_AUTO_INSTALL:"0",CARGO_NET_OFFLINE:"true"};for(let s of["SystemRoot","SYSTEMROOT","WINDIR","TEMP","TMP","LANG","LC_ALL"])process.env[s]&&(c[s]=process.env[s]);let o=process.platform==="win32"?"cargo.exe":"cargo";for(let s of r){let a=Ee(s,o);try{await ot(a,it.X_OK);let l=await le(a);if(J(e,l))continue;let d=Ee(s,process.platform==="win32"?"rustup.exe":"rustup"),f=/^rustup(?:\.exe)?$/i.test(at(l));if(!f)try{let[i,h]=await Promise.all([Fe(a),Fe(d)]);f=i.dev===h.dev&&i.ino===h.ino}catch{}if(!f)return{executable:a,env:c};let g=/^rustup(?:\.exe)?$/i.test(at(l))?l:d,p=(await Ge(g,["which","cargo"],n,c,t)).trim();if(!Me(p))throw new O("cargo-unavailable","Rustup did not identify an absolute host Cargo executable.");let u=await le(p);if(J(e,u))throw new O("cargo-unavailable","The selected Cargo executable is inside the scanned repository.");return await ot(u,it.X_OK),{executable:u,env:c}}catch(l){if(l instanceof O)throw l}U(t)}throw new O("cargo-unavailable","No trusted host Cargo executable is available on the absolute PATH.")}async function ut(e,t,r){let n=new Map;async function c(a){if(U(r),n.has(a))return n.get(a)??null;if(n.size>=nn)throw new O("cargo-metadata-limit","Cargo manifest discovery exceeded 64 ancestor-directory probes.");n.set(a,null);let l=Ee(a,"Cargo.toml");try{let d=await le(l);if(!J(e,d))throw new O("cargo-manifest-outside-root","A Cargo manifest symlink leaves the scanned root.");return(await Fe(d)).isFile()?(n.set(a,d),d):null}catch(d){if(d instanceof O)throw d;return null}}let o=await c(e);if(o)return[o];let s=new Set;for(let a of[...t].sort()){if(!a.endsWith(".rs"))continue;let l=lt(en(e,a));for(;J(e,l);){let d=await c(l);if(d){s.add(d);break}if(l===e)break;l=lt(l)}}if(!s.size)throw new O("cargo-manifest-missing","No Cargo.toml was found at the scan root or known Rust-file ancestors.");return[...s]}var re=new Set(["lib","rlib","dylib","cdylib","staticlib","proc-macro"]),sn=G.object({name:G.string(),rename:G.string().nullable().optional(),path:G.string().optional(),optional:G.boolean().default(!1),kind:G.string().nullable().optional(),target:G.string().nullable().optional()}),rn=G.object({id:G.string(),name:G.string(),manifest_path:G.string(),targets:G.array(G.object({name:G.string(),kind:G.array(G.string()).min(1),src_path:G.string(),edition:G.string().optional()})).min(1),dependencies:G.array(sn)}),on=G.object({version:G.literal(1),workspace_members:G.array(G.string()).min(1),packages:G.array(rn).min(1)});async function an(e,t,r,n,c){let o=[],s=new Map;for(let a of r){if(U(c),!Pe(a.manifest_path))throw new O("cargo-metadata-invalid","Cargo package manifests must use absolute paths.");let l=await oe(Ae(a.manifest_path)).catch(()=>Y(Ae(a.manifest_path)));s.set(l,[...s.get(l)??[],a]);for(let d of a.targets){U(c);let f=Pe(d.src_path)?Y(d.src_path):"",g=f?await oe(f).catch(()=>""):"",p=g?gt(e,g).split(ft).join("/"):"";if(!f||!g||!J(e,g)||!t.has(p)){n.push({code:"cargo-target-outside-scan",message:`Cargo target ${a.name}/${d.name} is outside the scanned file set; its crate context is unsupported.`});continue}o.push({id:JSON.stringify([a.id,d.name,d.kind,f]),packageId:a.id,packageName:a.name,crateName:d.name.replaceAll("-","_"),kind:d.kind,...d.edition!==void 0?{edition:d.edition}:{},srcPath:p,dependencyAliases:[]})}}for(let a of o){let l=r.find(f=>f.id===a.packageId),d=a.kind.includes("custom-build");for(let f of l.dependencies){if(U(c),d!==(f.kind==="build"))continue;let g=f.optional||!!f.target||f.kind==="dev",p=f.path&&Pe(f.path)?await oe(f.path).catch(()=>Y(f.path)):void 0,u=p?s.get(p)??[]:[],i=p!==void 0&&J(e,p),h=u.length===1?u[0].targets.filter(k=>k.kind.some(R=>re.has(R))):[],x=(f.rename??(h.length===1?h[0].name:f.name)).replaceAll("-","_"),y=u.length===1?o.filter(k=>k.packageId===u[0].id&&k.kind.some(R=>re.has(R))):[],w=!g&&y.length===1?y[0]:void 0;a.dependencyAliases.push({alias:x,packageName:f.name,...w?{targetId:w.id}:{},external:u.length===0&&!i,conditional:g}),g?n.push({code:"cargo-conditional-dependency",message:`Dependency ${x} of ${l.name} is conditional; metadata without dependency resolution does not establish an active import.`}):(u.length||i)&&!w&&n.push({code:"cargo-workspace-dependency-unresolved",message:`Local dependency ${x} of ${l.name} has no unique workspace library target in this scan.`})}if(!d&&!a.kind.some(f=>re.has(f))){let f=o.filter(g=>g.packageId===l.id&&g.kind.some(p=>re.has(p)));for(let g of l.targets.filter(p=>p.kind.some(u=>re.has(u)))){let p=f.length===1?f[0]:void 0;a.dependencyAliases.push({alias:g.name.replaceAll("-","_"),packageName:l.name,...p?{targetId:p.id}:{},external:!1,conditional:!1})}}}return o}async function mt(e){let t=Date.now()+pt,r=[],n=[];try{let c=await oe(Y(e.root)),o=new Set(e.files.map(g=>gt(c,Y(c,g)).split(ft).join("/"))),s=await ut(c,e.files,t),a=await dt(c,t),l=new Set,d=new Set,f=0;for(let g of s){if(U(t),d.has(g))continue;let p=await Ge(a.executable,["metadata","--no-deps","--offline","--locked","--format-version=1","--manifest-path",g],Ae(g),a.env,t);if(f+=Buffer.byteLength(p,"utf8"),f>pe)throw new O("cargo-metadata-limit","Combined Cargo metadata output exceeded one MiB.");let u;try{u=JSON.parse(p)}catch{throw new O("cargo-metadata-invalid","Cargo returned malformed metadata JSON.")}let i=on.safeParse(u);if(!i.success)throw new O("cargo-metadata-invalid","Cargo metadata does not satisfy format version 1 workspace requirements.");let h=new Set(i.data.workspace_members),x=i.data.packages.filter(w=>h.has(w.id)),y=await an(c,o,x,r,t);n.push(...y.filter(w=>!l.has(w.packageId)));for(let w of x)l.add(w.id),d.add(await oe(w.manifest_path).catch(()=>Y(w.manifest_path)));U(t)}!n.length&&!r.length&&r.push({code:"cargo-target-outside-scan",message:"Cargo metadata contained no workspace targets within this scan."})}catch(c){r.push(c instanceof O?{code:c.code,message:c.message}:{code:"cargo-metadata-failed",message:"Cargo workspace metadata could not be inspected within the scanned root."})}return{status:n.length?"ok":"unsupported",targets:n,diagnostics:r}}async function ht(e,t,r,n,c){let o=new Map(r.filter(d=>d.relativePath.endsWith(".rs")).map(d=>[d.relativePath,d.parsed])),s=[...o.keys()].filter(d=>["lib.rs","main.rs"].includes(cn.basename(d))&&!/(^|\/)(bin|tests|benches|examples)\//.test(d)),a=new Map,l=new Map;if(n==="cargo"&&o.size>0){let d=await mt({root:e,files:[...t]}),f=new Map,g=new Set;for(let i of d.targets){let h=JSON.stringify([i.edition,i.dependencyAliases.map(x=>[x.alias,x.targetId,x.external,x.conditional]).sort((x,y)=>String(x[0]).localeCompare(String(y[0])))]);f.has(i.srcPath)&&f.get(i.srcPath)!==h&&g.add(i.srcPath),f.set(i.srcPath,h)}let p=d.targets.filter(i=>!g.has(i.srcPath));s=p.map(i=>i.srcPath),l=new Map(p.filter(i=>i.edition!==void 0).map(i=>[i.srcPath,i.edition]));for(let i of g)c.diagnostics.push({file:i,code:"unsupported-linking",message:"Cargo targets share a source file but disagree on edition or dependency context; root resolution is ambiguous."});let u=new Map(d.targets.map(i=>[i.id,i.srcPath]));a=new Map(p.map(i=>{let h=new Map,x=new Map;for(let y of i.dependencyAliases){let w=JSON.stringify([y.packageName,y.targetId,y.external,y.conditional]);x.has(y.alias)&&x.get(y.alias)!==w?(h.set(y.alias,{external:!1}),x.set(y.alias,"ambiguous"),c.diagnostics.push({file:i.srcPath,code:"unsupported-linking",message:`Cargo dependency alias ${y.alias} has conflicting contexts; import resolution is ambiguous.`})):(x.set(y.alias,w),h.set(y.alias,{root:y.conditional?void 0:u.get(y.targetId??""),external:!y.conditional&&y.external}))}return[i.srcPath,h]}));for(let i of d.diagnostics)c.diagnostics.push({file:".",code:"unsupported-linking",message:`Cargo metadata ${i.code}: ${i.message}`})}return rt(o,t,s,a,l)}import{readFileSync as ln}from"node:fs";import{join as pn,posix as ue}from"node:path";function yt(e){return/[%\\?#]/.test(e)||e.split("/").some(t=>!t||t==="."||t===".."||t.toLowerCase()==="node_modules")}function Ie(e,t,r,n,c=0){if(--n.remaining<0||c>32)return{kind:"unsupported"};if(e===null)return{kind:"blocked"};if(typeof e=="string")return!e.startsWith("./")||yt(e.slice(2))?{kind:"invalid"}:r!==void 0&&yt(r)?{kind:"invalid"}:{kind:"target",target:r===void 0?e:e.replaceAll("*",r)};if(Array.isArray(e)){if(e.length===0)return{kind:"blocked"};let s={kind:"unmatched"};for(let a of e){let l=Ie(a,t,r,n,c+1);if(l.kind==="target"||l.kind==="unsupported")return l;l.kind!=="unmatched"&&(s=l)}return s}if(!e||typeof e!="object")return{kind:"invalid"};let o=Object.entries(e);if(o.some(([s])=>s.startsWith(".")||/^(0|[1-9]\d*)$/.test(s)))return{kind:"invalid"};for(let[s,a]of o){let l=t.startsWith("types");if(s==="default"||s==="node"||s==="types"&&l||s===(t==="require"||t==="types-require"?"require":"import")){let g=Ie(a,t,r,n,c+1);if(g.kind!=="unmatched")return g}else if(!["import","require","types"].includes(s)&&!(s.startsWith("types@")&&!l))return{kind:"unsupported"}}return{kind:"unmatched"}}function de(e,t,r){if(t.endsWith("/"))return{kind:"blocked"};if(r==="types"||r==="static"){let o=de(e,t,r==="types"?"types-import":"import"),s=de(e,t,r==="types"?"types-require":"require");return JSON.stringify(o)===JSON.stringify(s)?o:{kind:"unsupported"}}let n=e,c;if(e&&typeof e=="object"&&!Array.isArray(e)){let o=Object.entries(e);if(o.some(([s])=>s.startsWith("."))){if(o.some(([a])=>a!=="."&&!a.startsWith("./")))return{kind:"invalid"};let s=o.find(([a])=>a===t&&!a.includes("*"));if(s)n=s[1];else{let l=o.filter(([p])=>p.split("*").length===2).sort(([p],[u])=>u.indexOf("*")-p.indexOf("*")||u.length-p.length).find(([p])=>{let[u,i]=p.split("*");return t.startsWith(u)&&t.endsWith(i)&&t.length>=p.length});if(!l)return{kind:"blocked"};let[d,f]=l,g=d.indexOf("*");c=t.slice(g,t.length-(d.length-g-1)),n=f}}else if(t!==".")return{kind:"blocked"}}else if(t!==".")return{kind:"blocked"};return Ie(n,r,c,{remaining:2048})}var dn=new Set(["dist","out","lib","build"]),un={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts",".ts"],".cjs":[".cts",".ts"],".d.ts":[".ts"]};function gn(e,t){if(!t.startsWith("./"))return[];let r=t.slice(2).split("/"),n=[r];dn.has(r[0]??"")&&n.push(["src",...r.slice(1)]);let c=new Set;for(let o of n){let s=ue.normalize(ue.join(e,...o));c.add(s);for(let[a,l]of Object.entries(un))if(s.endsWith(a))for(let d of l)c.add(s.slice(0,-a.length)+d)}return[...c]}function xt(e,t){let r=new Set(["."]);for(let o of t){let s=ue.dirname(o);for(;s!==".";)r.add(s),s=ue.dirname(s)}let n=new Map;for(let o of r){let s;try{s=JSON.parse(ln(pn(e,o,"package.json"),"utf8"))}catch{continue}!s||typeof s.name!="string"||n.set(s.name,n.has(s.name)?null:{directory:o,exports:s.exports})}let c=new Map;return{resolve(o,s){let a=o.split("/"),l=o.startsWith("@")?2:1,d=a.slice(0,l).join("/");if(!n.has(d))return;let f=`${s}\0${o}`,g=c.get(f);if(g)return g;let p=n.get(d),u=a.slice(l).join("/"),i=p?de(p.exports,a.length>l?`./${u}`:".",s):{kind:"unsupported"},h=i.kind==="target"&&p?gn(p.directory,i.target).find(y=>t.has(y)):void 0,x=h?{target:h,status:"resolved"}:{target:null,status:i.kind==="invalid"||i.kind==="unsupported"?"unsupported":"unresolvedInternal",reason:p?p.exports===void 0?"package-exports-unavailable":i.kind==="target"?"package-export-target-unavailable":i.kind==="invalid"?"invalid-package-exports":i.kind==="unsupported"?"package-export-context-unavailable":"package-subpath-not-exported":"ambiguous-workspace-package"};return c.set(f,x),x}}}import{lstatSync as wt,readFileSync as fn,realpathSync as bt}from"node:fs";import{basename as mn,dirname as kt,isAbsolute as hn,relative as yn,resolve as Ne,sep as Oe}from"node:path";var xn=64*1024;function St(e,t,r,n){let c=new Set,o=new Map,s=Ne(e),a=!1,l,d=()=>{if(a)return;a=!0,s=bt(e);let g=s;for(let p=0;p<32;p++){let u=Ne(g,"package.json");try{if(wt(u).isFile()){l=u;break}}catch{}let i=kt(g);if(i===g)break;g=i}},f=!1;return{targets:c,truncated:()=>f,resolve(g,p){if(!g.startsWith(".")||mn(g)!=="package.json")return;d();let u=Ne(s,kt(p),g),i=o.get(u);if(i)return i;let h={target:null,status:"unresolvedInternal"},x=yn(s,u),y=x!==".."&&!x.startsWith(`..${Oe}`)&&!hn(x);if(!y&&u!==l||y&&x.split(Oe).some(w=>r.includes(w)))h={target:null,status:"unsupported"};else try{let w=wt(u);if(!w.isFile()||w.size>xn||bt(u)!==u)h={target:null,status:"unsupported"};else if(t.size>=n&&!t.has(x))f=!0;else{let k=JSON.parse(fn(u,"utf8"));if(k===null||typeof k!="object"||Array.isArray(k))h={target:null,status:"unsupported"};else{let R=x.split(Oe).join("/");c.add(R),t.add(R),h={target:R,status:"resolved"}}}}catch{}return o.set(u,h),h}}}import{createHash as wn}from"node:crypto";function Rt(e,t,r){for(let n of r??[])n.callee!=="require"&&n.callee!=="module.require"||(e.imports.unsupported++,e.diagnostics.push({file:t,...n.line!==void 0?{line:n.line}:{},code:"unsupported-linking",message:"CommonJS require calls are not linked: native call facts do not establish module arguments or binding identity. Verify dependencies with LSP."}))}function vt(e){let t=new Map;for(let n of e){let c=JSON.stringify([n.file,n.line??null,n.code,n.message]);t.has(c)||t.set(c,n)}let r=(n,c)=>n<c?-1:n>c?1:0;return[...t.values()].sort((n,c)=>r(n.file,c.file)||(n.line??-1)-(c.line??-1)||r(n.code,c.code)||r(n.message,c.message))}var Ct=new WeakMap;function ge(e){let t=Ct.get(e);if(t)return t;let r=vt(e).map(s=>Object.freeze({...s}));Object.freeze(r);let n=wn("sha256").update(JSON.stringify(r.map(s=>[s.file,s.line??null,s.code,s.message]))).digest("hex"),c={};for(let s of r)c[s.code]=(c[s.code]??0)+1;let o=Object.freeze({diagnostics:r,resultId:n,diagnosticCounts:Object.freeze(c)});return Ct.set(r,o),o}import{posix as kn}from"node:path";import{posix as fe}from"node:path";var _e=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],bn={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function Ft(e){return e.split("\\").join("/")}function Mt(e,t,r){let n=Ft(e);if(n.startsWith("/")||!n.startsWith("."))return null;let c=fe.dirname(Ft(t)),o=fe.normalize(fe.join(c,n)),s=[];if(_e.some(l=>o.endsWith(l))){s.push(o);for(let[l,d]of Object.entries(bn))if(o.endsWith(l)){s.push(o.slice(0,-l.length)+d);break}}else{s.push(o);for(let l of _e)s.push(`${o}${l}`);for(let l of _e)s.push(fe.join(o,`index${l}`))}for(let l of s)if(r.has(l))return l;return null}import{posix as j}from"node:path";var Q={target:null,status:"unsupported"};function Gt(e,t,r,n){if(r!=="c-relative"||j.isAbsolute(e))return Q;let c=j.normalize(j.join(j.dirname(t),e));return c===".."||c.startsWith("../")?Q:n.has(c)?{target:c,status:"resolved"}:{target:null,status:"unresolvedInternal"}}function Pt(e,t,r,n,c){if(n!=="python-relative"&&n!=="python-absolute")return Q;let o=0;for(;e[o]===".";)o++;let s=o?j.dirname(t):".",a=new Set;for(let u=0;u<o;u++){let i=me(s,c);if(i.length!==1)return Q;if(i[0]!==t&&a.add(i[0]),u+1<o){if(s==="."||s===".."||s.startsWith("../"))return Q;s=j.dirname(s)}}let l=e.slice(o).split(".").filter(Boolean).join("/"),d=j.normalize(j.join(s,l));if(j.isAbsolute(d)||d===".."||d.startsWith("../"))return Q;let f=!l&&o?me(d,c):Et(d,c);if(!o&&["sys","builtins"].includes(l)&&f.length||f.length>1)return Q;if(!f.length){let u=`${d}/`;return{target:null,status:[...c].some(h=>h.startsWith(u))?"unsupported":o?"unresolvedInternal":"external"}}let g=f[0];a.delete(g);let p="resolved";if(["__init__.py","__init__.pyi"].includes(j.basename(g))&&r){let u=r==="*"?[]:Et(j.join(j.dirname(g),r),c);u.length!==1?(r!=="*"||o)&&(p="unsupported"):(g!==t&&a.add(g),g=u[0],g!==t&&a.add(g))}for(d=j.dirname(g);d!==".";){let u=me(d,c);u.length>1&&(p="unsupported");for(let i of u)i!==g&&i!==t&&a.add(i);d=j.dirname(d)}return{target:g===t?null:g,status:p,additionalTargets:[...a].sort()}}function me(e,t){return["__init__.py","__init__.pyi"].map(r=>j.join(e,r)).filter(r=>t.has(r))}function Et(e,t){return[`${e}.py`,`${e}.pyi`,...me(e,t)].filter(r=>t.has(r))}function At(e){let{relativePath:t,parsed:r,knownFiles:n,getWorkspacePackageExports:c,metadata:o,resolveRust:s,coverage:a}=e,l=kn.extname(t).slice(1),d=r.language??l,f=["js","jsx","ts","tsx","mjs","cjs","mts","cts"].includes(l),g=["py","pyi"].includes(l),p=["c","h","cc","cpp","cxx","hh","hpp","hxx"].includes(l),u=f?"javascript-relative":l==="rs"?"rust-modules":g?"python-modules":p?"c-relative-includes":"unsupported",i=a.languages.find(y=>y.language===d);i?i.files++:a.languages.push({language:d,files:1,linking:u});for(let y of r.diagnostics??[])a.diagnostics.push({file:t,code:y.startsWith("unsupported ")?"unsupported-linking":y.startsWith("tree-sitter graph facts are syntax-only;")?"syntax-only":"parse-recovery",message:y});u==="unsupported"&&a.diagnostics.push({file:t,code:"unsupported-linking",message:`Import linking is unsupported for ${d}; declarations are syntax facts only.`}),f&&!r.commonJs&&Rt(a,t,r.calls);let h=new Set;return{extension:l,javascript:f,python:g,cFamily:p,auxiliaryTargets:h,resolve:(y,w,k={})=>{let{moduleDeclaration:R=!1,resolutionHint:v,moduleScope:C,importedName:N,exportMode:F="import"}=k,I=F==="types"?["mts","mjs"].includes(l)?"types-import":["cts","cjs"].includes(l)?"types-require":"types":F==="static"?l==="cts"?"require":["ts","tsx"].includes(l)?"static":"import":F,S;if(v==="unsupported"||u==="unsupported"||f&&y.startsWith("/"))S={target:null,status:"unsupported"};else if(l==="rs")S=s(y,t,C,R,w);else if(g)S=Pt(y,t,N,v,n);else if(p)S=Gt(y,t,v,n);else{let M=o.resolve(y,t),P=Mt(y,t,n),A=!y.startsWith(".")&&!y.startsWith("/")?c().resolve(y,I):void 0;S=M??A??{target:P,status:P?"resolved":y.startsWith(".")||y.startsWith("/")?"unresolvedInternal":"external"}}for(let M of S.additionalTargets??[])h.add(M);return a.imports[S.status]++,(S.status==="unsupported"||S.status==="unresolvedInternal")&&a.diagnostics.push({file:t,line:w,code:S.status==="unsupported"?"unsupported-linking":"unresolved-internal",message:`Cannot link import ${JSON.stringify(y)} (${S.status}${S.reason?`: ${S.reason}`:""}).`}),S.target}}}var Sn=["node_modules","dist","build","out","coverage",".git","target",".next",".cache"];function he(e){return[...new Set([...Sn,...e??[]])]}async function Z(e,t,r,n="syntax"){let c=await qe.scanGraphFacts({path:e,excludeDir:t,maxFiles:r,maxFileBytes:1e6}),o=c.entries,s=c.candidatePaths.map(R=>It.normalize(R.split("\\").join("/"))),a=new Set(s),l,d=()=>l??=xt(e,new Set(s)),f=St(e,a,t,r),g=new Map,p=new Map,u=new Set,i=new Set,h=new Map,x=c.filesSkipped,y={basis:"syntactic",referenceBasis:"lexical-occurrence",languages:[],imports:{resolved:0,external:0,unresolvedInternal:0,unsupported:0},diagnostics:[]},w=[];for(let R of o){let v=It.normalize(R.relativePath.split("\\").join("/"));try{let C=JSON.parse(R.factsJson);w.push({relativePath:v,parsed:C,referenceCounts:R.referenceCounts})}catch{x++}}let k=await ht(e,a,w,n,y);for(let R of w){let{relativePath:v,parsed:C}=R,{extension:N,javascript:F,python:I,cFamily:S,auxiliaryTargets:M,resolve:P}=At({relativePath:v,parsed:C,knownFiles:a,getWorkspacePackageExports:d,metadata:f,resolveRust:k,coverage:y}),A=(C.declarations??[]).filter(m=>!F||nt(m.name)).map(m=>({id:m.id,name:m.name,kind:m.kind,line:m.line,exported:m.exported??!1})),$=new Map(R.referenceCounts.map(({name:m,count:b})=>[m,b])),W=(C.exports??[]).filter(m=>m.source&&m.name!=="*").map(m=>({specifier:m.source,localName:m.name,importedName:m.localName??m.name,line:m.line,importKind:m.exportKind==="type"?"type":"value",resolvedTarget:P(m.source,m.line,{exportMode:m.exportKind==="type"?"types":"static"})})),D={relativePath:v,declarations:A,imports:(C.imports??[]).map(m=>({specifier:m.specifier,localName:m.localName,importedName:m.importedName,line:m.line,importKind:m.importKind==="type"?"type":m.importKind==="module"?"module":"value",resolvedTarget:P(m.specifier,m.line,{moduleDeclaration:m.importKind==="module",resolutionHint:m.resolutionHint,moduleScope:m.moduleScope,importedName:m.importedName,exportMode:m.importKind==="type"?"types":"static"})})),namedReexports:W,calls:(C.calls??[]).filter(m=>m.kind!=="dynamic-import").map(m=>({caller:m.caller,callee:m.callee})),referenceCounts:$};g.set(v,D);let te=new Set,ne=new Set,q=new Map,B=(m,b)=>{if(N==="rs"&&m===v)return;te.add(m);let E=q.get(m)??new Set;E.add(b),f.targets.has(m)&&!b.startsWith("type-")&&E.add("metadata-import"),q.set(m,E)};for(let m of D.imports){let b=m.resolvedTarget;b&&(B(b,N==="rs"?m.importKind==="module"?"rust-module":"rust-use":m.importKind==="type"?"type-import":I?"python-import":S?"c-include":"static-import"),(m.importedName==="*"||S)&&i.add(b))}for(let m of M)B(m,"python-import"),i.add(m);for(let m of D.namedReexports){let b=m.resolvedTarget;b&&B(b,N==="rs"?"rust-use":m.importKind==="type"?"type-named-reexport":"named-reexport")}for(let m of C.calls??[]){if(m.kind!=="dynamic-import")continue;let b=P(m.callee,0);b&&(B(b,"dynamic-import"),i.add(b))}for(let m of C.commonJs??[]){if(!m.specifier){y.imports.unsupported++,y.diagnostics.push({file:v,line:m.line,code:"unsupported-linking",message:`CommonJS require cannot be linked (${m.reason??"missing-native-provenance"}).`});continue}let b=P(m.specifier,m.line,{exportMode:"require"});b&&(B(b,m.binding==="create-require"?"create-require":"commonjs-require"),i.add(b))}for(let m of C.exports??[]){if(!m.source||m.name!=="*")continue;let b=P(m.source,m.line,{exportMode:m.exportKind==="type"?"types":"static"});if(b){B(b,N==="rs"?"rust-use":m.exportKind==="type"?"type-star-reexport":"star-reexport"),u.add(b);let E=h.get(b)??[];E.push(v),h.set(b,E)}}for(let[m,b]of q)b.size===1&&b.has("dynamic-import")&&ne.add(m);p.set(v,{relativePath:v,importsFiles:te,dynamicImportsFiles:ne,edgeKinds:q})}for(let R of f.targets)g.set(R,{relativePath:R,declarations:[],imports:[],namedReexports:[],calls:[],referenceCounts:new Map}),p.set(R,{relativePath:R,importsFiles:new Set,dynamicImportsFiles:new Set,edgeKinds:new Map});return f.targets.size&&y.languages.push({language:"json",files:f.targets.size,linking:"metadata"}),y.diagnostics=ge(y.diagnostics).diagnostics,{coverage:y,facts:g,fileGraph:p,filesScanned:g.size,filesSkipped:x,truncated:c.truncated||f.truncated(),starReexportTargets:u,namespaceImportTargets:i,starReexporters:h}}import{isAbsolute as Xt,relative as Ln}from"node:path";import{existsSync as Nt}from"node:fs";import{dirname as je,join as Ot}from"node:path";function ye(e,t="syntax"){let r=je(e),n=t==="cargo"||e.endsWith(".rs"),c;for(;;){if(n&&Nt(Ot(r,"Cargo.toml")))return r;if(!c&&Nt(Ot(r,"package.json"))){if(!n)return r;c=r}let o=je(r);if(o===r)break;r=o}return c??je(e)}import{readFileSync as Rn}from"node:fs";import{posix as ze}from"node:path";var vn=/(\.(test|spec)\.[^/]+$)|(^|\/)(__tests__|tests?)\//i;function De(e){return vn.test(e)}var Cn=/\.(mjs|cjs|jsx?|tsx?)$/i;function Fn(e){let t=[];for(let r of e.split(/\s+/)){let n=r.includes("=")?[r,r.slice(r.indexOf("=")+1)]:[r];for(let c of n){let o=c.replace(/^["']|["']$/g,"");Cn.test(o)&&!o.startsWith("-")&&t.push(o)}}return t}function Te(e){return e.split("\\").join("/")}function _t(e){return e.replace(/^\.\//,"")}var jt=["dist","build","out"],Mn={".js":".ts",".jsx":".tsx",".mjs":".mts",".cjs":".cts"};function zt(e){for(let[t,r]of Object.entries(Mn))if(e.endsWith(t))return e.slice(0,-t.length)+r}function En(e,t){let r=[],n=zt(e);n&&r.push(n);for(let c of jt){let o=`${c}/`;if(!e.startsWith(o))continue;let a=`src/${e.slice(o.length)}`;r.push(a);let l=zt(a);l&&r.push(l)}return jt.some(c=>e.startsWith(`${c}/`))&&t.has("src/index.ts")&&r.push("src/index.ts"),r.find(c=>t.has(c))}function ie(e,t){if(typeof e=="string"){t.push(e);return}if(Array.isArray(e)){for(let r of e)ie(r,t);return}if(e&&typeof e=="object")for(let r of Object.values(e))ie(r,t)}function xe(e,t,r,n){let c=[],o=new Set,s=!1;if(t&&t.length>0){let a=Te(e).replace(/\/$/,"");for(let l of t){let d=_t(Te(l));if(d===a?d=".":d.startsWith(a+"/")&&(d=d.slice(a.length+1)),d=ze.normalize(d),n.has(d)){o.add(d);continue}let f=d==="."?"":`${d.replace(/\/$/,"")}/`,g=[...n].filter(p=>p.startsWith(f));if(g.length>0)for(let p of g)o.add(p);else c.push(`entrypoint not found in scan: ${l} \u2014 pass a file or dynamic asset directory relative to the scanned path, or an absolute path under it`)}}else{let a;try{let l=ze.join(e,"package.json");a=JSON.parse(Rn(l,"utf-8"))}catch{}if(a){let l=[];if(ie(a.main,l),ie(a.exports,l),ie(a.bin,l),a.scripts&&typeof a.scripts=="object")for(let d of Object.values(a.scripts))typeof d=="string"&&l.push(...Fn(d));for(let d of l){let f=ze.normalize(_t(Te(d))),g=n.has(f)?f:En(f,n);g&&o.add(g)}}o.size===0&&(c.push("no entrypoints resolved from package.json \u2014 pass `entrypoints` explicitly, or every export in a reachable file will read as unreachable"),s=!0)}if(r)for(let a of n)De(a)&&o.add(a);return{entrypoints:[...o],warnings:c,lowConfidence:s}}function ae(e,t){let r=new Set,n=[];for(let c of t)r.has(c)||(r.add(c),n.push(c));for(;n.length>0;){let c=n.pop(),o=e.get(c);if(o)for(let s of o.importsFiles)r.has(s)||(r.add(s),n.push(s))}return r}function we(e){let t=0,r=new Map,n=new Map,c=new Set,o=[],s=[],a=[];for(let l of e.keys())if(!r.has(l))for(a.push({node:l,iterator:(e.get(l)?.importsFiles??new Set).values()}),r.set(l,t),n.set(l,t),t++,o.push(l),c.add(l);a.length>0;){let d=a[a.length-1],f=d.iterator.next();if(!f.done){let g=f.value;if(!r.has(g))r.set(g,t),n.set(g,t),t++,o.push(g),c.add(g),a.push({node:g,iterator:(e.get(g)?.importsFiles??new Set).values()});else if(c.has(g)){let p=n.get(d.node),u=r.get(g);n.set(d.node,Math.min(p,u))}continue}if(a.pop(),a.length>0){let g=a[a.length-1],p=n.get(g.node),u=n.get(d.node);n.set(g.node,Math.min(p,u))}if(n.get(d.node)===r.get(d.node)){let g=[],p;do p=o.pop(),c.delete(p),g.push(p);while(p!==d.node);(g.length>1||(e.get(g[0])?.importsFiles.has(g[0])??!1))&&s.push({files:g})}}return s}function ce(e,t){return`${e}::${t}`}function Gn(e,t,r,n,c,o){let s=new Set,a=[{file:e,name:t}];for(;a.length>0;){let l=a.pop(),d=ce(l.file,l.name);if(!s.has(d)){if(s.add(d),r.has(l.file)||n.has(d))return!0;for(let f of c.get(d)??[])a.push({file:f.file,name:f.localName});for(let f of o.get(l.file)??[])a.push({file:f,name:l.name})}}return!1}function Tt(e,t,r,n,c,o){let s=new Set(t.declarations.filter(p=>p.exported).map(p=>p.name)),a=new Set;for(let p of s)Gn(e,p,r,n,c,o)&&a.add(p);let l=new Map,d=new Map;for(let p of t.calls){let u=l.get(p.caller)??[];u.push(p.callee),l.set(p.caller,u),s.has(p.caller)&&d.set(p.callee,(d.get(p.callee)??0)+1)}let f=[...a],g=p=>{!s.has(p)||a.has(p)||(a.add(p),f.push(p))};for(let[p,u]of l)if(!s.has(p))for(let i of u)g(i);for(let p of s)(t.referenceCounts.get(p)??0)-(d.get(p)??0)>1&&g(p);for(let p=0;p<f.length;p++){let u=f[p];for(let i of l.get(u)??[])i!==u&&g(i)}return a}async function Dt(e,t,r){let n=he(t.excludeDir),c=t.maxFiles??2e4,{facts:o,fileGraph:s,filesScanned:a,filesSkipped:l,truncated:d,coverage:f,namespaceImportTargets:g,starReexporters:p}=r??await Z(e,n,c,t.rustWorkspace),u=new Set(o.keys()),{entrypoints:i,warnings:h,lowConfidence:x}=xe(e,t.entrypoints,t.includeTests??!0,u);d&&h.push(`scan stopped at maxFiles (${c}) \u2014 results are partial, not a full-repo verdict`),l>0&&h.push(`${l} file(s) could not be read or parsed within the native graph bounds \u2014 results are partial, not a full-repo verdict`);let y=f?.diagnostics.some(m=>m.code!=="syntax-only")??!1;y&&h.push("Incomplete import linking or parse recovery can hide live paths. Dead-code results are low-confidence candidates and require semantic reference verification.");let w=i.filter(m=>{let b=o.get(m);return(s.get(m)?.importsFiles.size??0)===0&&(b?.declarations.length??0)===0&&(b?.namedReexports.length??0)===0}),k=w.length>0;k&&h.push(`${w.length} entrypoint file(s) parsed to no imports/exports (likely an extractor parse failure on that file) \u2014 reachability from them is unreliable, so "unreachable-file" results here are low-confidence and may be false positives: ${w.join(", ")}`);let R=ae(s,i),v=new Set(i),C=new Set([...v,...g]),N=m=>t.includeTests!==!1||!De(m),F=new Map([...s].map(([m,b])=>[m,{relativePath:b.relativePath,importsFiles:new Set([...b.importsFiles].filter(E=>!b.dynamicImportsFiles.has(E))),dynamicImportsFiles:new Set,edgeKinds:new Map([...b.edgeKinds].map(([E,z])=>[E,new Set([...z].filter(_=>_!=="dynamic-import"))]).filter(([,E])=>E.size>0))}])),I=ae(F,i),S=[...R].filter(m=>!I.has(m)).sort();S.length>0&&h.push(`${S.length} file(s) reachable only through a dynamic import() \u2014 lower confidence than static analysis, verify with lspGetSemantics before treating as proof: ${S.join(", ")}`);let M=new Set,P=new Map;for(let m of R){let b=o.get(m);if(b){for(let E of b.imports){let z=E.resolvedTarget;z&&M.add(ce(z,E.importedName))}for(let E of b.namedReexports){let z=E.resolvedTarget;if(!z)continue;let _=ce(z,E.importedName),H=P.get(_)??[];H.push({file:m,localName:E.localName}),P.set(_,H)}}}let A=new Map;for(let[m,b]of p){let E=b.filter(z=>R.has(z));E.length>0&&A.set(m,E)}let $=new Set(A.keys()),W=[],D=we(s),te=new Map,ne=[],q=0;for(let m of D){let b=m.files.filter(N);if(b.length===0||!b.every(_=>!R.has(_)))continue;let z=q++;for(let _ of b)te.set(_,z);ne.push({id:z,files:b,reason:"mutually-referencing cluster with no path from any entrypoint \u2014 each file looks locally referenced by the others, but the cluster as a whole is unreachable"})}let B=new Map;for(let[m,b]of o){if(!N(m))continue;let E=v.has(m),z=R.has(m);for(let _ of b.declarations){if(!_.exported)continue;if(!z){let Ce=te.get(m);W.push({file:m,name:_.name,kind:_.kind,line:_.line,reason:Ce!==void 0?"dead-cluster":"unreachable-file",...Ce!==void 0?{clusterId:Ce}:{}});continue}if(E||$.has(m)||g.has(m))continue;let H=B.get(m);H||(H=Tt(m,b,C,M,P,A),B.set(m,H)),H.has(_.name)||W.push({file:m,name:_.name,kind:_.kind,line:_.line,reason:"unreferenced-export",viaHeuristic:P.has(ce(m,_.name))?"reexport-chain":"lexical-count"})}}return{filesScanned:a,filesSkipped:l,entrypointsResolved:i,deadExports:W,deadClusters:ne,warnings:h,...x||k||y||d||l>0?{confidence:"low"}:{}}}import{posix as Pn}from"node:path";function Lt(e){return Pn.normalize(e.split("\\").join("/")).replace(/^\.\//,"")}function be(e,t){return[...e?.edgeKinds.get(t)??["static-import"]].sort()}function Le(e,t){let r=new Set(t),n=new Set;for(let c of t){let o=e.get(c);for(let s of o?.importsFiles??[])if(r.has(s))for(let a of be(o,s))n.add(a)}return[...n].sort()}function Wt(e,t,r){let n=[],c=new Set([t]),o=[{file:t,distance:0}];for(let s=0;s<o.length;s++){let a=o[s];if(a.distance>=r)continue;let l=e.get(a.file),d=[...l?.importsFiles??[]].sort();for(let f of d){if(c.has(f))continue;c.add(f);let g=a.distance+1;o.push({file:f,distance:g}),n.push({file:f,distance:g,via:a.file,edgeKinds:be(l,f),confidence:"syntactic"})}}return n}function $t(e){let t=new Map;for(let r of e.keys())t.set(r,{relativePath:r,importsFiles:new Set,dynamicImportsFiles:new Set,edgeKinds:new Map});for(let[r,n]of e)for(let c of n.importsFiles){let o=t.get(c);if(!o)continue;o.importsFiles.add(r);let s=new Set(be(n,c));o.edgeKinds.set(r,s),s.size===1&&s.has("dynamic-import")&&o.dynamicImportsFiles.add(r)}return t}function Kt(e,t,r){let n=new Map,c=new Set([t]),o=[t];for(let l=0;l<o.length;l++){let d=o[l];if(d===r)break;for(let f of[...e.get(d)?.importsFiles??[]].sort())c.has(f)||(c.add(f),n.set(f,d),o.push(f))}if(!c.has(r))return{found:!1,files:[],edges:[]};let s=[r];for(;s[0]!==t;)s.unshift(n.get(s[0]));let a=s.slice(0,-1).map((l,d)=>{let f=s[d+1];return{from:l,to:f,edgeKinds:be(e.get(l),f),confidence:"syntactic"}});return{found:!0,files:s,edges:a,length:s.length,complete:!0,confidence:"syntactic"}}var An=new Set(["static-import","dynamic-import","named-reexport","star-reexport","commonjs-require","create-require","python-import"]);function Ut(e){return new Map([...e].map(([t,r])=>{let n=[...r.importsFiles].filter(c=>[...r.edgeKinds.get(c)??[]].some(s=>An.has(s)));return[t,{relativePath:t,importsFiles:new Set(n),dynamicImportsFiles:new Set(n.filter(c=>r.dynamicImportsFiles.has(c))),edgeKinds:new Map(n.map(c=>[c,new Set(r.edgeKinds.get(c)??["static-import"])]))}]}))}function We(e){let t=0,r=new Map,n=new Map,c=[],o=new Set,s=[];for(let u of[...e.keys()].sort()){if(r.has(u))continue;let i=[{node:u,successors:[...e.get(u)?.importsFiles??[]].sort(),offset:0}];for(r.set(u,t),n.set(u,t++),c.push(u),o.add(u);i.length>0;){let h=i[i.length-1],x=h.successors[h.offset++];if(x!==void 0){r.has(x)?o.has(x)&&n.set(h.node,Math.min(n.get(h.node),r.get(x))):(r.set(x,t),n.set(x,t++),c.push(x),o.add(x),i.push({node:x,successors:[...e.get(x)?.importsFiles??[]].sort(),offset:0}));continue}i.pop();let y=i[i.length-1];if(y&&n.set(y.node,Math.min(n.get(y.node),n.get(h.node))),n.get(h.node)!==r.get(h.node))continue;let w=[],k;do k=c.pop(),o.delete(k),w.push(k);while(k!==h.node);s.push(w.sort())}}s.sort((u,i)=>(u[0]??"").localeCompare(i[0]??""));let a=new Map;s.forEach((u,i)=>{for(let h of u)a.set(h,i)});let l=new Map,d=new Map;s.forEach((u,i)=>{l.set(i,new Set),d.set(i,new Set)});for(let[u,i]of e){let h=a.get(u);for(let x of i.importsFiles){let y=a.get(x);y===void 0||y===h||(l.get(h)?.add(y),d.get(y)?.add(h))}}let f=new Map(s.map((u,i)=>[i,d.get(i)?.size??0])),g=[],p=[...f].filter(([,u])=>u===0).map(([u])=>u).sort((u,i)=>u-i);for(;p.length>0;){g.push(p);let u=[];for(let i of p)for(let h of[...l.get(i)??[]].sort((x,y)=>x-y)){let x=f.get(h)-1;f.set(h,x),x===0&&u.push(h)}p=u.sort((i,h)=>i-h)}return{components:s,componentOf:a,edges:l,reverseEdges:d,layers:g}}function $e(e){let t=new Set;for(let[r,n]of e)for(let c of n){let o=new Set([r]),s=[...n].filter(a=>a!==c);for(;s.length>0;){let a=s.pop();if(a===c){t.add(`${r}:${c}`);break}o.has(a)||(o.add(a),s.push(...e.get(a)??[]))}}return t}function Bt(e,t){let r=new Set,n=[],c=[{node:t,successors:[...e.get(t)?.importsFiles??[]].sort(),offset:0}];for(r.add(t);c.length>0;){let p=c[c.length-1],u=p.successors[p.offset++];if(u!==void 0){if(r.has(u))continue;r.add(u),c.push({node:u,successors:[...e.get(u)?.importsFiles??[]].sort(),offset:0});continue}c.pop(),n.push(p.node)}let o=n.reverse(),s=new Map(o.map((p,u)=>[p,u])),a=new Map(o.map(p=>[p,new Set]));for(let p of o)for(let u of e.get(p)?.importsFiles??[])a.get(u)?.add(p);let l=new Map([[t,t]]),d=(p,u)=>{let i=p,h=u;for(;i!==h;){for(;s.get(i)>s.get(h);)i=l.get(i);for(;s.get(h)>s.get(i);)h=l.get(h)}return i},f=!0;for(;f;){f=!1;for(let p of o.slice(1)){let u=[...a.get(p)??[]].filter(h=>l.has(h));if(u.length===0)continue;let i=u[0];for(let h of u.slice(1))i=d(h,i);l.get(p)!==i&&(l.set(p,i),f=!0)}}let g=new Map([[t,null]]);for(let p of o.slice(1))g.set(p,l.get(p)??null);return g}function In(e,t){let r=new Map,n=new Map;for(let c of[...t].sort()){if(!e.has(c)||r.has(c))continue;r.set(c,"visiting");let o=[{node:c,successors:[...e.get(c)?.importsFiles??[]].filter(s=>t.has(s)).sort(),offset:0}];for(;o.length>0;){let s=o[o.length-1],a=s.successors[s.offset++];if(a===void 0){r.set(s.node,"done"),o.pop();continue}let l=r.get(a);if(!l){n.set(a,s.node),r.set(a,"visiting"),o.push({node:a,successors:[...e.get(a)?.importsFiles??[]].filter(g=>t.has(g)).sort(),offset:0});continue}if(l!=="visiting")continue;let d=[s.node];for(;d[d.length-1]!==a;){let g=n.get(d[d.length-1]);if(!g)return[];d.push(g)}d.reverse();let f=[];for(let g=0;g<d.length-1;g++)f.push({from:d[g],to:d[g+1]});return f.push({from:s.node,to:a}),f}}return[]}function Ke(e,t){return In(e,t).map(({from:r,to:n})=>({from:r,to:n,edgeKinds:[...e.get(r)?.edgeKinds.get(n)??new Set(["static-import"])].sort()}))}function Ue(e){let t=new Map;return e.forEach((r,n)=>{for(let c of r)t.set(c,n)}),t}var Nn=["parseRecovery","unresolvedImports","unsupportedLinking"];function On(e){return Nn.some(t=>t===e)}function Jt(e){let t=e.partialReasons??[],r=t.filter(On),n=t.some(s=>["maxFiles","filesSkipped"].includes(s)),c=t.some(s=>["limit","maxFiles","filesSkipped"].includes(s)),o=e.coverage?.diagnosticsPagination;return{...e,completeness:{results:e.pagination?.hasMore?"pageable":c?"truncated":"complete",graph:n?"scan-truncated":r.length>0?"coverage-incomplete":"complete",diagnostics:o?.terminalLimit?"truncated":o?.hasMore?"pageable":"complete",...r.length>0?{coverageGapReasons:r}:{}}}}var _n=50,Se=2e4,Re=5e4,Be=5e3;function ee(e,t){let r=t.limit?e.slice(0,t.limit):e,n=r.length<e.length,c=t.pageSize??_n,o=t.page??1,s=Math.max(1,Math.ceil(r.length/c)),a=Math.min(Math.max(1,o),s),l=(a-1)*c;return{results:r.slice(l,l+c),pagination:{currentPage:a,totalPages:s,entriesPerPage:c,totalEntries:r.length,hasMore:a<s,...o>s?{outOfRange:!0}:{}},...n?{truncated:!0,partialReasons:["limit"],totalAvailable:e.length}:{}}}function jn(e,t){let r=(e.filesSkipped??0)>0,n=e.coverage?.diagnostics??[],c=n.some(a=>a.code==="parse-recovery"),o=n.some(a=>a.code==="unresolved-internal"),s=n.some(a=>a.code==="unsupported-linking");return!t&&!r&&!c&&!o&&!s?e:{...e,truncated:!0,partialReasons:[...new Set([...e.partialReasons??[],...t?["maxFiles"]:[],...r?["filesSkipped"]:[],...c?["parseRecovery"]:[],...o?["unresolvedImports"]:[],...s?["unsupportedLinking"]:[]])]}}function zn(e,t){let r=e.partialReasons?.includes("maxFiles")===!0&&(t.maxFiles??Se)>=Re,n=e.partialReasons?.includes("limit")===!0&&t.limit!==void 0&&t.limit>=Be,c=e.pagination?.hasMore===!0&&e.pagination.currentPage>=1e3,o=e.partialReasons?.includes("filesSkipped")===!0,s=e.partialReasons?.includes("maxFiles")===!0&&(t.maxFiles??Se)<Re,a=e.partialReasons?.some(l=>["parseRecovery","unsupportedLinking"].includes(l)||l==="unresolvedImports"&&!s)===!0;return r||n||c||o||a?{...e,terminalLimit:!0,...a?{warnings:[...e.warnings??[],"Graph coverage is incomplete; parser recovery or unsupported/unresolved module linking cannot be repaired by pagination. Inspect coverage.diagnostics and verify with LSP."]}:{}}:e}function Tn(e,t,r){e.pagination?.outOfRange&&(e={...e,warnings:[...e.warnings??[],`page:${t.page} is out of range (only ${e.pagination.totalPages} page(s)) \u2014 returned page ${e.pagination.currentPage} instead.`]});let n={};if(e.pagination?.hasMore&&e.pagination.currentPage<1e3&&(n.nextPage=X("localAnalyzeGraph",{...t,page:e.pagination.currentPage+1},r)),e.partialReasons?.includes("maxFiles")&&(t.maxFiles??Se)<Re){let o=t.maxFiles??Se;n.expandScan=X("localAnalyzeGraph",{...t,maxFiles:Math.min(Re,Math.max(o+1,o*2)),page:1},"Re-run with a larger file-scan bound because this graph is partial.")}e.partialReasons?.includes("limit")&&t.limit!==void 0&&t.limit<Be&&(n.expandLimit=X("localAnalyzeGraph",{...t,limit:Math.min(Be,Math.max(t.limit+1,t.limit*2)),page:1},"Re-run with a larger result limit because additional graph results exist."));let c=t.path;if(t.operation==="deadCode"&&c){let o=e.results[0];if(o&&typeof o.file=="string"&&typeof o.name=="string"&&typeof o.line=="number"){let s=c.replace(/\/+$/,"");n.verifyReferences={tool:He,query:{type:"references",uri:`${s}/${o.file}`,symbolName:o.name,lineHint:o.line,includeDeclaration:!1,groupByFile:!0},why:`Verify candidate "${o.name}" before deletion; repeat for each result, prioritizing viaHeuristic:"reexport-chain".`,confidence:"high"}}}for(let o of["expandScan","expandLimit"]){let s=n[o];s&&(delete s.query.diagnosticSnapshot,s.query.diagnosticPage=1)}return Object.keys(n).length>0?{...e,next:n}:e}function Qt(e,t,r,n){return Jt(Dn(Tn(zn(jn(e,r),t),t,n),t))}function Dn(e,t){let r=e.coverage;if(!r)return e;let{diagnostics:n,resultId:c,diagnosticCounts:o}=ge(r.diagnostics),{diagnosticSnapshot:s,...a}=t,l=X("localAnalyzeGraph",{...a,diagnosticPage:1},"Restart diagnostic pagination from the current diagnostic snapshot.");if(t.diagnosticSnapshot&&t.diagnosticSnapshot!==c)return{...e,status:"error",errorCode:"graphDiagnosticsChanged",error:"Graph diagnostics changed between pages. Restart before combining diagnostic pages.",results:[],coverage:{...r,diagnostics:[],diagnosticCounts:o},next:{restartDiagnostics:l}};let d=Math.max(1,Math.min(t.diagnosticPageSize??25,100)),f=t.diagnosticPage??1,g=Math.max(1,Math.ceil(n.length/d)),p=Math.max(1,Math.min(f,g,1e3)),u=p<g,i=u&&p>=1e3,h=i&&d===100,x=f>g,y=(p-1)*d,w={...e.next};if(u&&!i&&(w.nextDiagnostics=X("localAnalyzeGraph",{...t,diagnosticPage:p+1,diagnosticPageSize:d,diagnosticSnapshot:c},"Continue coverage diagnostics from the same diagnostic snapshot.")),i&&!h){let k=Math.min(100,d*2);w.nextDiagnostics=X("localAnalyzeGraph",{...t,diagnosticPage:p*d/k+1,diagnosticPageSize:k,diagnosticSnapshot:c},"Continue the diagnostic snapshot with larger pages from the next unread row.")}return x&&(w.restartDiagnostics=l),{...e,coverage:{...r,diagnosticCounts:o,diagnostics:n.slice(y,y+d),diagnosticsPagination:{currentPage:p,totalPages:g,entriesPerPage:d,totalEntries:n.length,hasMore:u,resultId:c,...x?{outOfRange:!0}:{},...h?{terminalLimit:!0}:{}}},...Object.keys(w).length?{next:w}:{},...u?{truncated:!0,partialReasons:[...new Set([...e.partialReasons??[],"diagnosticPage"])]}:{},...h?{terminalLimit:!0}:{},...x||h?{warnings:[...e.warnings??[],x?`diagnosticPage:${f} is out of range; returned diagnostic page ${p}.`:"Diagnostic pagination reached its page limit; remaining diagnostics were not returned. Narrow the graph scope."]}:{}}}var Wn=2e4,Ht=1;function Je(e,t){return Lt(Xt(e)?Ln(t,e):e)}function Qe(e){return{entrypointsResolved:e,entrypointsResolvedCount:e.length}}function ve(e,t){return{status:"error",error:t,errorCode:"invalidGraphQuery",operation:e.operation,path:e.path,results:[]}}async function qt(e,t={}){let r=e.path;if(!r){let i=e.file??e.target??e.entrypoints?.[0];i&&Xt(i)&&(r=ye(i,e.rustWorkspace))}if(!r)return{status:"error",error:"path is required \u2014 or provide an absolute file path to infer its nearest Cargo.toml (Rust) or package.json root",errorCode:"invalidGraphQuery",operation:e.operation,path:"",results:[]};let n={...e,path:r},c=he(n.excludeDir),o=n.maxFiles??Wn,s=await(t.getGraph?.(n.path,c,o,n.rustWorkspace)??Z(n.path,c,o,n.rustWorkspace)),a=(i,h)=>Qt({...i,...s.coverage?{coverage:s.coverage}:{}},n,s.truncated,h);if(n.operation==="deadCode"){let i=await Dt(n.path,n,s),h=ee(i.deadExports,n),x=new Set(h.results.map(y=>y.clusterId).filter(y=>typeof y=="number"));return a({operation:n.operation,path:n.path,filesScanned:i.filesScanned,filesSkipped:i.filesSkipped,...h,summary:{...Qe(i.entrypointsResolved),deadClusters:i.deadClusters.filter(y=>x.has(y.id)).map(y=>({...y,files:y.files,size:y.files.length,edgeKinds:Le(s.fileGraph,y.files),confidence:"syntactic"})),deadClusterCount:i.deadClusters.length,deadExportCount:i.deadExports.length},...i.warnings.length>0?{warnings:i.warnings}:{},...i.confidence?{confidence:i.confidence}:{}},"Continue dead-code candidates.")}let l=[...s.truncated?[`scan stopped at maxFiles (${o}) \u2014 graph results are partial`]:[],...s.filesSkipped>0?[`${s.filesSkipped} file(s) could not be read or parsed within the native graph bounds \u2014 graph results are partial`]:[]],d={operation:n.operation,path:n.path,filesScanned:s.filesScanned,filesSkipped:s.filesSkipped};if(n.operation==="cycles"){let i=We(s.fileGraph),h=Ue(i.layers),x=$e(i.edges),y=Ut(s.fileGraph),w=we(y).map(v=>[...v.files].sort()),R=i.components.filter(v=>v.length>1||(s.fileGraph.get(v[0])?.importsFiles.has(v[0])??!1)).map(v=>{let C=i.componentOf.get(v[0]),N=new Set(v),F=w.filter(P=>P.every(A=>N.has(A))),I=Ke(s.fileGraph,N),S=Ke(y,N),M=C===void 0?[]:[...i.edges.get(C)??[]].sort((P,A)=>P-A);return{files:v,size:v.length,edgeKinds:Le(s.fileGraph,v),runtimeCycle:F.length>0,runtimeCycles:F,runtimeCycleCount:F.length,cycleEdges:I,runtimeCycleEdges:S,componentId:C,topologicalLayer:C===void 0?void 0:h.get(C),outgoingComponents:M,outgoingComponentCount:M.length,confidence:"syntactic"}}).sort((v,C)=>(v.files[0]??"").localeCompare(C.files[0]??""));return a({...d,...ee(R,n),summary:{cycleCount:R.length,runtimeCycleCount:R.filter(v=>v.runtimeCycle).length,condensationComponentCount:i.components.length,condensationEdgeCount:[...i.edges.values()].reduce((v,C)=>v+C.size,0),topologicalLayerCount:i.layers.length,transitiveEdgeCount:x.size},...l.length>0?{warnings:l}:{}},"Continue cycle components.")}if(n.operation==="dependencies"||n.operation==="dependents"){if(!n.file)return a(ve(n,`${n.operation} requires file`),`Retry ${n.operation} after expanding the graph scan.`);let i=Je(n.file,n.path);if(!s.fileGraph.has(i))return a(ve(n,`file is not in the scanned graph: ${i}`),`Retry ${n.operation} after expanding the graph scan.`);let h=n.operation==="dependencies"?s.fileGraph:$t(s.fileGraph),x=We(h),y=Ue(x.layers),w=$e(x.edges),k=n.depth??Ht,R=k>1?Bt(h,i):void 0,v=Wt(h,i,k).map(C=>{let N=C.file,F=C.via,I=x.componentOf.get(F),S=x.componentOf.get(N);return{...C,immediateDominator:k===1?i:R?.get(N)??null,topologicalLayer:S===void 0?void 0:y.get(S),transitiveEdge:I!==void 0&&S!==void 0?w.has(`${I}:${S}`):!1}});return a({...d,...ee(v,n),summary:{source:i,depth:n.depth??Ht,condensationComponentCount:x.components.length,topologicalLayerCount:x.layers.length,transitiveEdgeCount:w.size},...l.length>0?{warnings:l}:{}},`Continue ${n.operation}.`)}if(n.operation==="path"){if(!n.file||!n.target)return a(ve(n,"path requires file and target"),"Retry the path query after expanding the graph scan.");let i=Je(n.file,n.path),h=Je(n.target,n.path);return!s.fileGraph.has(i)||!s.fileGraph.has(h)?a(ve(n,"file and target must both be in the scanned graph"),"Retry the path query after expanding the graph scan."):a({...d,...ee([Kt(s.fileGraph,i,h)],n),summary:{source:i,target:h},...l.length>0?{warnings:l}:{}},"Continue path results.")}let f=new Set(s.facts.keys()),g=xe(n.path,n.entrypoints,n.includeTests??!0,f);if(g.lowConfidence&&g.entrypoints.length===0)return a({...d,status:"empty",results:[],summary:{...Qe(g.entrypoints),classifiedCount:0,unclassifiedCount:s.fileGraph.size},warnings:[...l,...g.warnings],confidence:"low"},"Retry reachability after expanding the graph scan.");let p=ae(s.fileGraph,g.entrypoints),u=[...s.fileGraph.keys()].sort().map(i=>({file:i,reachable:p.has(i),confidence:"syntactic"}));return a({...d,...ee(u,n),summary:{...Qe(g.entrypoints),reachableCount:p.size,unreachableCount:u.length-p.size},...l.length+g.warnings.length>0?{warnings:[...l,...g.warnings]}:{},...g.lowConfidence?{confidence:"low"}:{}},"Continue reachability classifications.")}function Kn(e){if(e.path)return e;let t=e,r=t.file??t.target??t.entrypoints?.[0];return!r||!$n(r)?e:{...e,path:ye(r,e.rustWorkspace)}}async function Er(e){let t=new Map,r=(n,c,o,s="syntax")=>{let a=JSON.stringify([n,[...c].sort(),o,s]),l=t.get(a);if(l)return l;let d=Z(n,c,o,s);return t.set(a,d),d};return Ve(e.queries||[],async n=>et({toolName:se.LOCAL_ANALYZE_GRAPH,query:n,contextMessage:"localAnalyzeGraph execution failed",execute:async()=>{let c=Ze(Xe,n);if(c.ok===!1)return c.error;let o=Kn(c.data),s=tt(o,se.LOCAL_ANALYZE_GRAPH);return s.isValid?qt({...o,path:s.sanitizedPath},{getGraph:r}):Ye(s.errorResult,o,{toolName:se.LOCAL_ANALYZE_GRAPH})}}),{toolName:se.LOCAL_ANALYZE_GRAPH},e)}export{Er as executeAnalyzeGraph};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __dirname_fn } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __dirname_fn(__filename);
8
+ import{a as D}from"./chunk-A4WMBDEC.js";import"./chunk-3AA4F3QO.js";import"./chunk-OA6NU4KO.js";import{a as M,b as U}from"./chunk-ZO44CZN5.js";import{d as T,l as _}from"./chunk-CBCZVCTZ.js";import"./chunk-DKGYPFGX.js";import"./chunk-USZL65FN.js";import{c as $,f as b,g as L,h as E}from"./chunk-ZSXRT7JL.js";import{ea as j,h as I,ha as h}from"./chunk-BMM5H6QF.js";import{existsSync as w,realpathSync as oe}from"fs";import{delimiter as se,dirname as R,join as y}from"path";function F(){return process.platform==="win32"?"npm.cmd":"npm"}function ie(){let e=R(process.execPath);return y(e,F())}function ae(){return process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin"]}function ce(){let e=(process.env.PATH??"").split(se).map(r=>r.trim()).filter(Boolean);return[...new Set([...e,...ae()])]}function pe(){let e=ie();if(w(e))return{command:process.execPath,argsPrefix:[e]};let r=F();for(let s of ce()){let n=y(s,r);if(w(n))return{command:n,argsPrefix:[]}}return{command:r,argsPrefix:[]}}function V(){let e=pe(),r=e.argsPrefix[0]??e.command;try{let s=oe(r),n=R(R(s));if(w(y(n,"bin","npm-cli.js")))return n;let o=y(R(s),"node_modules","npm");if(w(y(o,"bin","npm-cli.js")))return o}catch{}return y(R(process.execPath),"node_modules","npm")}var Le=[...M,...U,"NPM_CONFIG_REGISTRY","npm_config_registry","NPM_CONFIG_USERCONFIG","npm_config_userconfig","NPM_TOKEN","NODE_AUTH_TOKEN"];import{z as t}from"zod";var z=t.looseObject({name:t.string(),version:t.string(),repository:t.union([t.string(),t.object({url:t.string().optional(),type:t.string().optional(),directory:t.string().optional()})]).optional(),main:t.string().optional(),module:t.string().optional(),type:t.string().optional(),exports:t.unknown().optional(),types:t.string().optional(),typings:t.string().optional(),description:t.string().optional(),keywords:t.array(t.string()).optional(),license:t.union([t.string(),t.object({type:t.string().optional()})]).optional(),homepage:t.string().optional(),author:t.union([t.string(),t.object({name:t.string().optional(),email:t.string().optional(),url:t.string().optional()})]).optional(),maintainers:t.array(t.object({name:t.string().optional(),email:t.string().optional()})).optional(),engines:t.record(t.string(),t.string()).optional(),dependencies:t.record(t.string(),t.string()).optional(),devDependencies:t.record(t.string(),t.string()).optional(),peerDependencies:t.record(t.string(),t.string()).optional(),time:t.record(t.string(),t.string().optional()).optional()}),le=t.looseObject({package:t.looseObject({name:t.string().nullish(),version:t.string().nullish(),description:t.string().nullish(),links:t.looseObject({npm:t.string().nullish(),homepage:t.string().nullish(),repository:t.string().nullish()}).nullish()}),score:t.looseObject({final:t.number().nullish(),detail:t.looseObject({quality:t.number().nullish(),popularity:t.number().nullish(),maintenance:t.number().nullish()}).nullish()}).nullish()}),B=t.looseObject({objects:t.array(le),total:t.union([t.number(),t.string()]).optional()}),ue=t.union([t.string(),t.boolean(),t.number(),t.null(),t.record(t.string(),t.unknown())]);import{createHash as ge}from"node:crypto";import me from"@npmcli/config";import de from"@npmcli/config/lib/definitions/index.js";import fe from"npm-registry-fetch";var ye="https://registry.npmjs.org";async function G(e,r){let s=new me({...de,npmPath:V(),argv:["node","octocode","--no-workspaces"],env:{...process.env},cwd:process.cwd()});await s.load(),s.validate();let n=e?.startsWith("@")?e.split("/")[0]:void 0,o=String(r??(n?s.get(`${n}:registry`):void 0)??s.get("registry")??ye).replace(/\/+$/,""),i=new URL(o);if(!["http:","https:"].includes(i.protocol)||i.username||i.password||i.search||i.hash)throw new Error("Invalid npm registry URL: use HTTP(S) without credentials, query or fragment.");let p={...s.flat,registry:o},l=ge("sha256").update(JSON.stringify(Object.entries(p).sort(([a],[u])=>a.localeCompare(u)))).digest("hex");return{registry:o,cacheIdentity:l,options:p}}async function P(e,r){try{return await fe.json(`${e.registry}/${r}`,{...e.options,registry:e.registry,cache:!1,offline:!1,preferOffline:!1,retry:{retries:1,minTimeout:500,maxTimeout:1e3},timeout:8e3})}catch(s){let n=s.statusCode;throw n===401||n===403?new Error(`npm registry authentication failed (${n}). Check npm login and registry-scoped credentials.`):n===404?new Error("npm registry returned 404 Not Found."):new Error(n?`npm registry request failed (HTTP ${n}).`:"npm registry request failed: network or configuration error.")}}function N(e){return e.replace(/^git\+/,"").replace(/\.git$/,"")}function x(e){return e===void 0?0:j(e)}function k(e,r){return{values:e.slice(0,r),total:e.length,truncated:e.length>r}}function he(e){if(typeof e=="string")return k([e],12);if(!e||typeof e!="object")return;let s=Object.entries(e).flatMap(([n,o])=>typeof o=="string"?[`${n}:${o}`]:o&&typeof o=="object"?Object.entries(o).filter(([,i])=>typeof i=="string").map(([i,p])=>`${n}:${i}:${p}`):[]);return s.length>0?k(s,12):void 0}function Re(e,r){if(typeof e=="string"){let s=r?.replace(/^@[^/]+\//,"")??"";return k([s?`${s} \u2192 ${e}`:e],8)}if(e&&typeof e=="object"){let s=Object.entries(e).filter(([,n])=>typeof n=="string").map(([n,o])=>`${n} \u2192 ${o}`);return s.length>0?k(s,8):void 0}}function be(e){return e.type==="module"||e.module?"module":e.main?"commonjs":e.types||e.typings?"types-only":"unknown"}function H(e,r=!1,s="cli"){let n=he(e.exports),o=Re(e.bin,e.name),i=null,p;e.repository&&(typeof e.repository=="string"?i=N(e.repository):(e.repository.url&&(i=N(e.repository.url)),e.repository.directory&&(p=e.repository.directory.replace(/^\.\//,""))));let l;if(e.time){let g=(e.version?e.time[e.version]:void 0)||e.time.modified;g&&(l=g)}let a={name:e.name,npmUrl:`https://www.npmjs.com/package/${encodeURIComponent(e.name)}`,repoUrl:i,version:e.version||"latest",mainEntry:e.main||null,moduleEntry:e.module||null,typeDefinitions:e.types||e.typings||null,packageType:be(e),...p?{repositoryDirectory:p}:{},...n?{exports:n.values,exportsTotal:n.total,...n.truncated?{exportsTruncated:!0}:{}}:{},...o?{bin:o.values,binTotal:o.total,...o.truncated?{binTruncated:!0}:{}}:{},lastPublished:l,source:s};return e.description&&(a.description=e.description),e.license&&(a.license=typeof e.license=="string"?e.license:e.license.type),r&&(e.author&&(typeof e.author=="string"?a.author=e.author:e.author.name&&(a.author=e.author.name)),e.keywords&&e.keywords.length>0&&(a.keywords=e.keywords),e.homepage&&(a.homepage=e.homepage),e.engines&&Object.keys(e.engines).length>0&&(a.engines=e.engines),e.dependencies&&Object.keys(e.dependencies).length>0&&(a.dependencies=e.dependencies),e.peerDependencies&&Object.keys(e.peerDependencies).length>0&&(a.peerDependencies=e.peerDependencies)),a}function K(e){return e.startsWith("@")?"@"+e.slice(1).replace("/","%2F"):e}function W(e,r){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&/^\d+$/.test(e)){let s=Number(e);if(Number.isFinite(s))return s}return r}async function S(e,r,s){try{let n=await P(s,`${K(e)}/latest`),o=x(n),i=z.safeParse(n);return i.success?i.data.name!==e?{error:"npm registry returned a different package name.",rawResponseChars:o}:{packages:[H(i.data,r,"registry")],totalFound:1,rawResponseChars:o}:{error:"Invalid npm registry package response.",rawResponseChars:o}}catch(n){let o=n instanceof Error?n.message:"npm package request failed.";return o.includes("404 Not Found")?{packages:[],totalFound:0,rawResponseChars:0}:{error:o}}}async function Q(e,r,s,n,o){try{let i=n>0?`&from=${n}`:"",p=`-/v1/search?text=${encodeURIComponent(e)}&size=${r}${i}`,l;try{l=await P(o,p)}catch(c){return{error:`Could not reach the npm search API (${c instanceof Error?c.message:String(c)}). The package may not exist, or the registry search endpoint is unavailable.`,hints:['Verify the exact package name / scope (e.g. "@scope/name")',"For an exact known name, query it directly instead of a keyword search","Ensure the npm registry is accessible from this environment"]}}let a=x(l);if(!l||typeof l!="object")return{error:"Invalid npm registry search response; expected an object with results and a total.",rawResponseChars:a};let u=B.safeParse(l);if(!u.success)return{error:`Invalid npm registry search response format: ${u.error.issues.map(m=>m.message).join("; ")}`,rawResponseChars:a,hints:["Try a different search term","Use packageName for an exact package lookup"]};let g=W(u.data.total,NaN);if(!Number.isSafeInteger(g)||g<0)return{error:"npm registry search omitted a valid total; pagination cannot be determined.",rawResponseChars:a};if(u.data.objects.some(c=>!c.package.name))return{error:"npm registry search returned an unnamed package; refusing to skip a result.",rawResponseChars:a};let d=u.data.objects.map(c=>c.package).filter(c=>typeof c.name=="string"&&c.name.length>0).slice(0,r),f=await Promise.all(d.map(async c=>{if(s){let m=await S(c.name,!0,o);if(!("error"in m)&&m.packages[0])return{pkg:m.packages[0],rawResponseChars:m.rawResponseChars??0}}return{pkg:{name:c.name,npmUrl:(c.links?.npm??"")||`https://www.npmjs.com/package/${encodeURIComponent(c.name)}`,repoUrl:c.links?.repository&&typeof c.links.repository=="string"?N(c.links.repository):null,version:c.version??"unknown",source:"registry",...c.description?{description:c.description}:{},...typeof c.license=="string"?{license:c.license}:{},...typeof c.date=="string"?{lastPublished:c.date}:{},...c.links?.homepage?{homepage:c.links.homepage}:{}},rawResponseChars:0}})),te=f.map(c=>c.pkg).filter(c=>!!c),ne=f.reduce((c,m)=>c+m.rawResponseChars,0);return{packages:te,totalFound:g,rawResponseChars:a+ne}}catch(i){return{error:`NPM registry search failed: ${i instanceof Error?i.message:String(i)}`,hints:["Check package name for typos","Try searching with a simpler term","Ensure npm registry is accessible"]}}}async function J(e,r,s,n=0,o="exact",i){let p=await G(o==="exact"?e:void 0,i),l=T("npm-search",{registry:p.registry,identity:p.cacheIdentity,mode:o,name:e,limit:r,metadata:s,from:n});return _(l,async()=>{let a=o==="exact"?await S(e,s,p):await Q(e,r,s,n,p);return"error"in a?a:{...a,registry:p.registry}},{shouldCache:a=>!("error"in a||"totalFound"in a&&a.totalFound===0)})}async function Y(e){let r=e.mode==="exact",s=e.itemsPerPage??(r?1:10),n=Math.max(0,((e.page??1)-1)*s);return J(e.name,s,!1,n,e.mode,e.registry)}function X(e){if(e===void 0)return;let r=e.join(" ").trim();return r.length>0?r:void 0}var we=/\b(?:404|e404)\b|not\s+found|no\s+such\s+package|does\s+not\s+exist/i;function Z(e){return we.test(e)}import{getConfigSync as Pe}from"@octocodeai/config";function v(e,r=Pe()){let s=e===I.GITHUB_CLONE_REPO,n=s||e.startsWith("local")||e.startsWith("lsp"),o;return n&&!r.local.enabled?o="ENABLE_LOCAL":s&&r.storage.mode!=="persistent"?o="OCTOCODE_STORAGE_MODE":s&&!r.local.enableClone?o="ENABLE_CLONE":r.tools.enabled?.length?r.tools.enabled.includes(e)||(o="TOOLS_TO_RUN"):r.tools.disabled?.includes(e)&&(o="DISABLE_TOOLS"),o?{enabled:!1,envVar:o}:{enabled:!0}}function q(e,r,s,n){let o=Math.max(1,e.page??1),i=n?e.pageSize??10:1,p=Math.max(1,Math.ceil(r/i)),l=n&&o<p;return{currentPage:o,totalPages:p,perPage:i,totalFound:r,returned:s,hasMore:l,...l&&o<1e3?{nextPage:o+1}:{},...l&&o>=1e3?{continuationUnavailable:{reason:"schemaPageLimit",maxPage:1e3}}:{}}}function ee(e,r){if(!(!Array.isArray(e.keywords)||typeof r.nextPage!="number"))return{nextPage:{tool:"npmSearch",query:{keywords:e.keywords,...e.registry?{registry:e.registry}:{},page:r.nextPage,...typeof e.pageSize=="number"?{pageSize:e.pageSize}:{}},why:`Continue npm keyword discovery on page ${r.nextPage}.`,confidence:"exact"}}}function Ne(e){return"error"in e}function C(e){return"npmUrl"in e}function ke(e){return C(e)&&e.path?e.path:e.name}function xe(e){return C(e)?e.repoUrl:e.repository}function Se(e){if(!e)return;let r=e.replace(/^\.\//,"").replace(/^\//,"");return r.length>0?r:void 0}var Ce={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Ee(e){if(!e)return;let r=e.trim();if(!r)return;r=r.replace(/^git\+/,"");let s=p=>p.replace(/\.git$/,""),n=r.match(/^(github|gitlab|bitbucket):(.+)$/i);if(n&&n[1]&&n[2]){let p=Ce[n[1].toLowerCase()];return s(`https://${p}/${n[2]}`)}let o=r.match(/^[^@/]+@([^:/]+):(.+)$/);if(o&&o[1]&&o[2])return s(`https://${o[1]}/${o[2]}`);let i=r.match(/^(?:ssh|git|https?):\/\/(.+)$/);if(i&&i[1]){let p=i[1].replace(/^[^@/]+@/,"");return s(`https://${p}`)}return s(r)}function A(e){if(!e)return;let r=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/#?]+)/i);if(!(!r||!r[1]||!r[2]))return{owner:r[1],repo:r[2]}}function re(e,r){let s=A(e);if(!s)return;let{owner:n,repo:o}=s,i={viewTree:{tool:"ghSearch",query:{operation:"tree",owner:n,repo:o,...r?{path:r}:{}}},searchRepositoryCode:{tool:"ghSearch",query:{operation:"code",owner:n,repo:o}}};v("ghCloneRepo").enabled&&(i.cloneRepo={tool:"ghCloneRepo",query:{owner:n,repo:o,...r?{sparsePath:r}:{}}});for(let[p,l]of Object.entries(i))v(l.tool).enabled||delete i[p];return i}function ve(e){let r=ke(e),s=Ee(xe(e)),n={name:r};C(e)&&(e.version&&e.version!=="unknown"&&(n.version=e.version),e.description&&(n.description=e.description),e.license&&(n.license=e.license),typeof e.weeklyDownloads=="number"&&(n.downloads=e.weeklyDownloads)),s&&(n.repository=s);let o=Se(C(e)?e.repositoryDirectory:void 0);o&&(n.repositoryDirectory=o);let i=re(s,o);return i&&(n.next=i),n.version&&A(s)&&(n.warnings=[`npm version ${n.version} is the registry's latest publish and may not correspond to a release/tag in the linked repository \u2014 verify against the repo's releases or tags before citing it as the repo's latest release.`]),n}function Oe(e){if(e.length<=1)return{packages:e};let r={},s=new Map,n=1,o=e.map(i=>{if(!i.repository)return i;let p=A(i.repository);if(!p)return i;let l=`${i.repository}\0${i.repositoryDirectory??""}`,a=s.get(l);a||(a=`r${n++}`,s.set(l,a),r[a]={repository:i.repository,owner:p.owner,repo:p.repo,...i.repositoryDirectory?{repositoryDirectory:i.repositoryDirectory}:{},next:re(i.repository,i.repositoryDirectory)});let{repository:u,repositoryDirectory:g,next:d,...f}=i;return{...f,repositoryId:a}});return Object.keys(r).length?{packages:o,repositories:r}:{packages:e}}async function Or(e){return $(e.queries,async r=>{try{let s=L(D,r);if(s.ok===!1)return s.error;r=s.data;let n=r.packageName??X(r.keywords),o=Array.isArray(r.keywords);if(!n)return b("Provide a packageName or keywords for package search",r);let i=await Y({name:n,registry:r.registry,mode:o?"keywords":"exact",page:r.page,...o&&typeof r.pageSize=="number"?{itemsPerPage:r.pageSize}:{},goal:r.goal,reasoning:r.reasoning});if(Ne(i))return!o&&Z(i.error)?E(r,{packages:[],hints:[`No package named "${n}". Check spelling and scope.`]},!1,h.PACKAGE_SEARCH,{rawResponse:i}):b(i.error,r,{rawResponse:i});let l=i.packages.map(ve),a=l.length>0,u=q(r,i.totalFound,l.length,o),g=Oe(l),d=ee({...r,registry:i.registry??r.registry},u),f={...g,pagination:u,...u.continuationUnavailable?{terminalLimit:!0}:{},...d?{next:d}:{}};return E(r,f,a,h.PACKAGE_SEARCH,{rawResponse:i.rawResponseChars??i})}catch(s){return b(s,r,{toolName:h.PACKAGE_SEARCH})}},{toolName:h.PACKAGE_SEARCH,keysPriority:["packages","pagination","error"]},e)}export{Oe as compactPackageRepositories,ve as formatPackageData,Ee as normalizeRepoUrl,Or as searchPackages};